瀏覽代碼

initialize

stany.ferer 2 年之前
當前提交
4e15399ceb
共有 100 個文件被更改,包括 9166 次插入0 次删除
  1. 53 0
      access.inc.php
  2. 43 0
      conf.inc.php
  3. 121 0
      core/class/alert.class.php
  4. 166 0
      core/class/chart.class.php
  5. 174 0
      core/class/core.class.php
  6. 140 0
      core/class/db.class.php
  7. 397 0
      core/class/event.class.php
  8. 123 0
      core/class/file.class.php
  9. 118 0
      core/class/get.class.php
  10. 138 0
      core/class/json.class.php
  11. 10 0
      core/class/myQrcode.class.php
  12. 264 0
      core/class/proweb.class.php
  13. 54 0
      core/class/pwa.class.php
  14. 743 0
      core/class/salaries.class.php
  15. 92 0
      core/class/session.class.php
  16. 176 0
      core/class/sftp.class.php
  17. 184 0
      core/class/simpleCSV.class.php
  18. 1308 0
      core/class/simpleXLS.class.php
  19. 1188 0
      core/class/simpleXLSX.class.php
  20. 82 0
      core/class/stats.class.php
  21. 150 0
      core/class/user.class.php
  22. 9 0
      core/class/view.class.php
  23. 10 0
      core/controllers/cms.index.php
  24. 8 0
      core/controllers/cms.session.php
  25. 14 0
      core/controllers/events.index.php
  26. 8 0
      core/controllers/events.session.php
  27. 13 0
      core/controllers/header.php
  28. 23 0
      core/controllers/json/cms.event-inscrits.php
  29. 23 0
      core/controllers/json/cms.event-salaries.php
  30. 4 0
      core/controllers/json/cms.proweb-transfert-local.php
  31. 4 0
      core/controllers/json/cms.proweb-transfert-sftp.php
  32. 4 0
      core/controllers/json/cms.proweb-transfert-test-connexion.php
  33. 45 0
      core/controllers/json/events.check-control-emargement.php
  34. 18 0
      core/controllers/json/events.list-events.php
  35. 20 0
      core/controllers/json/events.login.php
  36. 5 0
      core/controllers/json/events.logout.php
  37. 38 0
      core/libs/phpqrcode/CHANGELOG
  38. 67 0
      core/libs/phpqrcode/INSTALL
  39. 165 0
      core/libs/phpqrcode/LICENSE
  40. 45 0
      core/libs/phpqrcode/README
  41. 2 0
      core/libs/phpqrcode/VERSION
  42. 2875 0
      core/libs/phpqrcode/bindings/tcpdf/qrcode.php
  43. 2 0
      core/libs/phpqrcode/cache/frame_1.dat
  44. 二進制
      core/libs/phpqrcode/cache/frame_1.png
  45. 二進制
      core/libs/phpqrcode/cache/frame_10.dat
  46. 二進制
      core/libs/phpqrcode/cache/frame_10.png
  47. 二進制
      core/libs/phpqrcode/cache/frame_11.dat
  48. 二進制
      core/libs/phpqrcode/cache/frame_11.png
  49. 二進制
      core/libs/phpqrcode/cache/frame_12.dat
  50. 二進制
      core/libs/phpqrcode/cache/frame_12.png
  51. 二進制
      core/libs/phpqrcode/cache/frame_13.dat
  52. 二進制
      core/libs/phpqrcode/cache/frame_13.png
  53. 二進制
      core/libs/phpqrcode/cache/frame_14.dat
  54. 二進制
      core/libs/phpqrcode/cache/frame_14.png
  55. 二進制
      core/libs/phpqrcode/cache/frame_15.dat
  56. 二進制
      core/libs/phpqrcode/cache/frame_15.png
  57. 1 0
      core/libs/phpqrcode/cache/frame_16.dat
  58. 二進制
      core/libs/phpqrcode/cache/frame_16.png
  59. 二進制
      core/libs/phpqrcode/cache/frame_17.dat
  60. 二進制
      core/libs/phpqrcode/cache/frame_17.png
  61. 2 0
      core/libs/phpqrcode/cache/frame_18.dat
  62. 二進制
      core/libs/phpqrcode/cache/frame_18.png
  63. 3 0
      core/libs/phpqrcode/cache/frame_19.dat
  64. 二進制
      core/libs/phpqrcode/cache/frame_19.png
  65. 1 0
      core/libs/phpqrcode/cache/frame_2.dat
  66. 二進制
      core/libs/phpqrcode/cache/frame_2.png
  67. 二進制
      core/libs/phpqrcode/cache/frame_20.dat
  68. 二進制
      core/libs/phpqrcode/cache/frame_20.png
  69. 1 0
      core/libs/phpqrcode/cache/frame_21.dat
  70. 二進制
      core/libs/phpqrcode/cache/frame_21.png
  71. 3 0
      core/libs/phpqrcode/cache/frame_22.dat
  72. 二進制
      core/libs/phpqrcode/cache/frame_22.png
  73. 3 0
      core/libs/phpqrcode/cache/frame_23.dat
  74. 二進制
      core/libs/phpqrcode/cache/frame_23.png
  75. 1 0
      core/libs/phpqrcode/cache/frame_24.dat
  76. 二進制
      core/libs/phpqrcode/cache/frame_24.png
  77. 3 0
      core/libs/phpqrcode/cache/frame_25.dat
  78. 二進制
      core/libs/phpqrcode/cache/frame_25.png
  79. 2 0
      core/libs/phpqrcode/cache/frame_26.dat
  80. 二進制
      core/libs/phpqrcode/cache/frame_26.png
  81. 二進制
      core/libs/phpqrcode/cache/frame_27.dat
  82. 二進制
      core/libs/phpqrcode/cache/frame_27.png
  83. 二進制
      core/libs/phpqrcode/cache/frame_28.dat
  84. 二進制
      core/libs/phpqrcode/cache/frame_28.png
  85. 2 0
      core/libs/phpqrcode/cache/frame_29.dat
  86. 二進制
      core/libs/phpqrcode/cache/frame_29.png
  87. 1 0
      core/libs/phpqrcode/cache/frame_3.dat
  88. 二進制
      core/libs/phpqrcode/cache/frame_3.png
  89. 二進制
      core/libs/phpqrcode/cache/frame_30.dat
  90. 二進制
      core/libs/phpqrcode/cache/frame_30.png
  91. 1 0
      core/libs/phpqrcode/cache/frame_31.dat
  92. 二進制
      core/libs/phpqrcode/cache/frame_31.png
  93. 2 0
      core/libs/phpqrcode/cache/frame_32.dat
  94. 二進制
      core/libs/phpqrcode/cache/frame_32.png
  95. 14 0
      core/libs/phpqrcode/cache/frame_33.dat
  96. 二進制
      core/libs/phpqrcode/cache/frame_33.png
  97. 二進制
      core/libs/phpqrcode/cache/frame_34.dat
  98. 二進制
      core/libs/phpqrcode/cache/frame_34.png
  99. 二進制
      core/libs/phpqrcode/cache/frame_35.dat
  100. 二進制
      core/libs/phpqrcode/cache/frame_35.png

+ 53 - 0
access.inc.php

@@ -0,0 +1,53 @@
+<?php
+    // Droits par profil
+    define("ACCESS_WHITE", array(
+        "page" => array(
+            "login",
+            "login-salarie",
+            "login-control",
+            "spash-screen"
+        ),
+        "json" => array(
+            "login",
+            "logout",
+        ),
+        "submit" => array(
+            "login",
+            "logout"
+        ))
+    );
+
+    define("ACCESS_SALARIES", array(
+        "page" => array(
+            "list-events"
+        ),
+        "json" => array(
+            "list-events",
+            "check-control-emargement"
+        ),
+        "submit" => array(
+            "emargement"
+        ))
+    );
+
+    define("ACCESS_CONTROLEURS", array(
+        "page" => array(
+            "validateQRCode"
+        ),
+        "json" => array(
+        ),
+        "submit" => array(
+            "emargement"
+        ))
+    );
+
+    define("ACCESS_SOCIAL", array(
+        "page" => array(
+            "sociale-check-salarie"
+        ),
+        "json" => array(
+        ),
+        "submit" => array(
+            "sociale-check-salarie"
+        ))
+    );

+ 43 - 0
conf.inc.php

@@ -0,0 +1,43 @@
+<?php
+
+require_once "env.inc.php";
+require_once("access.inc.php");
+
+define("PWA", 1);
+
+define("TIME_ZONE", "Europe/Paris");
+
+define("DIR_PHP_CLASS", DOCUMENT_ROOT . "core/class/");
+define("DIR_PHP_VIEWS", DOCUMENT_ROOT . "core/views/");
+define("DIR_PHP_VIEWS_PAGE", DOCUMENT_ROOT . "core/views/pages/");
+define("DIR_PHP_LAYOUTS", DOCUMENT_ROOT . "core/controllers/");
+define("DIR_PHP_SUBMIT", DOCUMENT_ROOT . "core/submit/");
+define("DIR_PHP_LIBS", DOCUMENT_ROOT . "core/libs/");
+define("DIR_DATAS_JSON", DOCUMENT_ROOT . "datas/json/");
+define("DIR_DATAS_JSONDATA", DOCUMENT_ROOT . "core/controllers/json/");
+define("DIR_DATAS_TEMP", DOCUMENT_ROOT . "datas/tmp/");
+define("DIR_DATAS_BACKUP", DOCUMENT_ROOT . "datas/backups/");
+define("DIR_DATAS_FILES", DOCUMENT_ROOT . "datas/files/");
+
+define("SFTP_LOCAL", DOCUMENT_ROOT . "datas/sftp/");
+
+define("DB_T_USER", "user");
+define("DB_T_USER_TYPE", "user_type");
+define("DB_T_SALARIES", "salaries");
+define("DB_T_TEMP_SALARIES", "tmp_salaries");
+define("DB_T_ENTREE_SORTIE", "entree_sortie");
+define("DB_T_EXCEL", "excelRH");
+define("DB_T_EVENTS", "evenement");
+define("DB_T_EVENTS_INSCRITS", "evenement_salaries");
+define("DB_T_SALARIES_PROWEB", "salariesProweb");
+define("DB_T_EXCEL_PROWEB", "excelProweb");
+define("DB_T_FILES", "files");
+
+define("DEFAUT_PAGE", "rh-liste-salaries");
+define("DEFAUT_PAGE_SOCIAL", "sociale-check-salarie");
+
+// Liens utiles
+define("FICHE_SALARIE_PROWEB", "https://www.cse-invent.com/gestion/beneficiaire/od/edit/");
+
+// Emargement
+define("EMEMARGEMENT_END", 1800); // Possibilité de s'émarger 1800 secondes soit 30 minutes après l'évènements

+ 121 - 0
core/class/alert.class.php

@@ -0,0 +1,121 @@
+<?php
+
+class alert
+{
+    public static function recSuccess(string $_string)
+    {
+        if (empty($_SESSION["alert"]["success"])) {
+            $_SESSION["alert"]["success"] = array();
+        }
+        array_push($_SESSION["alert"]["success"], $_string);
+    }
+
+    public static function recError(string $_string)
+    {
+        if (empty($_SESSION["alert"]["error"])) {
+            $_SESSION["alert"]["error"] = array();
+        }
+        array_push($_SESSION["alert"]["error"], $_string);
+    }
+
+    public static function recTab(string $_string)
+    {
+        $_SESSION["alert"]["tab"] = $_string;
+    }
+
+    public static function getSuccess()
+    {
+        if (!empty($_SESSION["alert"]["success"])) {
+            return $_SESSION["alert"]["success"];
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function getError()
+    {
+        if (!empty($_SESSION["alert"]["error"])) {
+            return $_SESSION["alert"]["error"];
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function getTab()
+    {
+        return (isset($_SESSION["alert"]["tab"])) ? $_SESSION["alert"]["tab"] : FALSE;
+    }
+
+    public static function ifSuccess()
+    {
+        return (empty($_SESSION["alert"]["success"])) ? FALSE : TRUE;
+    }
+
+    public static function ifError()
+    {
+        return (empty($_SESSION["alert"]["error"])) ? FALSE : TRUE;
+    }
+
+    public static function ifTab()
+    {
+        return (empty($_SESSION["alert"]["tab"])) ? FALSE : TRUE;
+    }
+
+    public static function printAlert(array $_array)
+    {
+        $return = NULL;
+        foreach ($_array as $value) {
+            $return .= "<div>" . $value . "</div>";
+        }
+        return $return;
+    }
+
+    public static function recErrorInput(string $_string)
+    {
+        if (empty($_SESSION["alert"]["input"])) {
+            $_SESSION["alert"]["input"] = array();
+        }
+        array_push($_SESSION["alert"]["input"], $_string);
+    }
+
+    public static function ifErrorInput(string $_string)
+    {
+        return (in_array($_string, $_SESSION["alert"]["input"])) ? TRUE : FALSE;
+    }
+
+    private static function printToast(string $_style, string $_icon, array $_texte)
+    {
+        echo '  <div class="toast hide" role="alert" aria-live="assertive" aria-atomic="true" data-delay="1500" style="margin-top:10px; ' . $_style . '">
+                    <div class="toast-header">' . $_icon . '</div><div class="toast-body">' . self::printAlert($_texte) . '</div>
+                </div>';
+    }
+
+    public static function show()
+    {
+        if (self::getSuccess() or self::getError()) {
+
+            echo '<div aria-live="polite" aria-atomic="true" class="position-fixed bottom-0 right-0 p-3"  style="z-index: 5; right: 5px; bottom: 0;">';
+
+            if (self::getSuccess()) {
+                $style = 'background:#d4edda;';
+                $icon = '<span data-feather="info" style="color:green;"></span> <strong style="color:green; margin-left:5px;" class="mr-auto">Succès</strong>';
+                $texte = self::getSuccess();
+                self::printToast($style, $icon, $texte);
+            }
+
+            if (self::getError()) {
+                $style = 'background:#f8d7da;';
+                $icon = '<span data-feather="alert-triangle" style="color:red;"></span> <strong style="color:red; margin-left:5px;" class="mr-auto">Erreur</strong>';
+                $texte = self::getError();
+                self::printToast($style, $icon, $texte);
+            }
+            echo '</div>';
+        }
+        self::destroyAlert();
+    }
+
+    public static function destroyAlert()
+    {
+        unset($_SESSION["alert"]);
+    }
+}

+ 166 - 0
core/class/chart.class.php

@@ -0,0 +1,166 @@
+<?php
+
+// Documentation
+// https://www.chartjs.org/docs/2.6.0/
+
+class chart
+{
+
+    public static function printCanvas(array $_config)
+    {
+        $id = $_config["id"];
+        $width = (isset($_config["width"])) ? $_config["width"] : 600;
+        $height = (isset($_config["height"])) ? $_config["height"] : 400;
+
+        echo '<canvas id="' . $id . '" width="' . $width . '" height="' . $height . '" style="display: block; width: ' . $width . 'px; height: ' . $height . 'px;" class="chartjs-render-monitor"></canvas>';
+
+        switch ($_config["charts"]) {
+            case "doughnut":
+                echo self::javascriptDoughnut($_config);
+                break;
+            case "bar":
+                echo self::javascriptBar($_config);
+                break;
+            case "line":
+                echo self::javascriptLine($_config);
+                break;
+            default:
+                break;
+        }
+    }
+
+    private static function constructData(array $_data)
+    {
+        $label = $nb = $backgroundColor = $borderColor = "";
+        $opacity = 0.5;
+        $nbData = count($_data);
+
+        $data["backgroundColor"] = array(
+            "rgba(255, 99, 132, " . $opacity . ")", // Red
+            "rgba(54, 162, 235, " . $opacity . ")", // Blue
+            "rgba(255, 206, 86, " . $opacity . ")", // Yellow
+            "rgba(75, 192, 192, " . $opacity . ")", // Green,
+            "rgba(153, 102, 255, " . $opacity . ")", // Purple
+            "rgba(255, 159, 64, " . $opacity . ")" // Orange
+        );
+
+        $data["borderColor"] = array(
+            "rgba(255,99,132,1)", // Red
+            "rgba(54, 162, 235, 1)", // Blue
+            "rgba(255, 206, 86, 1)", // Yellow
+            "rgba(75, 192, 192, 1)", // Green
+            "rgba(153, 102, 255, 1)", // Purple
+            "rgba(255, 159, 64, 1)" // Orange
+        );
+
+        for ($i = 0; $i < $nbData; $i++) {
+            $backgroundColor .= '"' . $data["backgroundColor"][$i] . '"';
+            if ($i != $nbData) {
+                $backgroundColor .= ", ";
+            }
+        }
+
+        for ($i = 0; $i < $nbData; $i++) {
+            $borderColor .= '"' . $data["borderColor"][$i] . '"';
+            if ($i != $nbData) {
+                $borderColor .= ", ";
+            }
+        }
+
+        for ($i = 0; $i < $nbData; $i++) {
+            $label .= '"' . $_data[$i]["label"] . '"';
+            if ($i != $nbData) {
+                $label .= ", ";
+            }
+        }
+
+        for ($i = 0; $i < $nbData; $i++) {
+            $nb .= '"' . $_data[$i]["nb"] . '"';
+            if ($i != $nbData) {
+                $nb .= ", ";
+            }
+        }
+
+        return array("label" => $label, "nb" => $nb, "backgroundColor" => $backgroundColor, "borderColor" => $borderColor);
+    }
+
+    private static function javascriptDoughnut(array $_config)
+    {
+
+        $sort = self::constructData($_config["data"]);
+
+        return '<script>
+                var ctx = document.getElementById("' . $_config["id"] . '");
+                var myChart = new Chart(ctx, {
+                    type: "doughnut",
+                    data: {
+                        labels: [' . $sort["label"] . '],
+                        datasets: [{
+                            label: "' . $_config["label"] . '",
+                            data: [' . $sort["nb"] . '],
+                            backgroundColor: [' . $sort["backgroundColor"] . '],
+                            borderColor: [' . $sort["borderColor"] . '],
+                            borderWidth: 1
+                        }]
+                    }
+                });
+            </script>';
+    }
+
+    private static function javascriptBar(array $_config)
+    {
+
+        $sort = self::constructData($_config["data"]);
+
+        return '<script>
+                var ctx = document.getElementById("' . $_config["id"] . '");
+                var myChart = new Chart(ctx, {
+                    type: "bar",
+                    data: {
+                        labels: [' . $sort["label"] . '],
+                        datasets: [{
+                            label: "' . $_config["label"] . '",
+                            data: [' . $sort["nb"] . '],
+                            backgroundColor: [' . $sort["backgroundColor"] . '],
+                            borderColor: [' . $sort["borderColor"] . '],
+                            borderWidth: 1
+                        }]
+                    }
+                });
+            </script>';
+    }
+
+    private static function constructDataLine(array $_data)
+    {
+        $return["labels"] = $return["data"] = NULL;
+        foreach ($_data[0] as $key => $value) {
+            $return["labels"] .= '"' . $key . '", ';
+            $return["data"] .= $value . ', ';
+        }
+        return $return;
+    }
+
+    private static function javascriptLine(array $_config)
+    {
+
+        $sort = self::constructDataLine($_config["data"]);
+
+        return '<script>
+                var ctx = document.getElementById("' . $_config["id"] . '");
+                var myChart = new Chart(ctx, {
+                    type: "line",
+                    data: {
+                            "labels":[' . $sort["labels"] . '],
+                            datasets: [{
+                                "label":"' . $_config["label"] . '", 
+                                "data":[' . $sort["data"] . '], 
+                                "fill":false, 
+                                "borderColor":"rgb(75, 192, 192)", 
+                                "lineTension":0.1
+                            }],
+                            "options":{}
+                    }
+                });
+            </script>';
+    }
+}

+ 174 - 0
core/class/core.class.php

@@ -0,0 +1,174 @@
+<?php
+
+class core
+{
+    public static function ifGet(string $_string)
+    {
+        if (isset($_GET[$_string])) {
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function ifPost(string $_string)
+    {
+        if (isset($_POST[$_string])) {
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function getGet(string $_string = NULL)
+    {
+        if ($_string == NULL) {
+            return $_GET;
+        } else {
+            if (isset($_GET[$_string])) {
+                return $_GET[$_string];
+            } else {
+                return NULL;
+            }
+        }
+    }
+
+    public static function getPost(string $_string = NULL)
+    {
+        if ($_string == NULL) {
+            return $_POST;
+        } else {
+            if (isset($_POST[$_string])) {
+                return $_POST[$_string];
+            } else {
+                return NULL;
+            }
+        }
+    }
+
+    public static function convertDate(string $datetime)
+    {
+        $pieces = explode(" ", $datetime);
+        $pieces3 = explode(":", $pieces[1]);
+        $pieces2 = explode("-", $pieces[0]);
+        return $pieces2[2] . "/" . $pieces2[1] . "/" . $pieces2[0] . " à " . $pieces3[0] . ":" . $pieces3[1];
+    }
+
+    public static function dateFr(string $_timestampMysql = NULL)
+    {
+        if ($_timestampMysql == NULL) {
+            $Now = new DateTime('now', new DateTimeZone(TIME_ZONE));
+            return $Now->format("d/m/Y H:i:s");
+        } else {
+            return DateTime::createFromFormat("d/m/Y H:i:s", $_timestampMysql);
+        }
+    }
+
+    public static function dateFromTimestamp(int $_timestamp = NULL)
+    {
+        if ($_timestamp == NULL) {
+            return NULL;
+        } else {
+            return date("Y-m-d H:i:s", $_timestamp);
+        }
+    }
+
+    public static function formatFileSize(float $_size, int $_decimalplaces = 0)
+    {
+        $sizes = array('O', 'Ko', 'Mo', 'Go', 'To');
+        for ($i = 0; $_size > 1024 && $i < count($sizes) - 1; $i++) {
+            $_size /= 1024;
+        }
+        return round($_size, $_decimalplaces) . ' ' . $sizes[$i];
+    }
+
+    public static function checkStringOnly(string $_string)
+    {
+        if (!ctype_alpha($_string)) {
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function print_r(array $_array, int $_exit = NULL)
+    {
+        echo "<pre>";
+        print_r($_array);
+        echo "</pre>";
+        ($_exit != NULL) ? exit() : NULL;
+    }
+
+    public static function elementMenu(string $_id, string $_href, string $_titre, string $_feather, string $_style = NULL)
+    {
+        ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
+        echo '<li class="nav-item">
+                <a class="nav-link' . get::currentPage($_id) . '" aria-current="page"  href="' . $_href . '"' . $_style . '>
+                    <span data-feather="' . $_feather . '"' . $_style . '></span>
+                    ' . $_titre . '
+                </a>
+            </li>';
+    }
+
+    public static function elementMenuLink(string $_href, string $_titre, string $_feather, string $_style = NULL, string $_target = "_blank")
+    {
+        ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
+        echo '<li class="nav-item">
+                <a class="nav-link" target="'. $_target .'" href="' . $_href . '"' . $_style . '>
+                    <span data-feather="' . $_feather . '"' . $_style . '></span>
+                    ' . $_titre . '
+                </a>
+            </li>';
+    }
+
+    public static function elementMenuH6(string $_titre, string $_style = NULL)
+    {
+        ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
+        echo '<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
+                    <span' . $_style . '>' . $_titre . '</span>
+                </h6>';
+    }
+
+    public static function filAriane(array $_arbo)
+    {
+
+        $return = '<nav aria-label="breadcrumb bg-300">';
+        $return .= '<ol class="breadcrumb" style="padding:5px 10px; border-bottom: 1px solid #e9ecef;">';
+
+        foreach ($_arbo["arbo"] as $label => $lien) {
+            if ($_arbo["current"] == $label) {
+                $return .= '<li class="breadcrumb-item active" aria-current="page">' . $label . '</li>';
+            } elseif ($lien == NULL) {
+                $return .= '<li class="breadcrumb-item">' . $label . '</li>';
+            } else {
+                $return .= '<li class="breadcrumb-item"><a href="' . $lien . '" title="' . $label . '">' . $label . '</a></li>';
+            }
+        }
+        $return .= '</ol>';
+        $return .= '</nav>';
+        return $return;
+    }
+
+    public static function encodeUTF8(string $_data)
+    {
+        return (mb_detect_encoding($_data) != "UTF-8") ? mb_convert_encoding($_data, 'UTF-8', mb_list_encodings()) : $_data;
+    }
+
+    public static function testConnexionInternet()
+    {
+        $hosts = ['1.1.1.1', '1.0.0.1', '8.8.8.8', '8.8.4.4'];
+        foreach ($hosts as $host) {
+            if ($connected = @fsockopen($host, 443)) {
+                fclose($connected);
+                return TRUE;
+            }
+        }
+        return FALSE;
+    }
+
+    public static function printDateTxt()
+    {
+        $date = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE);
+        return $date->format(time()) . " à " . date("H:m:s");
+    }
+}

+ 140 - 0
core/class/db.class.php

@@ -0,0 +1,140 @@
+<?php
+
+class db
+{
+    private static $dbh;
+    private static $error;
+    private static $qError;
+    private static $stmt;
+
+    private static function connexion()
+    {
+        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
+        $options = array(
+            PDO::ATTR_PERSISTENT => true,
+            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
+        );
+
+        try {
+            self::$dbh = new PDO($dsn, DB_USER, DB_PASS, $options);
+        } catch (PDOException $e) {
+            self::$error = $e->getMessage();
+        }
+    }
+
+    public static function query(string $query)
+    {
+        self::connexion();
+        self::$stmt = self::$dbh->prepare($query);
+    }
+
+    public static function bind(string $param, string $value = NULL, string $type = null)
+    {
+        if (is_null($type)) {
+            switch (true) {
+                case is_int($value):
+                    $type = PDO::PARAM_INT;
+                    break;
+                case is_bool($value):
+                    $type = PDO::PARAM_BOOL;
+                    break;
+                case is_null($value):
+                    $type = PDO::PARAM_NULL;
+                    break;
+                default:
+                    $type = PDO::PARAM_STR;
+            }
+        }
+        self::$stmt->bindValue($param, $value, $type);
+    }
+
+    public static function execute()
+    {
+        return self::$stmt->execute();
+    }
+
+    public static function resultset()
+    {
+        self::execute();
+        return self::$stmt->fetchAll(PDO::FETCH_ASSOC);
+    }
+
+    public static function single()
+    {
+        self::execute();
+        return self::$stmt->fetch(PDO::FETCH_ASSOC);
+    }
+
+    public static function rowCount()
+    {
+        return self::$stmt->rowCount();
+    }
+
+    public static function lastInsertId()
+    {
+        return self::$dbh->lastInsertId();
+    }
+
+    public static function beginTransaction()
+    {
+        return self::$dbh->beginTransaction();
+    }
+
+    public static function endTransaction()
+    {
+        return self::$dbh->commit();
+    }
+
+    public static function cancelTransaction()
+    {
+        return self::$dbh->rollBack();
+    }
+
+    public static function debugDumpParams()
+    {
+        return self::$stmt->debugDumpParams();
+    }
+
+    public static function queryError()
+    {
+        self::$qError = self::$dbh->errorInfo();
+        if (!is_null(self::$qError[2])) {
+            echo self::$qError[2];
+        }
+    }
+
+    public static function createBackupMysql(){
+        $backup_file = DIR_DATAS_BACKUP . date("YmdHis") . ".Mysql" . '.gz';
+        $command = "mysqldump --opt -h " . DB_HOST . " -u " . DB_USER . " -p" . DB_PASS ." ". DB_NAME ." | gzip > " . $backup_file;
+        try {
+            system($command);
+            return TRUE;
+        } catch (Exception $ex) {
+            return FALSE;
+        }
+    }
+
+    public static function restoreBackupMysql(string $_backupZip){
+
+        echo "<div>".$_backupZip."</div>";
+        
+        $backupFile = file::decompress($_backupZip);
+        echo "<div>".$backupFile."</div>";
+
+        $command = "mysql -h " . DB_HOST . " -u " . DB_USER . " -p" . DB_PASS ." ". DB_NAME ." < " . $backupFile;
+        try {
+            system($command);
+        } catch (Exception $ex) {
+            return FALSE;
+        }
+
+        file::compress($backupFile);
+
+        json::create("salaries");
+        json::create("excel");
+        json::create("excel-proweb");
+        json::create("events");
+        json::create("users");
+        json::create("salaries-proweb");
+    }
+}

+ 397 - 0
core/class/event.class.php

@@ -0,0 +1,397 @@
+<?php
+
+class event
+{
+
+    public static function getFiche(int $_id)
+    {
+        db::query("SELECT * FROM " . DB_T_EVENTS . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::single();
+    }
+
+    public static function getFicheByMd5(string $_md5)
+    {
+        db::query("SELECT * FROM " . DB_T_EVENTS . " WHERE md5 = :md5");
+        db::bind(':md5', $_md5);
+        return db::single();
+    }
+
+    public static function getQRCode(int $_id, $_width = 50, string $_link = NULL)
+    {
+        db::query("SELECT md5 FROM " . DB_T_EVENTS . " WHERE id = :id");
+        db::bind(':id', $_id);
+        $md5 = db::single()["md5"];
+        $link = base64_encode("https://" . DOMAIN_EVENTS . "/?e=" . $md5);
+
+        if ($_link == NULL) {
+            echo '<img src="/qrcode.php?q= ' . $link . '" width="' . $_width . '" >';
+        } else {
+            echo '<a href="https://' . DOMAIN_EVENTS . '/qrcode.php?q=' . $link . '" target="_blank"><img src="/qrcode.php?q= ' . $link . '" width="' . $_width . '" ></a>';
+        }
+    }
+
+    public static function getEvents()
+    {
+        db::query("SELECT "
+            . "" . DB_T_EVENTS . ".id, "
+            . "" . DB_T_EVENTS . ".md5, "
+            . "" . DB_T_EVENTS . ".titre, "
+            . "" . DB_T_EVENTS . ".description, "
+            . "" . DB_T_EVENTS . ".startDate, "
+            . "COUNT(" . DB_T_EVENTS_INSCRITS . ".id_salarie) AS m_global, "
+            . "COUNT(" . DB_T_EVENTS_INSCRITS . ".present) AS m_inscrit, "
+            . "" . DB_T_EVENTS . ".endDate, "
+            . "IF(" . DB_T_EVENTS . ".type_emargement = 1, 'Contôle', IF(" . DB_T_EVENTS . ".type_emargement = 2, 'Autonome', 'Contrôle & Autonome')) AS type_emargement, "
+            . "IF(" . DB_T_EVENTS . ".type_inscription = 1, 'Incription', 'Libre') AS type_inscription, "
+            . "" . DB_T_EVENTS . ".actif, "
+            . "" . DB_T_EVENTS . ".cree, "
+            . "" . DB_T_EVENTS . ".maj, "
+            . "CONCAT (" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS 'user' "
+            . "FROM " . DB_T_EVENTS . " "
+            . "LEFT JOIN " . DB_T_EVENTS_INSCRITS . " ON " . DB_T_EVENTS_INSCRITS . ".id_evenement = " . DB_T_EVENTS . ".id "
+            . "INNER JOIN " . DB_T_USER . " ON " . DB_T_EVENTS . ".id_user = " . DB_T_USER . ".id "
+            . "GROUP BY 1");
+        return db::resultset();
+    }
+
+    public static function connectSalarie(array $_post)
+    {
+
+        if (empty($_post["ident"])) {
+            return FALSE;
+        } elseif (empty($_post["date"])) {
+            return FALSE;
+        }
+        if (is_int($_post["ident"])) {
+            $login = intval($_post["ident"]);
+        } else {
+            $login = $_post["ident"];
+        }
+
+        $date = new DateTime($_post["date"]);
+        $date = $date->format('Y-m-d H:i:s');
+
+        db::query("SELECT "
+            . "id, "
+            . "sel, "
+            . "nom, "
+            . "prenom, "
+            . "actif, "
+            . "contrat, "
+            . "jourEntree "
+            . "FROM " . DB_T_SALARIES . " "
+            . "WHERE loginId = :login OR idLocal = :login");
+        db::bind(':login', $login);
+        $salarie = db::single();
+
+        if (isset($salarie["id"])) {
+            if ($salarie["actif"] == 0) {
+                return FALSE;
+            } elseif ($salarie["jourEntree"] != $date) {
+                return FALSE;
+            } else {
+                $_SESSION["salarie"] = array(
+                    "id" => $salarie["id"],
+                    "sel" => $salarie["sel"],
+                    "nom" => $salarie["nom"],
+                    "prenom" => $salarie["prenom"]
+                );
+                return TRUE;
+            }
+        } else {
+            return FALSE;
+        }
+        return FALSE;
+    }
+
+    public static function lastEvenement()
+    {
+        db::query("SELECT MAX(id) AS id FROM " . DB_T_EVENTS);
+        return db::single()["id"];
+    }
+
+    public static function getIdEvenementByMd5(string $_md5)
+    {
+        db::query("SELECT id FROM " . DB_T_EVENTS . " WHERE md5 = :md5");
+        db::bind(':md5', $_md5);
+        return db::single()["id"];
+    }
+
+    public static function presentEvenement(int $_idSalarie)
+    {
+        db::query("SELECT "
+            . "" . DB_T_EVENTS . ".id, "
+            . "" . DB_T_EVENTS . ".md5, "
+            . "" . DB_T_EVENTS . ".titre, "
+            . "" . DB_T_EVENTS . ".startDate, "
+            . "" . DB_T_EVENTS . ".endDate, "
+            . "" . DB_T_EVENTS . ".type_emargement, "
+            . "" . DB_T_EVENTS_INSCRITS . ".sel, "
+            . "" . DB_T_EVENTS_INSCRITS . ".present "
+            . "FROM " . DB_T_EVENTS . " "
+            . "LEFT JOIN " . DB_T_EVENTS_INSCRITS . " ON " . DB_T_EVENTS_INSCRITS . ".id_evenement = " . DB_T_EVENTS . ".id AND " . DB_T_EVENTS_INSCRITS . ".id_salarie = :id_salarie "
+            . "WHERE " . DB_T_EVENTS . ".startDate <= CURRENT_TIMESTAMP() "
+            . "AND " . DB_T_EVENTS . ".endDate >= CURRENT_TIMESTAMP() "
+            . "AND ((" . DB_T_EVENTS . ".type_inscription = 1 AND " . DB_T_EVENTS_INSCRITS . ".id_salarie = :id_salarie) OR (" . DB_T_EVENTS . ".type_inscription = 0))"
+            . "AND " . DB_T_EVENTS . ".actif = 1");
+        db::bind(':id_salarie', $_idSalarie);
+        $row = db::resultset();
+        return $row;
+    }
+
+    public static function deleteEvenement(int $_id)
+    {
+        db::query("DELETE FROM " . DB_T_EVENTS . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::execute();
+    }
+
+    public static function deleteInscriptionEvenement(int $_idEvenement)
+    {
+        db::query("DELETE FROM " . DB_T_EVENTS_INSCRITS . " WHERE id_evenement = :id_evenement");
+        db::bind(':id_evenement', $_idEvenement);
+        return db::execute();
+    }
+
+    public static function checkUrl(string $_url)
+    {
+        return parse_url($_url)["host"];
+    }
+
+    public static function getEvenementbyQRCode(string $_QRCode)
+    {
+        $query = parse_url($_QRCode)["query"];
+        parse_str($query, $params);
+        return $params;
+    }
+
+    public static function checkEmargement(int $_id_evenement)
+    {
+        db::query("SELECT "
+            . "COUNT(present) AS nb "
+            . "FROM " . DB_T_EVENTS_INSCRITS . " "
+            . "WHERE " . DB_T_EVENTS_INSCRITS . ".id_evenement = :id_evenement");
+        db::bind(':id_evenement', $_id_evenement);
+        $nb = db::single()["nb"];
+        return $nb;
+    }
+
+    public static function getInscriptionEvenementById(int $_id_evenement, int $_id_salarie)
+    {
+        db::query("SELECT "
+            . "" . DB_T_EVENTS_INSCRITS . ".id_salarie, "
+            . "" . DB_T_EVENTS_INSCRITS . ".present, "
+            . "" . DB_T_EVENTS . ".titre "
+            . "FROM " . DB_T_EVENTS_INSCRITS . " "
+            . "INNER JOIN " . DB_T_EVENTS . " ON " . DB_T_EVENTS_INSCRITS . ".id_evenement = " . DB_T_EVENTS . ".id "
+            . "WHERE " . DB_T_EVENTS_INSCRITS . ".id_salarie = :id_salarie AND " . DB_T_EVENTS_INSCRITS . ".id_evenement = :id_evenement");
+        db::bind(':id_salarie', $_id_salarie);
+        db::bind(':id_evenement', $_id_evenement);
+        $inscription = db::single();
+        return $inscription;
+    }
+
+    public static function checkEvenementBySalarie(string $_md5)
+    {
+
+        $return = array();
+        $now = time();
+
+        db::query("SELECT "
+            . "" . DB_T_SALARIES . ".id, "
+            . "" . DB_T_SALARIES . ".actif, "
+            . "" . DB_T_SALARIES . ".contrat "
+            . "FROM " . DB_T_SALARIES . " "
+            . "WHERE " . DB_T_SALARIES . ".id = :id");
+        db::bind(':id', session::getId("salarie"));
+        $salarie = db::single();
+
+        db::query("SELECT "
+            . "" . DB_T_EVENTS_INSCRITS . ".id_salarie, "
+            . "" . DB_T_EVENTS_INSCRITS . ".present "
+            . "FROM " . DB_T_EVENTS . " "
+            . "LEFT JOIN " . DB_T_EVENTS_INSCRITS . " ON " . DB_T_EVENTS_INSCRITS . ".id_evenement = " . DB_T_EVENTS . ".id "
+            . "WHERE " . DB_T_EVENTS_INSCRITS . ".id_salarie = :id_salarie AND " . DB_T_EVENTS . ".md5 = :md5");
+        db::bind(':id_salarie', session::getId("salarie"));
+        db::bind(':md5', $_md5);
+        $inscription = db::single();
+
+        db::query("SELECT "
+            . "" . DB_T_EVENTS . ".id, "
+            . "" . DB_T_EVENTS . ".md5, "
+            . "" . DB_T_EVENTS . ".titre, "
+            . "" . DB_T_EVENTS . ".startDate, "
+            . "" . DB_T_EVENTS . ".endDate, "
+            . "" . DB_T_EVENTS . ".type_emargement, "
+            . "" . DB_T_EVENTS . ".type_inscription, "
+            . "" . DB_T_EVENTS . ".actif "
+            . "FROM " . DB_T_EVENTS . " "
+            . "WHERE " . DB_T_EVENTS . ".md5 = :md5");
+        db::bind(':md5', $_md5);
+        $evenement = db::single();
+
+        // print_r($inscription); echo "<br />";
+        // print_r($evenement); echo "<br />";
+
+        if ($salarie["id"] == NULL) {
+            $return["result"] = FALSE;
+            $return["description"] = "Vous n'êtes pas un salarié rattaché à notre CSE";
+        } elseif ($salarie["actif"] == 0) {
+            $return["result"] = FALSE;
+            $return["description"] = "Vous n'êtes plus un salarié rattaché à notre CSE";
+        } elseif ($evenement["actif"] == 0) {
+            $return["result"] = FALSE;
+            $return["description"] = "Cet évènement n'est pas activée";
+        } elseif ($evenement["type_inscription"] == 1 and $inscription["id_salarie"] == NULL) {
+            $return["result"] = FALSE;
+            $return["description"] = "Vous n'êtes pas inscrit à cet évènement";
+        } elseif ($now < strtotime($evenement["startDate"])) {
+            $return["result"] = FALSE;
+            $return["description"] = "Cet évènement n'a pas encore commencé";
+        } elseif ($now > (strtotime($evenement["endDate"]) + EMEMARGEMENT_END)) {
+            $return["result"] = FALSE;
+            $return["description"] = "Cet évènement est terminé";
+        } elseif (isset($inscription["present"])) {
+            $return["result"] = FALSE;
+            $return["description"] = "Votre émargement a déjà été pris en compte<br />le " . core::convertDate($inscription["present"]);
+        } else {
+            $return["result"] = TRUE;
+            $return["description"] = "Votre émargement a été pris en compte";
+        }
+        $return["evenement"] = $evenement["titre"];
+        return $return;
+    }
+
+    public static function emargementEvenement(int $_idEvenement, int $_idSalarie)
+    {
+
+        $inscription = self::getInscriptionEvenementById($_idEvenement, $_idSalarie);
+        $evenement = self::getFiche($_idEvenement);
+
+        if (!isset($inscription["present"]) or empty($inscription["present"])) {
+            if (isset($inscription["id_salarie"])) {
+                db::query("UPDATE " . DB_T_EVENTS_INSCRITS . " SET present = CURRENT_TIMESTAMP() WHERE id_evenement = :id_evenement AND id_salarie = :id_salarie");
+                db::bind(':id_evenement', $_idEvenement);
+                db::bind(':id_salarie', $_idSalarie);
+                db::execute();
+                $return["result"] = TRUE;
+                $return["evenement"] = $evenement["titre"];
+                $return["description"] = "L'émargement a été pris en compte";
+            } else {
+                db::query("INSERT INTO " . DB_T_EVENTS_INSCRITS . " (id_evenement, id_salarie, present) "
+                    . "VALUES (:id_evenement, :id_salarie, CURRENT_TIMESTAMP())");
+                db::bind(':id_evenement', $_idEvenement);
+                db::bind(':id_salarie', $_idSalarie);
+                db::execute();
+                $return["result"] = TRUE;
+                $return["evenement"] = $evenement["titre"];
+                $return["description"] = "L'émargement a été pris en compte";
+            }
+        } else {
+            $return["result"] = FALSE;
+            $return["description"] = "Emargement déjà pris en compte le " . core::convertDate($inscription["present"]);
+        }
+        return $return;
+    }
+
+    public static function emargementEvenementByQRCode()
+    {
+
+        $idSalarie = core::getGet("s");
+        $md5Evenement = core::getGet("e");
+        $key = core::getGet("k");
+
+        $salarie = salaries::get_salarieById($idSalarie);
+
+        $constructKey = md5($md5Evenement . $salarie["sel"]);
+
+        if ($constructKey == $key) {
+            $checkEmarge = self::emargementEvenement(self::getIdEvenementByMd5($md5Evenement), $salarie["id"]);
+            return $checkEmarge;
+        } else {
+            $return["result"] = FALSE;
+            $return["description"] = "Le QR-Code n'est pas valide";
+            return $return;
+        }
+    }
+
+    public static function printEventBouton(array $_array)
+    {
+        switch ($_array["nb"]) {
+            case 0:
+                $class_fadeIn = "first";
+                break;
+            case 1:
+                $class_fadeIn = "second";
+                break;
+            case 2:
+                $class_fadeIn = "third";
+                break;
+            case 3:
+                $class_fadeIn = "fourth";
+                break;
+            default:
+                $class_fadeIn = "fifth";
+                break;
+        }
+
+        if ($_array["type_emargement"] == 1) {
+            $explication = '<p class="card-text">
+                                <div>[ QRCode à présenter à votre arrivée ]</div>
+                                <br />
+                                <div><span data-feather="maximize"></span></div>
+                            </p>';
+            $meta = 'data-toggle="modal" data-target="#QRCodeModal" data-qrr-qrcode-regexp="^https?:\/\/" data-sel="' . $_array["url_qrcode"] . '" data-titre="' . $_array["titre"] . '"';
+            $class_card = 'showQRCode';
+            $txt["footer"] = "Cliquez ici pour afficher votre QRCode";
+        } else {
+            $explication = '<p class="card-text">
+                                <div>[ QRCode à flasher vous même ]</div>
+                                <br />
+                                <div><span data-feather="camera"></span></div>
+                            </p>';
+            $meta = 'data-event="' . $_array["md5"] . '" data-qrr-target="#QRCodeRead" ';
+            $class_card = 'qrcodeReader';
+            $txt["footer"] = "Cliquez ici pour scanner le QRCode";
+        }
+
+        if (isset($_array["present"])) {
+            $meta = "";
+            $explication = '<p class="card-text">Votre émargement a bien été pris en compte</p>';
+            $class["card-text"] = "text-success";
+            $class["card"] = "";
+            $txt["footer"] = "Emargement réalisé le " . core::convertDate($_array["present"]);
+        } else {
+            $class["card-text"] = "text-dark";
+            $class["card"] = $class_card;
+        }
+
+        echo '  <div ' . $meta . ' class="card mb-3 text-center ' . $class["card"] . ' ' . $class["card-text"] . ' fadeIn ' . $class_fadeIn . '">
+                    <div class="card-header"><small>Du ' . core::convertDate($_array["startDate"]) . ' au ' . core::convertDate($_array["endDate"]) . '</small></div>
+                    <div class="card-body">
+                        <h5 class="card-title">' . $_array["titre"] . '</h5>
+                        ' . $explication . '
+                    </div>
+                    <div class="card-footer"><small>' . $txt["footer"] . '</small></div>
+                </div>';
+    }
+
+    public static function printIconeResultFlash(string $_result)
+    {
+        if ($_result == 1) {
+            echo '  <div class="swal2-icon swal2-success swal2-animate-success-icon" style="display: flex;">
+                        <div class="swal2-success-circular-line-left" style="background-color: rgb(255, 255, 255);"></div>
+                        <span class="swal2-success-line-tip"></span>
+                        <span class="swal2-success-line-long"></span>
+                        <div class="swal2-success-ring"></div> 
+                        <div class="swal2-success-fix" style="background-color: rgb(255, 255, 255);"></div>
+                        <div class="swal2-success-circular-line-right" style="background-color: rgb(255, 255, 255);"></div>
+                    </div>';
+        } else {
+            echo '  <div class="swal2-icon swal2-error swal2-animate-error-icon" style="display: flex;">
+                        <span class="swal2-x-mark"><span class="swal2-x-mark-line-left"></span><span class="swal2-x-mark-line-right"></span></span>
+                    </div>';
+        }
+    }
+}

+ 123 - 0
core/class/file.class.php

@@ -0,0 +1,123 @@
+<?php
+
+class file
+{
+    public static function record(array $_temp)
+    {
+        $md5 = md5_file($_temp["tmp_name"]);
+        if(copy($_temp["tmp_name"], DIR_DATAS_FILES . $md5)){
+            db::query("INSERT INTO ". DB_T_FILES ." (id, name, size, id_user) VALUES (:id, :name, :size, :id_user)");
+            db::bind(':id', $md5);
+            db::bind(':name', $_temp['name']);
+            db::bind(':size', $_temp['size']);
+            db::bind(':id_user', session::getId());
+
+            try {
+                db::execute();
+                return $md5;
+            } catch (Exception $ex) {
+                unlink(DIR_DATAS_FILES . $md5);
+                alert::recError("Erreur #record sur l'import du fichier " . $_temp['name']);
+                return FALSE;
+            }
+        }
+    }
+
+    public static function delete(string $_id)
+    {
+        if (file_exists(DIR_DATAS_FILES . $_id)) {
+            if(unlink(DIR_DATAS_FILES.$_id)){
+                db::query("DELETE FROM ". DB_T_FILES ." WHERE id = :id");
+                db::bind(':id', $_id);
+
+                try {
+                    db::execute();
+                    return TRUE;
+                } catch (Exception $ex) {
+                    alert::recError("Erreur sur la suppression du fichier");
+                    return FALSE;
+                }
+            } else {
+                alert::recError("Erreur sur la suppression du fichier");
+                return FALSE;
+            }
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function download(string $_id)
+    {
+        if (file_exists(DIR_DATAS_FILES . $_id)) {
+            return DIR_DATAS_FILES . $_id;
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function cleanFilesByOrder(string $_path, int $_nbFiles = 5)
+    {
+        $return = TRUE;
+        $cpt = 0;
+        $files = array();
+        $dir = new DirectoryIterator($_path);
+        $blackList = array(
+            ".",
+            "..",
+            "index.html",
+            "index.php"
+        );
+    
+        foreach ($dir as $fileinfo) {
+            $files[$fileinfo->getMTime()] = $fileinfo->getFilename();
+        }
+    
+        krsort($files);
+    
+        foreach($files as $file) {
+            if (!in_array($file, $blackList)) {
+                if($cpt++ >= $_nbFiles){
+                    $return = (unlink($_path . $file)) ? TRUE : FALSE;
+                }
+            }
+        }
+
+        return $return;
+    }
+
+    public static function cleanFilesByTime(string $_path, int $_limitTime = 24*3600) // 24*3600 pour une journée
+    {
+        if ($handle = opendir($_path)) {
+            while (false !== ($file = readdir($handle))) { 
+                $filelastmodified = filemtime($_path . $file);
+                if((time() - $filelastmodified) > $_limitTime)
+                {
+                    unlink($_path . $file);
+                }
+
+            }
+            closedir($handle); 
+        }
+    }
+
+    public static function compress(string $_file){
+        $command = "gzip " . $_file;
+        try {
+            system($command);
+            return $_file.".gz";
+        } catch (Exception $ex) {
+            return FALSE;
+        }
+    }
+
+    public static function decompress(string $_zip, bool $_delete = FALSE){
+        $command = "gunzip " . $_zip;
+        try {
+            system($command);
+            ($_delete == TRUE) ? unlink($_zip) : "";
+            return explode(".gz", $_zip)[0];
+        } catch (Exception $ex) {
+            return FALSE;
+        }
+    }
+}

+ 118 - 0
core/class/get.class.php

@@ -0,0 +1,118 @@
+<?php
+
+class get
+{
+    public static function environnement()
+    {
+        if ($_SERVER['HTTP_HOST'] == DOMAIN_CMS) {
+            return "cms.";
+        } elseif ($_SERVER['HTTP_HOST'] == DOMAIN_EVENTS or $_SERVER['HTTP_HOST'] == DOMAIN_CONTROL) {
+            return "events.";
+        }
+    }
+
+    public static function page(string $_page = NULL)
+    {
+        if (isset($_page)) {
+            $page = $_page;
+        } elseif (core::ifGet("p")) {
+            $page = core::getGet("p");
+        } else {
+            if (session::accessUserByType(1)) { // Admin
+                $page = DEFAUT_PAGE;
+            } elseif (session::accessUserByType(3)) { // Assistance sociale
+                $page = DEFAUT_PAGE_SOCIAL;
+            }
+        }
+
+        if (session::accessElement($page, "page")) {
+            (file_exists(DIR_PHP_VIEWS_PAGE . self::environnement() . $page . '.php')) ?
+                require_once DIR_PHP_VIEWS_PAGE . self::environnement() . $page . '.php' : alert::recError("Page introuvable : " . $page);
+        } else {
+            alert::recError("La page que vous tentez de charger ne vous est pas disponible.");
+        }
+    }
+
+    public static function submit()
+    {
+
+        if (core::ifPost("from")) {
+            $submit = core::getPost("from");
+        } elseif (core::ifGet("from")) {
+            $submit = core::getGet("from");
+        } else {
+            alert::recError("Submit introuvable #1");
+            header("Location: /");
+            exit();
+        }
+
+        if (session::accessElement($submit, "submit")) {
+            if (file_exists(DIR_PHP_SUBMIT . self::environnement() . $submit . '.php')) {
+                require_once DIR_PHP_SUBMIT . self::environnement() . $submit . '.php';
+            } else {
+                alert::recError("Submit introuvable #2");
+                header("Location: /");
+                exit();
+            }
+        }
+    }
+
+    public static function json()
+    {
+        if (core::ifGet("file")) {
+            if (session::accessElement(core::getGet("file"), "json")) {
+                if (file_exists(DIR_DATAS_JSON . core::getGet("file") . '.json')) {
+                    require_once DIR_DATAS_JSON . core::getGet("file") . '.json';
+                    exit();
+                } else {
+                    exit();
+                }
+            } else {
+                header('HTTP/1.0 401 Unauthorized');
+                exit();
+            }
+        }
+    }
+
+    public static function jsonData()
+    {
+        if (core::ifGet("jsonData")) {
+            if (session::accessElement(core::getGet("jsonData"), "json") == TRUE) {
+                if (file_exists(DIR_DATAS_JSONDATA . self::environnement() . core::getGet("jsonData") . '.php')) {
+                    require_once DIR_DATAS_JSONDATA . self::environnement() . core::getGet("jsonData") . '.php';
+                    exit();
+                } else {
+                    exit();
+                }
+            } else {
+                header('HTTP/1.0 401 Unauthorized');
+                exit();
+            }
+        }
+    }
+
+    public static function jsonDateDataExcel()
+    {
+
+        db::query("SELECT dateData FROM " . DB_T_EXCEL . " ORDER BY id DESC LIMIT 0, 1");
+        $data = db::single();
+        return (isset($data["dateData"])) ? $data["dateData"] : NULL;
+    }
+
+    public static function jsonDateDataExcelProweb()
+    {
+
+        db::query("SELECT dateData FROM " . DB_T_EXCEL_PROWEB . " ORDER BY id DESC LIMIT 0, 1");
+        $data = db::single();
+        return (isset($data["dateData"])) ? $data["dateData"] : NULL;
+    }
+
+    public static function currentPage($_page = NULL)
+    {
+        if (core::getGet("p") == $_page) {
+            return " active";
+        } elseif (!core::ifGet("p") and (($_SESSION["user"]["idType"] == 1 and $_page == DEFAUT_PAGE) or ($_SESSION["user"]["idType"] == 3 and $_page == DEFAUT_PAGE_SOCIAL))) {
+            return " active";
+        }
+    }
+}

+ 138 - 0
core/class/json.class.php

@@ -0,0 +1,138 @@
+<?php
+
+class json extends db
+{
+
+    public function __construct()
+    {
+    }
+
+    public static function create(string $_target)
+    {
+        if (isset($_target)) {
+            switch ($_target) {
+                case "salaries":
+                    return self::create_salaries();
+                    break;
+                case "excel":
+                    return self::create_excel();
+                    break;
+                case "excel-proweb":
+                    return self::create_excelProweb();
+                    break;
+                case "events":
+                    return self::create_events();
+                    break;
+                case "users":
+                    return self::create_users();
+                    break;
+                case "salaries-proweb":
+                    return self::create_salariesProweb();
+                    break;
+            }
+        } else {
+            return 0;
+        }
+    }
+
+    private static function create_salaries()
+    {
+        $row = salaries::get_salaries();
+        if (file_put_contents(DIR_DATAS_JSON . "salaries.json", json_encode($row))) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
+    private static function create_salariesProweb()
+    {
+        $row = proweb::getBase();
+        if (file_put_contents(DIR_DATAS_JSON . "salaries-proweb.json", json_encode($row))) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
+    private static function create_excel()
+    {
+        db::query("SELECT 
+        " . DB_T_EXCEL . ".id, 
+        " . DB_T_FILES . ".name, 
+        " . DB_T_EXCEL . ".nbSalaries, 
+        CONCAT(ROUND((" . DB_T_FILES . ".size / 1024 / 1024), 2), ' Mo') AS size, 
+        " . DB_T_EXCEL . ".md5, 
+        " . DB_T_EXCEL . ".cree, 
+        CONCAT (" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS 'user', 
+        dateData, 
+        goMysql, 
+        md5forSFTP, 
+        log 
+        FROM " . DB_T_EXCEL . " 
+        INNER JOIN " . DB_T_USER . " ON " . DB_T_EXCEL . ".id_user = " . DB_T_USER . ".id 
+        INNER JOIN " . DB_T_FILES . " ON " . DB_T_EXCEL . ".md5 = " . DB_T_FILES . ".id");
+        $row = db::resultset();
+
+        if (file_put_contents(DIR_DATAS_JSON . "excel.json", json_encode($row))) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
+    private static function create_excelProweb()
+    {
+        db::query("SELECT 
+        " . DB_T_EXCEL_PROWEB . ".id, 
+        " . DB_T_FILES . ".name, 
+        " . DB_T_EXCEL_PROWEB . ".nbSalaries, 
+        CONCAT(ROUND((" . DB_T_FILES . ".size / 1024 / 1024), 2), ' Mo') AS size, 
+        " . DB_T_EXCEL_PROWEB . ".md5, 
+        " . DB_T_EXCEL_PROWEB . ".cree, 
+        CONCAT (" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS 'user', 
+        dateData 
+        FROM " . DB_T_EXCEL_PROWEB . " 
+        INNER JOIN " . DB_T_USER . " ON " . DB_T_EXCEL_PROWEB . ".id_user = " . DB_T_USER . ".id 
+        INNER JOIN " . DB_T_FILES . " ON " . DB_T_EXCEL_PROWEB . ".md5 = " . DB_T_FILES . ".id");
+        $row = db::resultset();
+
+        if (file_put_contents(DIR_DATAS_JSON . "excel-proweb.json", json_encode($row))) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
+    private static function create_events()
+    {
+        $row = event::getEvents();
+        if (file_put_contents(DIR_DATAS_JSON . "events.json", json_encode($row))) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
+    private static function create_users()
+    {
+        $row = user::getUsers();
+        if (file_put_contents(DIR_DATAS_JSON . "users.json", json_encode($row))) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
+    public static function delete(string $_target)
+    {
+        if (is_file(DIR_DATAS_JSON . "/" . $_target . ".json")) {
+            unlink(DIR_DATAS_JSON . "/" . $_target . ".json");
+        }
+    }
+
+    public static function testSFTP()
+    {
+        return (sftp::testAccessHost()) ? "OK" : "KO";
+    }
+}

+ 10 - 0
core/class/myQrcode.class.php

@@ -0,0 +1,10 @@
+<?php
+
+class myQrcode {
+    
+    public static function show(string $_lien){
+        include_once(DIR_PHP_LIBS . "phpqrcode/qrlib.php");
+        QRcode::png($_lien, NULL ,QR_ECLEVEL_L, 10);
+    }
+    
+}

+ 264 - 0
core/class/proweb.class.php

@@ -0,0 +1,264 @@
+<?php
+
+class proweb
+{
+    public static function getBase()
+    {
+        db::query("SELECT * FROM " . DB_T_SALARIES_PROWEB);
+        return db::resultset();
+    }
+
+    public static function getExcelById(int $_id)
+    {
+        db::query("SELECT * FROM " . DB_T_EXCEL_PROWEB . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::single();
+    }
+
+    public static function deleteExcel(int $_id)
+    {
+
+        $tmp = self::getExcelById($_id);
+        file::delete($tmp["md5"]);
+
+        db::query("DELETE FROM " . DB_T_EXCEL_PROWEB . " WHERE id = :id");
+        db::bind(':id', $_id);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $ex) {
+            return FALSE;
+        }
+    }
+
+    public static function getExcel()
+    {
+        db::query("SELECT * FROM " . DB_T_EXCEL . " ORDER BY id DESC LIMIT 0, 1");
+        return db::single();
+    }
+
+    public static function convertDateMoisAn(string $datetime)
+    {
+        $pieces = explode(" ", $datetime);
+        $pieces2 = explode("-", $pieces[0]);
+        return $pieces2[0] . $pieces2[1];
+    }
+
+    public static function convertDateMoisAnJour(string $datetime)
+    {
+        $pieces = explode(" ", $datetime);
+        return $pieces[0];
+    }
+
+    public static function archiveExcelValues(array $_array)
+    {
+        $_return["error"] = 0;
+        $_return["errorJson"] = array();
+
+        // ----
+
+        $_return["idProweb"] = $_array[0];
+        $_return["nom"] = self::archiveExcelValuesNom($_array[1]);
+        $_return["prenom"] = self::archiveExcelValuesPrenom($_array[2]);
+        $_return["sexe"] = self::archiveExcelValuesSexe($_array[3]);
+        $_return["jourEntree"] = self::archiveExcelValuesDate($_array[4]);
+        $_return["jourSortie"] = self::archiveExcelValuesDate($_array[5]);
+        $_return["actif"] = self::archiveExcelValuesActif($_array[6]);
+        $_return["lieu"] = self::archiveExcelValuesLieu($_array[7]);
+        $_return["loginId"] = self::archiveExcelValuesloginId($_array[8]);
+
+        $verifRH = self::checksalarieByLoginId($_return["loginId"], $_return["nom"], $_return["prenom"]);
+
+        if ($_return["jourEntree"] != "N/A") { // On ignore les nouveaux salariés qui se sont inscrits post import du fichier RH
+            $dateDataRH = intval(self::convertDateMoisAn(self::getExcel()["dateData"]));
+            $dateDataProWeb = intval(self::convertDateMoisAn($_return["jourEntree"]));
+        } else {
+            $dateDataRH = $dateDataProWeb = 0;
+        }
+
+        if (empty($verifRH["id"]) and $_return["jourSortie"] == "N/A" and $dateDataRH > $dateDataProWeb) {
+            $_return["contrat"] = $_return["actif"] = $_return["RHBase"] = $_return["loginIdRH"] = $_return["jourEntreeRH"] = "N/A";
+            array_push($_return["errorJson"], "absent");
+        } else {
+            $_return["loginIdRH"] = (empty($verifRH["loginId"]) or $verifRH["loginId"] == $_return["loginId"]) ? NULL : $verifRH["loginId"];
+            $_return["jourEntreeRH"] = (empty($verifRH["jourEntree"]) or self::convertDateMoisAnJour($verifRH["jourEntree"]) == $_return["jourEntree"]) ? NULL : self::convertDateMoisAnJour($verifRH["jourEntree"]);
+            $_return["jourSortie"] = (isset($verifRH["jourSortie"])) ? $verifRH["jourSortie"] : $_return["jourSortie"];
+            $_return["RHBase"] = (isset($verifRH["jourSortie"]) or empty($verifRH["id"])) ? 0 : 1;
+            $_return["actif"] = (isset($verifRH["jourSortie"]) or empty($verifRH["id"])) ? 0 : 1;
+            $_return["contrat"] = (isset($verifRH["contrat"])) ? $verifRH["contrat"] : 0;
+
+            // ----
+
+            if (!self::checkValuesNom($_return["nom"])) {
+                $_return["error"] = 1;
+                array_push($_return["errorJson"], "nom");
+            }
+
+            if (!self::checkValuesPrenom($_return["prenom"])) {
+                $_return["error"] = 1;
+                array_push($_return["errorJson"], "prenom");
+            }
+
+            if (!self::checkValuesloginId($_return["loginId"], $_return["loginIdRH"])) {
+                $_return["error"] = 1;
+                array_push($_return["errorJson"], "loginId");
+            }
+
+            if (!self::checkValuesJourEntree($_return["jourEntree"])) {
+                $_return["error"] = 1;
+                array_push($_return["errorJson"], "jourEntree");
+            }
+
+            if ($_return["jourEntreeRH"] != NULL and $_return["jourEntree"] != "N/A") {
+                $_return["error"] = 1;
+                array_push($_return["errorJson"], "jourEntree");
+            }
+
+            if ($_return["jourEntree"] != "N/A") { // On ignore les nouveaux salariés qui se sont inscrits post import du fichier RH
+
+                if ($dateDataRH > $dateDataProWeb) {
+                    if (!self::checkValuesRHBase($_return["RHBase"], $_return["actif"], $_return["jourSortie"])) {
+                        $_return["error"] = 1;
+                        array_push($_return["errorJson"], "RHBase");
+                    }
+                }
+            }
+
+            //            if ($_return["contrat"] == 0 AND $_return["jourSortie"] == "N/A") {
+            //                $_return["error"] = 1;
+            //                array_push($_return["errorJson"], "contrat");
+            //            }
+        }
+
+        $_return["errorJson"] = (!empty($_return["errorJson"][0])) ? json_encode($_return["errorJson"]) : NULL;
+
+        return $_return;
+    }
+
+    // Les initialisations
+
+    private static function archiveExcelValuesDate(string $_string)
+    {
+        return (!isset($_string) or $_string == "00-00-0000") ? "N/A" : $_string;
+    }
+
+    private static function archiveExcelValuesSexe(string $_string)
+    {
+        return (empty($_string)) ? "N/A" : $_string;
+    }
+
+    private static function archiveExcelValuesloginId(string $_string)
+    {
+        return salaries::clean_accent($_string);
+    }
+
+    private static function archiveExcelValuesNom(string $_string)
+    {
+        return salaries::clean_accent($_string);
+    }
+
+    private static function archiveExcelValuesPrenom(string $_string)
+    {
+        return salaries::clean_accent($_string);
+    }
+
+    private static function archiveExcelValuesActif(string $_string)
+    {
+        if ($_string == "Actif") {
+            return  1;
+        } elseif ($_string == "Inactif") {
+            return 0;
+        } else {
+            return "N/A";
+        }
+    }
+
+    private static function archiveExcelValuesLieu(string $_string)
+    {
+        return (empty($_string)) ? "N/A" : $_string;
+    }
+
+    // Les checks 
+
+    public static function checkSalarieByLoginId(string $_loginId, string $_nom = NULL, string $_prenom = NULL)
+    {
+        // Récupération des données de l'excel au format Json
+        if ($_nom == NULL) {
+            db::query("SELECT id, loginId, jourEntree, jourSortie, contrat FROM " . DB_T_SALARIES . " WHERE loginId = :loginId");
+        } else {
+            db::query("SELECT id, loginId, jourEntree, jourSortie, contrat FROM " . DB_T_SALARIES . " WHERE loginId = :loginId OR (nom = :nom AND prenom = :prenom)");
+            db::bind(':nom', $_nom);
+            db::bind(':prenom', $_prenom);
+        }
+        db::bind(':loginId', $_loginId);
+        return db::single();
+    }
+
+    private static function checkValuesActif(string $_string)
+    {
+        return ($_string == "N/A") ? FALSE : TRUE;
+    }
+
+    private static function checkValuesloginId(string $_idLogin, string $_idLoginRH = NULL)
+    {
+        if ($_idLoginRH != NULL) {
+            if (empty(self::checkSalarieByLoginId($_idLogin)["id"])) {
+                return FALSE;
+            } elseif (core::checkStringOnly($_idLogin)) {
+                return FALSE;
+            } elseif (strlen($_idLogin) > 10) {
+                return FALSE;
+            } elseif (empty($_idLogin)) {
+                return FALSE;
+            } else {
+                return TRUE;
+            }
+        } else {
+            return TRUE;
+        }
+    }
+
+    private static function checkValuesRHBase(string $_string, int $_actif, string $_sortie)
+    {
+        return ($_string == 0 and $_actif == 1 and $_sortie == "N/A") ? FALSE : TRUE;
+    }
+
+    private static function checkValuesJourEntree(string $_string)
+    {
+        return ($_string == "N/A") ? FALSE : TRUE;
+    }
+
+    private static function checkValuesJourSortie(string $_string, int $_actif)
+    {
+        return ($_string != "N/A" and $_actif == 1) ? FALSE : TRUE;
+    }
+
+    private static function checkValuesNom(string $_string)
+    {
+        return (empty($_string)) ? FALSE : TRUE;
+    }
+
+    private static function checkValuesPrenom(string $_string)
+    {
+        return (empty($_string)) ? FALSE : TRUE;
+    }
+
+    private static function checkValuesSexe(string $_string)
+    {
+        return ($_string == NULL or ($_string != "M." and $_string != "Mme")) ? FALSE : TRUE;
+    }
+
+    private static function checkValuesLieu(string $_string)
+    {
+        return (empty($_string)) ? FALSE : TRUE;
+    }
+
+    public static function downloadExcel(int $_id, string $_file)
+    {
+        $data = base64_decode(self::getExcelById($_id)["file"]);
+        $fileTemp = fopen(DIR_DATAS_TEMP . $_file, "w");
+        file_put_contents(DIR_DATAS_TEMP . $_file, $data);
+        fclose($fileTemp);
+        return DIR_DATAS_TEMP . $_file;
+    }
+}

+ 54 - 0
core/class/pwa.class.php

@@ -0,0 +1,54 @@
+<?php
+
+class pwa
+{
+    private static $serviceWorker = "serviceWorker.js";
+
+    private static function getManifeste()
+    {
+        switch ($_SERVER['HTTP_HOST']) {
+            case URL_PROD_CONTROL:
+                return "manifest-control.json";
+                break;
+            case URL_PROD_EVENTS:
+                return "manifest-events.json";
+                break;
+            case URL_PROD_CMS:
+                return "manifest-cms.json";
+                break;
+            case URL_DEV_CONTROL:
+                return "manifest-control-dev.json";
+                break;
+            case URL_DEV_EVENTS:
+                return "manifest-events-dev.json";
+                break;
+            case URL_DEV_CMS:
+                return "manifest-cms-dev.json";
+                break;
+        }
+    }
+
+    public static function printServiceWorker()
+    {
+        echo '<script>';
+        if (PWA == 1) {
+            echo '  if("serviceWorker" in navigator){
+                        navigator.serviceWorker.register("/' . self::$serviceWorker . '");
+                    }';
+        } else {
+            echo '  navigator.serviceWorker.getRegistrations().then(function(registrations) {
+                        for(let registration of registrations) {
+                            registration.unregister();
+                        } 
+                    });';
+        }
+        echo '</script>';
+    }
+
+    public static function printManifeste()
+    {
+        if (PWA == 1) {
+            echo '<link rel="manifest" href="' . self::getManifeste() . '">';
+        }
+    }
+}

+ 743 - 0
core/class/salaries.class.php

@@ -0,0 +1,743 @@
+<?php
+
+class salaries
+{
+    public static function clean_tmp()
+    {
+        // Nettoyage de la table temporaire des salairés
+        db::query("TRUNCATE " . DB_T_TEMP_SALARIES);
+        db::execute();
+    }
+
+    public static function clean_accent(string $_data)
+    {
+        $search  = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ');
+        $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');
+        $return = str_replace($search, $replace, $_data);
+        return strtoupper($return);
+    }
+
+    public static function get_salarieByidLocal(int $_idLocal)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT * FROM " . DB_T_SALARIES . " WHERE idLocal = :idLocal");
+        db::bind(':idLocal', $_idLocal);
+        return db::single();
+    }
+
+    public static function get_salarieByLoginId(string $_loginId)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT * FROM " . DB_T_SALARIES . " WHERE loginId = :loginId");
+        db::bind(':loginId', $_loginId);
+        return db::single();
+    }
+
+    public static function get_salarieById(int $_id)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT * FROM " . DB_T_SALARIES . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::single();
+    }
+
+    public static function get_salaries()
+    {
+        db::query("SELECT "
+            . "idLocal, "
+            . "loginId, "
+            . "nom, "
+            . "prenom, "
+            . "sexe, "
+            . "contrat, "
+            . "DATE_FORMAT(jourEntree, '%Y-%m-%d') AS jourEntree, "
+            . "DATE_FORMAT(repriseContrat, '%Y-%m-%d') AS repriseContrat, "
+            . "DATE_FORMAT(jourSortie, '%Y-%m-%d') AS jourSortie, "
+            . "sel, "
+            . "lieu, "
+            . "cree, "
+            . "maj, "
+            . "actif "
+            . "FROM " . DB_T_SALARIES);
+        return db::resultset();
+    }
+
+    public static function lastExcel()
+    {
+        db::query("SELECT MAX(id) AS id FROM " . DB_T_EXCEL);
+        return db::single()["id"];
+    }
+
+    public static function lastExcel_forSFTP()
+    {
+        db::query("SELECT MAX(id) AS id FROM " . DB_T_EXCEL . " WHERE forSFTP IS NOT NULL");
+        return db::single()["id"];
+    }
+
+    public static function get_excel_Md5(int $_id)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT md5 FROM " . DB_T_EXCEL . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::single()["md5"];
+    }
+
+    public static function get_excel_Json_forSFTP(int $_id)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT forSFTP, md5forSFTP, createForSFTP, contratForSFTP FROM " . DB_T_EXCEL . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::single();
+    }
+
+    public static function get_excel_Json_transfer_forSFTP(string $_md5)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT transfertForSFTP FROM " . DB_T_EXCEL . " WHERE md5forSFTP = :md5forSFTP");
+        db::bind(':md5forSFTP', $_md5);
+        return db::single()["transfertForSFTP"];
+    }
+
+    public static function get_excel_json(int $_id)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT json FROM " . DB_T_EXCEL . " WHERE id = :id");
+        db::bind(':id', $_id);
+        return base64_decode(db::single()["json"]);
+    }
+
+    public static function get_excel_name(int $_id)
+    {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT 
+        " .DB_T_EXCEL. ".md5, 
+        " .DB_T_FILES. ".name 
+        FROM " . DB_T_EXCEL . " 
+        INNER JOIN " . DB_T_FILES . " ON " . DB_T_EXCEL . ".md5 = " . DB_T_FILES . ".id 
+        WHERE " . DB_T_EXCEL . ".id = :id");
+        db::bind(':id', $_id);
+        return db::single()["name"];
+    }
+
+    public static function excel_update_in_progress(int $_id, int $_action = 1)
+    {
+        db::query("UPDATE 
+        " . DB_T_EXCEL . " 
+        SET inProgress = :inProgress 
+        WHERE id = :id");
+        db::bind(':inProgress', $_action);
+        db::bind(':id', $_id);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function delete_excel(int $_id)
+    {
+        db::query("DELETE FROM " . DB_T_EXCEL . " WHERE id = :id");
+        db::bind(':id', $_id);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function excel_get_in_progress()
+    {
+        db::query("SELECT 
+        " .DB_T_EXCEL. ".id, 
+        " .DB_T_EXCEL. ".md5, 
+        " .DB_T_FILES. ".name 
+        FROM " . DB_T_EXCEL . " 
+        INNER JOIN " . DB_T_FILES . " ON " . DB_T_EXCEL . ".md5 = " . DB_T_FILES . ".id 
+        WHERE " . DB_T_EXCEL . ".inProgress = 1");
+        return db::single();
+    }
+
+    public static function get_excel_array(int $_id)
+    {
+        return json_decode(self::get_excel_json($_id));
+    }
+
+    public static function excel_to_mysql(array $_value)
+    {
+        if ($_value[4] == "Actif") {
+            $_value[4] = 1;
+        } else {
+            $_value[4] = 0;
+        }
+
+        return array(
+            "idLocal" => $_value[0],
+            "loginId" => $_value[7],
+            "nom" => self::clean_accent($_value[1]),
+            "prenom" => self::clean_accent($_value[2]),
+            "sexe" => $_value[3],
+            "contrat" => $_value[4],
+            "jourEntree" => $_value[5],
+            "lieu" => self::clean_accent($_value[6]),
+            "actif" => 1
+        );
+    }
+
+    public static function create_tmp(string $_excel)
+    {
+        db::query("SELECT idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif FROM " . DB_T_SALARIES);
+        $row = db::resultset();
+        if (!empty($row)) {
+            foreach ($row as $salaries) {
+                db::query("INSERT INTO " . DB_T_TEMP_SALARIES . " (idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif, new, excel) "
+                . "VALUES (:idLocal, :loginId, :nom, :prenom, :sexe, :contrat, :jourEntree, :lieu, :actif, :new, :excel)");
+                db::bind(':idLocal', $salaries["idLocal"]);
+                db::bind(':loginId', $salaries["loginId"]);
+                db::bind(':nom', $salaries["nom"]);
+                db::bind(':prenom', $salaries["prenom"]);
+                db::bind(':sexe', $salaries["sexe"]);
+                db::bind(':contrat', $salaries["contrat"]);
+                db::bind(':jourEntree', $salaries["jourEntree"]);
+                db::bind(':lieu', $salaries["lieu"]);
+                db::bind(':actif', 0);
+                db::bind(':new', 0);
+                db::bind(':excel', $_excel);
+                db::execute();
+            }
+        }
+    }
+
+    public static function update_inactive_temp_salarie()
+    {
+        db::query("UPDATE " . DB_T_TEMP_SALARIES . " SET "
+            . "log = :log "
+            . "WHERE actif = :actif");
+        db::bind(':log', "DISABLE");
+        db::bind(':actif', 0);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function update_json_excel(array $_json)
+    {
+        db::query("UPDATE " . DB_T_EXCEL . " SET "
+            . "goMysql = current_timestamp(), "
+            . "log = :log "
+            . "WHERE id = :id");
+        db::bind(':log', $_json["json"]);
+        db::bind(':id', $_json["excel"]);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function update_temp_salaries(array $_new_salaries, string $_excel)
+    {
+        $cp["INSERT"]["SUCCESS"] = 0;
+        $cp["INSERT"]["ERROR"] = 0;
+        $cp["UPDATE"]["SUCCESS"] = 0;
+        $cp["UPDATE"]["ERROR"] = 0;
+        $changeStatutContrat = NULL;
+
+        foreach ($_new_salaries as $key => $value) {
+            $sql = $change = NULL;
+            if ($key > 0) {
+                $tmp = self::excel_to_mysql($value);
+                $salarieByidLocal = self::get_salarieByidLocal($tmp["idLocal"]);
+
+                if (isset($salarieByidLocal["idLocal"])) {
+                    $tmp_sql = "";
+                    if ($tmp["loginId"] != $salarieByidLocal["loginId"]) {
+                        $tmp_sql .= "loginId = :loginId, ";
+                        $change = 1;
+                    }
+                    if ($tmp["contrat"] != $salarieByidLocal["contrat"]) {
+                        $tmp_sql .= "contrat = :contrat, ";
+                        $change = 1;
+
+                        // Indentifier les cas d'arrêt ou de reprise de contrat
+                        if ($tmp["contrat"] == 0 and $salarieByidLocal["contrat"] == 1) {
+                            $changeStatutContrat[$salarieByidLocal["idLocal"]] = "end";
+                        } else {
+                            $changeStatutContrat[$salarieByidLocal["idLocal"]] = "start";
+                        }
+                        // Indentifier les cas d'arrêt ou de reprise de contrat    
+                    }
+                    if ($tmp["lieu"] != $salarieByidLocal["lieu"]) {
+                        $tmp_sql .= "lieu = :lieu, ";
+                        $change = 1;
+                    }
+                    if ($tmp["actif"] != $salarieByidLocal["actif"]) {
+                        $change = 1;
+                    } else {
+                        $forSFTP["actif"] = NULL;
+                    }
+
+                    $tmp_sql .= "actif = :actif, ";
+
+                    if ($change == 1) {
+
+                        db::query($sql = "UPDATE " . DB_T_TEMP_SALARIES . " SET " . $tmp_sql . " log = :log WHERE idLocal = :idLocal");
+
+                        $log = NULL;
+
+                        if ($tmp["loginId"] != $salarieByidLocal["loginId"]) {
+                            db::bind(':loginId', $tmp["loginId"]);
+                            if ($log == "") {
+                                $log .= "UPDATE ";
+                            }
+                            $log .= "loginId ";
+                        }
+                        if ($tmp["contrat"] != $salarieByidLocal["contrat"]) {
+                            db::bind(':contrat', $tmp["contrat"]);
+                            if ($log == "") {
+                                $log .= "UPDATE ";
+                            }
+                            $log .= "contrat ";
+                        }
+                        if ($tmp["lieu"] != $salarieByidLocal["lieu"]) {
+                            db::bind(':lieu', $tmp["lieu"]);
+                            if ($log == "") {
+                                $log .= "UPDATE ";
+                            }
+                            $log .= "lieu ";
+                        }
+                        if ($tmp["actif"] != $salarieByidLocal["actif"]) {
+                            if ($log == "") {
+                                $log .= "UPDATE ";
+                            }
+                            $log .= "actif ";
+                        }
+
+                        db::bind(':actif', 1);
+
+                        if ($change == 1) {
+                            db::bind(':log', $log);
+                        } else {
+                            db::bind(':log', NULL);
+                        }
+
+                        db::bind(':idLocal', $tmp["idLocal"]);
+
+                        try {
+                            db::execute();
+                            $cp["UPDATE"]["SUCCESS"]++;
+                        } catch (Exception $ex) {
+                            $cp["UPDATE"]["ERROR"]++;
+                        }
+                    } else {
+                        db::query("UPDATE " . DB_T_TEMP_SALARIES . " SET actif = :actif WHERE idLocal = :idLocal");
+                        db::bind(':actif', 1);
+                        db::bind(':idLocal', $tmp["idLocal"]);
+                        db::execute();
+                    }
+                } else {
+
+                    db::query("INSERT INTO " . DB_T_TEMP_SALARIES . " (idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif, new, excel, log) "
+                        . "VALUES (:idLocal, :loginId, :nom, :prenom, :sexe, :contrat, :jourEntree, :lieu, :actif, :new, :excel, :log)");
+                    db::bind(':idLocal', $tmp["idLocal"]);
+                    db::bind(':loginId', $tmp["loginId"]);
+                    db::bind(':nom', $tmp["nom"]);
+                    db::bind(':prenom', $tmp["prenom"]);
+                    db::bind(':sexe', $tmp["sexe"]);
+                    db::bind(':contrat', $tmp["contrat"]);
+                    db::bind(':jourEntree', $tmp["jourEntree"]);
+                    db::bind(':lieu', $tmp["lieu"]);
+                    db::bind(':actif', 1);
+                    db::bind(':new', 1);
+                    db::bind(':excel', $_excel);
+                    db::bind(':log', "INSERT");
+                    try {
+                        db::execute();
+                        $cp["INSERT"]["SUCCESS"]++;
+                    } catch (Exception $ex) {
+                        $cp["INSERT"]["ERROR"]++;
+                    }
+                }
+            }
+        }
+
+        ($changeStatutContrat != NULL) ? self::recContratForSFTP($_excel, $changeStatutContrat) : "";
+
+        if ($cp["INSERT"]["ERROR"] != 0 or $cp["INSERT"]["ERROR"] != 0) {
+            alert::recError("Une erreur s'est produite lors de la mise en cache.");
+        } else {
+            alert::recSuccess("La mise en cache a été réalisée avec succès.");
+        }
+    }
+
+    private static function recContratForSFTP(int $_idExcel, array $_data)
+    {
+        db::query("UPDATE " . DB_T_EXCEL . " SET "
+            . "contratForSFTP = :contratForSFTP "
+            . "WHERE id = :id");
+        db::bind(':contratForSFTP', json_encode($_data));
+        db::bind(':id', $_idExcel);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function update_salaries(int $_excel)
+    {
+        $cp["INSERT"]["SUCCESS"] = 0;
+        $cp["INSERT"]["ERROR"] = 0;
+        $cp["DISABLE"]["SUCCESS"] = 0;
+        $cp["DISABLE"]["ERROR"] = 0;
+        $cp["UPDATE"]["SUCCESS"] = 0;
+        $cp["UPDATE"]["ERROR"] = 0;
+        $cp["forSFTP"] = 0;
+
+        $updateContrat = json_decode(self::get_excel_Json_forSFTP($_excel)["contratForSFTP"], TRUE);
+
+        $jourSortie = date("Y-m-d 00:00:00");
+        $dateReprise = date("Y-m-d 00:00:00");
+
+        db::query("SELECT idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif, new, log FROM " . DB_T_TEMP_SALARIES);
+        $row = db::resultset();
+
+        if (!empty($row)) {
+            foreach ($row as $key => $salaries) {
+                $forSFTP = $reprise = NULL;
+
+                if ($salaries["log"] == NULL) {
+
+                    $forSFTP["action"] = "valide";
+                    $forSFTP["idLocal"] = $salaries["idLocal"];
+                    $forSFTP["loginId"] = $salaries["loginId"];
+                    $forSFTP["contrat"] = $salaries["contrat"];
+                    $forSFTP["jourEntree"] = $salaries["jourEntree"];
+                    $forSFTP["jourSortie"] = NULL;
+                    $forSFTP["repriseContrat"] = NULL;
+                    $forSFTP["actif"] = 1;
+                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
+                } elseif ($salaries["log"] == "INSERT") {
+                    db::query("INSERT INTO " . DB_T_SALARIES . " (idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, jourSortie, sel, lieu, actif) "
+                        . "VALUES (:idLocal, :loginId, :nom, :prenom, :sexe, :contrat, :jourEntree, :jourSortie, :sel, :lieu, :actif)");
+
+                    db::bind(':idLocal', $salaries["idLocal"]);
+                    db::bind(':loginId', $salaries["loginId"]);
+                    db::bind(':nom', $salaries["nom"]);
+                    db::bind(':prenom', $salaries["prenom"]);
+                    db::bind(':sexe', $salaries["sexe"]);
+                    db::bind(':contrat', $salaries["contrat"]);
+                    db::bind(':jourEntree', $salaries["jourEntree"]);
+                    db::bind(':jourSortie', NULL);
+                    db::bind(':sel', md5($salaries["idLocal"] . time() . rand(100000000000, 999999999999)));
+                    db::bind(':lieu', $salaries["lieu"]);
+                    db::bind(':actif', $salaries["actif"]);
+
+                    try {
+                        db::execute();
+                        $cp["INSERT"]["SUCCESS"]++;
+                    } catch (Exception $ex) {
+                        $cp["INSERT"]["ERROR"]++;
+                    }
+
+                    $forSFTP["action"] = "insert";
+                    $forSFTP["idLocal"] = $salaries["idLocal"];
+                    $forSFTP["loginId"] = $salaries["loginId"];
+                    $forSFTP["contrat"] = $salaries["contrat"];
+                    $forSFTP["jourEntree"] = $salaries["jourEntree"];
+                    $forSFTP["jourSortie"] = NULL;
+                    $forSFTP["repriseContrat"] = NULL;
+                    $forSFTP["actif"] = 1;
+                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
+                } elseif ($salaries["log"] == "DISABLE") {
+                    db::query("UPDATE " . DB_T_SALARIES . " SET "
+                        . "jourSortie = :jourSortie, "
+                        . "maj = CURRENT_TIMESTAMP(), "
+                        . "actif = :actif "
+                        . "WHERE idLocal = :idLocal");
+
+                    db::bind(':jourSortie', $jourSortie);
+                    db::bind(':actif', 0);
+                    db::bind(':idLocal', $salaries["idLocal"]);
+
+                    try {
+                        db::execute();
+                        $cp["DISABLE"]["SUCCESS"]++;
+                    } catch (Exception $ex) {
+                        $cp["DISABLE"]["ERROR"]++;
+                    }
+
+                    $forSFTP["action"] = "disabled";
+                    $forSFTP["idLocal"] = $salaries["idLocal"];
+                    $forSFTP["loginId"] = $salaries["loginId"];
+                    $forSFTP["contrat"] = $salaries["contrat"];
+                    $forSFTP["jourEntree"] = $salaries["jourEntree"];
+                    $forSFTP["jourSortie"] = $jourSortie;
+                    $forSFTP["repriseContrat"] = NULL;
+                    $forSFTP["actif"] = 0;
+                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
+                } else {
+
+                    $forSFTP["action"] = "update";
+                    $forSFTP["idLocal"] = $salaries["idLocal"];
+                    $forSFTP["loginId"] = $salaries["loginId"];
+                    $forSFTP["contrat"] = $salaries["contrat"];
+
+                    if (is_array($updateContrat) and array_key_exists($salaries["idLocal"], $updateContrat)) {
+                        if ($updateContrat[$salaries["idLocal"]] == "start") {
+                            $forSFTP["jourEntree"] = $dateReprise;
+                            $forSFTP["jourSortie"] = NULL;
+                            $forSFTP["repriseContrat"] = $dateReprise;
+                            $forSFTP["actif"] = 1;
+                            $reprise = $dateReprise;
+                        } elseif ($updateContrat[$salaries["idLocal"]] == "end") {
+                            $forSFTP["jourEntree"] = $salaries["jourEntree"];
+                            $forSFTP["jourSortie"] = $jourSortie;
+                            $forSFTP["repriseContrat"] = NULL;
+                            $forSFTP["actif"] = 0;
+                        }
+                    } else {
+                        $forSFTP["jourEntree"] = $salaries["jourEntree"];
+                        $forSFTP["jourSortie"] = NULL;
+                        $forSFTP["repriseContrat"] = NULL;
+                        $forSFTP["actif"] = $salaries["actif"];
+                    }
+
+                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
+
+                    db::query("UPDATE " . DB_T_SALARIES . " SET "
+                        . "loginId = :loginId, "
+                        . "contrat = :contrat, "
+                        . "lieu = :lieu, "
+                        . "repriseContrat = :repriseContrat, "
+                        . "jourSortie = :jourSortie, "
+                        . "maj = CURRENT_TIMESTAMP(), "
+                        . "actif = :actif "
+                        . "WHERE idLocal = :idLocal");
+
+                    db::bind(':loginId', $salaries["loginId"]);
+                    db::bind(':contrat', $salaries["contrat"]);
+                    db::bind(':lieu', $salaries["lieu"]);
+                    db::bind(':repriseContrat', $reprise);
+                    db::bind(':jourSortie', NULL);
+                    db::bind(':actif', $salaries["actif"]);
+                    db::bind(':idLocal', $salaries["idLocal"]);
+
+                    try {
+                        db::execute();
+                        $cp["UPDATE"]["SUCCESS"]++;
+                    } catch (Exception $ex) {
+                        $cp["UPDATE"]["ERROR"]++;
+                    }
+                }
+            }
+
+            if ($cp["INSERT"]["SUCCESS"] == 1) {
+                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salarié traité.");
+            } elseif ($cp["INSERT"]["SUCCESS"] > 1) {
+                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salariés traités.");
+            }
+            if ($cp["DISABLE"]["SUCCESS"] == 1) {
+                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salarié traité.");
+            } elseif ($cp["DISABLE"]["SUCCESS"] > 1) {
+                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salariés traités.");
+            }
+            if ($cp["UPDATE"]["SUCCESS"] == 1) {
+                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salarié traité.");
+            } elseif ($cp["UPDATE"]["SUCCESS"] > 1) {
+                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salariés traités.");
+            }
+            if ($cp["INSERT"]["ERROR"] == 1) {
+                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salarié non traité.");
+            } elseif ($cp["INSERT"]["ERROR"] > 1) {
+                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salariés non traités.");
+            }
+            if ($cp["DISABLE"]["ERROR"] == 1) {
+                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salarié non traité.");
+            } elseif ($cp["DISABLE"]["ERROR"] > 1) {
+                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salariés non traités.");
+            }
+            if ($cp["UPDATE"]["ERROR"] == 1) {
+                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salarié non traité.");
+            } elseif ($cp["UPDATE"]["ERROR"] > 1) {
+                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salariés non traités.");
+            }
+
+            (self::recForSFTP($SFTP, $_excel)) ? alert::recSuccess("Les données d'exportation pour ProWeb ont été enregistrées") : alert::recError("Les données d'exportation pour ProWeb n'ont pas pu être enregistrées");
+        }
+    }
+
+    private static function recForSFTP(array $_array, int $_idExcel)
+    {
+        $json = json_encode($_array);
+
+        db::query("UPDATE " . DB_T_EXCEL . " SET "
+            . "forSFTP = :forSFTP ,"
+            . "md5forSFTP = :md5forSFTP "
+            . "WHERE id = :id");
+        db::bind(':forSFTP', $json);
+        db::bind(':md5forSFTP', md5($json));
+        db::bind(':id', $_idExcel);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function create_rapport()
+    {
+        $log = NULL;
+
+        db::query("SELECT idLocal, loginId, nom, prenom, contrat, jourEntree, lieu, excel, log FROM " . DB_T_TEMP_SALARIES . " WHERE log IS NOT NULL");
+        $row = db::resultset();
+
+        if ($row != NULL) {
+
+            foreach ($row as $key => $salaries) {
+                if ($salaries["log"] == "INSERT") {
+                    $log["json"][] = array(
+                        "action" => "INSERT",
+                        "excel" => $salaries["excel"],
+                        "idLocal" => $salaries["idLocal"],
+                        "loginId" => $salaries["loginId"],
+                        "nom" => $salaries["nom"],
+                        "prenom" => $salaries["prenom"],
+                        "jourEntree" => $salaries["jourEntree"],
+                        "contrat" => $salaries["contrat"],
+                        "lieu" => $salaries["lieu"]
+                    );
+                } elseif ($salaries["log"] == "DISABLE") {
+                    $log["json"][] = array(
+                        "action" => "DISABLE",
+                        "excel" => $salaries["excel"],
+                        "idLocal" => $salaries["idLocal"],
+                        "loginId" => $salaries["loginId"],
+                        "nom" => $salaries["nom"],
+                        "prenom" => $salaries["prenom"],
+                        "jourEntree" => $salaries["jourEntree"],
+                        "contrat" => $salaries["contrat"],
+                        "lieu" => $salaries["lieu"]
+                    );
+                } else {
+                    $tmp_log = array("action" => "UPDATE", "excel" => $salaries["excel"], "nom" => $salaries["nom"], "prenom" => $salaries["prenom"]);
+                    $tmp = explode(" ", $salaries["log"]);
+                    foreach ($tmp as $key => $value) {
+                        if ($key > 0) {
+                            switch ($value) {
+                                case "loginId":
+                                    $tmp_log["loginId"] = $salaries["loginId"];
+                                    break;
+                                case "contrat":
+                                    $tmp_log["contrat"] = $salaries["contrat"];
+                                    break;
+                                case "lieu":
+                                    $tmp_log["lieu"] = $salaries["lieu"];
+                                    break;
+                            }
+                        }
+                    }
+
+                    $log["json"][] = $tmp_log;
+                }
+            }
+
+            $log["json"] = json_encode($log["json"]);
+            $log["excel"] = $salaries["excel"];
+        } else {
+            $log["json"] = NULL;
+            $log["excel"] = NULL;
+        }
+
+        return $log;
+    }
+
+    public static function count_tmp_salaries()
+    {
+        db::query("SELECT COUNT(*) AS nb FROM " . DB_T_TEMP_SALARIES);
+        return db::single()["nb"];
+    }
+
+    public static function dataForSFTP()
+    {
+        $lastExcel = self::lastExcel_forSFTP();
+        $forSFTP = self::get_excel_Json_forSFTP($lastExcel);
+        $finalSalarie = NULL;
+        $csv = "OD_" . date("d-m-Y") . ".csv";
+
+        $tmpSFTP = fopen(SFTP_LOCAL . $csv, "w");
+        fputcsv($tmpSFTP, array("loginId", "jourSortie"), ";");
+
+        foreach (json_decode($forSFTP["forSFTP"], TRUE) as $salarie) {
+
+            $tmpSalarie = NULL;
+
+            if (isset($salarie["loginId"]) and $salarie["loginId"] != "" and isset($salarie["jourSortie"])) {
+                $tmpSalarie["loginId"] = $salarie["loginId"];
+                $tmpSalarie["jourSortie"] = $salarie["jourSortie"];
+                fputcsv($tmpSFTP, $tmpSalarie, ";");
+            }
+        }
+        self::recDateForSFTP($lastExcel);
+    }
+
+    private static function recDateForSFTP(int $_idExcel)
+    {
+        db::query("UPDATE " . DB_T_EXCEL . " SET "
+            . "createForSFTP = CURRENT_TIMESTAMP() "
+            . "WHERE id = :id");
+        db::bind(':id', $_idExcel);
+        try {
+            db::execute();
+            return TRUE;
+        } catch (Exception $e) {
+            return FALSE;
+        }
+    }
+
+    public static function ifSubmitLastForSFTP()
+    {
+        $lastExcel = self::lastExcel();
+        $forSFTP = self::get_excel_Json_forSFTP($lastExcel);
+        return (@$forSFTP["md5forSFTP"] != NULL and @$forSFTP["createForSFTP"] == NULL) ? TRUE : FALSE;
+    }
+
+    public static function checkSalarieByMatricule(string $_string)
+    {
+        db::query("SELECT "
+            . "id, "
+            . "nom, "
+            . "prenom, "
+            . "contrat, "
+            . "actif "
+            . "FROM " . DB_T_SALARIES . " "
+            . "WHERE idLocal = :idLocal");
+        db::bind(':idLocal', intval($_string));
+        $salarie = db::single();
+
+        if (isset($salarie["id"])) {
+            if ($salarie["actif"] == 0) {
+                $return["error"] = "<div>Ce matricule n'est plus sous contrat Capgemini Consulting.</div>";
+                $return["class"] = "danger";
+            } elseif ($salarie["contrat"] == 0) {
+                $return["error"] = "<div>Ce matricule est en suspension de contrat chez Capgemini Consulting mais peut-être pris en charge par le CSE.</div>";
+                $return["class"] = "success";
+            } else {
+                $return["success"] = "<div>Ce matricule est sous contrat Capgemini Consulting.</div>";
+                $return["class"] = "success";
+            }
+            $return["identity"] = $salarie["prenom"] . " " . $salarie["nom"];
+        } else {
+            $return["error"] = "<div>Ce matricule n'est pas ou plus rattaché à Capgemini Consulting.</div>";
+            $return["class"] = "danger";
+        }
+        return $return;
+    }
+}

+ 92 - 0
core/class/session.class.php

@@ -0,0 +1,92 @@
+<?php
+
+class session
+{
+    public static function createSession(array $_array, string $_type = "user")
+    {
+        $_SESSION[$_type] = $_array;
+    }
+
+    public static function getId(string $_type = "user")
+    {
+        return $_SESSION[$_type]["id"];
+    }
+
+    public static function getValue(string $_val, string $_type = "user")
+    {
+        return $_SESSION[$_type][$_val];
+    }
+
+    public static function getName(string $_type = "user")
+    {
+        return $_SESSION[$_type]["prenom"] . " " . $_SESSION[$_type]["nom"];
+    }
+
+    public static function isConnect(string $_type = "user")
+    {
+        return (isset($_SESSION[$_type]["id"])) ? TRUE : FALSE;
+    }
+
+    public static function accessUserByType(int $_type)
+    {
+
+        if (isset($_SESSION["user"]["id"])) {
+            if ($_SESSION["user"]["idType"] == 1) {
+                return TRUE;
+            } elseif ($_SESSION["user"]["idType"] == 2 and $_type == 2) {
+                return TRUE;
+            } elseif ($_SESSION["user"]["idType"] == 3 and $_type == 3) {
+                return TRUE;
+            } else {
+                return FALSE;
+            }
+        } else {
+            return FALSE;
+        }
+    }
+
+    public static function accessElement(string $_element, string $_type)
+    {
+        // Eléments autorisé sans authentification
+        if (self::elementWhite($_element, $_type)) {
+            return TRUE;
+        } else {
+            if (isset($_SESSION["salarie"]["id"])) { // Espaces spécifiques aux Salariés
+                if (self::elementSalaries($_element, $_type)) {
+                    return TRUE;
+                }
+            } elseif (isset($_SESSION["user"]["idType"]) and $_SESSION["user"]["idType"] == 2) { // Espaces spécifiques aux Contrôleurs
+                if (self::elementControleurs($_element, $_type)) {
+                    return TRUE;
+                }
+            } elseif (isset($_SESSION["user"]["idType"]) and $_SESSION["user"]["idType"] == 3) { // Espaces spécifiques aux Contrôleurs
+                if (self::elementServiceSocial($_element, $_type)) {
+                    return TRUE;
+                }
+            } elseif (isset($_SESSION["user"]["idType"]) and $_SESSION["user"]["idType"] == 1) { // Espaces spécifiques aux Admins
+                return TRUE;
+            }
+        }
+        return FALSE;
+    }
+
+    private static function elementWhite(string $_element, string $_type)
+    {
+        return (in_array($_element, ACCESS_WHITE[$_type])) ? TRUE : FALSE;
+    }
+
+    private static function elementSalaries(string $_element, string $_type)
+    {
+        return (in_array($_element, ACCESS_SALARIES[$_type])) ? TRUE : FALSE;
+    }
+
+    private static function elementControleurs(string $_element, string $_type)
+    {
+        return (in_array($_element, ACCESS_CONTROLEURS[$_type])) ? TRUE : FALSE;
+    }
+
+    private static function elementServiceSocial(string $_element, string $_type)
+    {
+        return (in_array($_element, ACCESS_SOCIAL[$_type])) ? TRUE : FALSE;
+    }
+}

+ 176 - 0
core/class/sftp.class.php

@@ -0,0 +1,176 @@
+<?php
+
+class sftp
+{
+
+    private static $authent;
+    private static $connexion;
+    private static $dataSend;
+
+    private static function connectHost(int $_sec = 2)
+    {
+        $originalConnectionTimeout = ini_get('default_socket_timeout');
+        ini_set('default_socket_timeout', $_sec);
+        if (self::$authent = @ssh2_connect(SFTP_HOST, 22)) {
+            ini_set('default_socket_timeout', $originalConnectionTimeout);
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+    }
+
+    private static function authentHost()
+    {
+        return (@ssh2_auth_password(self::$authent, SFTP_USER, SFTP_PASS)) ? TRUE : FALSE;
+    }
+
+    private static function initializeHost()
+    {
+        return (self::$connexion = @ssh2_sftp(self::$authent)) ? TRUE : FALSE;
+    }
+
+    private static function fileExist(string $_file = NULL)
+    {
+        return (file_exists($_file)) ? TRUE : FALSE;
+    }
+
+    private static function fileGetContents(string $_file = NULL)
+    {
+        return (self::$dataSend = @file_get_contents($_file)) ? TRUE : FALSE;
+    }
+
+    private static function accessHost(bool $_showAlert = TRUE)
+    {
+        if (!self::connectHost()) {
+            ($_showAlert == TRUE) ? alert::recError("Erreur de connection au serveur distant") : NULL;
+            return FALSE;
+        }
+        if (!self::authentHost()) {
+            ($_showAlert == TRUE) ? alert::recError("Erreur d'authentification au serveur distant") : NULL;
+            return FALSE;
+        }
+        if (!self::initializeHost()) {
+            ($_showAlert == TRUE) ? alert::recError("Erreur d'initialisation au serveur distant") : NULL;
+            return FALSE;
+        }
+        ($_showAlert == TRUE) ? alert::recSuccess("Accès au serveur distant") : NULL;
+        return TRUE;
+    }
+
+    public static function testAccessHost()
+    {
+        return (self::accessHost(FALSE)) ? TRUE : FALSE;
+    }
+
+    private static function sendFile(string $_file)
+    {
+        self::accessHost();
+        $stream = @fopen("ssh2.sftp://" . self::$authent . SFTP_REMOTE . $_file, "w");
+        $data = @file_get_contents(SFTP_LOCAL . $_file);
+        if (@fwrite($stream, $data) === false) {
+            alert::recError($_file . " n'a pas pu être transféré au serveur distant");
+            return FALSE;
+        } else {
+            alert::recSuccess($_file . " a été trasféré avec succès");
+            return TRUE;
+        }
+        @fclose($stream);
+    }
+
+    public static function deleteFileToRemote(string $_file)
+    {
+
+        db::query("UPDATE " . DB_T_EXCEL . " SET createForSFTP = NULL WHERE id = :id");
+        db::bind(':id', salaries::lastExcel());
+        try {
+            db::execute();
+            alert::recSuccess($_file . " a été supprimé du serveur local.");
+            return TRUE;
+        } catch (Exception $e) {
+            alert::recError($_file . " n'a pas pu être supprimé");
+            return FALSE;
+        }
+    }
+
+    public static function sendFileToRemote($_file = NULL)
+    {
+        if ($_file == NULL) {
+            alert::recError("Le fichier à envoyé n'a pas été défini");
+            return FALSE;
+        } elseif (!self::fileExist(SFTP_LOCAL . $_file)) {
+            alert::recError($_file . " n'est pas présent sur le serveur");
+            return FALSE;
+        } else {
+            return self::sendFile($_file);
+        }
+    }
+
+    public static function scanFolderRemote()
+    {
+        self::accessHost(FALSE);
+        $realpath = @ssh2_sftp_realpath(self::$connexion, SFTP_REMOTE);
+        $dir = "ssh2.sftp://" . self::$connexion . $realpath;
+        $tempArray = array();
+
+        if (is_dir($dir)) {
+            if ($dh = opendir($dir)) {
+                while (($file = readdir($dh)) !== false) {
+                    $tempFile = NULL;
+                    $realpath = @ssh2_sftp_realpath(self::$connexion, $file);
+                    $filetype = filetype($dir . $realpath);
+                    $size = sprintf("%.2f", filesize($dir . $realpath));
+
+                    if ($filetype != "dir") {
+                        $infos = @ssh2_sftp_stat(self::$connexion, $file);
+                        $tempFile["file"] = $file;
+                        $tempFile["size"] = core::formatFileSize($infos["size"], 2);
+                        $tempFile["date"] = core::dateFromTimestamp($infos["atime"]);
+                        $tempArray[] = $tempFile;
+                    }
+                }
+                closedir($dh);
+            }
+        }
+        return $tempArray;
+    }
+
+    public static function scanFolderLocal()
+    {
+        $tempArray = array();
+        if ($scandir = scandir(SFTP_LOCAL)) {
+            foreach ($scandir as $file) {
+                $tempFile = NULL;
+                if (is_file(SFTP_LOCAL . $file) === TRUE and $file != "index.html") {
+                    $tempFile["file"] = $file;
+                    $tempFile["size"] = core::formatFileSize(filesize(SFTP_LOCAL . $file), 2);
+                    $tempFile["date"] = core::dateFromTimestamp(filemtime(SFTP_LOCAL . $file));
+                    $tempArray[] = $tempFile;
+                }
+            }
+        }
+        return $tempArray;
+    }
+
+    public static function deleteFormRemote(string $_file)
+    {
+        self::accessHost(FALSE);
+        if (@ssh2_sftp_unlink(self::$connexion, SFTP_REMOTE . $_file)) {
+            alert::recSuccess($_file . " a été supprimé du serveur distant.");
+            return TRUE;
+        } else {
+            alert::recError($_file . " n'a pas été supprimé du serveur distant");
+            return FALSE;
+        }
+    }
+
+    public static function downloadFormRemote(string $_file)
+    {
+        self::accessHost(FALSE);
+        //ssh2_scp_recv(self::$authent, SFTP_REMOTE.$_file, SFTP_LOCAL.$_file);
+
+        $stream = @fopen("ssh2.sftp://" . self::$authent . SFTP_REMOTE . $_file, 'r');
+        $contents = stream_get_contents($stream);
+        file_put_contents(DIR_DATAS_TEMP . $_file, $contents);
+        @fclose($stream);
+    }
+}

+ 184 - 0
core/class/simpleCSV.class.php

@@ -0,0 +1,184 @@
+<?php
+
+class simpleCSV
+{
+
+    private $_delimiter;
+    private $_enclosure;
+    private $_linebreak;
+    private $_csv = '';
+
+    public static function import($filename_or_data, $is_data = false, $delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
+    {
+        $csv = new static($delimiter, $enclosure, $linebreak);
+        return $csv->toArray($filename_or_data, $is_data);
+    }
+
+    public static function export($items, $delimiter = ',', $enclosure = '"', $linebreak = "\r\n")
+    {
+        $csv = new static($delimiter, $enclosure, $linebreak);
+        return $csv->fromArray($items);
+    }
+
+    public function __construct($delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
+    {
+        $this->_delimiter = $delimiter;
+        $this->_enclosure = $enclosure;
+        $this->_linebreak = $linebreak;
+    }
+
+    public function delimiter($set = false)
+    {
+        if ($set !== false) {
+            return $this->_delimiter = $set;
+        }
+        if ($this->_delimiter === 'auto') {
+            // detect delimiter
+            if (strpos($this->_csv, $this->_enclosure . ',') !== false) {
+                $this->_delimiter = ',';
+            } else if (strpos($this->_csv, $this->_enclosure . "\t") !== false) {
+                $this->_delimiter = "\t";
+            } else if (strpos($this->_csv, $this->_enclosure . ';') !== false) {
+                $this->_delimiter = ';';
+            } else if (strpos($this->_csv, ',') !== false) {
+                $this->_delimiter = ',';
+            } else if (strpos($this->_csv, "\t") !== false) {
+                $this->_delimiter = "\t";
+            } else if (strpos($this->_csv, ';') !== false) {
+                $this->_delimiter = ';';
+            } else {
+                $this->_delimiter = ',';
+            }
+        }
+        return $this->_delimiter;
+    }
+
+    public function enclosure($set = false)
+    {
+        if ($set !== false) {
+            return $this->_enclosure = $set;
+        }
+        if ($this->_enclosure === 'auto') {
+            // detect quot
+            if (strpos($this->_csv, '"') !== false) {
+                $this->_enclosure = '"';
+            } else if (strpos($this->_csv, "'") !== false) {
+                $this->_enclosure = "'";
+            } else {
+                $this->_enclosure = '"';
+            }
+        }
+        return $this->_enclosure;
+    }
+
+    public function linebreak($set = false)
+    {
+        if ($set !== false) {
+            return $this->_linebreak = $set;
+        }
+        if ($this->_linebreak === 'auto') {
+            if (strpos($this->_csv, "\r\n") !== false) {
+                $this->_linebreak = "\r\n";
+            } else if (strpos($this->_csv, "\n") !== false) {
+                $this->_linebreak = "\n";
+            } else if (strpos($this->_csv, "\r") !== false) {
+                $this->_linebreak = "\r";
+            } else {
+                $this->_linebreak = "\r\n";
+            }
+        }
+        return $this->_linebreak;
+    }
+
+    public function toArray($filename, $is_csv_content = false)
+    {
+
+        $this->_csv = $is_csv_content ? $filename : file_get_contents($filename);
+
+        $CSV_LINEBREAK = $this->linebreak();
+        $CSV_ENCLOSURE = $this->enclosure();
+        $CSV_DELIMITER = $this->delimiter();
+
+        $r = array();
+        $cnt = strlen($this->_csv);
+
+        $esc = false;
+        $i = $k = $n = 0;
+        $r[$k][$n] = '';
+
+        while ($i < $cnt) {
+            $ch = $this->_csv[$i];
+            $chch = ($i < $cnt - 1) ? $ch . $this->_csv[$i + 1] : $ch;
+
+            if ($ch === $CSV_LINEBREAK) {
+                if ($esc) {
+                    $r[$k][$n] .= $ch;
+                } else {
+                    $k++;
+                    $n = 0;
+                    $esc = false;
+                    $r[$k][$n] = '';
+                }
+            } else if ($chch === $CSV_LINEBREAK) {
+                if ($esc) {
+                    $r[$k][$n] .= $chch;
+                } else {
+                    $k++;
+                    $n = 0;
+                    $esc = false;
+                    $r[$k][$n] = '';
+                }
+                $i++;
+            } else if ($ch === $CSV_DELIMITER) {
+                if ($esc) {
+                    $r[$k][$n] .= $ch;
+                } else {
+                    $n++;
+                    $r[$k][$n] = '';
+                    $esc = false;
+                }
+            } else if ($chch === $CSV_ENCLOSURE . $CSV_ENCLOSURE && $esc) {
+                $r[$k][$n] .= $CSV_ENCLOSURE;
+                $i++;
+            } elseif ($ch === $CSV_ENCLOSURE) {
+
+                $esc = !$esc;
+            } else {
+                $r[$k][$n] .= $ch;
+            }
+            $i++;
+        }
+        return $r;
+    }
+
+    public function fromArray($items)
+    {
+        if (!is_array($items)) {
+            trigger_error('CSV::export array required', E_USER_WARNING);
+            return false;
+        }
+
+        $CSV_DELIMITER = $this->delimiter();
+        $CSV_ENCLOSURE = $this->enclosure();
+        $CSV_LINEBREAK = $this->linebreak();
+
+        $result = '';
+        foreach ($items as $i) {
+            $line = '';
+
+            foreach ($i as $v) {
+                if (strpos($v, $CSV_ENCLOSURE) !== false) {
+                    $v = str_replace($CSV_ENCLOSURE, $CSV_ENCLOSURE . $CSV_ENCLOSURE, $v);
+                }
+
+                if ((strpos($v, $CSV_DELIMITER) !== false) || (strpos($v, $CSV_ENCLOSURE) !== false) || (strpos($v, $CSV_LINEBREAK) !== false)) {
+                    $v = $CSV_ENCLOSURE . $v . $CSV_ENCLOSURE;
+                }
+                $line .= $line ? $CSV_DELIMITER . $v : $v;
+            }
+            $result .= $result ? $CSV_LINEBREAK . $line : $line;
+        }
+
+        return $result;
+    }
+}

+ 1308 - 0
core/class/simpleXLS.class.php

@@ -0,0 +1,1308 @@
+<?php
+
+/*
+ * Example
+echo '<pre>';
+if ( $xls = SimpleXLS::parse('excel5book.xls')) {
+    print_r( $xls->rows() ); // dump first sheet
+    print_r( $xls->rows(1)); /// dump second sheet
+} else {
+    echo SimpleXLS::parseError();
+}
+echo '</pre>';
+ */
+
+class simpleXLS {
+    public const BIFF8 = 0x600;
+    public const BIFF7 = 0x500;
+    public const WORKBOOKGLOBALS = 0x5;
+    public const WORKSHEET = 0x10;
+
+    //const TYPE_BOF = 0x809;
+    public const TYPE_EOF = 0x0a;
+    public const TYPE_BOUNDSHEET = 0x85;
+    public const TYPE_DIMENSION = 0x200;
+    public const TYPE_ROW = 0x208;
+    public const TYPE_DBCELL = 0xd7;
+    public const TYPE_FILEPASS = 0x2f;
+    //const TYPE_NOTE = 0x1c;
+    //const TYPE_TXO = 0x1b6;
+    public const TYPE_RK = 0x7e;
+    public const TYPE_RK2 = 0x27e;
+    public const TYPE_MULRK = 0xbd;
+    public const TYPE_MULBLANK = 0xbe;
+    //const TYPE_INDEX = 0x20b;
+    public const TYPE_SST = 0xfc;
+    //const TYPE_EXTSST = 0xff;
+    //const TYPE_CONTINUE = 0x3c;
+    public const TYPE_LABEL = 0x204;
+    public const TYPE_LABELSST = 0xfd;
+    public const TYPE_NUMBER = 0x203;
+    public const TYPE_NAME = 0x18;
+    //const TYPE_ARRAY = 0x221;
+    //const TYPE_STRING = 0x207;
+    public const TYPE_FORMULA = 0x406;
+    public const TYPE_FORMULA2 = 0x6;
+    public const TYPE_FORMAT = 0x41e;
+    public const TYPE_XF = 0xe0;
+    public const TYPE_BOOLERR = 0x205;
+    //const TYPE_UNKNOWN = 0xffff;
+    public const TYPE_NINETEENFOUR = 0x22;
+    public const TYPE_MERGEDCELLS = 0xE5;
+    public const TYPE_WINDOW1 = 0x3D;
+
+    //const DEF_NUM_FORMAT = "%.2f";
+    public const DEF_NUM_FORMAT = '%s';
+
+    // OLE
+    public const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c;
+    public const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c;
+    public const ROOT_START_BLOCK_POS = 0x30;
+    public const BIG_BLOCK_SIZE = 0x200;
+    public const SMALL_BLOCK_SIZE = 0x40;
+    public const EXTENSION_BLOCK_POS = 0x44;
+    public const NUM_EXTENSION_BLOCK_POS = 0x48;
+    public const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
+    public const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c;
+    public const SMALL_BLOCK_THRESHOLD = 0x1000;
+    // property storage offsets
+    public const SIZE_OF_NAME_POS = 0x40;
+    public const TYPE_POS = 0x42;
+    public const START_BLOCK_POS = 0x74;
+    public const SIZE_POS = 0x78;
+    /**
+     * Array of worksheets found
+     *
+     * @var array
+     * @access public
+     */
+    public $boundsheets = array();
+    public $activeSheet = 0;
+
+    /**
+     * Array of format records found
+     *
+     * @var array
+     * @access public
+     */
+    public $formatRecords = array();
+
+    /**
+     *
+     * @var array
+     * @access public
+     */
+    public $sst = array();
+
+    /**
+     * Array of worksheets
+     *
+     * The data is stored in 'cells' and the meta-data is stored in an array
+     * called 'cellsInfo'
+     *
+     * Example:
+     *
+     * $sheets  -->  'cells'  -->  row --> column --> Interpreted value
+     *          -->  'cellsInfo' --> row --> column --> 'type' - Can be 'date', 'number', or 'unknown'
+     *                                            --> 'raw' - The raw data that Excel stores for that data cell
+     *
+     * @var array
+     * @access public
+     */
+    public $sheets = array();
+    /**
+     * List of default date formats used by Excel
+     *
+     * @var array
+     * @access public
+     */
+    public $dateFormats = array(
+        0xe  => 'd/m/Y',
+        0xf  => 'd-M-Y',
+        0x10 => 'd-M',
+        0x11 => 'M-Y',
+        0x12 => 'h:i a',
+        0x13 => 'h:i:s a',
+        0x14 => 'H:i',
+        0x15 => 'H:i:s',
+        0x16 => 'd/m/Y H:i',
+        0x2d => 'i:s',
+        0x2e => 'H:i:s',
+        0x2f => 'i:s.S'
+    );
+/**
+     * Default number formats used by Excel
+     *
+     * @var array
+     * @access public
+     */
+    public $numberFormats = array(
+        0x1  => '%1.0f',     // "0"
+        0x2  => '%1.2f',     // "0.00",
+        0x3  => '%1.0f',     //"#,##0",
+        0x4  => '%1.2f',     //"#,##0.00",
+        0x5  => '%1.0f',     /*"$#,##0;($#,##0)",*/
+        0x6  => '$%1.0f',    /*"$#,##0;($#,##0)",*/
+        0x7  => '$%1.2f',    //"$#,##0.00;($#,##0.00)",
+        0x8  => '$%1.2f',    //"$#,##0.00;($#,##0.00)",
+        0x9  => '%1.0f%%',   // "0%"
+        0xa  => '%1.2f%%',   // "0.00%"
+        0xb  => '%1.2f',     // 0.00E00",
+        0x25 => '%1.0f',    // "#,##0;(#,##0)",
+        0x26 => '%1.0f',    //"#,##0;(#,##0)",
+        0x27 => '%1.2f',    //"#,##0.00;(#,##0.00)",
+        0x28 => '%1.2f',    //"#,##0.00;(#,##0.00)",
+        0x29 => '%1.0f',    //"#,##0;(#,##0)",
+        0x2a => '$%1.0f',   //"$#,##0;($#,##0)",
+        0x2b => '%1.2f',    //"#,##0.00;(#,##0.00)",
+        0x2c => '$%1.2f',   //"$#,##0.00;($#,##0.00)",
+        0x30 => '%1.0f'
+    );
+    protected $datetimeFormat = 'Y-m-d H:i:s';
+    /**
+     * Default encoding
+     *
+     * @var string
+     * @access private
+     */
+    protected $defaultEncoding = 'UTF-8';
+    /**
+     * Default number format
+     *
+     * @var integer
+     * @access private
+     */
+    protected $defaultFormat = self::DEF_NUM_FORMAT;
+    /**
+     * List of formats to use for each column
+     *
+     * @var array
+     * @access private
+     */
+    protected $columnsFormat = array();
+
+    protected $nineteenFour;
+    protected $multiplier;
+    protected $sn;
+    protected $curFormat;
+
+    // OLERead
+    protected $data;
+    protected $bigBlockChain;
+    protected $smallBlockChain;
+    protected $rootEntry;
+    protected $entry;
+    protected $props;
+
+    // sergey.shuchkin@gmail.com
+    protected $wrkbook; // false - to use excel format
+    protected $error = false;
+    protected $debug;
+
+    // {{{ Spreadsheet_Excel_Reader()
+
+    /**
+     * Constructor
+     *
+     * @param string $filename XLS Filename or xls contents
+     * @param bool $isData If True then $filename is contents
+     * @param bool $debug Trigger PHP errors?
+     */
+    public function __construct(string $filename, bool $isData = false, bool $debug = false)
+    {
+        $this->debug = $debug;
+        $this->_oleread($filename, $isData);
+        $this->_parse();
+    }
+    public static function parseFile($filename, $debug = false)
+    {
+        return self::parse($filename, false, $debug);
+    }
+
+    public static function parseData($data, $debug = false)
+    {
+        return self::parse($data, true, $debug);
+    }
+    public static function parse($filename, $isData = false, $debug = false)
+    {
+        $xls = new self($filename, $isData, $debug);
+        if ($xls->success()) {
+            return $xls;
+        }
+        self::parseError($xls->error());
+
+        return false;
+    }
+    public static function parseError($set = false)
+    {
+        static $error = false;
+        return $set ? $error = $set : $error;
+    }
+    public function error($set = false)
+    {
+        if ($set) {
+            $this->error = $set;
+            if ($this->debug) {
+                trigger_error($set);
+            }
+        }
+
+        return $this->error;
+    }
+    public function success(): bool
+    {
+        return ! $this->error;
+    }
+    public function rows($sheetNum = 0, $limit = 0)
+    {
+        if ($this->sheets[ $sheetNum ]) {
+            $s      = $this->sheets[ $sheetNum ];
+            $result = array();
+            for ($i = 0; $i < $s['numRows']; $i ++) {
+                $r = array();
+                for ($j = 0; $j < $s['numCols']; $j ++) {
+                    $r[ $j ] = $s['cells'][$i][$j] ?? '';
+                }
+                $result[] = $r;
+                $limit--;
+                if ($limit === 0) {
+                    break;
+                }
+            }
+
+            return $result;
+        }
+
+        return false;
+    }
+    public function rowsEx($sheetNum = 0, $limit = 0): array
+    {
+        if ($this->sheets[ $sheetNum ]) {
+            $s      = $this->sheets[ $sheetNum ];
+            $result = array();
+            for ($i = 0; $i < $s['numRows']; $i ++) {
+                $r = array();
+                for ($j = 0; $j < $s['numCols']; $j ++) {
+                    $v = $s['cellsInfo'][$i][$j] ?? array();
+//                    if ( $v['type'] === self::TYPE_RK || $v['type'] === self::TYPE_RK2 ||
+                    $v['value'] = $s['cells'][$i][$j] ?? '';
+                    $r[ $j ] = $v;
+                }
+                $result[] = $r;
+                $limit--;
+                if ($limit === 0) {
+                    break;
+                }
+            }
+
+            return $result;
+        }
+
+        return [];
+    }
+    public function toHTML($worksheetIndex = 0): string
+    {
+        $s = '<table class=excel>';
+        foreach ($this->rows($worksheetIndex) as $r) {
+            $s .= '<tr>';
+            foreach ($r as $c) {
+                $s .= '<td nowrap>' . ( $c === '' ? '&nbsp' : htmlspecialchars($c, ENT_QUOTES) ) . '</td>';
+            }
+            $s .= "</tr>\r\n";
+        }
+        $s .= '</table>';
+
+        return $s;
+    }
+    public function setDateTimeFormat($value): SimpleXLS
+    {
+        $this->datetimeFormat = is_string($value) ? $value : false;
+        return $this;
+    }
+    public function sheetNames(): array
+    {
+        $result = array();
+        foreach ($this->boundsheets as $k => $v) {
+            $result[ $k ] = $v['name'];
+        }
+        return $result;
+    }
+    public function sheetName($index)
+    {
+        return isset($this->boundsheets[ $index ])  ? $this->boundsheets[ $index ]['name'] : null;
+    }
+
+    // }}}
+
+    protected function _oleread($sFileName, $isData = false): bool
+    {
+        if ($isData) {
+            $this->data = $sFileName;
+        } else {
+            // check if file exist and is readable (Darko Miljanovic)
+            if (! is_readable($sFileName)) {
+                $this->error('File not is readable ' . $sFileName);
+                return false;
+            }
+
+            $this->data = file_get_contents($sFileName);
+            if (! $this->data) {
+                $this->error('File reading error ' . $sFileName);
+                return false;
+            }
+        }
+        //echo IDENTIFIER_OLE;
+        //echo 'start';
+        if (strpos($this->data, pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1)) !== 0) {
+            $this->error('File is not XLS');
+
+            return false;
+        }
+
+        $numBigBlockDepotBlocks = $this->_getInt4d(self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
+        $sbdStartBlock = $this->_getInt4d(self::SMALL_BLOCK_DEPOT_BLOCK_POS);
+        $rootStartBlock = $this->_getInt4d(self::ROOT_START_BLOCK_POS);
+        $extensionBlock = $this->_getInt4d(self::EXTENSION_BLOCK_POS);
+        $numExtensionBlocks = $this->_getInt4d(self::NUM_EXTENSION_BLOCK_POS);
+
+/*
+            echo $this->numBigBlockDepotBlocks." ";
+            echo $this->sbdStartBlock." ";
+            echo $this->rootStartBlock." ";
+            echo $this->extensionBlock." ";
+            echo $this->numExtensionBlocks." ";
+*/
+        //echo "sbdStartBlock = $this->sbdStartBlock\n";
+        $bigBlockDepotBlocks = array();
+        $pos                 = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
+        // echo "pos = $pos";
+        $bbdBlocks = $numBigBlockDepotBlocks;
+
+        if ($numExtensionBlocks !== 0) {
+            $bbdBlocks = ( self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS ) / 4;
+        }
+
+        for ($i = 0; $i < $bbdBlocks; $i ++) {
+            $bigBlockDepotBlocks[ $i ] = $this->_getInt4d($pos);
+            $pos                       += 4;
+        }
+
+
+        for ($j = 0; $j < $numExtensionBlocks; $j ++) {
+            $pos          = ( $extensionBlock + 1 ) * self::BIG_BLOCK_SIZE;
+            $blocksToRead = min($numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
+
+            for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; $i ++) {
+                $bigBlockDepotBlocks[ $i ] = $this->_getInt4d($pos);
+                $pos                       += 4;
+            }
+
+            $bbdBlocks += $blocksToRead;
+            if ($bbdBlocks < $numBigBlockDepotBlocks) {
+                $extensionBlock = $this->_getInt4d($pos);
+            }
+        }
+
+        // var_dump($bigBlockDepotBlocks);
+
+        // readBigBlockDepot
+
+        $index               = 0;
+        $this->bigBlockChain = array();
+
+        for ($i = 0; $i < $numBigBlockDepotBlocks; $i ++) {
+            $pos = ( $bigBlockDepotBlocks[ $i ] + 1 ) * self::BIG_BLOCK_SIZE;
+            //echo "pos = $pos";
+            for ($j = 0; $j < self::BIG_BLOCK_SIZE / 4; $j ++) {
+                $this->bigBlockChain[ $index ] = $this->_getInt4d($pos);
+                $pos                           += 4;
+                $index ++;
+            }
+        }
+
+        //var_dump($this->bigBlockChain);
+        //echo '=====2';
+        // readSmallBlockDepot();
+
+        $index                 = 0;
+        $sbdBlock              = $sbdStartBlock;
+        $this->smallBlockChain = array();
+
+        while ($sbdBlock !== - 2) {
+            $pos = ( $sbdBlock + 1 ) * self::BIG_BLOCK_SIZE;
+
+            for ($j = 0; $j < self::BIG_BLOCK_SIZE / 4; $j ++) {
+                $this->smallBlockChain[ $index ] = $this->_getInt4d($pos);
+                $pos                             += 4;
+                $index ++;
+            }
+
+            $sbdBlock = $this->bigBlockChain[ $sbdBlock ];
+        }
+
+
+        // readData(rootStartBlock)
+        $block = $rootStartBlock;
+
+        $this->entry = $this->_readData($block);
+
+        /*
+        while ($block != -2)  {
+            $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
+            $this->entry = $this->entry.substr($this->_data, $pos, self::BIG_BLOCK_SIZE);
+            $block = $this->bigBlockChain[$block];
+        }
+        */
+        //echo '==='.$this->entry."===";
+        $this->_readPropertySets();
+        $this->data = $this->_readWorkBook();
+
+        return true;
+    }
+
+    // {{{ setOutputEncoding()
+    protected function _getInt2d($pos): int
+    {
+        return ord($this->data[ $pos ]) | ord($this->data[ $pos + 1 ]) << 8;
+//      return ($value > 0x7FFFFFFF) ? $value - 0x100000000 : $value;
+    }
+    protected function _getInt4d($pos): int
+    {
+        $value = ord($this->data[ $pos ]) | ( ord($this->data[ $pos + 1 ]) << 8 ) | ( ord($this->data[ $pos + 2 ]) << 16 ) | ( ord($this->data[ $pos + 3 ]) << 24 );
+        return ($value > 0x7FFFFFFF) ? $value - 0x100000000 : $value;
+    }
+
+    // }}}
+
+    // {{{ setRowColOffset()
+
+    protected function _readData($bl): string
+    {
+        $block = $bl;
+
+        $data = '';
+
+        while ($block !== - 2) {
+            $pos  = ( $block + 1 ) * self::BIG_BLOCK_SIZE;
+            $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
+            //echo "pos = $pos data=$data\n";
+            $block = $this->bigBlockChain[ $block ];
+        }
+
+        return $data;
+    }
+
+    // }}}
+    // {{{ setDefaultFormat()
+
+    protected function _readPropertySets(): void
+    {
+        $offset = 0;
+        //var_dump($this->entry);
+        while ($offset < strlen($this->entry)) {
+            $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
+
+            $nameSize = ord($d[ self::SIZE_OF_NAME_POS ]) | ( ord($d[ self::SIZE_OF_NAME_POS + 1 ]) << 8 );
+
+            $type = ord($d[ self::TYPE_POS ]);
+            //$maxBlock = $this->_strlen($d) / self::BIG_BLOCK_SIZE - 1;
+
+            $startBlock = ord($d[ self::START_BLOCK_POS]) | ( ord($d[ self::START_BLOCK_POS + 1 ]) << 8 ) | ( ord($d[ self::START_BLOCK_POS + 2 ]) << 16 ) | ( ord($d[ self::START_BLOCK_POS + 3 ]) << 24 );
+            $size       = ord($d[ self::SIZE_POS]) | ( ord($d[ self::SIZE_POS + 1 ]) << 8 ) | ( ord($d[ self::SIZE_POS + 2 ]) << 16 ) | ( ord($d[ self::SIZE_POS + 3 ]) << 24 );
+
+            $name = '';
+            for ($i = 0; $i < $nameSize; $i ++) {
+                $name .= $d[ $i ];
+            }
+
+            $name = str_replace("\x00", '', $name);
+
+            $this->props[] = array(
+                'name'       => $name,
+                'type'       => $type,
+                'startBlock' => $startBlock,
+                'size'       => $size
+            );
+
+            if (( $name === 'Workbook' ) || ( $name === 'Book' )) {
+                $this->wrkbook = count($this->props) - 1;
+            }
+
+            if ($name === 'Root Entry') {
+                $this->rootEntry = count($this->props) - 1;
+            }
+
+            //echo "name ==$name=\n";
+
+
+            $offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
+        }
+    }
+
+    // }}}
+    // {{{ setColumnFormat()
+
+    protected function _readWorkBook(): string
+    {
+        if ($this->props[ $this->wrkbook ]['size'] < self::SMALL_BLOCK_THRESHOLD) {
+//        getSmallBlockStream(PropertyStorage ps)
+
+            $rootdata = $this->_readData($this->props[ $this->rootEntry ]['startBlock']);
+
+            $streamData = '';
+            $block      = (int) $this->props[ $this->wrkbook ]['startBlock'];
+            //$count = 0;
+            while ($block !== - 2) {
+                $pos        = $block * self::SMALL_BLOCK_SIZE;
+                $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
+
+                $block = $this->smallBlockChain[ $block ];
+            }
+
+            return $streamData;
+        }
+
+        $numBlocks = $this->props[ $this->wrkbook ]['size'] / self::BIG_BLOCK_SIZE;
+        if ($this->props[ $this->wrkbook ]['size'] % self::BIG_BLOCK_SIZE !== 0) {
+            $numBlocks ++;
+        }
+
+        if ($numBlocks === 0) {
+            return '';
+        }
+
+        //echo "numBlocks = $numBlocks\n";
+        //byte[] streamData = new byte[numBlocks * self::BIG_BLOCK_SIZE];
+        //print_r($this->wrkbook);
+        $streamData = '';
+        $block      = $this->props[ $this->wrkbook ]['startBlock'];
+
+        //echo "block = $block";
+        while ($block !== - 2) {
+            $pos        = ( $block + 1 ) * self::BIG_BLOCK_SIZE;
+            $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
+            $block      = $this->bigBlockChain[ $block ];
+        }
+
+        //echo 'stream'.$streamData;
+        return $streamData;
+    }
+
+
+    // }}}
+    protected function parseSubstreamHeader($pos): array
+    {
+        $length = $this->_getInt2d($pos + 2);
+
+        $version       = $this->_getInt2d($pos + 4);
+        $substreamType = $this->_getInt2d($pos + 6);
+        return array( $length, $version, $substreamType );
+    }
+    // {{{ _parse()
+
+    /**
+     * Parse a workbook
+     *
+     * @access private
+     * @return bool
+     */
+    protected function _parse()
+    {
+        $pos = 0;
+
+//        $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
+        [$length, $version, $substreamType] = $this->parseSubstreamHeader($pos);
+//      echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
+
+//      die();
+
+        if (( $version !== self::BIFF8 ) &&
+             ( $version !== self::BIFF7 )
+        ) {
+            return false;
+        }
+
+        if ($substreamType !== self::WORKBOOKGLOBALS) {
+            return false;
+        }
+
+        //print_r($rec);
+        $pos += $length + 4;
+
+        $code   = ord($this->data[ $pos ]) | ord($this->data[ $pos + 1 ]) << 8;
+        $length = ord($this->data[ $pos + 2 ]) | ord($this->data[ $pos + 3 ]) << 8;
+
+        while ($code !== self::TYPE_EOF) {
+            switch ($code) {
+                case self::TYPE_SST:
+                    //echo "Type_SST\n";
+                    $formattingRuns    = 0;
+                    $extendedRunLength = 0;
+                    $spos              = $pos + 4;
+                    $limitpos          = $spos + $length;
+                    $uniqueStrings     = $this->_getInt4d($spos + 4);
+                    $spos              += 8;
+                    for ($i = 0; $i < $uniqueStrings; $i ++) {
+                        // Read in the number of characters
+                        if ($spos === $limitpos) {
+                            $opcode    = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                            $conlength = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+                            if ($opcode !== 0x3c) {
+                                return - 1;
+                            }
+                            $spos     += 4;
+                            $limitpos = $spos + $conlength;
+                        }
+                        $numChars = ord($this->data[ $spos ]) | ( ord($this->data[ $spos + 1 ]) << 8 );
+                        //echo "i = $i pos = $pos numChars = $numChars ";
+                        $spos        += 2;
+                        $optionFlags = ord($this->data[ $spos ]);
+                        $spos ++;
+                        $asciiEncoding  = ( ( $optionFlags & 0x01 ) === 0 );
+                        $extendedString = ( ( $optionFlags & 0x04 ) !== 0 );
+
+                        // See if string contains formatting information
+                        $richString = ( ( $optionFlags & 0x08 ) !== 0 );
+
+                        if ($richString) {
+                            // Read in the crun
+                            $formattingRuns = $this->_getInt2d($spos);
+                            $spos           += 2;
+                        }
+
+                        if ($extendedString) {
+                            // Read in cchExtRst
+                            $extendedRunLength = $this->_getInt4d($spos);
+                            $spos              += 4;
+                        }
+
+                        $len = $asciiEncoding ? $numChars : $numChars * 2;
+                        if ($spos + $len < $limitpos) {
+                            $retstr = substr($this->data, $spos, $len);
+                            $spos   += $len;
+                        } else {
+                            // found countinue
+                            $retstr    = substr($this->data, $spos, $limitpos - $spos);
+                            $bytesRead = $limitpos - $spos;
+                            $charsLeft = $numChars - ( $asciiEncoding ? $bytesRead : ( $bytesRead / 2 ) );
+                            $spos      = $limitpos;
+
+                            while ($charsLeft > 0) {
+                                $opcode    = $this->_getInt2d($spos);
+                                $conlength = $this->_getInt2d($spos + 2);
+                                if ($opcode !== 0x3c) {
+                                    return - 1;
+                                }
+                                $spos     += 4;
+                                $limitpos = $spos + $conlength;
+                                $option   = ord($this->data[ $spos ]);
+                                $spos ++;
+                                if ($asciiEncoding && ( $option === 0 )) {
+                                    $len           = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
+                                    $retstr        .= substr($this->data, $spos, $len);
+                                    $charsLeft     -= $len;
+                                    $asciiEncoding = true;
+                                } elseif (! $asciiEncoding && ( $option !== 0 )) {
+                                    $len           = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
+                                    $retstr        .= substr($this->data, $spos, $len);
+                                    $charsLeft     -= $len / 2;
+                                    $asciiEncoding = false;
+                                } elseif (! $asciiEncoding && ( $option === 0 )) {
+                                    // Bummer - the string starts off as Unicode, but after the
+                                    // continuation it is in straightforward ASCII encoding
+                                    $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
+                                    for ($j = 0; $j < $len; $j ++) {
+                                        $retstr .= $this->data[ $spos + $j ] . chr(0);
+                                    }
+                                    $charsLeft     -= $len;
+                                    $asciiEncoding = false;
+                                } else {
+                                    $newstr = '';
+                                    for ($j = 0, $len_retstr = strlen($retstr); $j < $len_retstr; $j ++) {
+                                        $newstr = $retstr[ $j ] . chr(0);
+                                    }
+                                    $retstr        = $newstr;
+                                    $len           = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
+                                    $retstr        .= substr($this->data, $spos, $len);
+                                    $charsLeft     -= $len / 2;
+                                    $asciiEncoding = false;
+                                    //echo "Izavrat\n";
+                                }
+                                $spos += $len;
+                            }
+                        }
+                        $retstr = $asciiEncoding ? $this->_latin1toDef($retstr) : $this->_UTF16toDef($retstr);
+//                                              echo "Str $i = $retstr\n";
+                        if ($richString) {
+                            $spos += 4 * $formattingRuns;
+                        }
+
+                        // For extended strings, skip over the extended string data
+                        if ($extendedString) {
+                            $spos += $extendedRunLength;
+                        }
+                        //if ($retstr == 'Derby'){
+                        //      echo "bb\n";
+                        //}
+                        $this->sst[] = $retstr;
+                    }
+                    /*$continueRecords = array();
+                    while ($this->getNextCode() == Type_CONTINUE) {
+                        $continueRecords[] = &$this->nextRecord();
+                    }
+                    //echo " 1 Type_SST\n";
+                    $this->shareStrings = new SSTRecord($r, $continueRecords);
+                    //print_r($this->shareStrings->strings);
+                     */
+                    // echo 'SST read: '.($time_end-$time_start)."\n";
+                    break;
+
+                case self::TYPE_FILEPASS:
+                    return false;
+                case self::TYPE_NAME:
+                    //echo "Type_NAME\n";
+                    break;
+                case self::TYPE_FORMAT:
+                    $indexCode = $this->_getInt2d($pos + 4);
+
+                    if ($version === self::BIFF8) {
+                        $numchars = $this->_getInt2d($pos + 6);
+                        if (ord($this->data[ $pos + 8 ]) === 0) { // ascii
+                            $formatString = substr($this->data, $pos + 9, $numchars);
+                            $formatString = $this->_latin1toDef($formatString);
+                        } else {
+                            $formatString = substr($this->data, $pos + 9, $numchars * 2);
+                            $formatString = $this->_UTF16toDef($formatString);
+                        }
+                    } else {
+                        $numchars     = ord($this->data[ $pos + 6 ]);
+                        $formatString = substr($this->data, $pos + 7, $numchars * 2);
+                        $formatString = $this->_latin1toDef($formatString);
+                    }
+
+                    $this->formatRecords[ $indexCode ] = $formatString;
+//                  echo "Type.FORMAT[$indexCode]=$formatString\n";
+                    break;
+                case self::TYPE_XF:
+                    $formatstr = '';
+                    $indexCode = $this->_getInt2d($pos + 6);
+//                  echo "\nType.XF code=".$indexCode." dateFormat=".$this->dateFormats[ $indexCode ]." numberFormats=".$this->numberFormats[ $indexCode ].PHP_EOL;
+                    if (array_key_exists($indexCode, $this->dateFormats)) {
+                        //echo "isdate ".$dateFormats[$indexCode];
+                        $this->formatRecords['xfrecords'][] = array(
+                            'type'   => 'date',
+                            'format' => $this->dateFormats[ $indexCode ]
+                        );
+                    } elseif (array_key_exists($indexCode, $this->numberFormats)) {
+                        //echo "isnumber ".$this->numberFormats[$indexCode];
+                        $this->formatRecords['xfrecords'][] = array(
+                            'type'   => 'number',
+                            'format' => $this->numberFormats[ $indexCode ]
+                        );
+                    } else {
+                        $isdate = false;
+                        if ($indexCode > 0) {
+                            if (isset($this->formatRecords[ $indexCode ])) {
+//                              die( 'L:'.__LINE__ );
+                                $formatstr = $this->formatRecords[ $indexCode ];
+                            }
+                            //echo '.other.';
+//                          echo "\nfl=".strlen( $formatstr)." fs=$formatstr=\n";
+//                          echo "\ncode=".$indexCode." fl=".strlen( $formatstr)." fs=$formatstr=\n";
+                            $fs = str_replace('\\', '', $formatstr);
+                            if ($fs && preg_match('/^[hmsday\/\-:\., ]+$/i', $fs)) { // found day and time format
+                                $isdate    = true;
+                                $formatstr = str_replace(array( 'yyyy',':mm','mm','dddd','dd', 'h','ss' ), array('Y',':i','m','l','d', 'H','s' ), $fs);
+                            }
+                        }
+
+                        if ($isdate) {
+                            $this->formatRecords['xfrecords'][] = array(
+                                'type'   => 'date',
+                                'format' => $formatstr,
+                                'code'   => $indexCode
+                            );
+                        } else {
+//                          echo 'fs='.$formatstr.PHP_EOL;
+                            $this->formatRecords['xfrecords'][] = array(
+                                'type'   => 'other',
+                                'format' => '',
+                                'code'   => $indexCode
+                            );
+                        }
+                    }
+//                  echo count( $this->formatRecords['xfrecords'] ).' fs='.$formatstr.' ' . PHP_EOL;
+                    //echo "\n";
+                    break;
+                case self::TYPE_NINETEENFOUR:
+                    //echo "Type.NINETEENFOUR\n";
+                    $this->nineteenFour = ( ord($this->data[ $pos + 4 ]) === 1 );
+                    break;
+                case self::TYPE_BOUNDSHEET:
+                    //echo "Type.BOUNDSHEET\n";
+                    $rec_offset = $this->_getInt4d($pos + 4);
+//                  $rec_typeFlag = ord($this->_data[$pos + 8]);
+                    $rec_length = ord($this->data[ $pos + 10 ]);
+                    $hidden = false;
+                    $rec_name   = '';
+                    if ($version === self::BIFF8) {
+                        //ord($this->data[$pos + 9])
+                        $hidden = ord($this->data[$pos + 8]) === 1;
+                        $chartype = ord($this->data[ $pos + 11 ]);
+                        if ($chartype === 0) {
+                            $rec_name = substr($this->data, $pos + 12, $rec_length);
+                            $rec_name = $this->_latin1toDef($rec_name);
+                        } else {
+                            $rec_name = substr($this->data, $pos + 12, $rec_length * 2);
+                            $rec_name = $this->_UTF16toDef($rec_name);
+                        }
+                    } elseif ($version === self::BIFF7) {
+                        $rec_name = substr($this->data, $pos + 11, $rec_length);
+                    }
+                    $this->boundsheets[] = array(
+                        'name'   => $rec_name,
+                        'offset' => $rec_offset,
+                        'hidden' => $hidden,
+                        'active' => false
+                    );
+
+                    break;
+
+                case self::TYPE_WINDOW1:
+                    $this->activeSheet = $this->_getInt2d($pos + 14);
+                    break;
+            }
+
+            //echo "Code = ".base_convert($r['code'],10,16)."\n";
+            $pos    += $length + 4;
+            $code   = $this->_getInt2d($pos);
+            $length = $this->_getInt2d($pos + 2);
+
+            //$r = &$this->nextRecord();
+            //echo "1 Code = ".base_convert($r['code'],10,16)."\n";
+        }
+
+        foreach ($this->boundsheets as $key => $val) {
+            $this->sn = $key;
+            $this->_parseSheet($val['offset']);
+            if ($key === $this->activeSheet) {
+                $this->boundsheets[ $key ]['active'] = true;
+            }
+        }
+
+        return true;
+    }
+    protected function _latin1toDef($string)
+    {
+        $result = $string;
+        if ($this->defaultEncoding) {
+            $result = mb_convert_encoding($string, $this->defaultEncoding, 'ISO-8859-1');
+        }
+
+        return $result;
+    }
+    protected function _UTF16toDef($string)
+    {
+        $result = $string;
+        if ($this->defaultEncoding && $this->defaultEncoding !== 'UTF-16LE') {
+            $result = mb_convert_encoding($string, $this->defaultEncoding, 'UTF-16LE');
+        }
+
+        return $result;
+    }
+
+    protected function _parseSheet($spos): bool
+    {
+        $cont = true;
+        // read BOF
+//      $code = ord($this->_data[$spos]) | ord($this->_data[$spos + 1]) << 8;
+        [$length, $version, $substreamType] = $this->parseSubstreamHeader($spos);
+
+        if (( $version !== self::BIFF8 ) && ( $version !== self::BIFF7 )) {
+            return false;
+        }
+
+        if ($substreamType !== self::WORKSHEET) {
+            return false;
+        }
+        //echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
+        $spos += $length + 4;
+        //var_dump($this->formatRecords);
+        //echo "code $code $length";
+
+        $this->sheets[ $this->sn ]['maxrow'] = 0;
+        $this->sheets[ $this->sn ]['maxcol'] = 0;
+        $this->sheets[ $this->sn ]['numRows'] = 0;
+        $this->sheets[ $this->sn ]['numCols'] = 0;
+
+        while ($cont) {
+            //echo "mem= ".memory_get_usage()."\n";
+//            $r = &$this->file->nextRecord();
+            $lowcode = ord($this->data[ $spos ]);
+            if ($lowcode === self::TYPE_EOF) {
+                break;
+            }
+            $t_code                                = $lowcode | ord($this->data[ $spos + 1 ]) << 8;
+            $length                              = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+            $spos                                += 4;
+
+            //echo "Code=".base_convert($code,10,16)." $code\n";
+            $this->multiplier = 1; // need for format with %
+            switch ($t_code) {
+                case self::TYPE_DIMENSION:
+                    //echo 'Type_DIMENSION ';
+                    if (!isset($this->numRows)) {
+                        if (( $length === 10 ) || ( $version === self::BIFF7 )) {
+                            $this->sheets[ $this->sn ]['numRows'] = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+                            $this->sheets[ $this->sn ]['numCols'] = ord($this->data[ $spos + 6 ]) | ord($this->data[ $spos + 7 ]) << 8;
+                        } else {
+                            $this->sheets[ $this->sn ]['numRows'] = ord($this->data[ $spos + 4 ]) | ord($this->data[ $spos + 5 ]) << 8;
+                            $this->sheets[ $this->sn ]['numCols'] = ord($this->data[ $spos + 10 ]) | ord($this->data[ $spos + 11 ]) << 8;
+                        }
+                    }
+                    //echo 'numRows '.$this->numRows.' '.$this->numCols."\n";
+                    break;
+                case self::TYPE_MERGEDCELLS:
+                    $cellRanges = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                    for ($i = 0; $i < $cellRanges; $i ++) {
+                        $fr = ord($this->data[ $spos + 8 * $i + 2 ]) | ord($this->data[ $spos + 8 * $i + 3 ]) << 8;
+                        $lr = ord($this->data[ $spos + 8 * $i + 4 ]) | ord($this->data[ $spos + 8 * $i + 5 ]) << 8;
+                        $fc = ord($this->data[ $spos + 8 * $i + 6 ]) | ord($this->data[ $spos + 8 * $i + 7 ]) << 8;
+                        $lc = ord($this->data[ $spos + 8 * $i + 8 ]) | ord($this->data[ $spos + 8 * $i + 9 ]) << 8;
+                        //$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1);
+                        if ($lr - $fr > 0) {
+                            $this->sheets[ $this->sn ]['cellsInfo'][ $fr + 1 ][ $fc + 1 ]['rowspan'] = $lr - $fr + 1;
+                        }
+                        if ($lc - $fc > 0) {
+                            $this->sheets[ $this->sn ]['cellsInfo'][ $fr + 1 ][ $fc + 1 ]['colspan'] = $lc - $fc + 1;
+                        }
+                    }
+                    //echo "Merged Cells $cellRanges $lr $fr $lc $fc\n";
+                    break;
+                case self::TYPE_RK:
+                case self::TYPE_RK2:
+                    //echo 'self::TYPE_RK'."\n";
+                    $row      = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                    $column   = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+                    $rknum    = $this->_getInt4d($spos + 6);
+                    $numValue = $this->_getIEEE754($rknum);
+                    //echo $numValue." ";
+                    $t_alias = 'n';
+                    if ($this->isDate($spos)) {
+                        [$string, $raw] = $this->createDate($numValue);
+                        $t_alias = 'd';
+                    } else {
+                        $raw = $numValue;
+                        if (isset($this->columnsFormat[ $column + 1 ])) {
+                            $this->curFormat = $this->columnsFormat[ $column + 1 ];
+                        }
+                        $string = sprintf($this->curFormat, $numValue * $this->multiplier);
+                        //$this->addcell(RKRecord($r));
+                    }
+                    $this->addCell($row, $column, $string, $raw, $t_code, $t_alias);
+                    //echo "Type_RK $row $column $string $raw {$this->curformat}\n";
+                    break;
+                case self::TYPE_LABELSST:
+                    $row    = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                    $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+//                  $xfindex = ord($this->_data[$spos + 4]) | ord($this->_data[$spos + 5]) << 8;
+                    $index = $this->_getInt4d($spos + 6);
+                    //var_dump($this->sst);
+                    $this->addCell($row, $column, $this->sst[ $index ], $index, $t_code, 's');
+                    //echo "LabelSST $row $column $string\n";
+                    break;
+                case self::TYPE_MULRK:
+                    $row      = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                    $colFirst = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+                    $colLast  = ord($this->data[ $spos + $length - 2 ]) | ord($this->data[ $spos + $length - 1 ]) << 8;
+                    $columns  = $colLast - $colFirst + 1;
+                    $tmppos   = $spos + 4;
+                    $t_alias = 'n';
+                    for ($i = 0; $i < $columns; $i ++) {
+                        $numValue = $this->_getIEEE754($this->_getInt4d($tmppos + 2));
+                        if ($this->isDate($tmppos - 4)) {
+                            [$string, $raw] = $this->createDate($numValue);
+                            $t_alias = 'd';
+                        } else {
+                            $raw = $numValue;
+                            if (isset($this->columnsFormat[ $colFirst + $i + 1 ])) {
+                                $this->curFormat = $this->columnsFormat[ $colFirst + $i + 1 ];
+                            }
+                            $string = sprintf($this->curFormat, $numValue * $this->multiplier);
+                        }
+                        //$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8;
+                        $tmppos += 6;
+                        $this->addCell($row, $colFirst + $i, $string, $raw, $t_code, $t_alias);
+                        //echo "MULRK $row ".($colFirst + $i)." $string\n";
+                    }
+                    //MulRKRecord($r);
+                    // Get the individual cell records from the multiple record
+                    //$num = ;
+
+                    break;
+                case self::TYPE_NUMBER:
+                    $row    = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                    $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+                    $tmp    = unpack('ddouble', substr($this->data, $spos + 6, 8)); // It machine machine dependent
+                    $t_alias = 'n';
+                    if ($this->isDate($spos)) {
+                        [$string, $raw] = $this->createDate($tmp['double']);
+                        $t_alias = 'd';
+                        //   $this->addcell(DateRecord($r, 1));
+                    } else {
+                        //$raw = $tmp[''];
+                        if (isset($this->columnsFormat[ $column + 1 ])) {
+                            $this->curFormat = $this->columnsFormat[ $column + 1 ];
+                        }
+                        $raw    = $this->createNumber($spos);
+                        $string = sprintf($this->curFormat, $raw * $this->multiplier);
+
+                        //   $this->addcell(NumberRecord($r));
+                    }
+                    $this->addCell($row, $column, $string, $raw, $t_code, $t_alias);
+                    //echo "Number $row $column $string\n";
+                    break;
+                case self::TYPE_FORMULA:
+                case self::TYPE_FORMULA2:
+                    $row    = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8;
+                    $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8;
+                    /*
+    $byte6 = ord($this->_data[$spos + 6]);
+    $byte12 = ord($this->_data[$spos + 12]);
+    $byte13 = ord($this->_data[$spos + 13]);
+    if ( $byte6 === 0 && $byte12 === 255 && $byte13 === 255 ) {
+    //String formula. Result follows in a STRING record
+    //echo "FORMULA $row $column Formula with a string<br>\n";
+    } else if ($byte6 === 1 && $byte12 === 255 && $byte13 === 255 ) {
+    //Boolean formula. Result is in +2; 0=false,1=true
+    } else if ($byte6 === 2 && $byte12 === 255 && $byte13 === 255) {
+    //Error formula. Error code is in +2;
+    } else if ( $byte6 === 3 && $byte12 === 255 && $byte13 === 255) {
+    //Formula result is a null string.
+    */
+                    if (! ( ord($this->data[ $spos + 6 ]) < 4 && ord($this->data[ $spos + 12 ]) === 255 && ord($this->data[ $spos + 13 ]) === 255 )) {
+                        // result is a number, so first 14 bytes are just like a _NUMBER record
+                        $tmp = unpack('ddouble', substr($this->data, $spos + 6, 8)); // It machine machine dependent
+                        if ($this->isDate($spos)) {
+                            [$string, $raw] = $this->createDate($tmp['double']);
+                            //   $this->addcell(DateRecord($r, 1));
+                        } else {
+                            //$raw = $tmp[''];
+                            if (isset($this->columnsFormat[ $column + 1 ])) {
+                                $this->curFormat = $this->columnsFormat[ $column + 1 ];
+                            }
+                            $raw    = $this->createNumber($spos);
+                            $string = sprintf($this->curFormat, $raw * $this->multiplier);
+
+                            //   $this->addcell(NumberRecord($r));
+                        }
+                        $this->addCell($row, $column, $string, $raw, $t_code, 'f');
+                        //echo "Number $row $column $string\n";
+                    }
+                    break;
+                case self::TYPE_BOOLERR:
+                    $row    = $this->_getInt2d($spos);
+                    $column = $this->_getInt2d($spos + 2);
+                    $string = ord($this->data[ $spos + 6 ]);
+                    $this->addCell($row, $column, $string, $string, $t_code, 'b');
+                    //echo 'Type_BOOLERR '."\n";
+                    break;
+                case self::TYPE_ROW:
+                case self::TYPE_DBCELL:
+                case self::TYPE_MULBLANK:
+                    break;
+                case self::TYPE_LABEL:
+                    $row    = $this->_getInt2d($spos);
+                    $column = $this->_getInt2d($spos);
+                    $string = substr($this->data, $spos + 8, ord($this->data[ $spos + 6 ]) | ord($this->data[ $spos + 7 ]) << 8);
+                    $this->addCell($row, $column, $string, '', $t_code, 'inlineStr');
+
+                    // $this->addcell(LabelRecord($r));
+                    break;
+
+                case self::TYPE_EOF:
+                    $cont = false;
+                    break;
+                default:
+                    //echo ' unknown :'.base_convert($r['code'],10,16)."\n";
+                    break;
+            }
+            $spos += $length;
+        }
+
+        if ($this->sheets[ $this->sn ]['numRows'] === 0) {
+            $this->sheets[ $this->sn ]['numRows'] = $this->sheets[ $this->sn ]['maxrow'];
+        }
+        if ($this->sheets[ $this->sn ]['numCols'] === 0) {
+            $this->sheets[ $this->sn ]['numCols'] = $this->sheets[ $this->sn ]['maxcol'];
+        }
+
+        return true;
+    }
+
+    //}}}
+    //{{{ createDate()
+
+    protected function _getIEEE754($rknum)
+    {
+        if (( $rknum & 0x02 ) !== 0) {
+            $value = $rknum >> 2;
+        } else {
+//mmp
+// first comment out the previously existing 7 lines of code here
+//                $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc)));
+//                //$value = $tmp[''];
+//                if (array_key_exists(1, $tmp)) {
+//                    $value = $tmp[1];
+//                } else {
+//                    $value = $tmp[''];
+//                }
+// I got my info on IEEE754 encoding from
+// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
+// The RK format calls for using only the most significant 30 bits of the
+// 64 bit floating point value. The other 34 bits are assumed to be 0
+// So, we use the upper 30 bits of $rknum as follows...
+            $sign     = ( $rknum & 0x80000000 ) >> 31;
+            $exp      = ( $rknum & 0x7ff00000 ) >> 20;
+            $mantissa = ( 0x100000 | ( $rknum & 0x000ffffc ) );
+            $value    = $mantissa / (2 ** (20 - ($exp - 1023)));
+            if ($sign) {
+                $value = - 1 * $value;
+            }
+//end of changes by mmp
+        }
+
+        if (( $rknum & 0x01 ) !== 0) {
+            $value /= 100;
+        }
+
+        return $value;
+    }
+
+    protected function isDate($spos): bool
+    {
+        //$xfindex = GetInt2d(, 4);
+        $xfindex = ord($this->data[ $spos + 4 ]) | ord($this->data[ $spos + 5 ]) << 8;
+//      echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']." ".$this->formatRecords['xfrecords'][ $xfindex ]['format']."\n";
+
+
+
+        if ($this->formatRecords['xfrecords'][ $xfindex ]['type'] === 'date') {
+            $this->curFormat = $this->formatRecords['xfrecords'][ $xfindex ]['format'];
+
+            return true;
+        }
+
+        if ($this->formatRecords['xfrecords'][ $xfindex ]['type'] === 'number') {
+            $this->curFormat = $this->formatRecords['xfrecords'][ $xfindex ]['format'];
+            if (strpos($this->curFormat, '%%') !== false) {
+                $this->multiplier = 100;
+            }
+        } else {
+            $this->curFormat = $this->defaultFormat;
+        }
+
+        return false;
+    }
+
+    /**
+     * Convert the raw Excel date into a human readable format
+     *
+     * Dates in Excel are stored as number of seconds from an epoch.  On
+     * Windows, the epoch is 30/12/1899 and on Mac it's 01/01/1904
+     *
+     * @param integer $timevalue The raw Excel value to convert
+     *
+     * @return array First element is the converted date, the second element is number a unix timestamp
+     */
+    public function createDate(int $timevalue): array
+    {
+//      $offset = ($timeoffset===null)? date('Z') : $timeoffset * 3600;
+        if ($timevalue > 1) {
+            $timevalue -= ( $this->nineteenFour ? 24107 : 25569 );
+        }
+        $ts = round($timevalue * 24 * 3600);
+        $string = $this->datetimeFormat ? gmdate($this->datetimeFormat, $ts) : gmdate($this->curFormat, $ts);
+        return array( $string, $ts );
+    }
+
+    protected function addCell($row, $col, $string, $raw = '', $type_code = 0, $type_alias = ''): void
+    {
+        //echo "ADD cel $row-$col $string\n";
+        $this->sheets[ $this->sn ]['maxrow'] = max($this->sheets[ $this->sn ]['maxrow'], $row);
+        $this->sheets[ $this->sn ]['maxcol'] = max($this->sheets[ $this->sn ]['maxcol'], $col);
+        $this->sheets[ $this->sn ]['cells'][ $row ][ $col ] = $string;
+        if ($raw) {
+            $this->sheets[ $this->sn ]['cellsInfo'][ $row ][ $col ]['raw'] = $raw;
+        }
+        if ($type_code) {
+            $this->sheets[$this->sn]['cellsInfo'][$row][$col]['type'] = $type_code;
+            $this->sheets[$this->sn]['cellsInfo'][$row][$col]['t'] = $type_alias;
+        }
+    }
+
+    protected function createNumber($spos)
+    {
+        $rknumhigh = $this->_getInt4d($spos + 10);
+        $rknumlow  = $this->_getInt4d($spos + 6);
+        //for ($i=0; $i<8; $i++) { echo ord($this->_data[$i+$spos+6]) . " "; } echo "<br>";
+        $sign         = ( $rknumhigh & 0x80000000 ) >> 31;
+        $exp          = ( $rknumhigh & 0x7ff00000 ) >> 20;
+        $mantissa     = ( 0x100000 | ( $rknumhigh & 0x000fffff ) );
+        $mantissalow1 = ( $rknumlow & 0x80000000 ) >> 31;
+        $mantissalow2 = ( $rknumlow & 0x7fffffff );
+        $value        = $mantissa / (2 ** (20 - ($exp - 1023)));
+        if ($mantissalow1 !== 0) {
+            $value += 1 / (2 ** (21 - ($exp - 1023)));
+        }
+        $value += $mantissalow2 / (2 ** (52 - ($exp - 1023)));
+        //echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2<br>\n";
+        if ($sign) {
+            $value = - 1 * $value;
+        }
+
+        return $value;
+    }
+
+    /**
+     * Set the encoding method
+     *
+     * @param string $encoding Encoding to use
+     *
+     * @access public
+     */
+    public function setOutputEncoding(string $encoding): SimpleXLS
+    {
+        $this->defaultEncoding = $encoding;
+        return $this;
+    }
+
+
+    /**
+     * Set the default number format, ex. "%.2f"
+     *
+     * @access public
+     *
+     * @param string $sFormat Default  format
+     */
+    public function setDefaultFormat(string $sFormat): SimpleXLS
+    {
+        $this->defaultFormat = $sFormat;
+        return $this;
+    }
+
+    /**
+     * Force a column to use a certain format
+     *
+     * @access public
+     *
+     * @param integer $column Column number
+     * @param string $sFormat Format
+     */
+    public function setColumnFormat(int $column, string $sFormat): SimpleXLS
+    {
+        $this->columnsFormat[ $column ] = $sFormat;
+        return $this;
+    }
+
+}

+ 1188 - 0
core/class/simpleXLSX.class.php

@@ -0,0 +1,1188 @@
+<?php
+
+/**
+ *    SimpleXLSX php class
+ *    MS Excel 2007+ workbooks reader
+ *
+ * Copyright (c) 2012 - 2022 SimpleXLSX
+ *
+ * @category   SimpleXLSX
+ * @package    SimpleXLSX
+ * @copyright  Copyright (c) 2012 - 2022 SimpleXLSX (https://github.com/shuchkin/simplexlsx/)
+ * @license    MIT
+ */
+
+/** Examples
+ *
+ * use Shuchkin\SimpleXLSX;
+ *
+ * Example 1:
+ * if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
+ *   foreach ($xlsx->rows() as $r) {
+ *     print_r( $r );
+ *   }
+ * } else {
+ *   echo SimpleXLSX::parseError();
+ * }
+ *
+ * Example 2: html table
+ * if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
+ *   echo $xlsx->toHTML();
+ * } else {
+ *   echo SimpleXLSX::parseError();
+ * }
+ *
+ * Example 3: rowsEx
+ * $xlsx = SimpleXLSX::parse('book.xlsx');
+ * foreach ( $xlsx->rowsEx() as $r ) {
+ *   print_r( $r );
+ * }
+ *
+ * Example 4: select worksheet
+ * $xlsx = SimpleXLSX::parse('book.xlsx');
+ * foreach( $xlsx->rows(1) as $r  ) { // second worksheet
+ *   print_t( $r );
+ * }
+ *
+ * Example 5: IDs and worksheet names
+ * $xlsx = SimpleXLSX::parse('book.xlsx');
+ * print_r( $xlsx->sheetNames() ); // array( 0 => 'Sheet 1', 1 => 'Catalog' );
+ *
+ * Example 6: get sheet name by index
+ * $xlsx = SimpleXLSX::parse('book.xlsx');
+ * echo 'Sheet Name 2 = '.$xlsx->sheetName(1);
+ *
+ * Example 7: getCell (very slow)
+ * echo $xlsx->getCell(1,'D12'); // reads D12 cell from second sheet
+ *
+ * Example 8: read data
+ * if ( $xlsx = SimpleXLSX::parseData( file_get_contents('http://www.example.com/example.xlsx') ) ) {
+ *   $dim = $xlsx->dimension(1);
+ *   $num_cols = $dim[0];
+ *   $num_rows = $dim[1];
+ *   echo $xlsx->sheetName(1).':'.$num_cols.'x'.$num_rows;
+ * } else {
+ *   echo SimpleXLSX::parseError();
+ * }
+ *
+ * Example 9: old style
+ * $xlsx = new SimpleXLSX('book.xlsx');
+ * if ( $xlsx->success() ) {
+ *   print_r( $xlsx->rows() );
+ * } else {
+ *   echo 'xlsx error: '.$xlsx->error();
+ * }
+ */
+class simpleXLSX {
+
+    public static $CF = [// Cell formats
+        0 => 'General',
+        1 => '0',
+        2 => '0.00',
+        3 => '#,##0',
+        4 => '#,##0.00',
+        9 => '0%',
+        10 => '0.00%',
+        11 => '0.00E+00',
+        12 => '# ?/?',
+        13 => '# ??/??',
+        14 => 'mm-dd-yy',
+        15 => 'd-mmm-yy',
+        16 => 'd-mmm',
+        17 => 'mmm-yy',
+        18 => 'h:mm AM/PM',
+        19 => 'h:mm:ss AM/PM',
+        20 => 'h:mm',
+        21 => 'h:mm:ss',
+        22 => 'm/d/yy h:mm',
+        37 => '#,##0 ;(#,##0)',
+        38 => '#,##0 ;[Red](#,##0)',
+        39 => '#,##0.00;(#,##0.00)',
+        40 => '#,##0.00;[Red](#,##0.00)',
+        44 => '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
+        45 => 'mm:ss',
+        46 => '[h]:mm:ss',
+        47 => 'mmss.0',
+        48 => '##0.0E+0',
+        49 => '@',
+        27 => '[$-404]e/m/d',
+        30 => 'm/d/yy',
+        36 => '[$-404]e/m/d',
+        50 => '[$-404]e/m/d',
+        57 => '[$-404]e/m/d',
+        59 => 't0',
+        60 => 't0.00',
+        61 => 't#,##0',
+        62 => 't#,##0.00',
+        67 => 't0%',
+        68 => 't0.00%',
+        69 => 't# ?/?',
+        70 => 't# ??/??',
+    ];
+    public $nf = []; // number formats
+    public $cellFormats = []; // cellXfs
+    public $datetimeFormat = 'Y-m-d H:i:s';
+    public $debug;
+    public $activeSheet = 0;
+    public $rowsExReader;
+
+    /* @var SimpleXMLElement[] $sheets */
+    protected $sheets;
+    protected $sheetNames = [];
+    protected $sheetFiles = [];
+    // scheme
+    public $styles;
+    protected $hyperlinks;
+    /* @var array[] $package */
+    protected $package;
+    protected $sharedstrings;
+    protected $date1904 = 0;
+
+
+    /*
+      private $date_formats = array(
+      0xe => "d/m/Y",
+      0xf => "d-M-Y",
+      0x10 => "d-M",
+      0x11 => "M-Y",
+      0x12 => "h:i a",
+      0x13 => "h:i:s a",
+      0x14 => "H:i",
+      0x15 => "H:i:s",
+      0x16 => "d/m/Y H:i",
+      0x2d => "i:s",
+      0x2e => "H:i:s",
+      0x2f => "i:s.S"
+      );
+      private $number_formats = array(
+      0x1 => "%1.0f",     // "0"
+      0x2 => "%1.2f",     // "0.00",
+      0x3 => "%1.0f",     //"#,##0",
+      0x4 => "%1.2f",     //"#,##0.00",
+      0x5 => "%1.0f",     //"$#,##0;($#,##0)",
+      0x6 => '$%1.0f',    //"$#,##0;($#,##0)",
+      0x7 => '$%1.2f',    //"$#,##0.00;($#,##0.00)",
+      0x8 => '$%1.2f',    //"$#,##0.00;($#,##0.00)",
+      0x9 => '%1.0f%%',   //"0%"
+      0xa => '%1.2f%%',   //"0.00%"
+      0xb => '%1.2f',     //"0.00E00",
+      0x25 => '%1.0f',    //"#,##0;(#,##0)",
+      0x26 => '%1.0f',    //"#,##0;(#,##0)",
+      0x27 => '%1.2f',    //"#,##0.00;(#,##0.00)",
+      0x28 => '%1.2f',    //"#,##0.00;(#,##0.00)",
+      0x29 => '%1.0f',    //"#,##0;(#,##0)",
+      0x2a => '$%1.0f',   //"$#,##0;($#,##0)",
+      0x2b => '%1.2f',    //"#,##0.00;(#,##0.00)",
+      0x2c => '$%1.2f',   //"$#,##0.00;($#,##0.00)",
+      0x30 => '%1.0f');   //"##0.0E0";
+      // }}}
+     */
+    protected $errno = 0;
+    protected $error = false;
+
+    /**
+     * @var false|SimpleXMLElement
+     */
+    public $theme;
+
+    public function __construct($filename = null, $is_data = null, $debug = null) {
+        if ($debug !== null) {
+            $this->debug = $debug;
+        }
+        $this->package = [
+            'filename' => '',
+            'mtime' => 0,
+            'size' => 0,
+            'comment' => '',
+            'entries' => []
+        ];
+        if ($filename && $this->_unzip($filename, $is_data)) {
+            $this->_parse();
+        }
+    }
+
+    protected function _unzip($filename, $is_data = false) {
+
+        if ($is_data) {
+            $this->package['filename'] = 'default.xlsx';
+            $this->package['mtime'] = time();
+            $this->package['size'] = $this->_strlen($filename);
+
+            $vZ = $filename;
+        } else {
+            if (!is_readable($filename)) {
+                $this->error(1, 'File not found ' . $filename);
+
+                return false;
+            }
+
+            // Package information
+            $this->package['filename'] = $filename;
+            $this->package['mtime'] = filemtime($filename);
+            $this->package['size'] = filesize($filename);
+
+            // Read file
+            $vZ = file_get_contents($filename);
+        }
+        // Cut end of central directory
+        /*      $aE = explode("\x50\x4b\x05\x06", $vZ);
+          if (count($aE) == 1) {
+          $this->error('Unknown format');
+          return false;
+          }
+         */
+        // Explode to each part
+        $aE = explode("\x50\x4b\x03\x04", $vZ);
+        array_shift($aE);
+
+        $aEL = count($aE);
+        if ($aEL === 0) {
+            $this->error(2, 'Unknown archive format');
+
+            return false;
+        }
+        // Search central directory end record
+        $last = $aE[$aEL - 1];
+        $last = explode("\x50\x4b\x05\x06", $last);
+        if (count($last) !== 2) {
+            $this->error(2, 'Unknown archive format');
+
+            return false;
+        }
+        // Search central directory
+        $last = explode("\x50\x4b\x01\x02", $last[0]);
+        if (count($last) < 2) {
+            $this->error(2, 'Unknown archive format');
+
+            return false;
+        }
+        $aE[$aEL - 1] = $last[0];
+
+        // Loop through the entries
+        foreach ($aE as $vZ) {
+            $aI = [];
+            $aI['E'] = 0;
+            $aI['EM'] = '';
+            // Retrieving local file header information
+//          $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL', $vZ);
+            $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL/v1EFL', $vZ);
+
+            // Check if data is encrypted
+//          $bE = ($aP['GPF'] && 0x0001) ? TRUE : FALSE;
+//          $bE = false;
+            $nF = $aP['FNL'];
+            $mF = $aP['EFL'];
+
+            // Special case : value block after the compressed data
+            if ($aP['GPF'] & 0x0008) {
+                $aP1 = unpack('V1CRC/V1CS/V1UCS', $this->_substr($vZ, -12));
+
+                $aP['CRC'] = $aP1['CRC'];
+                $aP['CS'] = $aP1['CS'];
+                $aP['UCS'] = $aP1['UCS'];
+                // 2013-08-10
+                $vZ = $this->_substr($vZ, 0, -12);
+                if ($this->_substr($vZ, -4) === "\x50\x4b\x07\x08") {
+                    $vZ = $this->_substr($vZ, 0, -4);
+                }
+            }
+
+            // Getting stored filename
+            $aI['N'] = $this->_substr($vZ, 26, $nF);
+            $aI['N'] = str_replace('\\', '/', $aI['N']);
+
+            if ($this->_substr($aI['N'], -1) === '/') {
+                // is a directory entry - will be skipped
+                continue;
+            }
+
+            // Truncate full filename in path and filename
+            $aI['P'] = dirname($aI['N']);
+            $aI['P'] = ($aI['P'] === '.') ? '' : $aI['P'];
+            $aI['N'] = basename($aI['N']);
+
+            $vZ = $this->_substr($vZ, 26 + $nF + $mF);
+
+            if ($this->_strlen($vZ) !== (int) $aP['CS']) { // check only if availabled
+                $aI['E'] = 1;
+                $aI['EM'] = 'Compressed size is not equal with the value in header information.';
+            }
+//          } elseif ( $bE ) {
+//              $aI['E']  = 5;
+//              $aI['EM'] = 'File is encrypted, which is not supported from this class.';
+            /*            } else {
+              switch ($aP['CM']) {
+              case 0: // Stored
+              // Here is nothing to do, the file ist flat.
+              break;
+              case 8: // Deflated
+              $vZ = gzinflate($vZ);
+              break;
+              case 12: // BZIP2
+              if (extension_loaded('bz2')) {
+              $vZ = bzdecompress($vZ);
+              } else {
+              $aI['E'] = 7;
+              $aI['EM'] = 'PHP BZIP2 extension not available.';
+              }
+              break;
+              default:
+              $aI['E'] = 6;
+              $aI['EM'] = "De-/Compression method {$aP['CM']} is not supported.";
+              }
+              if (!$aI['E']) {
+              if ($vZ === false) {
+              $aI['E'] = 2;
+              $aI['EM'] = 'Decompression of data failed.';
+              } elseif ($this->_strlen($vZ) !== (int)$aP['UCS']) {
+              $aI['E'] = 3;
+              $aI['EM'] = 'Uncompressed size is not equal with the value in header information.';
+              } elseif (crc32($vZ) !== $aP['CRC']) {
+              $aI['E'] = 4;
+              $aI['EM'] = 'CRC32 checksum is not equal with the value in header information.';
+              }
+              }
+              }
+             */
+
+            // DOS to UNIX timestamp
+            $aI['T'] = mktime(
+                    ($aP['FT'] & 0xf800) >> 11,
+                    ($aP['FT'] & 0x07e0) >> 5,
+                    ($aP['FT'] & 0x001f) << 1,
+                    ($aP['FD'] & 0x01e0) >> 5,
+                    $aP['FD'] & 0x001f,
+                    (($aP['FD'] & 0xfe00) >> 9) + 1980
+            );
+
+            $this->package['entries'][] = [
+                'data' => $vZ,
+                'ucs' => (int) $aP['UCS'], // ucompresses size
+                'cm' => $aP['CM'], // compressed method
+                'cs' => isset($aP['CS']) ? (int) $aP['CS'] : 0, // compresses size
+                'crc' => $aP['CRC'],
+                'error' => $aI['E'],
+                'error_msg' => $aI['EM'],
+                'name' => $aI['N'],
+                'path' => $aI['P'],
+                'time' => $aI['T']
+            ];
+        } // end for each entries
+
+        return true;
+    }
+
+    protected function _strlen($str) {
+        return (ini_get('mbstring.func_overload') & 2) ? mb_strlen($str, '8bit') : strlen($str);
+    }
+
+    public function error($num = null, $str = null) {
+        if ($num) {
+            $this->errno = $num;
+            $this->error = $str;
+            if ($this->debug) {
+                trigger_error(__CLASS__ . ': ' . $this->error, E_USER_WARNING);
+            }
+        }
+
+        return $this->error;
+    }
+
+    protected function _substr($str, $start, $length = null) {
+        return (ini_get('mbstring.func_overload') & 2) ? mb_substr($str, $start, ($length === null) ? mb_strlen($str, '8bit') : $length, '8bit') : substr($str, $start, ($length === null) ? strlen($str) : $length);
+    }
+
+    protected function _parse() {
+        // Document data holders
+        $this->sharedstrings = [];
+        $this->sheets = [];
+//      $this->styles = array();
+//        $m1 = 0; // memory_get_peak_usage( true );
+        // Read relations and search for officeDocument
+        if ($relations = $this->getEntryXML('_rels/.rels')) {
+            foreach ($relations->Relationship as $rel) {
+                $rel_type = basename(trim((string) $rel['Type'])); // officeDocument
+                $rel_target = $this->_getTarget('', (string) $rel['Target']); // /xl/workbook.xml or xl/workbook.xml
+
+                if ($rel_type === 'officeDocument' && $workbook = $this->getEntryXML($rel_target)) {
+                    $index_rId = []; // [0 => rId1]
+
+                    $index = 0;
+                    foreach ($workbook->sheets->sheet as $s) {
+                        $this->sheetNames[$index] = (string) $s['name'];
+                        $index_rId[$index] = (string) $s['id'];
+                        $index++;
+                    }
+                    if ((int) $workbook->workbookPr['date1904'] === 1) {
+                        $this->date1904 = 1;
+                    }
+
+
+                    if ($workbookRelations = $this->getEntryXML(dirname($rel_target) . '/_rels/workbook.xml.rels')) {
+                        // Loop relations for workbook and extract sheets...
+                        foreach ($workbookRelations->Relationship as $workbookRelation) {
+                            $wrel_type = basename(trim((string) $workbookRelation['Type'])); // worksheet
+                            $wrel_path = $this->_getTarget(dirname($rel_target), (string) $workbookRelation['Target']);
+                            if (!$this->entryExists($wrel_path)) {
+                                continue;
+                            }
+
+
+                            if ($wrel_type === 'worksheet') { // Sheets
+                                if ($sheet = $this->getEntryXML($wrel_path)) {
+                                    $index = array_search((string) $workbookRelation['Id'], $index_rId, true);
+                                    $this->sheets[$index] = $sheet;
+                                    $this->sheetFiles[$index] = $wrel_path;
+                                }
+                            } elseif ($wrel_type === 'sharedStrings') {
+                                if ($sharedStrings = $this->getEntryXML($wrel_path)) {
+                                    foreach ($sharedStrings->si as $val) {
+                                        if (isset($val->t)) {
+                                            $this->sharedstrings[] = (string) $val->t;
+                                        } elseif (isset($val->r)) {
+                                            $this->sharedstrings[] = $this->_parseRichText($val);
+                                        }
+                                    }
+                                }
+                            } elseif ($wrel_type === 'styles') {
+                                $this->styles = $this->getEntryXML($wrel_path);
+
+                                // number formats
+                                $this->nf = [];
+                                if (isset($this->styles->numFmts->numFmt)) {
+                                    foreach ($this->styles->numFmts->numFmt as $v) {
+                                        $this->nf[(int) $v['numFmtId']] = (string) $v['formatCode'];
+                                    }
+                                }
+
+                                $this->cellFormats = [];
+                                if (isset($this->styles->cellXfs->xf)) {
+                                    foreach ($this->styles->cellXfs->xf as $v) {
+                                        $x = [
+                                            'format' => null
+                                        ];
+                                        foreach ($v->attributes() as $k1 => $v1) {
+                                            $x[$k1] = (int) $v1;
+                                        }
+                                        if (isset($x['numFmtId'])) {
+                                            if (isset($this->nf[$x['numFmtId']])) {
+                                                $x['format'] = $this->nf[$x['numFmtId']];
+                                            } elseif (isset(self::$CF[$x['numFmtId']])) {
+                                                $x['format'] = self::$CF[$x['numFmtId']];
+                                            }
+                                        }
+
+                                        $this->cellFormats[] = $x;
+                                    }
+                                }
+                            } elseif ($wrel_type === 'theme') {
+                                $this->theme = $this->getEntryXML($wrel_path);
+                            }
+                        }
+
+                        break;
+                    }
+                    // reptile hack :: find active sheet from workbook.xml
+                    foreach ($workbook->bookViews->workbookView as $s) {
+                        if (!empty($s['activeTab'])) {
+                            $this->activeSheet = (int) $s['activeTab'];
+                        }
+                    }
+                }
+            }
+        }
+
+//        $m2 = memory_get_peak_usage(true);
+//        echo __FUNCTION__.' M='.round( ($m2-$m1) / 1048576, 2).'MB'.PHP_EOL;
+
+        if (count($this->sheets)) {
+            // Sort sheets
+            ksort($this->sheets);
+
+            return true;
+        }
+
+        return false;
+    }
+
+    public function getEntryXML($name) {
+        if ($entry_xml = $this->getEntryData($name)) {
+            $this->deleteEntry($name); // economy memory
+            // dirty remove namespace prefixes and empty rows
+            $entry_xml = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $entry_xml); // remove namespaces
+            $entry_xml .= ' '; // force run garbage collector
+            $entry_xml = preg_replace('/[a-zA-Z0-9]+:([a-zA-Z0-9]+="[^"]+")/', '$1', $entry_xml); // remove namespaced attrs
+            $entry_xml .= ' ';
+            $entry_xml = preg_replace('/<[a-zA-Z0-9]+:([^>]+)>/', '<$1>', $entry_xml); // fix namespaced openned tags
+            $entry_xml .= ' ';
+            $entry_xml = preg_replace('/<\/[a-zA-Z0-9]+:([^>]+)>/', '</$1>', $entry_xml); // fix namespaced closed tags
+            $entry_xml .= ' ';
+
+            if (strpos($name, '/sheet')) { // dirty skip empty rows
+                // remove <row...> <c /><c /></row>
+                $entry_xml = preg_replace('/<row[^>]+>\s*(<c[^\/]+\/>\s*)+<\/row>/', '', $entry_xml, -1, $cnt);
+                $entry_xml .= ' ';
+                // remove <row />
+                $entry_xml = preg_replace('/<row[^\/>]*\/>/', '', $entry_xml, -1, $cnt2);
+                $entry_xml .= ' ';
+                // remove <row...></row>
+                $entry_xml = preg_replace('/<row[^>]*><\/row>/', '', $entry_xml, -1, $cnt3);
+                $entry_xml .= ' ';
+                if ($cnt || $cnt2 || $cnt3) {
+                    $entry_xml = preg_replace('/<dimension[^\/]+\/>/', '', $entry_xml);
+                    $entry_xml .= ' ';
+                }
+//              file_put_contents( basename( $name ), $entry_xml ); // @to do comment!!!
+            }
+            $entry_xml = trim($entry_xml);
+
+//            $m1 = memory_get_usage();
+            // XML External Entity (XXE) Prevention, libxml_disable_entity_loader deprecated in PHP 8
+            if (LIBXML_VERSION < 20900 && function_exists('libxml_disable_entity_loader')) {
+                $_old = libxml_disable_entity_loader();
+            }
+
+            $_old_uie = libxml_use_internal_errors(true);
+
+            $entry_xmlobj = simplexml_load_string($entry_xml, 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE);
+
+            libxml_use_internal_errors($_old_uie);
+
+            if (LIBXML_VERSION < 20900 && function_exists('libxml_disable_entity_loader')) {
+                /** @noinspection PhpUndefinedVariableInspection */
+                libxml_disable_entity_loader($_old);
+            }
+
+//            $m2 = memory_get_usage();
+//            echo round( ($m2-$m1) / (1024 * 1024), 2).' MB'.PHP_EOL;
+
+            if ($entry_xmlobj) {
+                return $entry_xmlobj;
+            }
+            $e = libxml_get_last_error();
+            if ($e) {
+                $this->error(3, 'XML-entry ' . $name . ' parser error ' . $e->message . ' line ' . $e->line);
+            }
+        } else {
+            $this->error(4, 'XML-entry not found ' . $name);
+        }
+
+        return false;
+    }
+
+    // sheets numeration: 1,2,3....
+
+    public function getEntryData($name) {
+        $name = ltrim(str_replace('\\', '/', $name), '/');
+        $dir = $this->_strtoupper(dirname($name));
+        $name = $this->_strtoupper(basename($name));
+        foreach ($this->package['entries'] as &$entry) {
+            if ($this->_strtoupper($entry['path']) === $dir && $this->_strtoupper($entry['name']) === $name) {
+                if ($entry['error']) {
+                    return false;
+                }
+                switch ($entry['cm']) {
+                    case -1:
+                    case 0: // Stored
+                        // Here is nothing to do, the file ist flat.
+                        break;
+                    case 8: // Deflated
+                        $entry['data'] = gzinflate($entry['data']);
+                        break;
+                    case 12: // BZIP2
+                        if (extension_loaded('bz2')) {
+                            $entry['data'] = bzdecompress($entry['data']);
+                        } else {
+                            $entry['error'] = 7;
+                            $entry['error_message'] = 'PHP BZIP2 extension not available.';
+                        }
+                        break;
+                    default:
+                        $entry['error'] = 6;
+                        $entry['error_msg'] = 'De-/Compression method ' . $entry['cm'] . ' is not supported.';
+                }
+                if (!$entry['error'] && $entry['cm'] > -1) {
+                    $entry['cm'] = -1;
+                    if ($entry['data'] === false) {
+                        $entry['error'] = 2;
+                        $entry['error_msg'] = 'Decompression of data failed.';
+                    } elseif ($this->_strlen($entry['data']) !== (int) $entry['ucs']) {
+                        $entry['error'] = 3;
+                        $entry['error_msg'] = 'Uncompressed size is not equal with the value in header information.';
+                    } elseif (crc32($entry['data']) !== $entry['crc']) {
+                        $entry['error'] = 4;
+                        $entry['error_msg'] = 'CRC32 checksum is not equal with the value in header information.';
+                    }
+                }
+
+                return $entry['data'];
+            }
+        }
+        unset($entry);
+        $this->error(5, 'Entry not found ' . ($dir ? $dir . '/' : '') . $name);
+
+        return false;
+    }
+
+    public function deleteEntry($name) {
+        $name = ltrim(str_replace('\\', '/', $name), '/');
+        $dir = $this->_strtoupper(dirname($name));
+        $name = $this->_strtoupper(basename($name));
+        foreach ($this->package['entries'] as $k => $entry) {
+            if ($this->_strtoupper($entry['path']) === $dir && $this->_strtoupper($entry['name']) === $name) {
+                unset($this->package['entries'][$k]);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    protected function _strtoupper($str) {
+        return (ini_get('mbstring.func_overload') & 2) ? mb_strtoupper($str, '8bit') : strtoupper($str);
+    }
+
+    protected function _getTarget($base, $target) {
+        $target = trim($target);
+        if (strpos($target, '/') === 0) {
+            return $this->_substr($target, 1);
+        }
+        $target = ($base ? $base . '/' : '') . $target;
+        // a/b/../c -> a/c
+        $parts = explode('/', $target);
+        $abs = [];
+        foreach ($parts as $p) {
+            if ('.' === $p) {
+                continue;
+            }
+            if ('..' === $p) {
+                array_pop($abs);
+            } else {
+                $abs[] = $p;
+            }
+        }
+        return implode('/', $abs);
+    }
+
+    /*
+     * @param string $name Filename in archive
+     * @return SimpleXMLElement|bool
+     */
+
+    public function entryExists($name) {
+        // 0.6.6
+        $dir = $this->_strtoupper(dirname($name));
+        $name = $this->_strtoupper(basename($name));
+        foreach ($this->package['entries'] as $entry) {
+            if ($this->_strtoupper($entry['path']) === $dir && $this->_strtoupper($entry['name']) === $name) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    protected function _parseRichText($is = null) {
+        $value = [];
+
+        if (isset($is->t)) {
+            $value[] = (string) $is->t;
+        } elseif (isset($is->r)) {
+            foreach ($is->r as $run) {
+                $value[] = (string) $run->t;
+            }
+        }
+
+        return implode('', $value);
+    }
+
+    public static function parseFile($filename, $debug = false) {
+        return self::parse($filename, false, $debug);
+    }
+
+    public static function parse($filename, $is_data = false, $debug = false) {
+        $xlsx = new self();
+        $xlsx->debug = $debug;
+        if ($xlsx->_unzip($filename, $is_data)) {
+            $xlsx->_parse();
+        }
+        if ($xlsx->success()) {
+            return $xlsx;
+        }
+        self::parseError($xlsx->error());
+        self::parseErrno($xlsx->errno());
+
+        return false;
+    }
+
+    public function success() {
+        return !$this->error;
+    }
+
+    // https://github.com/shuchkin/simplexlsx#gets-extend-cell-info-by--rowsex
+
+    public static function parseError($set = false) {
+        static $error = false;
+
+        return $set ? $error = $set : $error;
+    }
+
+    public static function parseErrno($set = false) {
+        static $errno = false;
+
+        return $set ? $errno = $set : $errno;
+    }
+
+    public function errno() {
+        return $this->errno;
+    }
+
+    public static function parseData($data, $debug = false) {
+        return self::parse($data, true, $debug);
+    }
+
+    public function worksheet($worksheetIndex = 0) {
+
+
+        if (isset($this->sheets[$worksheetIndex])) {
+            $ws = $this->sheets[$worksheetIndex];
+
+            if (!isset($this->hyperlinks[$worksheetIndex]) && isset($ws->hyperlinks)) {
+                $this->hyperlinks[$worksheetIndex] = [];
+                $sheet_rels = str_replace('worksheets', 'worksheets/_rels', $this->sheetFiles[$worksheetIndex]) . '.rels';
+                $link_ids = [];
+
+                if ($rels = $this->getEntryXML($sheet_rels)) {
+                    // hyperlink
+//                  $rel_base = dirname( $sheet_rels );
+                    foreach ($rels->Relationship as $rel) {
+                        $rel_type = basename(trim((string) $rel['Type']));
+                        if ($rel_type === 'hyperlink') {
+                            $rel_id = (string) $rel['Id'];
+                            $rel_target = (string) $rel['Target'];
+                            $link_ids[$rel_id] = $rel_target;
+                        }
+                    }
+                }
+                foreach ($ws->hyperlinks->hyperlink as $hyperlink) {
+                    $ref = (string) $hyperlink['ref'];
+                    if ($this->_strpos($ref, ':') > 0) { // A1:A8 -> A1
+                        $ref = explode(':', $ref);
+                        $ref = $ref[0];
+                    }
+//                      $this->hyperlinks[ $worksheetIndex ][ $ref ] = (string) $hyperlink['display'];
+                    $loc = (string) $hyperlink['location'];
+                    $id = (string) $hyperlink['id'];
+                    if ($id) {
+                        $href = $link_ids[$id] . ($loc ? '#' . $loc : '');
+                    } else {
+                        $href = $loc;
+                    }
+                    $this->hyperlinks[$worksheetIndex][$ref] = $href;
+                }
+            }
+
+            return $ws;
+        }
+        $this->error(6, 'Worksheet not found ' . $worksheetIndex);
+
+        return false;
+    }
+
+    protected function _strpos($haystack, $needle, $offset = 0) {
+        return (ini_get('mbstring.func_overload') & 2) ? mb_strpos($haystack, $needle, $offset, '8bit') : strpos($haystack, $needle, $offset);
+    }
+
+    /**
+     * returns [numCols,numRows] of worksheet
+     *
+     * @param int $worksheetIndex
+     *
+     * @return array
+     */
+    public function dimension($worksheetIndex = 0) {
+
+        if (($ws = $this->worksheet($worksheetIndex)) === false) {
+            return [0, 0];
+        }
+        /* @var SimpleXMLElement $ws */
+
+        $ref = (string) $ws->dimension['ref'];
+
+        if ($this->_strpos($ref, ':') !== false) {
+            $d = explode(':', $ref);
+            $idx = $this->getIndex($d[1]);
+
+            return [$idx[0] + 1, $idx[1] + 1];
+        }
+        /*
+          if ( $ref !== '' ) { // 0.6.8
+          $index = $this->getIndex( $ref );
+          return [ $index[0] + 1, $index[1] + 1 ];
+          }
+         */
+
+        // slow method
+        $maxC = $maxR = 0;
+        $iR = -1;
+        foreach ($ws->sheetData->row as $row) {
+            $iR++;
+            $iC = -1;
+            foreach ($row->c as $c) {
+                $iC++;
+                $idx = $this->getIndex((string) $c['r']);
+                $x = $idx[0];
+                $y = $idx[1];
+                if ($x > -1) {
+                    if ($x > $maxC) {
+                        $maxC = $x;
+                    }
+                    if ($y > $maxR) {
+                        $maxR = $y;
+                    }
+                } else {
+                    if ($iC > $maxC) {
+                        $maxC = $iC;
+                    }
+                    if ($iR > $maxR) {
+                        $maxR = $iR;
+                    }
+                }
+            }
+        }
+
+        return [$maxC + 1, $maxR + 1];
+    }
+
+    public function getIndex($cell = 'A1') {
+
+        if (preg_match('/([A-Z]+)(\d+)/', $cell, $m)) {
+            $col = $m[1];
+            $row = $m[2];
+
+            $colLen = $this->_strlen($col);
+            $index = 0;
+
+            for ($i = $colLen - 1; $i >= 0; $i--) {
+                $index += (ord($col[$i]) - 64) * pow(26, $colLen - $i - 1);
+            }
+
+            return [$index - 1, $row - 1];
+        }
+
+//      $this->error( 'Invalid cell index ' . $cell );
+
+        return [-1, -1];
+    }
+
+    public function value($cell) {
+        // Determine data type
+        $dataType = (string) $cell['t'];
+
+        if ($dataType === '' || $dataType === 'n') { // number
+            $s = (int) $cell['s'];
+            if ($s > 0 && isset($this->cellFormats[$s])) {
+                if (array_key_exists('format', $this->cellFormats[$s])) {
+                    $format = $this->cellFormats[$s]['format'];
+                    if (preg_match('/(m|AM|PM)/', preg_replace('/\"[^"]+\"/', '', $format))) { // [mm]onth,AM|PM
+                        $dataType = 'D';
+                    }
+                } else {
+                    $dataType = 'n';
+                }
+            }
+        }
+
+        $value = '';
+
+        switch ($dataType) {
+            case 's':
+                // Value is a shared string
+                if ((string) $cell->v !== '') {
+                    $value = $this->sharedstrings[(int) $cell->v];
+                }
+                break;
+
+            case 'str': // formula?
+                if ((string) $cell->v !== '') {
+                    $value = (string) $cell->v;
+                }
+                break;
+
+            case 'b':
+                // Value is boolean
+                $value = (string) $cell->v;
+                if ($value === '0') {
+                    $value = false;
+                } elseif ($value === '1') {
+                    $value = true;
+                } else {
+                    $value = (bool) $cell->v;
+                }
+
+                break;
+
+            case 'inlineStr':
+                // Value is rich text inline
+                $value = $this->_parseRichText($cell->is);
+
+                break;
+
+            case 'e':
+                // Value is an error message
+                if ((string) $cell->v !== '') {
+                    $value = (string) $cell->v;
+                }
+                break;
+
+            case 'D':
+                // Date as float
+                if (!empty($cell->v)) {
+                    $value = $this->datetimeFormat ? gmdate($this->datetimeFormat, $this->unixstamp((float) $cell->v)) : (float) $cell->v;
+                }
+                break;
+
+            case 'd':
+                // Date as ISO YYYY-MM-DD
+                if ((string) $cell->v !== '') {
+                    $value = (string) $cell->v;
+                }
+                break;
+
+            default:
+                // Value is a string
+                $value = (string) $cell->v;
+
+                // Check for numeric values
+                if (is_numeric($value)) {
+                    /** @noinspection TypeUnsafeComparisonInspection */
+                    if ($value == (int) $value) {
+                        $value = (int) $value;
+                    } /** @noinspection TypeUnsafeComparisonInspection */ elseif ($value == (float) $value) {
+                        $value = (float) $value;
+                    }
+                }
+        }
+
+        return $value;
+    }
+
+    public function unixstamp($excelDateTime) {
+
+        $d = floor($excelDateTime); // days since 1900 or 1904
+        $t = $excelDateTime - $d;
+
+        if ($this->date1904) {
+            $d += 1462;
+        }
+
+        $t = (abs($d) > 0) ? ($d - 25569) * 86400 + round($t * 86400) : round($t * 86400);
+
+        return (int) $t;
+    }
+
+    public function href($worksheetIndex, $cell) {
+        $ref = (string) $cell['r'];
+        return isset($this->hyperlinks[$worksheetIndex][$ref]) ? $this->hyperlinks[$worksheetIndex][$ref] : '';
+    }
+
+    public function toHTML($worksheetIndex = 0) {
+        $s = '<table class=excel>';
+        foreach ($this->readRows($worksheetIndex) as $r) {
+            $s .= '<tr>';
+            foreach ($r as $c) {
+                $s .= '<td nowrap>' . ($c === '' ? '&nbsp' : htmlspecialchars($c, ENT_QUOTES)) . '</td>';
+            }
+            $s .= "</tr>\r\n";
+        }
+        $s .= '</table>';
+
+        return $s;
+    }
+
+    public function toHTMLEx($worksheetIndex = 0) {
+        $s = '<table class=excel>';
+        $y = 0;
+        foreach ($this->readRowsEx($worksheetIndex) as $r) {
+            $s .= '<tr>';
+            $x = 0;
+            foreach ($r as $c) {
+                $tag = 'td';
+                $css = $c['css'];
+                if ($y === 0) {
+                    $tag = 'th';
+                    $css .= $c['width'] ? 'width: ' . round($c['width'] * 0.47, 2) . 'em;' : '';
+                }
+
+                if ($x === 0 && $c['height']) {
+                    $css .= 'height: ' . round($c['height'] * 1.3333) . 'px;';
+                }
+                $s .= '<' . $tag . ' style="' . $css . '" nowrap>' . ($c['value'] === '' ? '&nbsp' : htmlspecialchars($c['value'], ENT_QUOTES)) . '</' . $tag . '>';
+                $x++;
+            }
+            $s .= "</tr>\r\n";
+            $y++;
+        }
+        $s .= '</table>';
+
+        return $s;
+    }
+
+    public function rows($worksheetIndex = 0, $limit = 0) {
+        return iterator_to_array($this->readRows($worksheetIndex, $limit), false);
+    }
+
+    // thx Gonzo
+
+    /**
+     * @param $worksheetIndex
+     * @param $limit
+     * @return \Generator
+     */
+    public function readRows($worksheetIndex = 0, $limit = 0) {
+
+        if (($ws = $this->worksheet($worksheetIndex)) === false) {
+            return;
+        }
+        $dim = $this->dimension($worksheetIndex);
+        $numCols = $dim[0];
+        $numRows = $dim[1];
+
+        $emptyRow = [];
+        for ($i = 0; $i < $numCols; $i++) {
+            $emptyRow[] = '';
+        }
+
+        $curR = 0;
+        $_limit = $limit;
+        /* @var SimpleXMLElement $ws */
+        foreach ($ws->sheetData->row as $row) {
+            $r = $emptyRow;
+            $curC = 0;
+            foreach ($row->c as $c) {
+                // detect skipped cols
+                $idx = $this->getIndex((string) $c['r']);
+                $x = $idx[0];
+                $y = $idx[1];
+
+                if ($x > -1) {
+                    $curC = $x;
+                    while ($curR < $y) {
+                        yield $emptyRow;
+                        $curR++;
+                        $_limit--;
+                        if ($_limit === 0) {
+                            return;
+                        }
+                    }
+                }
+                $r[$curC] = $this->value($c);
+                $curC++;
+            }
+            yield $r;
+
+            $curR++;
+            $_limit--;
+            if ($_limit === 0) {
+                return;
+            }
+        }
+        while ($curR < $numRows) {
+            yield $emptyRow;
+            $curR++;
+            $_limit--;
+            if ($_limit === 0) {
+                return;
+            }
+        }
+    }
+
+    public function rowsEx($worksheetIndex = 0, $limit = 0) {
+        return iterator_to_array($this->readRowsEx($worksheetIndex, $limit), false);
+    }
+
+    // https://github.com/shuchkin/simplexlsx#gets-extend-cell-info-by--rowsex
+
+    /**
+     * @param $worksheetIndex
+     * @param $limit
+     * @return \Generator|null
+     */
+    public function readRowsEx($worksheetIndex = 0, $limit = 0) {
+        if (!$this->rowsExReader) {
+            require_once __DIR__ . '/SimpleXLSXEx.php';
+            $this->rowsExReader = new SimpleXLSXEx($this);
+        }
+        return $this->rowsExReader->readRowsEx($worksheetIndex, $limit);
+    }
+
+    /**
+     * Returns cell value
+     * VERY SLOW! Use ->rows() or ->rowsEx()
+     *
+     * @param int $worksheetIndex
+     * @param string|array $cell ref or coords, D12 or [3,12]
+     *
+     * @return mixed Returns NULL if not found
+     */
+    public function getCell($worksheetIndex = 0, $cell = 'A1') {
+
+        if (($ws = $this->worksheet($worksheetIndex)) === false) {
+            return false;
+        }
+        if (is_array($cell)) {
+            $cell = $this->_num2name($cell[0]) . $cell[1]; // [3,21] -> D21
+        }
+        if (is_string($cell)) {
+            $result = $ws->sheetData->xpath("row/c[@r='" . $cell . "']");
+            if (count($result)) {
+                return $this->value($result[0]);
+            }
+        }
+
+        return null;
+    }
+
+    protected function _num2name($num) {
+        $numeric = ($num - 1) % 26;
+        $letter = chr(65 + $numeric);
+        $num2 = (int) (($num - 1) / 26);
+        if ($num2 > 0) {
+            return $this->_num2name($num2) . $letter;
+        }
+        return $letter;
+    }
+
+    public function getSheets() {
+        return $this->sheets;
+    }
+
+    public function sheetsCount() {
+        return count($this->sheets);
+    }
+
+    public function sheetName($worksheetIndex) {
+        if (isset($this->sheetNames[$worksheetIndex])) {
+            return $this->sheetNames[$worksheetIndex];
+        }
+
+        return false;
+    }
+
+    public function sheetNames() {
+
+        return $this->sheetNames;
+    }
+
+    public function getStyles() {
+        return $this->styles;
+    }
+
+    public function getPackage() {
+        return $this->package;
+    }
+
+    public function setDateTimeFormat($value) {
+        $this->datetimeFormat = is_string($value) ? $value : false;
+    }
+
+}

+ 82 - 0
core/class/stats.class.php

@@ -0,0 +1,82 @@
+<?php
+
+class stats {
+    
+    public static function countStatistiquesGenrale(int $_actifOnly = 1){
+        $actif = ($_actifOnly == 1) ? " AND actif = 1" : "";
+        db::query("SELECT "
+                . "SUM(IF(sexe = 'F'" . $actif . ", 1, 0)) AS Femme, "
+                . "SUM(IF(sexe = 'M'" . $actif . ", 1, 0)) AS Homme, "
+                . "SUM(IF(contrat = 1" . $actif . ", 1, 0)) AS ContratOn, "
+                . "SUM(IF(contrat = 0" . $actif . ", 1, 0)) AS ContratOff, "
+                . "SUM(IF(actif = 1, 1, 0)) AS ActifOn, "
+                . "SUM(IF(actif = 0, 1, 0)) AS ActifOff, "
+                . "SUM(IF(lieu = 'ISSY - 147', 1, 0)) AS lieuParis147, "
+                . "SUM(IF(lieu = 'LYON (IVOIRE)', 1, 0)) AS lieuLyonIvoire, "
+                . "SUM(IF(lieu = 'PEROLS', 1, 0)) AS lieuPerols, "
+                . "SUM(IF(lieu = 'PARIS CAMBACERE', 1, 0)) AS lieuParisCambaceres, "
+                . "SUM(IF(lieu = 'BLAGNAC CENT. 3', 1, 0)) AS lieuToulouseBalgnac, "
+                . "SUM(IF(lieu = 'PARIS-BOUCHARDO', 1, 0)) AS lieuParisBouchardo "
+                . "FROM " . DB_T_SALARIES);
+        return db::single();
+    }
+    
+    private static function byLieu(string $_lieu){
+        switch ($_lieu) {
+            case "147":
+            return "ISSY - 147";
+                break;
+            case "LYON":
+            return "LYON (IVOIRE)";   
+                break;
+            case "PEROLS":
+            return "PEROLS";
+                break;
+            case "CAMBACERE":
+            return "PARIS CAMBACERE";
+                break;
+            case "BLAGNAC":
+            return "BLAGNAC CENT. 3";
+                break;
+            case "BOUCHARDO":
+            return "PARIS-BOUCHARDO";
+                break;
+            default:
+            return NULL;  
+        }
+    }
+
+    public static function countStatistiquesGenraleEntrees(string $_lieu = NULL, int $_actifOnly = 1){
+        $return = NULL;
+        $actif = ($_actifOnly == 1) ? " WHERE contrat = 1" : "";
+        $lieu = ($_lieu == NULL) ? "" : " AND lieu = '" . self::byLieu($_lieu) . "'";
+        
+        db::query("SELECT SUBSTR(jourEntree, 1 , 4) AS anEntree FROM " . DB_T_SALARIES . $actif . $lieu);
+        foreach (db::resultset() as $value) {
+            $return[$value["anEntree"]] = (empty($return[$value["anEntree"]])) ? 1 : $return[$value["anEntree"]]+1;
+        }
+        ksort($return);
+        return $return;
+    }
+    
+    public static function countStatistiquesByLieu(string $_lieu){
+        $lieu = self::byLieu($_lieu);
+        
+        if($lieu == NULL){
+            return FALSE;
+        }
+
+        db::query("SELECT "
+                . "SUM(IF(sexe = 'F' AND actif = 1, 1, 0)) AS Femme, "
+                . "SUM(IF(sexe = 'M' AND actif = 1, 1, 0)) AS Homme, "
+                . "SUM(IF(contrat = 1 AND actif = 1, 1, 0)) AS ContratOn, "
+                . "SUM(IF(contrat = 0 AND actif = 1, 1, 0)) AS ContratOff, "
+                . "SUM(IF(actif = 1, 1, 0)) AS ActifOn, "
+                . "SUM(IF(actif = 0, 1, 0)) AS ActifOff "
+                . "FROM " . DB_T_SALARIES . " "
+                . "WHERE lieu = :lieu");
+        db::bind(':lieu', $lieu);
+        return db::single();
+    }
+    
+}

+ 150 - 0
core/class/user.class.php

@@ -0,0 +1,150 @@
+<?php
+
+class user {
+    
+    public function __construct() {
+    }
+ 
+    public static function getUserById(int $_id) {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT "
+                . "" . DB_T_USER . ".id AS id, "
+                . "" . DB_T_USER . ".email ,"
+                . "" . DB_T_USER . ".prenom, "
+                . "" . DB_T_USER . ".nom, "
+                . "" . DB_T_USER . ".cree, "
+                . "" . DB_T_USER . ".last_connect, "
+                . "" . DB_T_USER . ".actif, "
+                . "" . DB_T_USER . ".id_type, "
+                . "" . DB_T_USER_TYPE . ".type "
+                . "FROM " . DB_T_USER . " "
+                . "INNER JOIN " . DB_T_USER_TYPE . " ON " . DB_T_USER . ".id_type = " . DB_T_USER_TYPE . ".id "
+                . "WHERE " . DB_T_USER . ".id = :id");
+        db::bind(':id', $_id);
+        return db::single();
+    }
+
+    public static function getUsers() {
+        // Récupération des données de l'excel au format Json
+        db::query("SELECT "
+                . "" . DB_T_USER . ".id AS id, "
+                . "" . DB_T_USER . ".email ,"
+                . "" . DB_T_USER . ".prenom, "
+                . "" . DB_T_USER . ".nom, "
+                . "" . DB_T_USER . ".cree, "
+                . "" . DB_T_USER . ".last_connect, "
+                . "" . DB_T_USER . ".actif, "
+                . "" . DB_T_USER . ".id_type, "
+                . "" . DB_T_USER_TYPE . ".type "
+                . "FROM " . DB_T_USER . " "
+                . "INNER JOIN " . DB_T_USER_TYPE . " ON " . DB_T_USER . ".id_type = " . DB_T_USER_TYPE . ".id");
+        return db::resultset();
+    }
+
+    public static function connect(array $_input) {
+        $return = NULL;
+        if (isset($_input["email"]) AND isset($_input["password"])) {
+            db::query("SELECT id, email, password, prenom, nom, id_type, actif FROM " . DB_T_USER . " WHERE email = :email");
+            db::bind(':email', $_input["email"]);
+            $row = db::single();
+
+            if (isset($row["id"])) {
+                if ($row["actif"] == 0) {
+                    alert::recError("Votre compte est désactivé");
+                    return FALSE;
+                } elseif (isset($_input["password"]) AND md5($_input["password"]) == $row["password"]) {
+                    $_SESSION["user"] = array(
+                        "id" => $row["id"],
+                        "prenom" => $row["prenom"],
+                        "nom" => $row["nom"],
+                        "idType" => $row["id_type"],
+                        "email" => $row["email"],
+                        "actif" => $row["actif"]
+                    );
+                    self::updateLastConnect($row["id"]);
+                    return TRUE;
+                } else {
+                    alert::recError("Erreur d'authentification");
+                    return FALSE; 
+                }
+            } else {
+                alert::recError("Erreur d'authentification");
+                return FALSE; 
+            }
+        } else {
+            alert::recError("Erreur d'authentification");
+            return FALSE; 
+        }
+    }
+    
+    private static function updateLastConnect(int $_id){
+        db::query("UPDATE " . DB_T_USER . " SET `last_connect` = CURRENT_TIMESTAMP() WHERE id = :id");
+        db::bind(':id', $_id);
+        db::execute();
+    }
+    
+    public static function add_user(array $_input){
+        db::query("INSERT INTO " . DB_T_USER . " "
+                . "(email, password, prenom, nom, id_type, actif) "
+                . "VALUES (:email, :password, :prenom, :nom, :id_type, :actif)");
+        db::bind(':email', $_input["email"]);
+        db::bind(':password', md5($_input["password"]));
+        db::bind(':prenom', $_input["prenom"]);
+        db::bind(':nom', $_input["nom"]);
+        db::bind(':id_type', $_input["id_type"]);
+        db::bind(':actif', $_input["actif"]);
+        
+        try {
+            db::execute();
+            alert::recSuccess("La création a bien été prise en compte");
+        } catch (Exception $ex) {
+            alert::recError("Erreur lors de la création de l'utilisateur");
+            header("Location: /?p=user&id=add");
+            exit();
+        }
+    }
+    
+    public static function lastUser(){
+        db::query("SELECT MAX(id) AS id FROM ". DB_T_USER);
+        return db::single()["id"];
+    }
+    
+    public static function maj_user(array $_input){
+        if($_input["password"] != ""){
+            db::query("UPDATE " . DB_T_USER . " SET password = :password WHERE id = :id");
+            db::bind(':password', md5($_input["password"]));
+            db::bind(':id', $_input["id"]);
+            try {
+                db::execute();
+            } catch (Exception $ex) {
+                alert::recError("Erreur lors de la modification de l'utilisateur");
+                header("Location: /?p=user&id=" . $_input["id"]);
+                exit();
+            }
+        }
+        
+        db::query("UPDATE " . DB_T_USER . " SET email = :email, prenom = :prenom, nom = :nom, id_type = :id_type, actif = :actif WHERE id = :id");
+        db::bind(':email', $_input["email"]);
+        db::bind(':prenom', $_input["prenom"]);
+        db::bind(':nom', $_input["nom"]);
+        db::bind(':id_type', $_input["id_type"]);
+        db::bind(':actif', $_input["actif"]);
+        db::bind(':id', $_input["id"]);
+        
+        try {
+            db::execute();
+            alert::recSuccess("La modification a bien été prise en compte");
+        } catch (Exception $ex) {
+            alert::recError("Erreur lors de la modification de l'utilisateur");
+            header("Location: /?p=user&id=" . $_input["id"]);
+            exit();
+        }
+    }
+    
+    public static function deleteUser(int $_id){
+        db::query("DELETE FROM ". DB_T_USER ." WHERE id = :id");
+        db::bind(':id', $_id);
+        return db::execute();
+    }
+
+}

+ 9 - 0
core/class/view.class.php

@@ -0,0 +1,9 @@
+<?php
+
+class view {
+    
+    public function printPage(string $_view, array $_array){
+        
+    }
+    
+}

+ 10 - 0
core/controllers/cms.index.php

@@ -0,0 +1,10 @@
+<?php
+
+if(session::isConnect()){
+    require_once DIR_PHP_LAYOUTS . "cms.session.php";
+    require_once DIR_PHP_VIEWS . "_cms.head.php"; 
+    get::page();
+    require_once DIR_PHP_VIEWS . "_cms.foot.php";
+} else {
+    get::page("login");
+}

+ 8 - 0
core/controllers/cms.session.php

@@ -0,0 +1,8 @@
+<?php
+
+if (!session::isConnect()) { // Si non logué
+    if (core::getPost("from") != "login") {
+        header('Location: ./');
+        exit();
+    } 
+}

+ 14 - 0
core/controllers/events.index.php

@@ -0,0 +1,14 @@
+<?php
+if(session::isConnect("salarie") OR session::isConnect())
+{
+    require_once DIR_PHP_VIEWS . "_events.head.php";
+    require_once DIR_PHP_VIEWS . "_events.nav.php";
+    (session::isConnect("salarie")) ? get::page("list-events") : get::page("validateQRCode");
+    require_once DIR_PHP_VIEWS . "_events.foot.php";
+} 
+else
+{ 
+    get::page("login");
+}
+
+

+ 8 - 0
core/controllers/events.session.php

@@ -0,0 +1,8 @@
+<?php 
+
+if (!session::isConnect("salarie") AND !session::isConnect()) { // Si non logué
+    if (core::getPost("from") != "login" AND !core::ifGet("status") AND core::getGet("jsonData") != "logout") {
+        header('Location: ./');
+        exit();
+    } 
+}

+ 13 - 0
core/controllers/header.php

@@ -0,0 +1,13 @@
+<?php
+    setlocale(LC_TIME, 'fr_FR');
+    date_default_timezone_set(TIME_ZONE);
+    
+    if(isset($_SESSION["debug"])){
+        error_reporting(E_ALL);
+        ini_set("display_errors", 1);
+    }
+    
+    spl_autoload_register(function ($class_name) {
+        (file_exists(DIR_PHP_CLASS.'/'.$class_name.'.class.php'))?	
+        require_once DIR_PHP_CLASS.'/'.$class_name.'.class.php' : '';
+    });

+ 23 - 0
core/controllers/json/cms.event-inscrits.php

@@ -0,0 +1,23 @@
+<?php 
+
+db::query("SELECT "
+            . "" . DB_T_SALARIES . ".id, "
+            . "" . DB_T_SALARIES . ".loginId, "
+            . "" . DB_T_SALARIES . ".nom, "
+            . "" . DB_T_SALARIES . ".prenom, "
+            . "" . DB_T_SALARIES . ".sexe, "
+            . "" . DB_T_SALARIES . ".contrat, "
+            . "" . DB_T_SALARIES . ".lieu, "
+            . "" . DB_T_SALARIES . ".actif, "
+            . "" . DB_T_EVENTS_INSCRITS . ".id_evenement, "
+            . "" . DB_T_EVENTS_INSCRITS . ".present "
+            . "FROM " . DB_T_SALARIES . " "
+            . "INNER JOIN " . DB_T_EVENTS_INSCRITS . " ON " . DB_T_EVENTS_INSCRITS . ".id_salarie = " . DB_T_SALARIES . ".id "
+            . "WHERE " . DB_T_EVENTS_INSCRITS . ".id_evenement = " . core::getGet("id"));
+            $row = db::resultset();
+if (!empty($row)) {
+    echo json_encode($row);
+    exit();
+} else {
+    exit();
+}

+ 23 - 0
core/controllers/json/cms.event-salaries.php

@@ -0,0 +1,23 @@
+<?php 
+
+db::query("SELECT "
+            . "" . DB_T_SALARIES . ".id, "
+            . "" . DB_T_SALARIES . ".loginId, "
+            . "" . DB_T_SALARIES . ".nom, "
+            . "" . DB_T_SALARIES . ".prenom, "
+            . "" . DB_T_SALARIES . ".sexe, "
+            . "" . DB_T_SALARIES . ".contrat, "
+            . "" . DB_T_SALARIES . ".lieu, "
+            . "" . DB_T_SALARIES . ".actif, "
+            . "IF(" . DB_T_EVENTS_INSCRITS . ".id_salarie IS NOT NULL, 1, 0) AS inscrit, "
+            . "" . DB_T_EVENTS_INSCRITS . ".present "
+            . "FROM " . DB_T_SALARIES . " "
+            . "LEFT JOIN " . DB_T_EVENTS_INSCRITS . " ON " . DB_T_SALARIES . ".id = " . DB_T_EVENTS_INSCRITS . ".id_salarie "
+            . "AND " . DB_T_EVENTS_INSCRITS . ".id_evenement = " . core::getGet("id"));
+            $row = db::resultset();
+if (!empty($row)) {
+    echo json_encode($row);
+    exit();
+} else {
+    exit();
+}

+ 4 - 0
core/controllers/json/cms.proweb-transfert-local.php

@@ -0,0 +1,4 @@
+<?php 
+
+$row = sftp::scanFolderLocal();
+echo json_encode($row);

+ 4 - 0
core/controllers/json/cms.proweb-transfert-sftp.php

@@ -0,0 +1,4 @@
+<?php 
+
+$row = sftp::scanFolderRemote();
+echo json_encode($row);

+ 4 - 0
core/controllers/json/cms.proweb-transfert-test-connexion.php

@@ -0,0 +1,4 @@
+<?php 
+
+$result = (sftp::testAccessHost()) ? "OK" : "KO"; 
+echo json_encode(array($result));

+ 45 - 0
core/controllers/json/events.check-control-emargement.php

@@ -0,0 +1,45 @@
+<?php
+
+if (session::isConnect("salarie")) {
+    $return = array();
+    if (event::checkUrl(core::getPost("qRcode")) != DOMAIN_EVENTS and event::checkUrl(core::getPost("qRcode")) != DOMAIN_CONTROL and PWA == 0) {
+        $return["result"] = false;
+        $return["description"] = "Le QR-Code n'est pas valide";
+        $return["salarie"] = null;
+        $return["evenement"] = null;
+    } elseif (event::checkUrl(core::getPost("qRcode")) == DOMAIN_CONTROL) {
+        $return["result"] = false;
+        $return["description"] = "Ce QR-Code doit être validé par un contrôleur";
+        $return["salarie"] = null;
+        $return["evenement"] = null;
+    } else {
+        $md5Evenement = event::getEvenementbyQRCode(core::getPost("qRcode"))["e"];
+        $checkEmarge = event::checkEvenementBySalarie($md5Evenement);
+        if ($checkEmarge["result"] == TRUE) {
+            $return = event::emargementEvenement(event::getIdEvenementByMd5($md5Evenement), session::getId("salarie"));
+        } else {
+            $return = $checkEmarge;
+        }
+        $return["salarie"] = session::getName("salarie", session::getId("salarie"));
+    }
+    echo json_encode($return);
+    exit();
+} elseif (session::isConnect()) {
+    if (core::ifGet("s") and core::ifGet("e") and core::ifGet("k")) {
+        $salarie = salaries::get_salarieById(core::getGet("s"));
+        $evenement = event::getFicheByMd5(core::getGet("e"));
+        $return = event::emargementEvenementByQRCode();
+        $return["salarie"] = $salarie["prenom"] . " " . $salarie["nom"];
+        $return["evenement"] = $evenement["titre"];
+    } else {
+        $return["result"] = false;
+        $return["description"] = "Le QR-Code n'est pas valide";
+        $return["salarie"] = null;
+        $return["evenement"] = null;
+    }
+    echo json_encode($return);
+    exit();
+} else {
+    header('HTTP/1.0 401 Unauthorized');
+    exit();
+}

+ 18 - 0
core/controllers/json/events.list-events.php

@@ -0,0 +1,18 @@
+<?php 
+if(session::isConnect("salarie")){
+    $evenements = event::presentEvenement(session::getId("salarie"));
+    if (empty($evenements)) {
+        echo json_encode(array(NULL));
+    } else {
+        $return = array();
+        foreach ($evenements as $nb => $ev) {
+            $ev["nb"] = $nb;
+            $ev["url_qrcode"] = base64_encode("https://" . DOMAIN_CONTROL . "/json.php?jsonData=check-control-emargement&s=".session::getId("salarie")."&e=".$ev["md5"]."&k=".md5($ev["md5"].session::getValue("sel", "salarie"))); 
+            $ev["startDate"] = core::convertDate($ev["startDate"]);
+            $ev["endDate"] = core::convertDate($ev["endDate"]);
+            $ev["present"] = (isset($ev["present"])) ? core::convertDate($ev["present"]) : NULL;
+            $return[] = $ev;       
+        }
+        echo json_encode($return);
+    }
+}

+ 20 - 0
core/controllers/json/events.login.php

@@ -0,0 +1,20 @@
+<?php
+
+if (core::ifPost("from") and core::getPost("from") == "login") {
+    $return = array();
+    if ($_SERVER['HTTP_HOST'] == DOMAIN_EVENTS) {
+        if (event::connectSalarie(core::getPost())) {
+            $return["success"] = TRUE;
+        } else {
+            $return["success"] = FALSE;
+        }
+    } else {
+        if (user::connect(core::getPost())) {
+            $return["success"] = TRUE;
+        } else {
+            $return["success"] = FALSE;
+        }
+    }
+    echo json_encode($return);
+    exit();
+}

+ 5 - 0
core/controllers/json/events.logout.php

@@ -0,0 +1,5 @@
+<?php
+session_destroy();
+$return["success"] = TRUE;
+echo json_encode($return);
+exit();

+ 38 - 0
core/libs/phpqrcode/CHANGELOG

@@ -0,0 +1,38 @@
+* 1.0.0 build 2010031920 
+
+  - first public release
+  - help in readme, install
+  - cleanup ans separation of QRtools and QRspec
+  - now TCPDF binding requires minimal changes in TCPDF, having most of job
+    done in QRtools tcpdfBarcodeArray
+  - nicer QRtools::timeBenchmark output
+  - license and copyright notices in files
+  - indent cleanup - from tab to 4spc, keep it that way please :)
+  - sf project, repository, wiki
+  - simple code generator in index.php
+  
+* 1.1.0 build 2010032113
+
+  - added merge tool wich generate merged version of code
+    located in phpqrcode.php
+  - splited qrconst.php from qrlib.php
+  
+* 1.1.1 build 2010032405
+
+  - patch by Rick Seymour allowing saving PNG and displaying it at the same time
+  - added version info in VERSION file
+  - modified merge tool to include version info into generated file
+  - fixed e-mail in almost all head comments
+  
+* 1.1.2 build 2010032722
+
+  - full integration with TCPDF thanks to Nicola Asuni, it's author
+  - fixed bug with alphanumeric encoding detection
+  
+* 1.1.3 build 2010081807
+
+  - short opening tags replaced with standard ones
+  
+* 1.1.4 build 2010100721
+
+  - added missing static keyword QRinput::check (found by Luke Brookhart, Onjax LLC)

+ 67 - 0
core/libs/phpqrcode/INSTALL

@@ -0,0 +1,67 @@
+== REQUIREMENTS ==
+
+ * PHP5
+ * PHP GD2 extension with JPEG and PNG support
+ 
+== INSTALLATION ==
+
+If you want to recreate cache by yourself make sure cache directory is
+writable and you have permisions to write into it. Also make sure you are
+able to read files in it if you have cache option enabled
+ 
+== CONFIGURATION ==
+
+Feel free to modify config constants in qrconfig.php file. Read about it in
+provided comments and project wiki page (links in README file)
+
+== QUICK START ==
+
+Notice: probably you should'nt use all of this in same script :)
+
+<?phpb
+
+//include only that one, rest required files will be included from it
+include "qrlib.php"
+
+//write code into file, Error corection lecer is lowest, L (one form: L,M,Q,H)
+//each code square will be 4x4 pixels (4x zoom)
+//code will have 2 code squares white boundary around 
+
+QRcode::png('PHP QR Code :)', 'test.png', 'L', 4, 2);
+
+//same as above but outputs file directly into browser (with appr. header etc.)
+//all other settings are default
+//WARNING! it should be FIRST and ONLY output generated by script, otherwise
+//rest of output will land inside PNG binary, breaking it for sure
+QRcode::png('PHP QR Code :)');
+
+//show benchmark
+QRtools::timeBenchmark();
+
+//rebuild cache
+QRtools::buildCache();
+
+//code generated in text mode - as a binary table
+//then displayed out as HTML using Unicode block building chars :)
+$tab = $qr->encode('PHP QR Code :)');
+QRspec::debug($tab, true);
+
+== TCPDF INTEGRATION ==
+
+Inside bindings/tcpdf you will find slightly modified 2dbarcodes.php.
+Instal phpqrcode liblaty inside tcpdf folder, then overwrite (or merge)
+2dbarcodes.php 
+
+Then use similar as example #50 from TCPDF examples:
+
+<?php
+
+$style = array(
+    'border' => true,
+    'padding' => 4,
+    'fgcolor' => array(0,0,0),
+    'bgcolor' => false, //array(255,255,255)
+);
+
+//code name: QR, specify error correction level after semicolon (L,M,Q,H)
+$pdf->write2DBarcode('PHP QR Code :)', 'QR,L', '', '', 30, 30, $style, 'N');

+ 165 - 0
core/libs/phpqrcode/LICENSE

@@ -0,0 +1,165 @@
+                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.

+ 45 - 0
core/libs/phpqrcode/README

@@ -0,0 +1,45 @@
+This is PHP implementation of QR Code 2-D barcode generator. It is pure-php
+LGPL-licensed implementation based on C libqrencode by Kentaro Fukuchi.
+
+== LICENSING ==
+
+Copyright (C) 2010 by Dominik Dzienia 
+
+This library is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free
+Software Foundation; either version 3 of the License, or any later version.
+
+This library is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+PARTICULAR PURPOSE. See the GNU Lesser General Public License (LICENSE file)
+for more details.
+
+You should have received a copy of the GNU Lesser General Public License along
+with this library; if not, write to the Free Software Foundation, Inc., 51
+Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+== INSTALATION AND USAGE ==
+
+ * INSTALL file
+ * http://sourceforge.net/apps/mediawiki/phpqrcode/index.php?title=Main_Page
+
+== CONTACT ==
+
+Fell free to contact me via e-mail (deltalab at poczta dot fm) or using
+folowing project pages:
+
+ * http://sourceforge.net/projects/phpqrcode/
+ * http://phpqrcode.sourceforge.net/
+  
+== ACKNOWLEDGMENTS ==
+
+Based on C libqrencode library (ver. 3.1.1) 
+Copyright (C) 2006-2010 by Kentaro Fukuchi
+http://megaui.net/fukuchi/works/qrencode/index.en.html
+
+QR Code is registered trademarks of DENSO WAVE INCORPORATED in JAPAN and other
+countries.
+
+Reed-Solomon code encoder is written by Phil Karn, KA9Q.
+Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q
+ 

+ 2 - 0
core/libs/phpqrcode/VERSION

@@ -0,0 +1,2 @@
+1.1.4
+2010100721

+ 2875 - 0
core/libs/phpqrcode/bindings/tcpdf/qrcode.php

@@ -0,0 +1,2875 @@
+<?php
+//============================================================+
+// File name   : qrcode.php
+// Begin       : 2010-03-22
+// Last Update : 2010-03-29
+// Version     : 1.0.002
+// License     : GNU LGPL v.3 (http://www.gnu.org/copyleft/lesser.html)
+// 	----------------------------------------------------------------------------
+//
+// 	This library is free software; you can redistribute it and/or
+// 	modify it under the terms of the GNU Lesser General Public
+// 	License as published by the Free Software Foundation; either
+// 	version 3 of the License, or any later version.
+//
+// 	This library is distributed in the hope that it will be useful,
+// 	but WITHOUT ANY WARRANTY; without even the implied warranty of
+// 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// 	Lesser General Public License for more details.
+//
+// 	You should have received a copy of the GNU Lesser General Public
+// 	License along with this library; if not, write to the Free Software
+// 	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+//  or browse http://www.gnu.org/copyleft/lesser.html
+//
+//  ----------------------------------------------------------------------------
+//
+// DESCRIPTION :
+//
+// Class to create QR-code arrays for TCPDF class.
+// QR Code symbol is a 2D barcode that can be scanned by
+// handy terminals such as a mobile phone with CCD.
+// The capacity of QR Code is up to 7000 digits or 4000
+// characters, and has high robustness.
+// This class supports QR Code model 2, described in
+// JIS (Japanese Industrial Standards) X0510:2004
+// or ISO/IEC 18004.
+// Currently the following features are not supported:
+// ECI and FNC1 mode, Micro QR Code, QR Code model 1,
+// Structured mode.
+//
+// This class is derived from the following projects:
+// ---------------------------------------------------------
+// "PHP QR Code encoder"
+// License: GNU-LGPLv3
+// Copyright (C) 2010 by Dominik Dzienia <deltalab at poczta dot fm>
+// http://phpqrcode.sourceforge.net/
+// https://sourceforge.net/projects/phpqrcode/
+//
+// The "PHP QR Code encoder" is based on
+// "C libqrencode library" (ver. 3.1.1)
+// License: GNU-LGPL 2.1
+// Copyright (C) 2006-2010 by Kentaro Fukuchi
+// http://megaui.net/fukuchi/works/qrencode/index.en.html
+//
+// Reed-Solomon code encoder is written by Phil Karn, KA9Q.
+// Copyright (C) 2002-2006 Phil Karn, KA9Q
+//
+// QR Code is registered trademark of DENSO WAVE INCORPORATED
+// http://www.denso-wave.com/qrcode/index-e.html
+// ---------------------------------------------------------
+//
+// Author: Nicola Asuni
+//
+// (c) Copyright 2010:
+//               Nicola Asuni
+//               Tecnick.com S.r.l.
+//               Via della Pace, 11
+//               09044 Quartucciu (CA)
+//               ITALY
+//               www.tecnick.com
+//               info@tecnick.com
+//============================================================+
+
+/**
+ * Class to create QR-code arrays for TCPDF class.
+ * QR Code symbol is a 2D barcode that can be scanned by handy terminals such as a mobile phone with CCD.
+ * The capacity of QR Code is up to 7000 digits or 4000 characters, and has high robustness.
+ * This class supports QR Code model 2, described in JIS (Japanese Industrial Standards) X0510:2004 or ISO/IEC 18004.
+ * Currently the following features are not supported: ECI and FNC1 mode, Micro QR Code, QR Code model 1, Structured mode.
+ *
+ * This class is derived from "PHP QR Code encoder" by Dominik Dzienia (http://phpqrcode.sourceforge.net/) based on "libqrencode C library 3.1.1." by Kentaro Fukuchi (http://megaui.net/fukuchi/works/qrencode/index.en.html), contains Reed-Solomon code written by Phil Karn, KA9Q. QR Code is registered trademark of DENSO WAVE INCORPORATED (http://www.denso-wave.com/qrcode/index-e.html).
+ * Please read comments on this class source file for full copyright and license information.
+ *
+ * @package com.tecnick.tcpdf
+ * @abstract Class for generating QR-code array for TCPDF.
+ * @author Nicola Asuni
+ * @copyright 2010 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
+ * @link http://www.tcpdf.org
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL
+ * @version 1.0.002
+ */
+
+// definitions
+if (!defined('QRCODEDEFS')) {
+
+	/**
+	 * Indicate that definitions for this class are set
+	 */
+	define('QRCODEDEFS', true);
+
+	// -----------------------------------------------------
+
+	// Encoding modes (characters which can be encoded in QRcode)
+
+	/**
+	 * Encoding mode
+	 */
+	define('QR_MODE_NL', -1);
+
+	/**
+	 * Encoding mode numeric (0-9). 3 characters are encoded to 10bit length. In theory, 7089 characters or less can be stored in a QRcode.
+	 */
+	define('QR_MODE_NM', 0);
+
+	/**
+	 * Encoding mode alphanumeric (0-9A-Z $%*+-./:) 45characters. 2 characters are encoded to 11bit length. In theory, 4296 characters or less can be stored in a QRcode.
+	 */
+	define('QR_MODE_AN', 1);
+
+	/**
+	 * Encoding mode 8bit byte data. In theory, 2953 characters or less can be stored in a QRcode.
+	 */
+	define('QR_MODE_8B', 2);
+
+	/**
+	 * Encoding mode KANJI. A KANJI character (multibyte character) is encoded to 13bit length. In theory, 1817 characters or less can be stored in a QRcode.
+	 */
+	define('QR_MODE_KJ', 3);
+
+	/**
+	 * Encoding mode STRUCTURED (currently unsupported)
+	 */
+	define('QR_MODE_ST', 4);
+
+	// -----------------------------------------------------
+
+	// Levels of error correction.
+	// QRcode has a function of an error correcting for miss reading that white is black.
+	// Error correcting is defined in 4 level as below.
+
+	/**
+	 * Error correction level L : About 7% or less errors can be corrected.
+	 */
+	define('QR_ECLEVEL_L', 0);
+
+	/**
+	 * Error correction level M : About 15% or less errors can be corrected.
+	 */
+	define('QR_ECLEVEL_M', 1);
+
+	/**
+	 * Error correction level Q : About 25% or less errors can be corrected.
+	 */
+	define('QR_ECLEVEL_Q', 2);
+
+	/**
+	 * Error correction level H : About 30% or less errors can be corrected.
+	 */
+	define('QR_ECLEVEL_H', 3);
+
+	// -----------------------------------------------------
+
+	// Version. Size of QRcode is defined as version.
+	// Version is from 1 to 40.
+	// Version 1 is 21*21 matrix. And 4 modules increases whenever 1 version increases.
+	// So version 40 is 177*177 matrix.
+
+	/**
+	 * Maximum QR Code version.
+	 */
+	define('QRSPEC_VERSION_MAX', 40);
+
+	/**
+	 * Maximum matrix size for maximum version (version 40 is 177*177 matrix).
+	 */
+    define('QRSPEC_WIDTH_MAX', 177);
+
+	// -----------------------------------------------------
+
+	/**
+	 * Matrix index to get width from $capacity array.
+	 */
+    define('QRCAP_WIDTH',    0);
+
+    /**
+	 * Matrix index to get number of words from $capacity array.
+	 */
+    define('QRCAP_WORDS',    1);
+
+    /**
+	 * Matrix index to get remainder from $capacity array.
+	 */
+    define('QRCAP_REMINDER', 2);
+
+    /**
+	 * Matrix index to get error correction level from $capacity array.
+	 */
+    define('QRCAP_EC',       3);
+
+	// -----------------------------------------------------
+
+	// Structure (currently usupported)
+
+	/**
+	 * Number of header bits for structured mode
+	 */
+    define('STRUCTURE_HEADER_BITS',  20);
+
+    /**
+	 * Max number of symbols for structured mode
+	 */
+    define('MAX_STRUCTURED_SYMBOLS', 16);
+
+	// -----------------------------------------------------
+
+    // Masks
+
+    /**
+	 * Down point base value for case 1 mask pattern (concatenation of same color in a line or a column)
+	 */
+    define('N1',  3);
+
+    /**
+	 * Down point base value for case 2 mask pattern (module block of same color)
+	 */
+	define('N2',  3);
+
+    /**
+	 * Down point base value for case 3 mask pattern (1:1:3:1:1(dark:bright:dark:bright:dark)pattern in a line or a column)
+	 */
+	define('N3', 40);
+
+    /**
+	 * Down point base value for case 4 mask pattern (ration of dark modules in whole)
+	 */
+	define('N4', 10);
+
+	// -----------------------------------------------------
+
+	// Optimization settings
+
+	/**
+	 * if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
+	 */
+	define('QR_FIND_BEST_MASK', true);
+
+	/**
+	 * if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
+	 */
+	define('QR_FIND_FROM_RANDOM', 2);
+
+	/**
+	 * when QR_FIND_BEST_MASK === false
+	 */
+	define('QR_DEFAULT_MASK', 2);
+
+	// -----------------------------------------------------
+
+} // end of definitions
+
+// #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#
+
+if (!class_exists('QRcode', false)) {
+
+	// for compaibility with PHP4
+	if (!function_exists('str_split')) {
+    	/**
+    	 * Convert a string to an array (needed for PHP4 compatibility)
+    	 * @param string $string The input string.
+    	 * @param int $split_length Maximum length of the chunk.
+    	 * @return  If the optional split_length  parameter is specified, the returned array will be broken down into chunks with each being split_length  in length, otherwise each chunk will be one character in length. FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string , the entire string is returned as the first (and only) array element.
+    	 */
+		function str_split($string, $split_length=1) {
+			if ((strlen($string) > $split_length) OR (!$split_length)) {
+				do {
+					$c = strlen($string);
+					$parts[] = substr($string, 0, $split_length);
+					$string = substr($string, $split_length);
+				} while ($string !== false);
+			} else {
+				$parts = array($string);
+			}
+			return $parts;
+		}
+	}
+
+	// #####################################################
+
+	/**
+	 * Class to create QR-code arrays for TCPDF class.
+	 * QR Code symbol is a 2D barcode that can be scanned by handy terminals such as a mobile phone with CCD.
+	 * The capacity of QR Code is up to 7000 digits or 4000 characters, and has high robustness.
+	 * This class supports QR Code model 2, described in JIS (Japanese Industrial Standards) X0510:2004 or ISO/IEC 18004.
+	 * Currently the following features are not supported: ECI and FNC1 mode, Micro QR Code, QR Code model 1, Structured mode.
+	 *
+	 * This class is derived from "PHP QR Code encoder" by Dominik Dzienia (http://phpqrcode.sourceforge.net/) based on "libqrencode C library 3.1.1." by Kentaro Fukuchi (http://megaui.net/fukuchi/works/qrencode/index.en.html), contains Reed-Solomon code written by Phil Karn, KA9Q. QR Code is registered trademark of DENSO WAVE INCORPORATED (http://www.denso-wave.com/qrcode/index-e.html).
+	 * Please read comments on this class source file for full copyright and license information.
+	 *
+	 * @name QRcode
+	 * @package com.tecnick.tcpdf
+	 * @abstract Class for generating QR-code array for TCPDF.
+	 * @author Nicola Asuni
+	 * @copyright 2010 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
+	 * @link http://www.tcpdf.org
+	 * @license http://www.gnu.org/copyleft/lesser.html LGPL
+	 * @version 1.0.002
+	 */
+	class QRcode {
+
+		/**
+		 * @var barcode array to be returned which is readable by TCPDF
+		 * @access protected
+		 */
+		protected $barcode_array = array();
+
+		/**
+		 * @var QR code version. Size of QRcode is defined as version. Version is from 1 to 40. Version 1 is 21*21 matrix. And 4 modules increases whenever 1 version increases. So version 40 is 177*177 matrix.
+		 * @access protected
+		 */
+		protected $version = 0;
+
+		/**
+		 * @var Levels of error correction. See definitions for possible values.
+		 * @access protected
+		 */
+		protected $level = QR_ECLEVEL_L;
+
+		/**
+		 * @var Encoding mode
+		 * @access protected
+		 */
+		protected $hint = QR_MODE_8B;
+
+		/**
+		 * @var if true the input string will be converted to uppercase
+		 * @access protected
+		 */
+		protected $casesensitive = true;
+
+		/**
+		 * @var structured QR code (not supported yet)
+		 * @access protected
+		 */
+		protected $structured = 0;
+
+		/**
+		 * @var mask data
+		 * @access protected
+		 */
+		protected $data;
+
+		// FrameFiller
+
+		/**
+		 * @var width
+		 * @access protected
+		 */
+		protected $width;
+
+		/**
+		 * @var frame
+		 * @access protected
+		 */
+		protected $frame;
+
+		/**
+		 * @var X position of bit
+		 * @access protected
+		 */
+		protected $x;
+
+		/**
+		 * @var Y position of bit
+		 * @access protected
+		 */
+		protected $y;
+
+		/**
+		 * @var direction
+		 * @access protected
+		 */
+		protected $dir;
+
+		/**
+		 * @var single bit
+		 * @access protected
+		 */
+		protected $bit;
+
+		// ---- QRrawcode ----
+
+		/**
+		 * @var data code
+		 * @access protected
+		 */
+		protected $datacode = array();
+
+		/**
+		 * @var error correction code
+		 * @access protected
+		 */
+		protected $ecccode = array();
+
+		/**
+		 * @var blocks
+		 * @access protected
+		 */
+		protected $blocks;
+
+		/**
+		 * @var Reed-Solomon blocks
+		 * @access protected
+		 */
+		protected $rsblocks = array(); //of RSblock
+
+		/**
+		 * @var counter
+		 * @access protected
+		 */
+		protected $count;
+
+		/**
+		 * @var data length
+		 * @access protected
+		 */
+		protected $dataLength;
+
+		/**
+		 * @var error correction length
+		 * @access protected
+		 */
+		protected $eccLength;
+
+		/**
+		 * @var b1
+		 * @access protected
+		 */
+		protected $b1;
+
+		// ---- QRmask ----
+
+		/**
+		 * @var run length
+		 * @access protected
+		 */
+		protected $runLength = array();
+
+		// ---- QRsplit ----
+
+		/**
+		 * @var input data string
+		 * @access protected
+		 */
+		protected $dataStr = '';
+
+		/**
+		 * @var input items
+		 * @access protected
+		 */
+		protected $items;
+
+		// Reed-Solomon items
+
+		/**
+		 * @var Reed-Solomon items
+		 * @access protected
+		 */
+		protected $rsitems = array();
+
+		/**
+		 * @var array of frames
+		 * @access protected
+		 */
+		protected $frames = array();
+
+		/**
+		 * @var alphabet-numeric convesion table
+		 * @access protected
+		 */
+		protected $anTable = array(
+			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //
+			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //
+			36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, //
+			 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 44, -1, -1, -1, -1, -1, //
+			-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, //
+			25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, //
+			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //
+			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1  //
+			);
+
+		/**
+		 * @var array Table of the capacity of symbols
+		 * See Table 1 (pp.13) and Table 12-16 (pp.30-36), JIS X0510:2004.
+		 * @access protected
+		 */
+		protected $capacity = array(
+			array(  0,    0, 0, array(   0,    0,    0,    0)), //
+			array( 21,   26, 0, array(   7,   10,   13,   17)), //  1
+			array( 25,   44, 7, array(  10,   16,   22,   28)), //
+			array( 29,   70, 7, array(  15,   26,   36,   44)), //
+			array( 33,  100, 7, array(  20,   36,   52,   64)), //
+			array( 37,  134, 7, array(  26,   48,   72,   88)), //  5
+			array( 41,  172, 7, array(  36,   64,   96,  112)), //
+			array( 45,  196, 0, array(  40,   72,  108,  130)), //
+			array( 49,  242, 0, array(  48,   88,  132,  156)), //
+			array( 53,  292, 0, array(  60,  110,  160,  192)), //
+			array( 57,  346, 0, array(  72,  130,  192,  224)), // 10
+			array( 61,  404, 0, array(  80,  150,  224,  264)), //
+			array( 65,  466, 0, array(  96,  176,  260,  308)), //
+			array( 69,  532, 0, array( 104,  198,  288,  352)), //
+			array( 73,  581, 3, array( 120,  216,  320,  384)), //
+			array( 77,  655, 3, array( 132,  240,  360,  432)), // 15
+			array( 81,  733, 3, array( 144,  280,  408,  480)), //
+			array( 85,  815, 3, array( 168,  308,  448,  532)), //
+			array( 89,  901, 3, array( 180,  338,  504,  588)), //
+			array( 93,  991, 3, array( 196,  364,  546,  650)), //
+			array( 97, 1085, 3, array( 224,  416,  600,  700)), // 20
+			array(101, 1156, 4, array( 224,  442,  644,  750)), //
+			array(105, 1258, 4, array( 252,  476,  690,  816)), //
+			array(109, 1364, 4, array( 270,  504,  750,  900)), //
+			array(113, 1474, 4, array( 300,  560,  810,  960)), //
+			array(117, 1588, 4, array( 312,  588,  870, 1050)), // 25
+			array(121, 1706, 4, array( 336,  644,  952, 1110)), //
+			array(125, 1828, 4, array( 360,  700, 1020, 1200)), //
+			array(129, 1921, 3, array( 390,  728, 1050, 1260)), //
+			array(133, 2051, 3, array( 420,  784, 1140, 1350)), //
+			array(137, 2185, 3, array( 450,  812, 1200, 1440)), // 30
+			array(141, 2323, 3, array( 480,  868, 1290, 1530)), //
+			array(145, 2465, 3, array( 510,  924, 1350, 1620)), //
+			array(149, 2611, 3, array( 540,  980, 1440, 1710)), //
+			array(153, 2761, 3, array( 570, 1036, 1530, 1800)), //
+			array(157, 2876, 0, array( 570, 1064, 1590, 1890)), // 35
+			array(161, 3034, 0, array( 600, 1120, 1680, 1980)), //
+			array(165, 3196, 0, array( 630, 1204, 1770, 2100)), //
+			array(169, 3362, 0, array( 660, 1260, 1860, 2220)), //
+			array(173, 3532, 0, array( 720, 1316, 1950, 2310)), //
+			array(177, 3706, 0, array( 750, 1372, 2040, 2430))  // 40
+		);
+
+		/**
+		 * @var array Length indicator
+		 * @access protected
+		 */
+		protected $lengthTableBits = array(
+			array(10, 12, 14),
+			array( 9, 11, 13),
+			array( 8, 16, 16),
+			array( 8, 10, 12)
+		);
+
+		/**
+		 * @var array Table of the error correction code (Reed-Solomon block)
+		 * See Table 12-16 (pp.30-36), JIS X0510:2004.
+		 * @access protected
+		 */
+		protected $eccTable = array(
+			array(array( 0,  0), array( 0,  0), array( 0,  0), array( 0,  0)), //
+			array(array( 1,  0), array( 1,  0), array( 1,  0), array( 1,  0)), //  1
+			array(array( 1,  0), array( 1,  0), array( 1,  0), array( 1,  0)), //
+			array(array( 1,  0), array( 1,  0), array( 2,  0), array( 2,  0)), //
+			array(array( 1,  0), array( 2,  0), array( 2,  0), array( 4,  0)), //
+			array(array( 1,  0), array( 2,  0), array( 2,  2), array( 2,  2)), //  5
+			array(array( 2,  0), array( 4,  0), array( 4,  0), array( 4,  0)), //
+			array(array( 2,  0), array( 4,  0), array( 2,  4), array( 4,  1)), //
+			array(array( 2,  0), array( 2,  2), array( 4,  2), array( 4,  2)), //
+			array(array( 2,  0), array( 3,  2), array( 4,  4), array( 4,  4)), //
+			array(array( 2,  2), array( 4,  1), array( 6,  2), array( 6,  2)), // 10
+			array(array( 4,  0), array( 1,  4), array( 4,  4), array( 3,  8)), //
+			array(array( 2,  2), array( 6,  2), array( 4,  6), array( 7,  4)), //
+			array(array( 4,  0), array( 8,  1), array( 8,  4), array(12,  4)), //
+			array(array( 3,  1), array( 4,  5), array(11,  5), array(11,  5)), //
+			array(array( 5,  1), array( 5,  5), array( 5,  7), array(11,  7)), // 15
+			array(array( 5,  1), array( 7,  3), array(15,  2), array( 3, 13)), //
+			array(array( 1,  5), array(10,  1), array( 1, 15), array( 2, 17)), //
+			array(array( 5,  1), array( 9,  4), array(17,  1), array( 2, 19)), //
+			array(array( 3,  4), array( 3, 11), array(17,  4), array( 9, 16)), //
+			array(array( 3,  5), array( 3, 13), array(15,  5), array(15, 10)), // 20
+			array(array( 4,  4), array(17,  0), array(17,  6), array(19,  6)), //
+			array(array( 2,  7), array(17,  0), array( 7, 16), array(34,  0)), //
+			array(array( 4,  5), array( 4, 14), array(11, 14), array(16, 14)), //
+			array(array( 6,  4), array( 6, 14), array(11, 16), array(30,  2)), //
+			array(array( 8,  4), array( 8, 13), array( 7, 22), array(22, 13)), // 25
+			array(array(10,  2), array(19,  4), array(28,  6), array(33,  4)), //
+			array(array( 8,  4), array(22,  3), array( 8, 26), array(12, 28)), //
+			array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), //
+			array(array( 7,  7), array(21,  7), array( 1, 37), array(19, 26)), //
+			array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), // 30
+			array(array(13,  3), array( 2, 29), array(42,  1), array(23, 28)), //
+			array(array(17,  0), array(10, 23), array(10, 35), array(19, 35)), //
+			array(array(17,  1), array(14, 21), array(29, 19), array(11, 46)), //
+			array(array(13,  6), array(14, 23), array(44,  7), array(59,  1)), //
+			array(array(12,  7), array(12, 26), array(39, 14), array(22, 41)), // 35
+			array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), //
+			array(array(17,  4), array(29, 14), array(49, 10), array(24, 46)), //
+			array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), //
+			array(array(20,  4), array(40,  7), array(43, 22), array(10, 67)), //
+			array(array(19,  6), array(18, 31), array(34, 34), array(20, 61))  // 40
+		);
+
+		/**
+		 * @var array Positions of alignment patterns.
+		 * This array includes only the second and the third position of the alignment patterns. Rest of them can be calculated from the distance between them.
+		 * See Table 1 in Appendix E (pp.71) of JIS X0510:2004.
+		 * @access protected
+		 */
+		protected $alignmentPattern = array(
+			array( 0,  0),
+			array( 0,  0), array(18,  0), array(22,  0), array(26,  0), array(30,  0), //  1- 5
+			array(34,  0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), //  6-10
+			array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), // 11-15
+			array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), // 16-20
+			array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), // 21-25
+			array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), // 26-30
+			array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), // 31-35
+			array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58)  // 35-40
+		);
+
+		/**
+		 * @var array Version information pattern (BCH coded).
+		 * See Table 1 in Appendix D (pp.68) of JIS X0510:2004.
+		 * size: [QRSPEC_VERSION_MAX - 6]
+		 * @access protected
+		 */
+		protected $versionPattern = array(
+			0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, //
+			0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, //
+			0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, //
+			0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, //
+			0x27541, 0x28c69
+		);
+
+		/**
+		 * @var array Format information
+		 * @access protected
+		 */
+		protected $formatInfo = array(
+			array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), //
+			array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), //
+			array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), //
+			array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b)  //
+		);
+
+
+		// -------------------------------------------------
+		// -------------------------------------------------
+
+
+		/**
+		 * This is the class constructor.
+		 * Creates a QRcode object
+		 * @param string $code code to represent using QRcode
+		 * @param string $eclevel error level: <ul><li>L : About 7% or less errors can be corrected.</li><li>M : About 15% or less errors can be corrected.</li><li>Q : About 25% or less errors can be corrected.</li><li>H : About 30% or less errors can be corrected.</li></ul>
+		 * @access public
+		 * @since 1.0.000
+		 */
+		public function __construct($code, $eclevel = 'L') {
+			$barcode_array = array();
+			if ((is_null($code)) OR ($code == '\0') OR ($code == '')) {
+				return false;
+			}
+			// set error correction level
+			$this->level = array_search($eclevel, array('L', 'M', 'Q', 'H'));
+			if ($this->level === false) {
+				$this->level = QR_ECLEVEL_L;
+			}
+			if (($this->hint != QR_MODE_8B) AND ($this->hint != QR_MODE_KJ)) {
+				return false;
+			}
+			if (($this->version < 0) OR ($this->version > QRSPEC_VERSION_MAX)) {
+				return false;
+			}
+			$this->items = array();
+			$this->encodeString($code);
+			$qrTab = $this->binarize($this->data);
+			$size = count($qrTab);
+			$barcode_array['num_rows'] = $size;
+			$barcode_array['num_cols'] = $size;
+			$barcode_array['bcode'] = array();
+			foreach ($qrTab as $line) {
+				$arrAdd = array();
+				foreach (str_split($line) as $char) {
+					$arrAdd[] = ($char=='1')?1:0;
+				}
+				$barcode_array['bcode'][] = $arrAdd;
+			}
+			$this->barcode_array = $barcode_array;
+		}
+
+		/**
+		 * Returns a barcode array which is readable by TCPDF
+		 * @return array barcode array readable by TCPDF;
+		 * @access public
+		 */
+		public function getBarcodeArray() {
+			return $this->barcode_array;
+		}
+
+		/**
+		 * Convert the frame in binary form
+		 * @param array $frame array to binarize
+		 * @return array frame in binary form
+		 */
+		protected function binarize($frame) {
+			$len = count($frame);
+			// the frame is square (width = height)
+			foreach ($frame as &$frameLine) {
+				for ($i=0; $i<$len; $i++) {
+					$frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';
+				}
+			}
+			return $frame;
+		}
+
+		/**
+		 * Encode the input string to QR code
+		 * @param string $string input string to encode
+		 */
+		protected function encodeString($string) {
+			$this->dataStr = $string;
+			if (!$this->casesensitive) {
+				$this->toUpper();
+			}
+			$ret = $this->splitString();
+			if ($ret < 0) {
+				return NULL;
+			}
+			$this->encodeMask(-1);
+		}
+
+		/**
+		 * Encode mask
+		 * @param int $mask masking mode
+		 */
+		protected function encodeMask($mask) {
+			$spec = array(0, 0, 0, 0, 0);
+			$this->datacode = $this->getByteStream($this->items);
+			if (is_null($this->datacode)) {
+				return NULL;
+			}
+			$spec = $this->getEccSpec($this->version, $this->level, $spec);
+			$this->b1 = $this->rsBlockNum1($spec);
+			$this->dataLength = $this->rsDataLength($spec);
+			$this->eccLength = $this->rsEccLength($spec);
+			$this->ecccode = array_fill(0, $this->eccLength, 0);
+			$this->blocks = $this->rsBlockNum($spec);
+			$ret = $this->init($spec);
+			if ($ret < 0) {
+				return NULL;
+			}
+			$this->count = 0;
+			$this->width = $this->getWidth($this->version);
+			$this->frame = $this->newFrame($this->version);
+			$this->x = $this->width - 1;
+			$this->y = $this->width - 1;
+			$this->dir = -1;
+			$this->bit = -1;
+			// inteleaved data and ecc codes
+			for ($i=0; $i < ($this->dataLength + $this->eccLength); $i++) {
+				$code = $this->getCode();
+				$bit = 0x80;
+				for ($j=0; $j<8; $j++) {
+					$addr = $this->getNextPosition();
+					$this->setFrameAt($addr, 0x02 | (($bit & $code) != 0));
+					$bit = $bit >> 1;
+				}
+			}
+			// remainder bits
+			$j = $this->getRemainder($this->version);
+			for ($i=0; $i<$j; $i++) {
+				$addr = $this->getNextPosition();
+				$this->setFrameAt($addr, 0x02);
+			}
+			// masking
+			$this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0);
+			if ($mask < 0) {
+				if (QR_FIND_BEST_MASK) {
+					$masked = $this->mask($this->width, $this->frame, $this->level);
+				} else {
+					$masked = $this->makeMask($this->width, $this->frame, (intval(QR_DEFAULT_MASK) % 8), $this->level);
+				}
+			} else {
+				$masked = $this->makeMask($this->width, $this->frame, $mask, $this->level);
+			}
+			if ($masked == NULL) {
+				return NULL;
+			}
+			$this->data = $masked;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// FrameFiller
+
+		/**
+		 * Set frame value at specified position
+		 * @param array $at x,y position
+		 * @param int $val value of the character to set
+		 */
+		protected function setFrameAt($at, $val) {
+			$this->frame[$at['y']][$at['x']] = chr($val);
+		}
+
+		/**
+		 * Get frame value at specified position
+		 * @param array $at x,y position
+		 * @return value at specified position
+		 */
+		protected function getFrameAt($at) {
+			return ord($this->frame[$at['y']][$at['x']]);
+		}
+
+		/**
+		 * Return the next frame position
+		 * @return array of x,y coordinates
+		 */
+		protected function getNextPosition() {
+			do {
+				if ($this->bit == -1) {
+					$this->bit = 0;
+					return array('x'=>$this->x, 'y'=>$this->y);
+				}
+				$x = $this->x;
+				$y = $this->y;
+				$w = $this->width;
+				if ($this->bit == 0) {
+					$x--;
+					$this->bit++;
+				} else {
+					$x++;
+					$y += $this->dir;
+					$this->bit--;
+				}
+				if ($this->dir < 0) {
+					if ($y < 0) {
+						$y = 0;
+						$x -= 2;
+						$this->dir = 1;
+						if ($x == 6) {
+							$x--;
+							$y = 9;
+						}
+					}
+				} else {
+					if ($y == $w) {
+						$y = $w - 1;
+						$x -= 2;
+						$this->dir = -1;
+						if ($x == 6) {
+							$x--;
+							$y -= 8;
+						}
+					}
+				}
+				if (($x < 0) OR ($y < 0)) {
+					return NULL;
+				}
+				$this->x = $x;
+				$this->y = $y;
+			} while(ord($this->frame[$y][$x]) & 0x80);
+			return array('x'=>$x, 'y'=>$y);
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRrawcode
+
+		/**
+		 * Initialize code.
+		 * @param array $spec array of ECC specification
+		 * @return 0 in case of success, -1 in case of error
+		 */
+		protected function init($spec) {
+			$dl = $this->rsDataCodes1($spec);
+			$el = $this->rsEccCodes1($spec);
+			$rs = $this->init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+			$blockNo = 0;
+			$dataPos = 0;
+			$eccPos = 0;
+			$endfor = $this->rsBlockNum1($spec);
+			for ($i=0; $i < $endfor; ++$i) {
+				$ecc = array_slice($this->ecccode, $eccPos);
+				$this->rsblocks[$blockNo] = array();
+				$this->rsblocks[$blockNo]['dataLength'] = $dl;
+				$this->rsblocks[$blockNo]['data'] = array_slice($this->datacode, $dataPos);
+				$this->rsblocks[$blockNo]['eccLength'] = $el;
+				$ecc = $this->encode_rs_char($rs, $this->rsblocks[$blockNo]['data'], $ecc);
+				$this->rsblocks[$blockNo]['ecc'] = $ecc;
+				$this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
+				$dataPos += $dl;
+				$eccPos += $el;
+				$blockNo++;
+			}
+			if ($this->rsBlockNum2($spec) == 0) {
+				return 0;
+			}
+			$dl = $this->rsDataCodes2($spec);
+			$el = $this->rsEccCodes2($spec);
+			$rs = $this->init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
+			if ($rs == NULL) {
+				return -1;
+			}
+			$endfor = $this->rsBlockNum2($spec);
+			for ($i=0; $i < $endfor; ++$i) {
+				$ecc = array_slice($this->ecccode, $eccPos);
+				$this->rsblocks[$blockNo] = array();
+				$this->rsblocks[$blockNo]['dataLength'] = $dl;
+				$this->rsblocks[$blockNo]['data'] = array_slice($this->datacode, $dataPos);
+				$this->rsblocks[$blockNo]['eccLength'] = $el;
+				$ecc = $this->encode_rs_char($rs, $this->rsblocks[$blockNo]['data'], $ecc);
+				$this->rsblocks[$blockNo]['ecc'] = $ecc;
+				$this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc);
+				$dataPos += $dl;
+				$eccPos += $el;
+				$blockNo++;
+			}
+			return 0;
+		}
+
+		/**
+		 * Return Reed-Solomon block code.
+		 * @return array rsblocks
+		 */
+		protected function getCode() {
+			if ($this->count < $this->dataLength) {
+				$row = $this->count % $this->blocks;
+				$col = $this->count / $this->blocks;
+				if ($col >= $this->rsblocks[0]['dataLength']) {
+					$row += $this->b1;
+				}
+				$ret = $this->rsblocks[$row]['data'][$col];
+			} elseif ($this->count < $this->dataLength + $this->eccLength) {
+				$row = ($this->count - $this->dataLength) % $this->blocks;
+				$col = ($this->count - $this->dataLength) / $this->blocks;
+				$ret = $this->rsblocks[$row]['ecc'][$col];
+			} else {
+				return 0;
+			}
+			$this->count++;
+			return $ret;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRmask
+
+		/**
+		 * Write Format Information on frame and returns the number of black bits
+		 * @param int $width frame width
+		 * @param array $frame frame
+		 * @param array $mask masking mode
+		 * @param int $level error correction level
+		 * @return int blacks
+		 */
+		 protected function writeFormatInformation($width, &$frame, $mask, $level) {
+			$blacks = 0;
+			$format =  $this->getFormatInfo($mask, $level);
+			for ($i=0; $i<8; ++$i) {
+				if ($format & 1) {
+					$blacks += 2;
+					$v = 0x85;
+				} else {
+					$v = 0x84;
+				}
+				$frame[8][$width - 1 - $i] = chr($v);
+				if ($i < 6) {
+					$frame[$i][8] = chr($v);
+				} else {
+					$frame[$i + 1][8] = chr($v);
+				}
+				$format = $format >> 1;
+			}
+			for ($i=0; $i<7; ++$i) {
+			if ($format & 1) {
+				$blacks += 2;
+				$v = 0x85;
+			} else {
+				$v = 0x84;
+			}
+			$frame[$width - 7 + $i][8] = chr($v);
+			if ($i == 0) {
+				$frame[8][7] = chr($v);
+			} else {
+				$frame[8][6 - $i] = chr($v);
+			}
+			$format = $format >> 1;
+			}
+			return $blacks;
+		}
+
+		/**
+		 * mask0
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask0($x, $y) {
+			return ($x + $y) & 1;
+		}
+
+		/**
+		 * mask1
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask1($x, $y) {
+			return ($y & 1);
+		}
+
+		/**
+		 * mask2
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask2($x, $y) {
+			return ($x % 3);
+		}
+
+		/**
+		 * mask3
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask3($x, $y) {
+			return ($x + $y) % 3;
+		}
+
+		/**
+		 * mask4
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask4($x, $y) {
+			return (((int)($y / 2)) + ((int)($x / 3))) & 1;
+		}
+
+		/**
+		 * mask5
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask5($x, $y) {
+			return (($x * $y) & 1) + ($x * $y) % 3;
+		}
+
+		/**
+		 * mask6
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask6($x, $y) {
+			return ((($x * $y) & 1) + ($x * $y) % 3) & 1;
+		}
+
+		/**
+		 * mask7
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @return int mask
+		 */
+		 protected function mask7($x, $y) {
+			return ((($x * $y) % 3) + (($x + $y) & 1)) & 1;
+		}
+
+		/**
+		 * Return bitmask
+		 * @param int $maskNo mask number
+		 * @param int $width width
+		 * @param array $frame frame
+		 * @return array bitmask
+		 */
+		protected function generateMaskNo($maskNo, $width, $frame) {
+			$bitMask = array_fill(0, $width, array_fill(0, $width, 0));
+			for ($y=0; $y<$width; ++$y) {
+				for ($x=0; $x<$width; ++$x) {
+					if (ord($frame[$y][$x]) & 0x80) {
+						$bitMask[$y][$x] = 0;
+					} else {
+						$maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y);
+						$bitMask[$y][$x] = ($maskFunc == 0)?1:0;
+					}
+				}
+			}
+			return $bitMask;
+		}
+
+		/**
+		 * makeMaskNo
+		 * @param int $maskNo
+		 * @param int $width
+		 * @param int $s
+		 * @param int $d
+		 * @param boolean $maskGenOnly
+		 * @return int b
+		 */
+		 protected function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly=false) {
+			$b = 0;
+			$bitMask = array();
+			$bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
+			if ($maskGenOnly) {
+				return;
+			}
+			$d = $s;
+			for ($y=0; $y<$width; ++$y) {
+				for ($x=0; $x<$width; ++$x) {
+					if ($bitMask[$y][$x] == 1) {
+						$d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]);
+					}
+					$b += (int)(ord($d[$y][$x]) & 1);
+				}
+			}
+			return $b;
+		}
+
+		/**
+		 * makeMask
+		 * @param int $width
+		 * @param array $frame
+		 * @param int $maskNo
+		 * @param int $level
+		 * @return array mask
+		 */
+		 protected function makeMask($width, $frame, $maskNo, $level) {
+			$masked = array_fill(0, $width, str_repeat("\0", $width));
+			$this->makeMaskNo($maskNo, $width, $frame, $masked);
+			$this->writeFormatInformation($width, $masked, $maskNo, $level);
+			return $masked;
+		}
+
+		/**
+		 * calcN1N3
+		 * @param int $length
+		 * @return int demerit
+		 */
+		 protected function calcN1N3($length) {
+			$demerit = 0;
+			for ($i=0; $i<$length; ++$i) {
+				if ($this->runLength[$i] >= 5) {
+					$demerit += (N1 + ($this->runLength[$i] - 5));
+				}
+				if ($i & 1) {
+					if (($i >= 3) AND ($i < ($length-2)) AND ($this->runLength[$i] % 3 == 0)) {
+						$fact = (int)($this->runLength[$i] / 3);
+						if (($this->runLength[$i-2] == $fact)
+							AND ($this->runLength[$i-1] == $fact)
+							AND ($this->runLength[$i+1] == $fact)
+							AND ($this->runLength[$i+2] == $fact)) {
+							if (($this->runLength[$i-3] < 0) OR ($this->runLength[$i-3] >= (4 * $fact))) {
+								$demerit += N3;
+							} elseif ((($i+3) >= $length) OR ($this->runLength[$i+3] >= (4 * $fact))) {
+								$demerit += N3;
+							}
+						}
+					}
+				}
+			}
+			return $demerit;
+		}
+
+		/**
+		 * evaluateSymbol
+		 * @param int $width
+		 * @param array $frame
+		 * @return int demerit
+		 */
+		 protected function evaluateSymbol($width, $frame) {
+			$head = 0;
+			$demerit = 0;
+			for ($y=0; $y<$width; ++$y) {
+				$head = 0;
+				$this->runLength[0] = 1;
+				$frameY = $frame[$y];
+				if ($y > 0) {
+					$frameYM = $frame[$y-1];
+				}
+				for ($x=0; $x<$width; ++$x) {
+					if (($x > 0) AND ($y > 0)) {
+						$b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]);
+						$w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]);
+						if (($b22 | ($w22 ^ 1)) & 1) {
+							$demerit += N2;
+						}
+					}
+					if (($x == 0) AND (ord($frameY[$x]) & 1)) {
+						$this->runLength[0] = -1;
+						$head = 1;
+						$this->runLength[$head] = 1;
+					} elseif ($x > 0) {
+						if ((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) {
+							$head++;
+							$this->runLength[$head] = 1;
+						} else {
+							$this->runLength[$head]++;
+						}
+					}
+				}
+				$demerit += $this->calcN1N3($head+1);
+			}
+			for ($x=0; $x<$width; ++$x) {
+				$head = 0;
+				$this->runLength[0] = 1;
+				for ($y=0; $y<$width; ++$y) {
+					if (($y == 0) AND (ord($frame[$y][$x]) & 1)) {
+						$this->runLength[0] = -1;
+						$head = 1;
+						$this->runLength[$head] = 1;
+					} elseif ($y > 0) {
+						if ((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) {
+							$head++;
+							$this->runLength[$head] = 1;
+						} else {
+							$this->runLength[$head]++;
+						}
+					}
+				}
+				$demerit += $this->calcN1N3($head+1);
+			}
+			return $demerit;
+		}
+
+		/**
+		 * mask
+		 * @param int $width
+		 * @param array $frame
+		 * @param int $level
+		 * @return array best mask
+		 */
+		 protected function mask($width, $frame, $level) {
+			$minDemerit = PHP_INT_MAX;
+			$bestMaskNum = 0;
+			$bestMask = array();
+			$checked_masks = array(0, 1, 2, 3, 4, 5, 6, 7);
+			if (QR_FIND_FROM_RANDOM !== false) {
+				$howManuOut = 8 - (QR_FIND_FROM_RANDOM % 9);
+				for ($i = 0; $i <  $howManuOut; ++$i) {
+					$remPos = rand (0, count($checked_masks)-1);
+					unset($checked_masks[$remPos]);
+					$checked_masks = array_values($checked_masks);
+				}
+			}
+			$bestMask = $frame;
+			foreach ($checked_masks as $i) {
+				$mask = array_fill(0, $width, str_repeat("\0", $width));
+				$demerit = 0;
+				$blacks = 0;
+				$blacks  = $this->makeMaskNo($i, $width, $frame, $mask);
+				$blacks += $this->writeFormatInformation($width, $mask, $i, $level);
+				$blacks  = (int)(100 * $blacks / ($width * $width));
+				$demerit = (int)((int)(abs($blacks - 50) / 5) * N4);
+				$demerit += $this->evaluateSymbol($width, $mask);
+				if ($demerit < $minDemerit) {
+					$minDemerit = $demerit;
+					$bestMask = $mask;
+					$bestMaskNum = $i;
+				}
+			}
+			return $bestMask;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRsplit
+
+		/**
+		 * Return true if the character at specified position is a number
+		 * @param string $str string
+		 * @param int $pos characted position
+		 * @return boolean true of false
+		 */
+		 protected function isdigitat($str, $pos) {
+			if ($pos >= strlen($str)) {
+				return false;
+			}
+			return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9')));
+		}
+
+		/**
+		 * Return true if the character at specified position is an alphanumeric character
+		 * @param string $str string
+		 * @param int $pos characted position
+		 * @return boolean true of false
+		 */
+		 protected function isalnumat($str, $pos) {
+			if ($pos >= strlen($str)) {
+				return false;
+			}
+			return ($this->lookAnTable(ord($str[$pos])) >= 0);
+		}
+
+		/**
+		 * identifyMode
+		 * @param int $pos
+		 * @return int mode
+		 */
+		 protected function identifyMode($pos) {
+			if ($pos >= strlen($this->dataStr)) {
+				return QR_MODE_NL;
+			}
+			$c = $this->dataStr[$pos];
+			if ($this->isdigitat($this->dataStr, $pos)) {
+				return QR_MODE_NM;
+			} elseif ($this->isalnumat($this->dataStr, $pos)) {
+				return QR_MODE_AN;
+			} elseif ($this->hint == QR_MODE_KJ) {
+				if ($pos+1 < strlen($this->dataStr)) {
+					$d = $this->dataStr[$pos+1];
+					$word = (ord($c) << 8) | ord($d);
+					if (($word >= 0x8140 && $word <= 0x9ffc) OR ($word >= 0xe040 && $word <= 0xebbf)) {
+						return QR_MODE_KJ;
+					}
+				}
+			}
+			return QR_MODE_8B;
+		}
+
+		/**
+		 * eatNum
+		 * @return int run
+		 */
+		 protected function eatNum() {
+			$ln = $this->lengthIndicator(QR_MODE_NM, $this->version);
+			$p = 0;
+			while($this->isdigitat($this->dataStr, $p)) {
+				$p++;
+			}
+			$run = $p;
+			$mode = $this->identifyMode($p);
+			if ($mode == QR_MODE_8B) {
+				$dif = $this->estimateBitsModeNum($run) + 4 + $ln
+				+ $this->estimateBitsMode8(1)         // + 4 + l8
+				- $this->estimateBitsMode8($run + 1); // - 4 - l8
+				if ($dif > 0) {
+					return $this->eat8();
+				}
+			}
+			if ($mode == QR_MODE_AN) {
+				$dif = $this->estimateBitsModeNum($run) + 4 + $ln
+				+ $this->estimateBitsModeAn(1)        // + 4 + la
+				- $this->estimateBitsModeAn($run + 1);// - 4 - la
+				if ($dif > 0) {
+					return $this->eatAn();
+				}
+			}
+			$this->items = $this->appendNewInputItem($this->items, QR_MODE_NM, $run, str_split($this->dataStr));
+			return $run;
+		}
+
+		/**
+		 * eatAn
+		 * @return int run
+		 */
+		 protected function eatAn() {
+			$la = $this->lengthIndicator(QR_MODE_AN,  $this->version);
+			$ln = $this->lengthIndicator(QR_MODE_NM, $this->version);
+			$p = 0;
+			while($this->isalnumat($this->dataStr, $p)) {
+				if ($this->isdigitat($this->dataStr, $p)) {
+					$q = $p;
+					while($this->isdigitat($this->dataStr, $q)) {
+						$q++;
+					}
+					$dif = $this->estimateBitsModeAn($p) // + 4 + la
+					+ $this->estimateBitsModeNum($q - $p) + 4 + $ln
+					- $this->estimateBitsModeAn($q); // - 4 - la
+					if ($dif < 0) {
+						break;
+					} else {
+						$p = $q;
+					}
+				} else {
+					$p++;
+				}
+			}
+			$run = $p;
+			if (!$this->isalnumat($this->dataStr, $p)) {
+				$dif = $this->estimateBitsModeAn($run) + 4 + $la
+				+ $this->estimateBitsMode8(1) // + 4 + l8
+				- $this->estimateBitsMode8($run + 1); // - 4 - l8
+				if ($dif > 0) {
+					return $this->eat8();
+				}
+			}
+			$this->items = $this->appendNewInputItem($this->items, QR_MODE_AN, $run, str_split($this->dataStr));
+			return $run;
+		}
+
+		/**
+		 * eatKanji
+		 * @return int run
+		 */
+		 protected function eatKanji() {
+			$p = 0;
+			while($this->identifyMode($p) == QR_MODE_KJ) {
+				$p += 2;
+			}
+			$this->items = $this->appendNewInputItem($this->items, QR_MODE_KJ, $p, str_split($this->dataStr));
+			return $run;
+		}
+
+		/**
+		 * eat8
+		 * @return int run
+		 */
+		 protected function eat8() {
+			$la = $this->lengthIndicator(QR_MODE_AN, $this->version);
+			$ln = $this->lengthIndicator(QR_MODE_NM, $this->version);
+			$p = 1;
+			$dataStrLen = strlen($this->dataStr);
+			while($p < $dataStrLen) {
+				$mode = $this->identifyMode($p);
+				if ($mode == QR_MODE_KJ) {
+					break;
+				}
+				if ($mode == QR_MODE_NM) {
+					$q = $p;
+					while($this->isdigitat($this->dataStr, $q)) {
+						$q++;
+					}
+					$dif = $this->estimateBitsMode8($p) // + 4 + l8
+					+ $this->estimateBitsModeNum($q - $p) + 4 + $ln
+					- $this->estimateBitsMode8($q); // - 4 - l8
+					if ($dif < 0) {
+						break;
+					} else {
+						$p = $q;
+					}
+				} elseif ($mode == QR_MODE_AN) {
+					$q = $p;
+					while($this->isalnumat($this->dataStr, $q)) {
+						$q++;
+					}
+					$dif = $this->estimateBitsMode8($p)  // + 4 + l8
+					+ $this->estimateBitsModeAn($q - $p) + 4 + $la
+					- $this->estimateBitsMode8($q); // - 4 - l8
+					if ($dif < 0) {
+						break;
+					} else {
+						$p = $q;
+					}
+				} else {
+					$p++;
+				}
+			}
+			$run = $p;
+			$this->items = $this->appendNewInputItem($this->items, QR_MODE_8B, $run, str_split($this->dataStr));
+			return $run;
+		}
+
+		/**
+		 * splitString
+		 */
+		 protected function splitString() {
+			while (strlen($this->dataStr) > 0) {
+				if ($this->dataStr == '') {
+					return 0;
+				}
+				$mode = $this->identifyMode(0);
+				switch ($mode) {
+					case QR_MODE_NM: {
+						$length = $this->eatNum();
+						break;
+					}
+					case QR_MODE_AN: {
+						$length = $this->eatAn();
+						break;
+					}
+					case QR_MODE_KJ: {
+						if ($hint == QR_MODE_KJ) {
+							$length = $this->eatKanji();
+						} else {
+							$length = $this->eat8();
+						}
+						break;
+					}
+					default: {
+						$length = $this->eat8();
+						break;
+					}
+				}
+				if ($length == 0) {
+					return 0;
+				}
+				if ($length < 0) {
+					return -1;
+				}
+				$this->dataStr = substr($this->dataStr, $length);
+			}
+		}
+
+		/**
+		 * toUpper
+		 */
+		 protected function toUpper() {
+			$stringLen = strlen($this->dataStr);
+			$p = 0;
+			while ($p < $stringLen) {
+				$mode = $this->identifyMode(substr($this->dataStr, $p), $this->hint);
+				if ($mode == QR_MODE_KJ) {
+					$p += 2;
+				} else {
+					if ((ord($this->dataStr[$p]) >= ord('a')) AND (ord($this->dataStr[$p]) <= ord('z'))) {
+						$this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32);
+					}
+					$p++;
+				}
+			}
+			return $this->dataStr;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRinputItem
+
+		/**
+		 * newInputItem
+		 * @param int $mode
+		 * @param int $size
+		 * @param array $data
+		 * @param array $bstream
+		 * @return array input item
+		 */
+		 protected function newInputItem($mode, $size, $data, $bstream=null) {
+			$setData = array_slice($data, 0, $size);
+			if (count($setData) < $size) {
+				$setData = array_merge($setData, array_fill(0, ($size - count($setData)), 0));
+			}
+			if (!$this->check($mode, $size, $setData)) {
+				return NULL;
+			}
+			$inputitem = array();
+			$inputitem['mode'] = $mode;
+			$inputitem['size'] = $size;
+			$inputitem['data'] = $setData;
+			$inputitem['bstream'] = $bstream;
+			return $inputitem;
+		}
+
+		/**
+		 * encodeModeNum
+		 * @param array $inputitem
+		 * @param int $version
+		 * @return array input item
+		 */
+		 protected function encodeModeNum($inputitem, $version) {
+			$words = (int)($inputitem['size'] / 3);
+			$inputitem['bstream'] = array();
+			$val = 0x1;
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, $val);
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], $this->lengthIndicator(QR_MODE_NM, $version), $inputitem['size']);
+			for ($i=0; $i < $words; ++$i) {
+				$val  = (ord($inputitem['data'][$i*3  ]) - ord('0')) * 100;
+				$val += (ord($inputitem['data'][$i*3+1]) - ord('0')) * 10;
+				$val += (ord($inputitem['data'][$i*3+2]) - ord('0'));
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 10, $val);
+			}
+			if ($inputitem['size'] - $words * 3 == 1) {
+				$val = ord($inputitem['data'][$words*3]) - ord('0');
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, $val);
+			} elseif (($inputitem['size'] - ($words * 3)) == 2) {
+				$val  = (ord($inputitem['data'][$words*3  ]) - ord('0')) * 10;
+				$val += (ord($inputitem['data'][$words*3+1]) - ord('0'));
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 7, $val);
+			}
+			return $inputitem;
+		}
+
+		/**
+		 * encodeModeAn
+		 * @param array $inputitem
+		 * @param int $version
+		 * @return array input item
+		 */
+		 protected function encodeModeAn($inputitem, $version) {
+			$words = (int)($inputitem['size'] / 2);
+			$inputitem['bstream'] = array();
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x02);
+			$inputitem['bstream'] = $this->appendNum(v, $this->lengthIndicator(QR_MODE_AN, $version), $inputitem['size']);
+			for ($i=0; $i < $words; ++$i) {
+				$val  = (int)$this->lookAnTable(ord($inputitem['data'][$i*2  ])) * 45;
+				$val += (int)$this->lookAnTable(ord($inputitem['data'][$i*2+1]));
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 11, $val);
+			}
+			if ($inputitem['size'] & 1) {
+				$val = $this->lookAnTable(ord($inputitem['data'][($words * 2)]));
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 6, $val);
+			}
+			return $inputitem;
+		}
+
+		/**
+		 * encodeMode8
+		 * @param array $inputitem
+		 * @param int $version
+		 * @return array input item
+		 */
+		 protected function encodeMode8($inputitem, $version) {
+			$inputitem['bstream'] = array();
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x4);
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], $this->lengthIndicator(QR_MODE_8B, $version), $inputitem['size']);
+			for ($i=0; $i < $inputitem['size']; ++$i) {
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 8, ord($inputitem['data'][$i]));
+			}
+			return $inputitem;
+		}
+
+		/**
+		 * encodeModeKanji
+		 * @param array $inputitem
+		 * @param int $version
+		 * @return array input item
+		 */
+		 protected function encodeModeKanji($inputitem, $version) {
+			$inputitem['bstream'] = array();
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x8);
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], $this->lengthIndicator(QR_MODE_KJ, $version), (int)($inputitem['size'] / 2));
+			for ($i=0; $i<$inputitem['size']; $i+=2) {
+				$val = (ord($inputitem['data'][$i]) << 8) | ord($inputitem['data'][$i+1]);
+				if ($val <= 0x9ffc) {
+					$val -= 0x8140;
+				} else {
+					$val -= 0xc140;
+				}
+				$h = ($val >> 8) * 0xc0;
+				$val = ($val & 0xff) + $h;
+				$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 13, $val);
+			}
+			return $inputitem;
+		}
+
+		/**
+		 * encodeModeStructure
+		 * @param array $inputitem
+		 * @return array input item
+		 */
+		 protected function encodeModeStructure($inputitem) {
+			$inputitem['bstream'] = array();
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, 0x03);
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, ord($inputitem['data'][1]) - 1);
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 4, ord($inputitem['data'][0]) - 1);
+			$inputitem['bstream'] = $this->appendNum($inputitem['bstream'], 8, ord($inputitem['data'][2]));
+			return $inputitem;
+		}
+
+		/**
+		 * encodeBitStream
+		 * @param array $inputitem
+		 * @param int $version
+		 * @return array input item
+		 */
+		 protected function encodeBitStream($inputitem, $version) {
+			$inputitem['bstream'] = array();
+			$words = $this->maximumWords($inputitem['mode'], $version);
+			if ($inputitem['size'] > $words) {
+				$st1 = $this->newInputItem($inputitem['mode'], $words, $inputitem['data']);
+				$st2 = $this->newInputItem($inputitem['mode'], $inputitem['size'] - $words, array_slice($inputitem['data'], $words));
+				$st1 = $this->encodeBitStream($st1, $version);
+				$st2 = $this->encodeBitStream($st2, $version);
+				$inputitem['bstream'] = array();
+				$inputitem['bstream'] = $this->appendBitstream($inputitem['bstream'], $st1['bstream']);
+				$inputitem['bstream'] = $this->appendBitstream($inputitem['bstream'], $st2['bstream']);
+			} else {
+				switch($inputitem['mode']) {
+					case QR_MODE_NM: {
+						$inputitem = $this->encodeModeNum($inputitem, $version);
+						break;
+					}
+					case QR_MODE_AN: {
+						$inputitem = $this->encodeModeAn($inputitem, $version);
+						break;
+					}
+					case QR_MODE_8B: {
+						$inputitem = $this->encodeMode8($inputitem, $version);
+						break;
+					}
+					case QR_MODE_KJ: {
+						$inputitem = $this->encodeModeKanji($inputitem, $version);
+						break;
+					}
+					case QR_MODE_ST: {
+						$inputitem = $this->encodeModeStructure($inputitem);
+						break;
+					}
+					default: {
+						break;
+					}
+				}
+			}
+			return $inputitem;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRinput
+
+		/**
+		 * Append data to an input object.
+		 * The data is copied and appended to the input object.
+		 * @param array items input items
+		 * @param int $mode encoding mode.
+		 * @param int $size size of data (byte).
+		 * @param array $data array of input data.
+		 * @return items
+		 *
+		 */
+		protected function appendNewInputItem($items, $mode, $size, $data) {
+			$items[] = $this->newInputItem($mode, $size, $data);
+			return $items;
+		}
+
+		/**
+		 * insertStructuredAppendHeader
+		 * @param array $items
+		 * @param int $size
+		 * @param int $index
+		 * @param int $parity
+		 * @return array items
+		 */
+		 protected function insertStructuredAppendHeader($items, $size, $index, $parity) {
+			if ($size > MAX_STRUCTURED_SYMBOLS) {
+				return -1;
+			}
+			if (($index <= 0) OR ($index > MAX_STRUCTURED_SYMBOLS)) {
+				return -1;
+			}
+			$buf = array($size, $index, $parity);
+			$entry = $this->newInputItem(QR_MODE_ST, 3, buf);
+			array_unshift($items, $entry);
+			return $items;
+		}
+
+		/**
+		 * calcParity
+		 * @param array $items
+		 * @return int parity
+		 */
+		 protected function calcParity($items) {
+			$parity = 0;
+			foreach ($items as $item) {
+				if ($item['mode'] != QR_MODE_ST) {
+					for ($i=$item['size']-1; $i>=0; --$i) {
+						$parity ^= $item['data'][$i];
+					}
+				}
+			}
+			return $parity;
+		}
+
+		/**
+		 * checkModeNum
+		 * @param int $size
+		 * @param array $data
+		 * @return boolean true or false
+		 */
+		 protected function checkModeNum($size, $data) {
+			for ($i=0; $i<$size; ++$i) {
+				if ((ord($data[$i]) < ord('0')) OR (ord($data[$i]) > ord('9'))){
+					return false;
+				}
+			}
+			return true;
+		}
+
+		/**
+		 * estimateBitsModeNum
+		 * @param int $size
+		 * @return int number of bits
+		 */
+		 protected function estimateBitsModeNum($size) {
+			$w = (int)$size / 3;
+			$bits = $w * 10;
+			switch($size - $w * 3) {
+				case 1: {
+					$bits += 4;
+					break;
+				}
+				case 2: {
+					$bits += 7;
+					break;
+				}
+				default: {
+					break;
+				}
+			}
+			return $bits;
+		}
+
+		/**
+		 * Look up the alphabet-numeric convesion table (see JIS X0510:2004, pp.19).
+		 * @param int $c character value
+		 * @return value
+		 */
+		protected function lookAnTable($c) {
+			return (($c > 127)?-1:$this->anTable[$c]);
+		}
+
+		/**
+		 * checkModeAn
+		 * @param int $size
+		 * @param array $data
+		 * @return boolean true or false
+		 */
+		 protected function checkModeAn($size, $data) {
+			for ($i=0; $i<$size; ++$i) {
+				if ($this->lookAnTable(ord($data[$i])) == -1) {
+					return false;
+				}
+			}
+			return true;
+		}
+
+		/**
+		 * estimateBitsModeAn
+		 * @param int $size
+		 * @return int number of bits
+		 */
+		 protected function estimateBitsModeAn($size) {
+			$w = (int)($size / 2);
+			$bits = $w * 11;
+			if ($size & 1) {
+				$bits += 6;
+			}
+			return $bits;
+		}
+
+		/**
+		 * estimateBitsMode8
+		 * @param int $size
+		 * @return int number of bits
+		 */
+		 protected function estimateBitsMode8($size) {
+			return $size * 8;
+		}
+
+		/**
+		 * estimateBitsModeKanji
+		 * @param int $size
+		 * @return int number of bits
+		 */
+		 protected function estimateBitsModeKanji($size) {
+			return (int)(($size / 2) * 13);
+		}
+
+		/**
+		 * checkModeKanji
+		 * @param int $size
+		 * @param array $data
+		 * @return boolean true or false
+		 */
+		 protected function checkModeKanji($size, $data) {
+			if ($size & 1) {
+				return false;
+			}
+			for ($i=0; $i<$size; $i+=2) {
+				$val = (ord($data[$i]) << 8) | ord($data[$i+1]);
+				if (($val < 0x8140) OR (($val > 0x9ffc) AND ($val < 0xe040)) OR ($val > 0xebbf)) {
+					return false;
+				}
+			}
+			return true;
+		}
+
+		/**
+		 * Validate the input data.
+		 * @param int $mode encoding mode.
+		 * @param int $size size of data (byte).
+		 * @param array data data to validate
+		 * @return boolean true in case of valid data, false otherwise
+		 */
+		protected function check($mode, $size, $data) {
+			if ($size <= 0) {
+				return false;
+			}
+			switch($mode) {
+				case QR_MODE_NM: {
+					return $this->checkModeNum($size, $data);
+				}
+				case QR_MODE_AN: {
+					return $this->checkModeAn($size, $data);
+				}
+				case QR_MODE_KJ: {
+					return $this->checkModeKanji($size, $data);
+				}
+				case QR_MODE_8B: {
+					return true;
+				}
+				case QR_MODE_ST: {
+					return true;
+				}
+				default: {
+					break;
+				}
+			}
+			return false;
+		}
+
+		/**
+		 * estimateBitStreamSize
+		 * @param array $items
+		 * @param int $version
+		 * @return int bits
+		 */
+		 protected function estimateBitStreamSize($items, $version) {
+			$bits = 0;
+			if ($version == 0) {
+				$version = 1;
+			}
+			foreach ($items as $item) {
+				switch($item['mode']) {
+					case QR_MODE_NM: {
+						$bits = $this->estimateBitsModeNum($item['size']);
+						break;
+					}
+					case QR_MODE_AN: {
+						$bits = $this->estimateBitsModeAn($item['size']);
+						break;
+					}
+					case QR_MODE_8B: {
+						$bits = $this->estimateBitsMode8($item['size']);
+						break;
+					}
+					case QR_MODE_KJ: {
+						$bits = $this->estimateBitsModeKanji($item['size']);
+						break;
+					}
+					case QR_MODE_ST: {
+						return STRUCTURE_HEADER_BITS;
+					}
+					default: {
+						return 0;
+					}
+				}
+				$l = $this->lengthIndicator($item['mode'], $version);
+				$m = 1 << $l;
+				$num = (int)(($item['size'] + $m - 1) / $m);
+				$bits += $num * (4 + $l);
+			}
+			return $bits;
+		}
+
+		/**
+		 * estimateVersion
+		 * @param array $items
+		 * @return int version
+		 */
+		 protected function estimateVersion($items) {
+			$version = 0;
+			$prev = 0;
+			do {
+				$prev = $version;
+				$bits = $this->estimateBitStreamSize($items, $prev);
+				$version = $this->getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+				if ($version < 0) {
+					return -1;
+				}
+			} while ($version > $prev);
+			return $version;
+		}
+
+		/**
+		 * lengthOfCode
+		 * @param int $mode
+		 * @param int $version
+		 * @param int $bits
+		 * @return int size
+		 */
+		 protected function lengthOfCode($mode, $version, $bits) {
+			$payload = $bits - 4 - $this->lengthIndicator($mode, $version);
+			switch($mode) {
+				case QR_MODE_NM: {
+					$chunks = (int)($payload / 10);
+					$remain = $payload - $chunks * 10;
+					$size = $chunks * 3;
+					if ($remain >= 7) {
+						$size += 2;
+					} elseif ($remain >= 4) {
+						$size += 1;
+					}
+					break;
+				}
+				case QR_MODE_AN: {
+					$chunks = (int)($payload / 11);
+					$remain = $payload - $chunks * 11;
+					$size = $chunks * 2;
+					if ($remain >= 6) {
+						++$size;
+					}
+					break;
+				}
+				case QR_MODE_8B: {
+					$size = (int)($payload / 8);
+					break;
+				}
+				case QR_MODE_KJ: {
+					$size = (int)(($payload / 13) * 2);
+					break;
+				}
+				case QR_MODE_ST: {
+					$size = (int)($payload / 8);
+					break;
+				}
+				default: {
+					$size = 0;
+					break;
+				}
+			}
+			$maxsize = $this->maximumWords($mode, $version);
+			if ($size < 0) {
+				$size = 0;
+			}
+			if ($size > $maxsize) {
+				$size = $maxsize;
+			}
+			return $size;
+		}
+
+		/**
+		 * createBitStream
+		 * @param array $items
+		 * @return array of items and total bits
+		 */
+		 protected function createBitStream($items) {
+			$total = 0;
+			foreach ($items as $key => $item) {
+				$items[$key] = $this->encodeBitStream($item, $this->version);
+				$bits = count($items[$key]['bstream']);
+				$total += $bits;
+			}
+			return array($items, $total);
+		}
+
+		/**
+		 * convertData
+		 * @param array $items
+		 * @return array items
+		 */
+		 protected function convertData($items) {
+			$ver = $this->estimateVersion($items);
+			if ($ver > $this->version) {
+				$this->version = $ver;
+			}
+			for (;;) {
+				$cbs = $this->createBitStream($items);
+				$items = $cbs[0];
+				$bits = $cbs[1];
+				if ($bits < 0) {
+					return -1;
+				}
+				$ver = $this->getMinimumVersion((int)(($bits + 7) / 8), $this->level);
+				if ($ver < 0) {
+					return -1;
+				} elseif ($ver > $this->version) {
+					$this->version = $ver;
+				} else {
+					break;
+				}
+			}
+			return $items;
+		}
+
+		/**
+		 * Append Padding Bit to bitstream
+		 * @param array $bstream
+		 * @return array bitstream
+		 */
+		 protected function appendPaddingBit($bstream) {
+			$bits = count($bstream);
+			$maxwords = $this->getDataLength($this->version, $this->level);
+			$maxbits = $maxwords * 8;
+			if ($maxbits == $bits) {
+				return 0;
+			}
+			if ($maxbits - $bits < 5) {
+				return $this->appendNum($bstream, $maxbits - $bits, 0);
+			}
+			$bits += 4;
+			$words = (int)(($bits + 7) / 8);
+			$padding = array();
+			$padding = $this->appendNum($padding, $words * 8 - $bits + 4, 0);
+			$padlen = $maxwords - $words;
+			if ($padlen > 0) {
+				$padbuf = array();
+				for ($i=0; $i<$padlen; ++$i) {
+					$padbuf[$i] = ($i&1)?0x11:0xec;
+				}
+				$padding = $this->appendBytes($padding, $padlen, $padbuf);
+			}
+			return $this->appendBitstream($bstream, $padding);
+		}
+
+		/**
+		 * mergeBitStream
+		 * @param array $bstream
+		 * @return array bitstream
+		 */
+		 protected function mergeBitStream($items) {
+			$items = $this->convertData($items);
+			$bstream = array();
+			foreach ($items as $item) {
+				$bstream = $this->appendBitstream($bstream, $item['bstream']);
+			}
+			return $bstream;
+		}
+
+		/**
+		 * Returns a stream of bits.
+		 * @param int $items
+		 * @return array padded merged byte stream
+		 */
+		protected function getBitStream($items) {
+			$bstream = $this->mergeBitStream($items);
+			return $this->appendPaddingBit($bstream);
+		}
+
+		/**
+		 * Pack all bit streams padding bits into a byte array.
+		 * @param int $items
+		 * @return array padded merged byte stream
+		 */
+		protected function getByteStream($items) {
+			$bstream = $this->getBitStream($items);
+			return $this->bitstreamToByte($bstream);
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRbitstream
+
+		/**
+		 * Return an array with zeros
+		 * @param int $setLength array size
+		 * @return array
+		 */
+		 protected function allocate($setLength) {
+			return array_fill(0, $setLength, 0);
+		}
+
+		/**
+		 * Return new bitstream from number
+		 * @param int $bits number of bits
+		 * @param int $num number
+		 * @return array bitstream
+		 */
+		 protected function newFromNum($bits, $num) {
+			$bstream = $this->allocate($bits);
+			$mask = 1 << ($bits - 1);
+			for ($i=0; $i<$bits; ++$i) {
+				if ($num & $mask) {
+					$bstream[$i] = 1;
+				} else {
+					$bstream[$i] = 0;
+				}
+				$mask = $mask >> 1;
+			}
+			return $bstream;
+		}
+
+		/**
+		 * Return new bitstream from bytes
+		 * @param int $size size
+		 * @param array $data bytes
+		 * @return array bitstream
+		 */
+		 protected function newFromBytes($size, $data) {
+			$bstream = $this->allocate($size * 8);
+			$p=0;
+			for ($i=0; $i<$size; ++$i) {
+				$mask = 0x80;
+				for ($j=0; $j<8; ++$j) {
+					if ($data[$i] & $mask) {
+						$bstream[$p] = 1;
+					} else {
+						$bstream[$p] = 0;
+					}
+					$p++;
+					$mask = $mask >> 1;
+				}
+			}
+			return $bstream;
+		}
+
+		/**
+		 * Append one bitstream to another
+		 * @param array $bitstream original bitstream
+		 * @param array $append bitstream to append
+		 * @return array bitstream
+		 */
+		 protected function appendBitstream($bitstream, $append) {
+			if ((!is_array($append)) OR (count($append) == 0)) {
+				return $bitstream;
+			}
+			if (count($bitstream) == 0) {
+				return $append;
+			}
+			return array_values(array_merge($bitstream, $append));
+		}
+
+		/**
+		 * Append one bitstream created from number to another
+		 * @param array $bitstream original bitstream
+		 * @param int $bits number of bits
+		 * @param int $num number
+		 * @return array bitstream
+		 */
+		 protected function appendNum($bitstream, $bits, $num) {
+			if ($bits == 0) {
+				return 0;
+			}
+			$b = $this->newFromNum($bits, $num);
+			return $this->appendBitstream($bitstream, $b);
+		}
+
+		/**
+		 * Append one bitstream created from bytes to another
+		 * @param array $bitstream original bitstream
+		 * @param int $size size
+		 * @param array $data bytes
+		 * @return array bitstream
+		 */
+		 protected function appendBytes($bitstream, $size, $data) {
+			if ($size == 0) {
+				return 0;
+			}
+			$b = $this->newFromBytes($size, $data);
+			return $this->appendBitstream($bitstream, $b);
+		}
+
+		/**
+		 * Convert bitstream to bytes
+		 * @param array $bitstream original bitstream
+		 * @return array of bytes
+		 */
+		 protected function bitstreamToByte($bstream) {
+			$size = count($bstream);
+			if ($size == 0) {
+				return array();
+			}
+			$data = array_fill(0, (int)(($size + 7) / 8), 0);
+			$bytes = (int)($size / 8);
+			$p = 0;
+			for ($i=0; $i<$bytes; $i++) {
+				$v = 0;
+				for ($j=0; $j<8; $j++) {
+					$v = $v << 1;
+					$v |= $bstream[$p];
+					$p++;
+				}
+				$data[$i] = $v;
+			}
+			if ($size & 7) {
+				$v = 0;
+				for ($j=0; $j<($size & 7); $j++) {
+					$v = $v << 1;
+					$v |= $bstream[$p];
+					$p++;
+				}
+				$data[$bytes] = $v;
+			}
+			return $data;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRspec
+
+		/**
+		 * Replace a value on the array at the specified position
+		 * @param array $srctab
+		 * @param int $x X position
+		 * @param int $y Y position
+		 * @param string $repl value to replace
+		 * @param int $replLen length of the repl string
+		 * @return array srctab
+		 */
+		 protected function qrstrset($srctab, $x, $y, $repl, $replLen=false) {
+			$srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));
+			return $srctab;
+		}
+
+		/**
+		 * Return maximum data code length (bytes) for the version.
+		 * @param int $version version
+		 * @param int $level error correction level
+		 * @return int maximum size (bytes)
+		 */
+		protected function getDataLength($version, $level) {
+			return $this->capacity[$version][QRCAP_WORDS] - $this->capacity[$version][QRCAP_EC][$level];
+		}
+
+		/**
+		 * Return maximum error correction code length (bytes) for the version.
+		 * @param int $version version
+		 * @param int $level error correction level
+		 * @return int ECC size (bytes)
+		 */
+		protected function getECCLength($version, $level){
+			return $this->capacity[$version][QRCAP_EC][$level];
+		}
+
+		/**
+		 * Return the width of the symbol for the version.
+		 * @param int $version version
+		 * @return int width
+		 */
+		protected function getWidth($version) {
+			return $this->capacity[$version][QRCAP_WIDTH];
+		}
+
+		/**
+		 * Return the numer of remainder bits.
+		 * @param int $version version
+		 * @return int number of remainder bits
+		 */
+		protected function getRemainder($version) {
+			return $this->capacity[$version][QRCAP_REMINDER];
+		}
+
+		/**
+		 * Return a version number that satisfies the input code length.
+		 * @param int $size input code length (byte)
+		 * @param int $level error correction level
+		 * @return int version number
+		 */
+		protected function getMinimumVersion($size, $level) {
+			for ($i=1; $i <= QRSPEC_VERSION_MAX; ++$i) {
+				$words  = $this->capacity[$i][QRCAP_WORDS] - $this->capacity[$i][QRCAP_EC][$level];
+				if ($words >= $size) {
+					return $i;
+				}
+			}
+			return -1;
+		}
+
+		/**
+		 * Return the size of length indicator for the mode and version.
+		 * @param int $mode encoding mode
+		 * @param int $version version
+		 * @return int the size of the appropriate length indicator (bits).
+		 */
+		protected function lengthIndicator($mode, $version) {
+			if ($mode == QR_MODE_ST) {
+				return 0;
+			}
+			if ($version <= 9) {
+				$l = 0;
+			} elseif ($version <= 26) {
+				$l = 1;
+			} else {
+				$l = 2;
+			}
+			return $this->lengthTableBits[$mode][$l];
+		}
+
+		/**
+		 * Return the maximum length for the mode and version.
+		 * @param int $mode encoding mode
+		 * @param int $version version
+		 * @return int the maximum length (bytes)
+		 */
+		protected function maximumWords($mode, $version) {
+			if ($mode == QR_MODE_ST) {
+				return 3;
+			}
+			if ($version <= 9) {
+				$l = 0;
+			} else if ($version <= 26) {
+				$l = 1;
+			} else {
+				$l = 2;
+			}
+			$bits = $this->lengthTableBits[$mode][$l];
+			$words = (1 << $bits) - 1;
+			if ($mode == QR_MODE_KJ) {
+				$words *= 2; // the number of bytes is required
+			}
+			return $words;
+		}
+
+		/**
+		 * Return an array of ECC specification.
+		 * @param int $version version
+		 * @param int $level error correction level
+		 * @param array $spec an array of ECC specification contains as following: {# of type1 blocks, # of data code, # of ecc code, # of type2 blocks, # of data code}
+		 * @return array spec
+		 */
+		protected function getEccSpec($version, $level, $spec) {
+			if (count($spec) < 5) {
+				$spec = array(0, 0, 0, 0, 0);
+			}
+			$b1 = $this->eccTable[$version][$level][0];
+			$b2 = $this->eccTable[$version][$level][1];
+			$data = $this->getDataLength($version, $level);
+			$ecc = $this->getECCLength($version, $level);
+			if ($b2 == 0) {
+				$spec[0] = $b1;
+				$spec[1] = (int)($data / $b1);
+				$spec[2] = (int)($ecc / $b1);
+				$spec[3] = 0;
+				$spec[4] = 0;
+			} else {
+				$spec[0] = $b1;
+				$spec[1] = (int)($data / ($b1 + $b2));
+				$spec[2] = (int)($ecc  / ($b1 + $b2));
+				$spec[3] = $b2;
+				$spec[4] = $spec[1] + 1;
+			}
+			return $spec;
+		}
+
+		/**
+		 * Put an alignment marker.
+		 * @param array $frame frame
+		 * @param int $width width
+		 * @param int $ox X center coordinate of the pattern
+		 * @param int $oy Y center coordinate of the pattern
+		 * @return array frame
+		 */
+		protected function putAlignmentMarker($frame, $ox, $oy) {
+			$finder = array(
+				"\xa1\xa1\xa1\xa1\xa1",
+				"\xa1\xa0\xa0\xa0\xa1",
+				"\xa1\xa0\xa1\xa0\xa1",
+				"\xa1\xa0\xa0\xa0\xa1",
+				"\xa1\xa1\xa1\xa1\xa1"
+				);
+			$yStart = $oy - 2;
+			$xStart = $ox - 2;
+			for ($y=0; $y < 5; $y++) {
+				$frame = $this->qrstrset($frame, $xStart, $yStart+$y, $finder[$y]);
+			}
+			return $frame;
+		}
+
+		/**
+		 * Put an alignment pattern.
+		 * @param int $version version
+		 * @param array $fram frame
+		 * @param int $width width
+		 * @return array frame
+		 */
+		 protected function putAlignmentPattern($version, $frame, $width) {
+			if ($version < 2) {
+				return $frame;
+			}
+			$d = $this->alignmentPattern[$version][1] - $this->alignmentPattern[$version][0];
+			if ($d < 0) {
+				$w = 2;
+			} else {
+				$w = (int)(($width - $this->alignmentPattern[$version][0]) / $d + 2);
+			}
+			if ($w * $w - 3 == 1) {
+				$x = $this->alignmentPattern[$version][0];
+				$y = $this->alignmentPattern[$version][0];
+				$frame = $this->putAlignmentMarker($frame, $x, $y);
+				return $frame;
+			}
+			$cx = $this->alignmentPattern[$version][0];
+			$wo = $w - 1;
+			for ($x=1; $x < $wo; ++$x) {
+				$frame = $this->putAlignmentMarker($frame, 6, $cx);
+				$frame = $this->putAlignmentMarker($frame, $cx,  6);
+				$cx += $d;
+			}
+			$cy = $this->alignmentPattern[$version][0];
+			for ($y=0; $y < $wo; ++$y) {
+				$cx = $this->alignmentPattern[$version][0];
+				for ($x=0; $x < $wo; ++$x) {
+					$frame = $this->putAlignmentMarker($frame, $cx, $cy);
+					$cx += $d;
+				}
+				$cy += $d;
+			}
+			return $frame;
+		}
+
+		/**
+		 * Return BCH encoded version information pattern that is used for the symbol of version 7 or greater. Use lower 18 bits.
+		 * @param int $version version
+		 * @return BCH encoded version information pattern
+		 */
+		protected function getVersionPattern($version) {
+			if (($version < 7) OR ($version > QRSPEC_VERSION_MAX)) {
+				return 0;
+			}
+			return $this->versionPattern[($version - 7)];
+		}
+
+		/**
+		 * Return BCH encoded format information pattern.
+		 * @param array $mask
+		 * @param int $level error correction level
+		 * @return BCH encoded format information pattern
+		 */
+		protected function getFormatInfo($mask, $level) {
+			if (($mask < 0) OR ($mask > 7)) {
+				return 0;
+			}
+			if (($level < 0) OR ($level > 3)) {
+				return 0;
+			}
+			return $this->formatInfo[$level][$mask];
+		}
+
+		/**
+		 * Put a finder pattern.
+		 * @param array $frame frame
+		 * @param int $width width
+		 * @param int $ox X center coordinate of the pattern
+		 * @param int $oy Y center coordinate of the pattern
+		 * @return array frame
+		 */
+		protected function putFinderPattern($frame, $ox, $oy) {
+			$finder = array(
+			"\xc1\xc1\xc1\xc1\xc1\xc1\xc1",
+			"\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+			"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+			"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+			"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
+			"\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
+			"\xc1\xc1\xc1\xc1\xc1\xc1\xc1"
+			);
+			for ($y=0; $y < 7; $y++) {
+				$frame = $this->qrstrset($frame, $ox, ($oy + $y), $finder[$y]);
+			}
+			return $frame;
+		}
+
+		/**
+		 * Return a copy of initialized frame.
+		 * @param int $version version
+		 * @return Array of unsigned char.
+		 */
+		protected function createFrame($version) {
+			$width = $this->capacity[$version][QRCAP_WIDTH];
+			$frameLine = str_repeat ("\0", $width);
+			$frame = array_fill(0, $width, $frameLine);
+			// Finder pattern
+			$frame = $this->putFinderPattern($frame, 0, 0);
+			$frame = $this->putFinderPattern($frame, $width - 7, 0);
+			$frame = $this->putFinderPattern($frame, 0, $width - 7);
+			// Separator
+			$yOffset = $width - 7;
+			for ($y=0; $y < 7; ++$y) {
+				$frame[$y][7] = "\xc0";
+				$frame[$y][$width - 8] = "\xc0";
+				$frame[$yOffset][7] = "\xc0";
+				++$yOffset;
+			}
+			$setPattern = str_repeat("\xc0", 8);
+			$frame = $this->qrstrset($frame, 0, 7, $setPattern);
+			$frame = $this->qrstrset($frame, $width-8, 7, $setPattern);
+			$frame = $this->qrstrset($frame, 0, $width - 8, $setPattern);
+			// Format info
+			$setPattern = str_repeat("\x84", 9);
+			$frame = $this->qrstrset($frame, 0, 8, $setPattern);
+			$frame = $this->qrstrset($frame, $width - 8, 8, $setPattern, 8);
+			$yOffset = $width - 8;
+			for ($y=0; $y < 8; ++$y,++$yOffset) {
+				$frame[$y][8] = "\x84";
+				$frame[$yOffset][8] = "\x84";
+			}
+			// Timing pattern
+			$wo = $width - 15;
+			for ($i=1; $i < $wo; ++$i) {
+				$frame[6][7+$i] = chr(0x90 | ($i & 1));
+				$frame[7+$i][6] = chr(0x90 | ($i & 1));
+			}
+			// Alignment pattern
+			$frame = $this->putAlignmentPattern($version, $frame, $width);
+			// Version information
+			if ($version >= 7) {
+				$vinf = $this->getVersionPattern($version);
+				$v = $vinf;
+				for ($x=0; $x<6; ++$x) {
+					for ($y=0; $y<3; ++$y) {
+						$frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));
+						$v = $v >> 1;
+					}
+				}
+				$v = $vinf;
+				for ($y=0; $y<6; ++$y) {
+					for ($x=0; $x<3; ++$x) {
+						$frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));
+						$v = $v >> 1;
+					}
+				}
+			}
+			// and a little bit...
+			$frame[$width - 8][8] = "\x81";
+			return $frame;
+		}
+
+		/**
+		 * Set new frame for the specified version.
+		 * @param int $version version
+		 * @return Array of unsigned char.
+		 */
+		protected function newFrame($version) {
+			if (($version < 1) OR ($version > QRSPEC_VERSION_MAX)) {
+				return NULL;
+			}
+			if (!isset($this->frames[$version])) {
+				$this->frames[$version] = $this->createFrame($version);
+			}
+			if (is_null($this->frames[$version])) {
+				return NULL;
+			}
+			return $this->frames[$version];
+		}
+
+		/**
+		 * Return block number 0
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsBlockNum($spec) {
+			return ($spec[0] + $spec[3]);
+		}
+
+		/**
+		* Return block number 1
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsBlockNum1($spec) {
+			return $spec[0];
+		}
+
+		/**
+		 * Return data codes 1
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsDataCodes1($spec) {
+			return $spec[1];
+		}
+
+		/**
+		 * Return ecc codes 1
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsEccCodes1($spec) {
+			return $spec[2];
+		}
+
+		/**
+		 * Return block number 2
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsBlockNum2($spec) {
+			return $spec[3];
+		}
+
+		/**
+		 * Return data codes 2
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsDataCodes2($spec) {
+			return $spec[4];
+		}
+
+		/**
+		 * Return ecc codes 2
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsEccCodes2($spec) {
+			return $spec[2];
+		}
+
+		/**
+		 * Return data length
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsDataLength($spec) {
+			return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]);
+		}
+
+		/**
+		 * Return ecc length
+		 * @param array $spec
+		 * @return int value
+		 */
+		 protected function rsEccLength($spec) {
+			return ($spec[0] + $spec[3]) * $spec[2];
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRrs
+
+		/**
+		 * Initialize a Reed-Solomon codec and add it to existing rsitems
+		 * @param int $symsize symbol size, bits
+		 * @param int $gfpoly  Field generator polynomial coefficients
+		 * @param int $fcr  first root of RS code generator polynomial, index form
+		 * @param int $prim  primitive element to generate polynomial roots
+		 * @param int $nroots RS code generator polynomial degree (number of roots)
+		 * @param int $pad  padding bytes at front of shortened block
+		 * @return array Array of RS values:<ul><li>mm = Bits per symbol;</li><li>nn = Symbols per block;</li><li>alpha_to = log lookup table array;</li><li>index_of = Antilog lookup table array;</li><li>genpoly = Generator polynomial array;</li><li>nroots = Number of generator;</li><li>roots = number of parity symbols;</li><li>fcr = First consecutive root, index form;</li><li>prim = Primitive element, index form;</li><li>iprim = prim-th root of 1, index form;</li><li>pad = Padding bytes in shortened block;</li><li>gfpoly</ul>.
+		 */
+		 protected function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) {
+			foreach ($this->rsitems as $rs) {
+				if (($rs['pad'] != $pad) OR ($rs['nroots'] != $nroots) OR ($rs['mm'] != $symsize)
+					OR ($rs['gfpoly'] != $gfpoly) OR ($rs['fcr'] != $fcr) OR ($rs['prim'] != $prim)) {
+					continue;
+				}
+				return $rs;
+			}
+			$rs = $this->init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad);
+			array_unshift($this->rsitems, $rs);
+			return $rs;
+		}
+
+		// - - - - - - - - - - - - - - - - - - - - - - - - -
+
+		// QRrsItem
+
+		/**
+		 * modnn
+		 * @param array RS values
+		 * @param int $x X position
+		 * @return int X osition
+		 */
+		 protected function modnn($rs, $x) {
+			while ($x >= $rs['nn']) {
+				$x -= $rs['nn'];
+				$x = ($x >> $rs['mm']) + ($x & $rs['nn']);
+			}
+			return $x;
+		}
+
+		/**
+		 * Initialize a Reed-Solomon codec and returns an array of values.
+		 * @param int $symsize symbol size, bits
+		 * @param int $gfpoly  Field generator polynomial coefficients
+		 * @param int $fcr  first root of RS code generator polynomial, index form
+		 * @param int $prim  primitive element to generate polynomial roots
+		 * @param int $nroots RS code generator polynomial degree (number of roots)
+		 * @param int $pad  padding bytes at front of shortened block
+		 * @return array Array of RS values:<ul><li>mm = Bits per symbol;</li><li>nn = Symbols per block;</li><li>alpha_to = log lookup table array;</li><li>index_of = Antilog lookup table array;</li><li>genpoly = Generator polynomial array;</li><li>nroots = Number of generator;</li><li>roots = number of parity symbols;</li><li>fcr = First consecutive root, index form;</li><li>prim = Primitive element, index form;</li><li>iprim = prim-th root of 1, index form;</li><li>pad = Padding bytes in shortened block;</li><li>gfpoly</ul>.
+		 */
+		protected function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) {
+			// Based on Reed solomon encoder by Phil Karn, KA9Q (GNU-LGPLv2)
+			$rs = null;
+			// Check parameter ranges
+			if (($symsize < 0) OR ($symsize > 8)) {
+				return $rs;
+			}
+			if (($fcr < 0) OR ($fcr >= (1<<$symsize))) {
+				return $rs;
+			}
+			if (($prim <= 0) OR ($prim >= (1<<$symsize))) {
+				return $rs;
+			}
+			if (($nroots < 0) OR ($nroots >= (1<<$symsize))) {
+				return $rs;
+			}
+			if (($pad < 0) OR ($pad >= ((1<<$symsize) -1 - $nroots))) {
+				return $rs;
+			}
+			$rs = array();
+			$rs['mm'] = $symsize;
+			$rs['nn'] = (1 << $symsize) - 1;
+			$rs['pad'] = $pad;
+			$rs['alpha_to'] = array_fill(0, ($rs['nn'] + 1), 0);
+			$rs['index_of'] = array_fill(0, ($rs['nn'] + 1), 0);
+			// PHP style macro replacement ;)
+			$NN =& $rs['nn'];
+			$A0 =& $NN;
+			// Generate Galois field lookup tables
+			$rs['index_of'][0] = $A0; // log(zero) = -inf
+			$rs['alpha_to'][$A0] = 0; // alpha**-inf = 0
+			$sr = 1;
+			for ($i=0; $i<$rs['nn']; ++$i) {
+				$rs['index_of'][$sr] = $i;
+				$rs['alpha_to'][$i] = $sr;
+				$sr <<= 1;
+				if ($sr & (1 << $symsize)) {
+					$sr ^= $gfpoly;
+				}
+				$sr &= $rs['nn'];
+			}
+			if ($sr != 1) {
+				// field generator polynomial is not primitive!
+				return NULL;
+			}
+			// Form RS code generator polynomial from its roots
+			$rs['genpoly'] = array_fill(0, ($nroots + 1), 0);
+			$rs['fcr'] = $fcr;
+			$rs['prim'] = $prim;
+			$rs['nroots'] = $nroots;
+			$rs['gfpoly'] = $gfpoly;
+			// Find prim-th root of 1, used in decoding
+			for ($iprim=1; ($iprim % $prim) != 0; $iprim += $rs['nn']) {
+				; // intentional empty-body loop!
+			}
+			$rs['iprim'] = (int)($iprim / $prim);
+			$rs['genpoly'][0] = 1;
+
+
+			for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) {
+				$rs['genpoly'][$i+1] = 1;
+				// Multiply rs->genpoly[] by  @**(root + x)
+				for ($j = $i; $j > 0; --$j) {
+					if ($rs['genpoly'][$j] != 0) {
+						$rs['genpoly'][$j] = $rs['genpoly'][$j-1] ^ $rs['alpha_to'][$this->modnn($rs, $rs['index_of'][$rs['genpoly'][$j]] + $root)];
+					} else {
+						$rs['genpoly'][$j] = $rs['genpoly'][$j-1];
+					}
+				}
+				// rs->genpoly[0] can never be zero
+				$rs['genpoly'][0] = $rs['alpha_to'][$this->modnn($rs, $rs['index_of'][$rs['genpoly'][0]] + $root)];
+			}
+			// convert rs->genpoly[] to index form for quicker encoding
+			for ($i = 0; $i <= $nroots; ++$i) {
+				$rs['genpoly'][$i] = $rs['index_of'][$rs['genpoly'][$i]];
+			}
+			return $rs;
+		}
+
+		/**
+		 * Encode a Reed-Solomon codec and returns the parity array
+		 * @param array $rs RS values
+		 * @param array $data data
+		 * @param array $parity parity
+		 * @return parity array
+		 */
+		 protected function encode_rs_char($rs, $data, $parity) {
+			$MM       =& $rs['mm']; // bits per symbol
+			$NN       =& $rs['nn']; // the total number of symbols in a RS block
+			$ALPHA_TO =& $rs['alpha_to']; // the address of an array of NN elements to convert Galois field elements in index (log) form to polynomial form
+			$INDEX_OF =& $rs['index_of']; // the address of an array of NN elements to convert Galois field elements in polynomial form to index (log) form
+			$GENPOLY  =& $rs['genpoly']; // an array of NROOTS+1 elements containing the generator polynomial in index form
+			$NROOTS   =& $rs['nroots']; // the number of roots in the RS code generator polynomial, which is the same as the number of parity symbols in a block
+			$FCR      =& $rs['fcr']; // first consecutive root, index form
+			$PRIM     =& $rs['prim']; // primitive element, index form
+			$IPRIM    =& $rs['iprim']; // prim-th root of 1, index form
+			$PAD      =& $rs['pad']; // the number of pad symbols in a block
+			$A0       =& $NN;
+			$parity = array_fill(0, $NROOTS, 0);
+			for ($i=0; $i < ($NN - $NROOTS - $PAD); $i++) {
+				$feedback = $INDEX_OF[$data[$i] ^ $parity[0]];
+				if ($feedback != $A0) {
+					// feedback term is non-zero
+					// This line is unnecessary when GENPOLY[NROOTS] is unity, as it must
+					// always be for the polynomials constructed by init_rs()
+					$feedback = $this->modnn($rs, $NN - $GENPOLY[$NROOTS] + $feedback);
+					for ($j=1; $j < $NROOTS; ++$j) {
+					$parity[$j] ^= $ALPHA_TO[$this->modnn($rs, $feedback + $GENPOLY[($NROOTS - $j)])];
+					}
+				}
+				// Shift
+				array_shift($parity);
+				if ($feedback != $A0) {
+					array_push($parity, $ALPHA_TO[$this->modnn($rs, $feedback + $GENPOLY[0])]);
+				} else {
+					array_push($parity, 0);
+				}
+			}
+			return $parity;
+		}
+
+	} // end QRcode class
+
+} // END OF "class_exists QRcode"
+?>

+ 2 - 0
core/libs/phpqrcode/cache/frame_1.dat

@@ -0,0 +1,2 @@
+xÚ��Á
À E9³u��`³"PÅ„CÛ牗T!0$
+E•ɲQ™�Ém½úhÛ¾9{kI"› 9Ln)Ap¤åÖ¾Ë>ß^‡Õz³mënÅ–;ü´mßn†ú¦Ë

二進制
core/libs/phpqrcode/cache/frame_1.png


二進制
core/libs/phpqrcode/cache/frame_10.dat


二進制
core/libs/phpqrcode/cache/frame_10.png


二進制
core/libs/phpqrcode/cache/frame_11.dat


二進制
core/libs/phpqrcode/cache/frame_11.png


二進制
core/libs/phpqrcode/cache/frame_12.dat


二進制
core/libs/phpqrcode/cache/frame_12.png


二進制
core/libs/phpqrcode/cache/frame_13.dat


二進制
core/libs/phpqrcode/cache/frame_13.png


二進制
core/libs/phpqrcode/cache/frame_14.dat


二進制
core/libs/phpqrcode/cache/frame_14.png


二進制
core/libs/phpqrcode/cache/frame_15.dat


二進制
core/libs/phpqrcode/cache/frame_15.png


+ 1 - 0
core/libs/phpqrcode/cache/frame_16.dat

@@ -0,0 +1 @@
+xÚí™A„ E]sëIX´;¸Ün6€È`‚q”êêW6ñ奚`Œ%A/3!¢°‚¢Š!g–ÈÌ¡’1N)éE¢Ï|;®—>6â¸�Þ97$ëÄôëc]kkö�wé1Öü[·m­CÍœcÊRºÄê¹>¦èµ¾šE,•hʼnp„#áxF�yWÏÇVWGçòÕ3¼Õ+шþàË“úSŽâ}Äž�#áG8b^c^cÏÀŽp„c&3YQ"ñŽ÷çÌvµù›…ñàÎþþ¼–¹kÞ9ŠÜ‡÷}”¹³ï×ú	¢Ä¿�QäÿL—/ÝÔÀÏ

二進制
core/libs/phpqrcode/cache/frame_16.png


二進制
core/libs/phpqrcode/cache/frame_17.dat


二進制
core/libs/phpqrcode/cache/frame_17.png


+ 2 - 0
core/libs/phpqrcode/cache/frame_18.dat

@@ -0,0 +1,2 @@
+xÚí™A
+ƒ0E]çÖ…,2;sƒä&ÉÍšh¥ÛêO¡ôÝÈàã1&09OIv@DDÒÌ&§Ù‰K�XÈÕFv•<Ádqò9Ö<%h•¹Yïs!(d¥²ës;~||b(ÏøYůg#µ`œK ±S¼Åô¹Ä¶˜ùsàidß�Lg:Ó™Îtþ/gmª�™ƒkÅMâ3³{­4rTÈQýÿe¥·s·>ó<Ó™Ît¦3�éÌ;ïH¼#Ñ™Ît¦3�ÍYœ+og©hù¶óµÙ½¬lnðûF>Øi^»#awm;gè~pÛgìNs{6z’‘»ãºïÞäp¾Ê'

二進制
core/libs/phpqrcode/cache/frame_18.png


+ 3 - 0
core/libs/phpqrcode/cache/frame_19.dat

@@ -0,0 +1,3 @@
+xÚíšA
+Ä E»öÖ.ĚNo 7Ń›Ť¶iiRÚN2‹áW%đxÁ@ÚÚśę'­
+u�6×ę�.ť*S;}�«ŇĂ ĎTúčĚzrŤtąď%ç,ŇĹÚâÎ}ç;“âç)ąź�âÝZÚîLĺčą÷¬Pçç$Ż×÷ĎqËgśLÂôdJ‡;Üáw¸Ăý.]z#źľ«[Íť˝ďOg‚­Ćô"ĐË	áBíî¦}Ç}‡;Üáw¸Ăî�#1GbŽ„;Üáw¸Ăý_ÝC+w˘@Dfî÷ďç™uťř2™ĹÚÉNţű9R7|pWßkďű®ż“ßßkşöżşú»ĽÎÓ

二進制
core/libs/phpqrcode/cache/frame_19.png


+ 1 - 0
core/libs/phpqrcode/cache/frame_2.dat

@@ -0,0 +1 @@
+xÚÍ’Í
À F{vë& à&°Y+?Z1öÐSŸ'y!¢ŸÌÁa�815&£•Û´ŽÙHå£Ùžc³•l«ÏFÆè1º#é6fÊÖü©§6Äø•O7ˆ¨†C¦«›ðÖ�ž�Ï8gI®ÏöfB¦ÃÄÿæ\DÔ»(

二進制
core/libs/phpqrcode/cache/frame_2.png


二進制
core/libs/phpqrcode/cache/frame_20.dat


二進制
core/libs/phpqrcode/cache/frame_20.png


+ 1 - 0
core/libs/phpqrcode/cache/frame_21.dat

@@ -0,0 +1 @@
+xÚíšA„ E]sëIX´;¹Ün6Up‚�“в™ÿ]Ù˜þ<i-eWö‹¶˜)×äÅ•¼ÉÂ…H\jvqÙHL\6–šÝÐ…rI›¢LܹÜÕ%ÅÓ@´þ±V—vÆÂúý¤(ÏP4|ÎXnÒgÉ�ß¼~]D¾ÉÕ×u1Us	S\À°€,ÿÅ2Þ¢N§Ã?D›KºüF-:“eJ]p_À°€,˜a0Ã`†ÁÝXÀ°`†Áƒw,`X´]˜ˆ™‚¹‹˜°5‰®Y4{屿ñ2íûåvçJs†±Ûí9±˜í)õu±Û¹êÏØ,«]¸“‹Ù^_§7$ƒ_Í

二進制
core/libs/phpqrcode/cache/frame_21.png


+ 3 - 0
core/libs/phpqrcode/cache/frame_22.dat

@@ -0,0 +1,3 @@
+xÚíšA
+„0E]{ë�.’]{{{³©Z¥BepÆÞwe@�V›ERZ3»Á"*2o€4¦y‰)i#dÒbdFÒ…´ŒI"ú‘—4ž½W­IíuŠÓ45ßx«.Z­SÙ{ÁŸ¯8åËÿk={o.±qÊÙ£[œÍ:帒q»õƒy
+)t#á„N8ádCj�-O�OG}¼:/Ÿ:s�z!Å)^<ùe½·S·uâ{Â	'œpÂ	'ú=ú=ú=¾'œpÂ	'œp¢ß£ß£ßã�N8á„Óÿ9©ªˆôpQQõ]HÔpz¾�ØGœ^æ½Qº˜I|¾ß³�u;9™ÎïÕëd;“X~$ËÙÑÉt¶ÊÛédy

二進制
core/libs/phpqrcode/cache/frame_22.png


+ 3 - 0
core/libs/phpqrcode/cache/frame_23.dat

@@ -0,0 +1,3 @@
+xзМ A
+ц EЁЖжfo═7я⌡U█)	%M!н■бШYu(< П⌠sK╡⌠T°⌡с
+и&╖Iз\i+╔п╙≥(m╝╢FQ║╧╞h╠ФЖЭХv~n1└oо]sКГжО╓_ч÷й3`Н_w2Ух╧∙lc[╪∙;╥шcж÷к╓▓NС╙4эpц
7эpцМmTЪ╦°⌡▒щЙrчiЯД_┐Г©pS=7ч7эpц
7эpц█>I÷╓OР-а
7эpц
7З$}▓>и╥7эpц
╥tss┴сrs
╖ЕVмнэфВ▓mЩО║р╧Р┤²чЯ}R~7ТЮ&╬В╨?7Ы²чЩ²т╕IОbhБ{Ф╩<юMi-

二進制
core/libs/phpqrcode/cache/frame_23.png


+ 1 - 0
core/libs/phpqrcode/cache/frame_24.dat

@@ -0,0 +1 @@
+xΪν›Aƒ E»φΦMX0;Έ�άnVP4ΪHSS»xίU3±/O΄ύLiJ4��±VβJC�%ύ‰6VR&ΓήD‘B�HjDω‚JΟ??™―κBl­cΗ±ρ½§'σU­λXοUοή�0ζΓywΝΔ―χj¬ιλ�³€3Ε›Ύλ�cj†ω£{¨¥½:GqΔG�έρψ�ϋΪ°N†v;Ή¶η¬“J‡ΔΠ<ϋ‡Ι]�κλΘσ�#�8β�#�8βH'§“ΣΙωΝΑGqΔGιδtr:9Ο#�8β�#�8βΨ“h­�―NΤt”�΄Φ_έΨ>tΉeλμS­―¦ζ�ω^�\g―υΞQe?ωvuφΜoοΥ;�ο>μ�*οwlςΧmΡ

二進制
core/libs/phpqrcode/cache/frame_24.png


+ 3 - 0
core/libs/phpqrcode/cache/frame_25.dat

@@ -0,0 +1,3 @@
+xÚíÛA
+à …á¬së‚‹™]rƒx½Y51mMÈBG
+ÿ¸*Sx|Ua5Ƶ‚Z—Š„-,Ž1ä²HÑPÒRj–šX5§®i†©’áG©>W¥ŽžRïöÕ/Ëâ+uT廯åÏӯ嗴ªuæÏ¥Ú[Sía£[kví÷5•+5n§Á´JêÜ%+V¬X±bÅŠõ߬u'Á�±þÔû SRýå÷štzZ»ì+÷+V¬X±bÅŠ•ٟٟٟûŠ+V¬X±bÅÊìÏìÏìÏ}ÅŠ+V¬X±ö±ª¤¥ÖVI©¢ÖÖ‘+k«qÿ[úËtŽ·oVZÍþvoNV³wÇ}µ{³r<ýR­Þ"�RÍÞ]ê
W«r}

二進制
core/libs/phpqrcode/cache/frame_25.png


+ 2 - 0
core/libs/phpqrcode/cache/frame_26.dat

@@ -0,0 +1,2 @@
+xÚí›A
+à E³öÖ…,t§7ˆ7Ñ›U�		E)i7ï»*~cÃüÅÄXÖEBÆè°FC–˜³6¡:&çL,å¬Mv.ŽÂÎæKgŸÕ¸ãYMç>ŸÎí>ûmÛš·?ª•vô¹¾mg?�ßÒ±Îþ³æÎ·ªd˜“Cµ¹U¦ÏIk•ÚÚE\ÕÙMs†f˜a†f˜a>œ[sÓˆ9쬩ެ8bö<kÕÙ7œ}ç†k³™§õ™ÿ3Ì0Ã3Ì0Ã3Ìä*r¹Š\Å7f˜a†f˜a†fr¹Š\Å7f˜a†f˜a†YÆÙ�Îæd›4ƒ9kíÆÌÔÝyûX	y‰gŒØÙ)›«dw�nÌ¢ûU×>Ëî”]ßöLgÉÝÁ›³è¾äEo‚ w1

二進制
core/libs/phpqrcode/cache/frame_26.png


二進制
core/libs/phpqrcode/cache/frame_27.dat


二進制
core/libs/phpqrcode/cache/frame_27.png


二進制
core/libs/phpqrcode/cache/frame_28.dat


二進制
core/libs/phpqrcode/cache/frame_28.png


+ 2 - 0
core/libs/phpqrcode/cache/frame_29.dat

@@ -0,0 +1,2 @@
+xÚíÜA� …a×Ţş	‹™ťÜ@n7+*¶šÖÚ4‘!Í?®Jšđň	ł�”抮«]Ş—ÉSźâTf)–ŮsŠIÂ"…Č”bžÝ0…Š|•"Luٸî,Ž×EÇ1\6®*ĎuQŢ?Ľ>aĚĎ…ăţńŽÄRő-r­“÷n.ďꯋ\®Tżü:Ó*)|)°Ŕ,°Ŕ,ţŃâęóĺéx_ă¬}:^R„�Uoɢ‰uÁ~ÁމX`�XĐŹĐŹĐŹĐŹ°_`�X`�XĐŹĐŹĐŹ°_`�X`�XĐŹĐŹĐŹĐŹ°wb�X`�żĄPUőö)DÔŢ"cČ{‹zçÎő3ę›é<}¸óˇ^?b÷m˙ÎÂěž�íş°»óaűŽ´’Âę.�]
+ł{Q6uáT,9

二進制
core/libs/phpqrcode/cache/frame_29.png


+ 1 - 0
core/libs/phpqrcode/cache/frame_3.dat

@@ -0,0 +1 @@
+xÚí“Á
À E{vë& à&°Y+¢b¤öÐkŸ'yù‘¤¿ÌÁa :äÀTXl�Þ¶$W+Ó�vû®îœ¢9}gRæ¬@H0YPB½ÆÃEmÚÚ?ûœÍ±ísœÖ"bµìt2cnÖé†É:½ﺭë;¿Y§“ÃzÿQã«7¿Ô

二進制
core/libs/phpqrcode/cache/frame_3.png


二進制
core/libs/phpqrcode/cache/frame_30.dat


二進制
core/libs/phpqrcode/cache/frame_30.png


+ 1 - 0
core/libs/phpqrcode/cache/frame_31.dat

@@ -0,0 +1 @@
+xÚíÜAƒ …a×Þº	ØÉ
à&r³‚ Á´¸ªÎ4ù§«†´yù‚Ä·!¥mV3I�µv­!ÒœÖ2¢i\NSSä4EF2�+65Å¥‰e¾þÃ/Wœs]šñ¾‰!„Á?ÿpÅõû¦=S~ùüÄ�?Ëý+þx¦Ö6r6yö³Ùƹ}“Ç´™ë×eR1-�W•l°Ál°Á›ûÒŒÞXŸz/>Væ«·ù§:ñÒÒÄAš8üý-+mTíÎÎbl°Ál°ÁlèštMº&]“³l°Ál°Áº&]“®I×ä¼Ál°Ál°Áº&]“®Éyƒ
6Ø`ƒ
6Ø`ƒÍÝi¬uy´ØXWòè±Éi¬²\t†ýz•—Š>•.î”z¾kÊß
t²¿7©ß7òwJõÏ”¶4Òw‘�ÒˆßÓÖÍ85‰

二進制
core/libs/phpqrcode/cache/frame_31.png


+ 2 - 0
core/libs/phpqrcode/cache/frame_32.dat

@@ -0,0 +1,2 @@
+xЪнЬБ
+„ …бЦѕхЂ‹л.Я ЯDЯl¬,¦љMz‰я6›†Г‡	gcJЛD;ф'.®A’IqћЮ‰ДI,IrўYЁ»‘ЛFk%‰DюOжy|EDЄDЧы(LУ_YЌК>*Яљ?aКOѓїk±L_Ј<[c—с¶п>КcЛ�хuФLIдХ%В#Њ0В#Њ0В#ЊЮotСўљхµ}ЕЬ4Нfќv_)‰ВEўpъЏ¬h5R·Џ8Џ8і1В#Њ0В#Њ0ўУТiйґtZО#Њ0В#Њ0В#Њ0ўУТiйґtZО#Њ0В#Њ0В#Њ0ўУТiйґtZОlЊ0В#Њ0ВЈч9q"ўЙHЬњH™Qюќµп"ЫХL5}-ЭЬYЧѕУкёkм`¤в>¶zйёі®юЦ4&Тpчб!‘Љы!«щ`ї:5

二進制
core/libs/phpqrcode/cache/frame_32.png


+ 14 - 0
core/libs/phpqrcode/cache/frame_33.dat

@@ -0,0 +1,14 @@
+xЪнЬAѓ …aЧЮє‰‹™ќЬ@n7+*L++Ужџ®ут‰МbbЬ*LCп‘°‡‰ck™HҐrљ”j•ІђJ5Yнi~0•_«тЊыЧTКTх}е—e©>эц5‘b_еwРНџ?ї¤Ямж§ЦЬщ†\э­RaЖi+7хЯW©¦\гюwLUNеL¦В
++¬°В
++¬°Вкя­jЯТO·џkcлЮсфз\Л©|%•o<б‹k–­Lо+О+Оv¬°В
++¬°В
++¬°ВЉ>}ъф8Ї°В
++¬°В
++¬°В
++ъфи3РgајВ
++¬°В
++¬°В
++¬и3Рg П@џЃу
++¬°В
++¬°В
++¬°:R‰ЁЄXіЪB‰9«”IФ=зkЮЏ±o/SwзШ�™ЩЇП`g¶бЕКМИr_Щ™™YѕѓVSY™ЕzIefnmQoz
>б

二進制
core/libs/phpqrcode/cache/frame_33.png


二進制
core/libs/phpqrcode/cache/frame_34.dat


二進制
core/libs/phpqrcode/cache/frame_34.png


二進制
core/libs/phpqrcode/cache/frame_35.dat


二進制
core/libs/phpqrcode/cache/frame_35.png


部分文件因文件數量過多而無法顯示