Browse Source

* Large refactor
- added classes: user class, web controller, login
- changed logic of username/password login check
- added class error handler and added a web page
- small plugin change: added @var for visibility
- font changed to Roboto, locally installed
- removed many of COOKIE variables and using new SESSION logic
- added custom js and css for plugin
- many other changes...

Giancarlo 8 years ago
parent
commit
0142581f65

+ 4 - 2
build.js

@@ -4,6 +4,7 @@ compressor.minify({
     compressor: 'clean-css',
     compressor: 'clean-css',
     input: [
     input: [
       "node_modules/bootstrap/dist/css/bootstrap.min.css",
       "node_modules/bootstrap/dist/css/bootstrap.min.css",
+      "ui/omlink.css",
       "ui/custom.css"
       "ui/custom.css"
     ],
     ],
     output: 'bundle.css'
     output: 'bundle.css'
@@ -13,9 +14,10 @@ compressor.minify({
 compressor.minify({
 compressor.minify({
     compressor: 'uglifyjs',
     compressor: 'uglifyjs',
     input: [
     input: [
+      "ui/omlink.js",
       "ui/custom.js"
       "ui/custom.js"
     ],
     ],
-    output: 'ui/custom.min.js'
+    output: 'ui/bundle.min.js'
   }
   }
 );
 );
 
 
@@ -24,7 +26,7 @@ compressor.minify({
     input: [
     input: [
       "node_modules/jquery/dist/jquery.min.js",
       "node_modules/jquery/dist/jquery.min.js",
       "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js",
       "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js",
-      "ui/custom.min.js"
+      "ui/bundle.min.js"
     ],
     ],
     output: 'bundle.js'
     output: 'bundle.js'
   }
   }

+ 3 - 2
config.ini

@@ -1,6 +1,6 @@
 [globals]
 [globals]
 AUTOLOAD="src/"
 AUTOLOAD="src/"
-CACHE = "folder=cache/"
+CACHE = TRUE
 UI=ui/
 UI=ui/
 DEBUG=3
 DEBUG=3
 ENCODING="UTF-8"
 ENCODING="UTF-8"
@@ -14,7 +14,8 @@ SITENAME=OM-Link Lamborghini
 LOGO_CUSTOMER={{@BASEURL}}/ui/images/logo_text.png
 LOGO_CUSTOMER={{@BASEURL}}/ui/images/logo_text.png
 
 
 [CORE.fb]
 [CORE.fb]
-host=192.168.1.140
+;:host=192.168.1.140
+host=127.0.0.1
 port=50443
 port=50443
 key=C0000000000011511187894
 key=C0000000000011511187894
 pass=X8sCUiGBEbWTRWCUW72n95tRT7wYriac
 pass=X8sCUiGBEbWTRWCUW72n95tRT7wYriac

+ 2 - 1
index.php

@@ -9,6 +9,7 @@
 
 
 // Init Framework
 // Init Framework
 require_once 'lib/f3/base.php';
 require_once 'lib/f3/base.php';
+$f3 = \Base::instance();
 
 
 // Load Utility Class
 // Load Utility Class
 require_once "src\OpenMind\System\OMUtils.php";
 require_once "src\OpenMind\System\OMUtils.php";
@@ -18,4 +19,4 @@ $frameworkUtils->DieByOldPhpVersion();
 $frameworkUtils->LoadEncryptedConfig('config.bin');
 $frameworkUtils->LoadEncryptedConfig('config.bin');
 $frameworkUtils->PluginLoader('src/');
 $frameworkUtils->PluginLoader('src/');
 
 
-\F3::run();
+$f3->run();

+ 69 - 69
omlinkimporter.php

@@ -10,62 +10,62 @@ const ARTICLES_COLONNE = 15;
 
 
 class CSVImporter
 class CSVImporter
 {
 {
-    private $currentFileName;
-    private $folderToWatch;
-    private $dbMysql;
+  private $currentFileName;
+  private $folderToWatch;
+  private $dbMysql;
 
 
-    public function __construct($folderPath, $databaseName, $dbusername, $dbpassword)
-    {
-        $this->currentFileName = '';
-        $this->folderToWatch = $folderPath;
-        $this->dbMysql = new mysqli('localhost', $dbusername, $dbpassword, $databaseName);
-        if ($this->dbMysql->connect_error) {
-            die('Database connection error (' . $this->dbMysql->connect_errno . ') ' . $this->dbMysql->connect_error);
-        }
+  public function __construct($folderPath, $databaseName, $dbusername, $dbpassword)
+  {
+    $this->currentFileName = '';
+    $this->folderToWatch = $folderPath;
+    $this->dbMysql = new mysqli('localhost', $dbusername, $dbpassword, $databaseName);
+    if ($this->dbMysql->connect_error) {
+      die('Database connection error (' . $this->dbMysql->connect_errno . ') ' . $this->dbMysql->connect_error);
     }
     }
+  }
 
 
-    public function ScanAndStoreData()
-    {
-        foreach (glob("{$this->folderToWatch}/*.csv") as $fname) {
-            if (is_file($fname)) {
-                $allData = $this->loadCSV($fname);
+  public function ScanAndStoreData()
+  {
+    foreach (glob("{$this->folderToWatch}/*.csv") as $fname) {
+      if (is_file($fname)) {
+        $allData = $this->loadCSV($fname);
 
 
-                // Esce se il file non è una distinta, lo riconosce solamente dal numero di colonne del file CSV
-                if ($allData == NULL)
-                    return;
+        // Esce se il file non è una distinta, lo riconosce solamente dal numero di colonne del file CSV
+        if ($allData == NULL)
+          return;
 
 
-                switch (count($allData[0])) {
-                    case DISTINTA_COLONNE:
-                        $this->importOnDatabase($fname, $allData);
-                        break;
-                    case ARTICLES_COLONNE:
-                        $this->mysqlLoadCSV(addslashes(realpath($fname)), 'articles');
-                        break;
-                default:
-                    echo "Numero di colonne non riconosciute ne come DISTINTA e ne come LISTA ARTICOLI per il file '{$fname}'";
-                }
-            }
+        switch (count($allData[0])) {
+          case DISTINTA_COLONNE:
+            $this->importOnDatabase($fname, $allData);
+            break;
+          case ARTICLES_COLONNE:
+            $this->mysqlLoadCSV(addslashes(realpath($fname)), 'articles');
+            break;
+          default:
+            echo "Numero di colonne non riconosciute ne come DISTINTA e ne come LISTA ARTICOLI per il file '{$fname}'";
         }
         }
+      }
     }
     }
+  }
 
 
-    private function loadCSV(string $path): ?array
-    {
-        $fh = fopen($path, "r");
-        $csvData = [];
-        while (($d = fgetcsv($fh, 0, ';'))) {
-            if ($d)
-                $csvData[] = $d;
-        }
-        fclose($fh);
-        return $csvData;
+  private function loadCSV(string $path): ?array
+  {
+    $fh = fopen($path, "r");
+    $csvData = [];
+    while (($d = fgetcsv($fh, 0, ';'))) {
+      if ($d)
+        $csvData[] = $d;
     }
     }
+    fclose($fh);
+    return $csvData;
+  }
 
 
-    private function importOnDatabase(string $fileName, array $data)
-    {
-      $this->dbMysql->query("TRUNCATE TABLE `distinte`");
-        foreach ($data as $dataRow) {
-          $descr = $this->dbMysql->escape_string($dataRow[10]);
-            $sql = <<<EOL
+  private function importOnDatabase(string $fileName, array $data)
+  {
+    $this->dbMysql->query("TRUNCATE TABLE `distinte`");
+    foreach ($data as $dataRow) {
+      $descr = $this->dbMysql->escape_string($dataRow[10]);
+      $sql = <<<EOL
 INSERT INTO distinte (
 INSERT INTO distinte (
 origine, consegna, commessa, ordine_produzione, data_creazione, time_creazione, destinazione_merci, barcode, descrizione, qta_prelevare, qta_mancante
 origine, consegna, commessa, ordine_produzione, data_creazione, time_creazione, destinazione_merci, barcode, descrizione, qta_prelevare, qta_mancante
 ) VALUES (
 ) VALUES (
@@ -73,36 +73,36 @@ origine, consegna, commessa, ordine_produzione, data_creazione, time_creazione,
 '$descr', '$dataRow[11]', 0
 '$descr', '$dataRow[11]', 0
 );
 );
 EOL;
 EOL;
-            if (!$this->dbMysql->query($sql)) {
-                echo "Error on query: {$sql}" . PHP_EOL;
-                echo $this->dbMysql->error . PHP_EOL;
-                return;
-            }
-        }
-        echo "{$fileName} successfully imported" . PHP_EOL;
-        $this->markFileAsDone($fileName);
+      if (!$this->dbMysql->query($sql)) {
+        echo "Error on query: {$sql}" . PHP_EOL;
+        echo $this->dbMysql->error . PHP_EOL;
+        return;
+      }
     }
     }
+    echo "{$fileName} successfully imported" . PHP_EOL;
+    $this->markFileAsDone($fileName);
+  }
 
 
-    private function markFileAsDone(string $csvPath)
-    {
-        rename($csvPath, "{$csvPath}_imported");
-    }
+  private function markFileAsDone(string $csvPath)
+  {
+    rename($csvPath, "{$csvPath}_imported");
+  }
 
 
-    private function mysqlLoadCSV(string $CSVPath, string $tableName)
-    {
-      $this->dbMysql->query("TRUNCATE TABLE `{$tableName}`");
-        $sql = <<<EOF
+  private function mysqlLoadCSV(string $CSVPath, string $tableName)
+  {
+    $this->dbMysql->query("TRUNCATE TABLE `{$tableName}`");
+    $sql = <<<EOF
 LOAD DATA INFILE '$CSVPath' INTO TABLE `$tableName`
 LOAD DATA INFILE '$CSVPath' INTO TABLE `$tableName`
 FIELDS TERMINATED BY ';' ENCLOSED BY '' LINES TERMINATED BY '\\n';
 FIELDS TERMINATED BY ';' ENCLOSED BY '' LINES TERMINATED BY '\\n';
 EOF;
 EOF;
-        if (!$this->dbMysql->query($sql)) {
-            echo "Error on query: {$sql}" . PHP_EOL;
-            echo $this->dbMysql->error . PHP_EOL;
-            return;
-        }
-        echo "{$CSVPath} successfully imported" . PHP_EOL;
-        $this->markFileAsDone($CSVPath);
+    if (!$this->dbMysql->query($sql)) {
+      echo "Error on query: {$sql}" . PHP_EOL;
+      echo $this->dbMysql->error . PHP_EOL;
+      return;
     }
     }
+    echo "{$CSVPath} successfully imported" . PHP_EOL;
+    $this->markFileAsDone($CSVPath);
+  }
 }
 }
 
 
 echo PHP_EOL . 'Scanning import folder for new CSV to import...' . PHP_EOL . PHP_EOL;
 echo PHP_EOL . 'Scanning import folder for new CSV to import...' . PHP_EOL . PHP_EOL;

+ 9 - 7
src/Customers/Lamborghini/Distinta.php

@@ -7,8 +7,8 @@
 
 
 namespace Customers\Lamborghini;
 namespace Customers\Lamborghini;
 
 
-use OpenMind\Labeling\FindBoxCoreSystem;
-use OpenMind\Labeling\SmartESL;
+use OpenMind\FindBox\FindBoxCoreSystem;
+use OpenMind\FindBox\SmartESL;
 
 
 class Distinta
 class Distinta
 {
 {
@@ -28,7 +28,9 @@ class Distinta
 
 
   /**
   /**
    * Esplode la disinta in modo che tutti abbiano quantità 1
    * Esplode la disinta in modo che tutti abbiano quantità 1
+   *
    * @param string $commessa
    * @param string $commessa
+   * @throws \Exception
    */
    */
   public function CopyDistinta(string $commessa)
   public function CopyDistinta(string $commessa)
   {
   {
@@ -41,12 +43,12 @@ EOF;
     $dataset = $this->dbHandle->exec($sql);
     $dataset = $this->dbHandle->exec($sql);
     $idutente = $this->userId;
     $idutente = $this->userId;
 
 
-    foreach($dataset as $row) {
+    foreach ($dataset as $row) {
       $sqlInsert = "INSERT INTO distinta_esplosa (idutente, commessa, barcode, descrizione, origine, ubicazione, sequenza, qta_prelevare, anomalie)" .
       $sqlInsert = "INSERT INTO distinta_esplosa (idutente, commessa, barcode, descrizione, origine, ubicazione, sequenza, qta_prelevare, anomalie)" .
         "VALUES ({$idutente}, '{$row['consegna']}', '{$row['barcode']}', '{$row['descrizione']}', '{$row['origine']}', '{$row['ubicazione']}', '{$row['sequenza']}', '{$row['qta_prelevare']}', 0)";
         "VALUES ({$idutente}, '{$row['consegna']}', '{$row['barcode']}', '{$row['descrizione']}', '{$row['origine']}', '{$row['ubicazione']}', '{$row['sequenza']}', '{$row['qta_prelevare']}', 0)";
       $err = $this->dbHandle->exec($sqlInsert);
       $err = $this->dbHandle->exec($sqlInsert);
       if (!$err)
       if (!$err)
-        die(__FUNCTION__ . ' error insert in table distinta_esplosa');
+        throw new \Exception(__FUNCTION__ . ' error insert in table distinta_esplosa');
     }
     }
   }
   }
 
 
@@ -61,7 +63,7 @@ EOF;
     $findBoxCore = new FindBoxCoreSystem(...array_values($CORE_SETTINGS));
     $findBoxCore = new FindBoxCoreSystem(...array_values($CORE_SETTINGS));
 
 
     $datiDistinta = $this->getDistinta($maxArticles);
     $datiDistinta = $this->getDistinta($maxArticles);
-    foreach($datiDistinta as $row) {
+    foreach ($datiDistinta as $row) {
 
 
       $labelId = $this->GetLabelIdFromBarcode($row['barcode']);
       $labelId = $this->GetLabelIdFromBarcode($row['barcode']);
       if ($labelId != null) {
       if ($labelId != null) {
@@ -192,7 +194,7 @@ EOF;
 
 
     $xmlField = '<?xml version="1.0" encoding="UTF-8"?><distinta>';
     $xmlField = '<?xml version="1.0" encoding="UTF-8"?><distinta>';
 
 
-    foreach($articles as $i => $articolo) {
+    foreach ($articles as $i => $articolo) {
       $xmlField .= "<materiale anomalia=\"{$articolo['anomalie']}\"><barcode>{$articolo['barcode']}</barcode><description>{$articolo['descrizione']}</description><qta_nominale>{$articolo['qta_nominale']}</qta_nominale><qta_prelevare>{$articolo['qta_prelevare']}</qta_prelevare></materiale>";
       $xmlField .= "<materiale anomalia=\"{$articolo['anomalie']}\"><barcode>{$articolo['barcode']}</barcode><description>{$articolo['descrizione']}</description><qta_nominale>{$articolo['qta_nominale']}</qta_nominale><qta_prelevare>{$articolo['qta_prelevare']}</qta_prelevare></materiale>";
     }
     }
 
 
@@ -227,7 +229,7 @@ EOF;
     $CORE_SETTINGS = \F3::get('CORE.fb');
     $CORE_SETTINGS = \F3::get('CORE.fb');
     $findBoxCore = new FindBoxCoreSystem(...array_values($CORE_SETTINGS));
     $findBoxCore = new FindBoxCoreSystem(...array_values($CORE_SETTINGS));
 
 
-    foreach($dataset as $row) {
+    foreach ($dataset as $row) {
       $dataFields = array(
       $dataFields = array(
         'qr_code' => $row['barcode'],
         'qr_code' => $row['barcode'],
         'qta_prelevare' => ''
         'qta_prelevare' => ''

+ 1 - 1
src/Customers/Lamborghini/LabelingSystem.php

@@ -7,7 +7,7 @@
 
 
 namespace Customers\Lamborghini;
 namespace Customers\Lamborghini;
 
 
-use OpenMind\Labeling\FindBoxCoreSystem as FBCS;
+use OpenMind\FindBox\FindBoxCoreSystem as FBCS;
 
 
 class LabelingSystem extends FBCS
 class LabelingSystem extends FBCS
 {
 {

+ 11 - 7
src/Customers/Lamborghini/Lamborghini.php

@@ -11,13 +11,17 @@ use OpenMind\System\PluginStrategy;
 
 
 class Lamborghini extends PluginStrategy
 class Lamborghini extends PluginStrategy
 {
 {
-  public static function Init()
+  public function __construct()
   {
   {
-    \F3::route('GET /', __NAMESPACE__ . '\Pages->Login');
-    \F3::route('GET /homemenu', __NAMESPACE__ . '\Pages->HomeMenu');
-    \F3::route('GET|POST /pick2light/@step', __NAMESPACE__ . '\Pages->Pick2Light');
-    \F3::route("GET|POST /bind/@step", __NAMESPACE__ . '\Pages->Bind');
-    \F3::route("GET|POST /unbind/@step", __NAMESPACE__ . '\Pages->UnBind');
-    \F3::route('GET /elencodistinta', __NAMESPACE__ . '\Pages->ElencoDistinta');
+    \F3::config('labels.ini', true);
+
+    $this->AddRoute('GET /homemenu', __NAMESPACE__ . '\Pages->HomeMenu');
+    $this->AddRoute('GET|POST /pick2light/@step', __NAMESPACE__ . '\Pages->Pick2Light');
+    $this->AddRoute("GET|POST /bind/@step", __NAMESPACE__ . '\Pages->Bind');
+    $this->AddRoute("GET|POST /unbind/@step", __NAMESPACE__ . '\Pages->UnBind');
+    $this->AddRoute('GET /elencodistinta', __NAMESPACE__ . '\Pages->ElencoDistinta');
   }
   }
 }
 }
+
+/** @var \Customers\Lamborghini\Lamborghini $Lamborghini */
+Global $Lamborghini;

+ 4 - 15
src/Customers/Lamborghini/Pages.php

@@ -7,10 +7,10 @@
 
 
 namespace Customers\Lamborghini;
 namespace Customers\Lamborghini;
 
 
-use OpenMind\Labeling\FindBoxCoreSystem;
-use OpenMind\Labeling\SmartESL;
+use OpenMind\FindBox\FindBoxCoreSystem;
+use OpenMind\FindBox\SmartESL;
 
 
-class Pages extends \OpenMind\Web\BaseController
+class Pages extends \OpenMind\Web\Controller
 {
 {
   private $CORE_SETTINGS;
   private $CORE_SETTINGS;
   private $findBoxCore;
   private $findBoxCore;
@@ -22,17 +22,6 @@ class Pages extends \OpenMind\Web\BaseController
     $this->findBoxCore = new FindBoxCoreSystem(...array_values($this->CORE_SETTINGS));
     $this->findBoxCore = new FindBoxCoreSystem(...array_values($this->CORE_SETTINGS));
   }
   }
 
 
-  public function Login($f3)
-  {
-    if (!is_null($this->userId)) {
-      $f3->reroute('/homemenu');
-      return;
-    } else
-      $f3->set('CONTENT', 'login.tpl');
-
-    echo \Template::instance()->render('masterpage.tpl');
-  }
-
   public function HomeMenu($f3)
   public function HomeMenu($f3)
   {
   {
     $f3->set('CONTENT', 'homemenu.tpl');
     $f3->set('CONTENT', 'homemenu.tpl');
@@ -125,7 +114,7 @@ class Pages extends \OpenMind\Web\BaseController
           }
           }
         } else {
         } else {
           // Seleziona le prossime tre etichette
           // Seleziona le prossime tre etichette
-          foreach($rowsDistinta as $rowDist) {
+          foreach ($rowsDistinta as $rowDist) {
             $labelId = $distinta->GetLabelIdFromBarcode($rowDist['barcode']);
             $labelId = $distinta->GetLabelIdFromBarcode($rowDist['barcode']);
             if ($labelId != null) {
             if ($labelId != null) {
               $label = new SmartESL($this->findBoxCore, [$labelId]);
               $label = new SmartESL($this->findBoxCore, [$labelId]);

+ 0 - 18
src/OpenMind/Database/Modulo.php

@@ -1,18 +0,0 @@
-<?php
-/**
- * @author Open Mind
- * @date 12/06/2018
- * @time 11:41
- */
-
-namespace OpenMind\Database;
-
-class Modulo
-{
-  /**
-   * Modulo constructor.
-   */
-  public function __construct()
-  {
-  }
-}

+ 0 - 18
src/OpenMind/Database/ModuloParts.php

@@ -1,18 +0,0 @@
-<?php
-/**
- * @author Open Mind
- * @date 12/06/2018
- * @time 11:43
- */
-
-namespace OpenMind\Database;
-
-class ModuloParts
-{
-  /**
-   * ModuloParts constructor.
-   */
-  public function __construct()
-  {
-  }
-}

+ 20 - 8
src/OpenMind/Labeling/FindBoxCoreSystem.php → src/OpenMind/Findbox/FindBoxCoreSystem.php

@@ -8,7 +8,9 @@
  * @return array
  * @return array
  */
  */
 
 
-namespace OpenMind\Labeling;
+namespace OpenMind\FindBox;
+
+use OpenMind\System\System;
 
 
 function array_filter_keys(array $array, array $keysToExtract)
 function array_filter_keys(array $array, array $keysToExtract)
 {
 {
@@ -30,6 +32,7 @@ class FindBoxCoreSystem
    * @param int $port
    * @param int $port
    * @param string $APIKey
    * @param string $APIKey
    * @param string $Password
    * @param string $Password
+   * @throws \Exception
    */
    */
   public function __construct(string $host, int $port, string $APIKey, string $Password)
   public function __construct(string $host, int $port, string $APIKey, string $Password)
   {
   {
@@ -38,15 +41,24 @@ class FindBoxCoreSystem
     $this->Key = $APIKey;
     $this->Key = $APIKey;
     $this->Pass = $Password;
     $this->Pass = $Password;
 
 
-    $URI = '/1.0.0/index.php/getstatus/1.0.0/';
-    $ret = $this->CallAPI($URI, "");
+    Global $System;
+    /** @var System $System */
+    $Cache = $System->getCache();
+
+    if (!$Cache->exists('FindBoxDetails')) {
+      $URI = '/1.0.0/index.php/getstatus/1.0.0/';
+      $ret = $this->CallAPI($URI, "");
 
 
-    if ($ret['err'] != 0)
-      die("<p style='text-align:center'>Can't connect to FindBox server<br/><br/>{$ret['value']}.</p>");
+      if ($ret['err'] != 0)
+        throw new \Exception("Can't connect to FindBox server:<br/><br/>{$ret['value']}");
 
 
-    if ($ret['err'] == 0 && $ret['value']['code'] == 0) {
-      $details = $ret['value']['value'];
-      $this->coreDetails = array_filter_keys($details, ['core.box_id', 'core.version']);
+      if ($ret['err'] == 0 && $ret['value']['code'] == 0) {
+        $details = $ret['value']['value'];
+        $this->coreDetails = array_filter_keys($details, ['core.box_id', 'core.version']);
+      }
+      $Cache->set('FindBoxDetails', $this->coreDetails, 0);
+    } else {
+      $this->coreDetails = $Cache->get('FindBoxDetails');
     }
     }
   }
   }
 
 

+ 1 - 1
src/OpenMind/Labeling/SmartESL.php → src/OpenMind/Findbox/SmartESL.php

@@ -5,7 +5,7 @@
  * @time 09:09
  * @time 09:09
  */
  */
 
 
-namespace OpenMind\Labeling;
+namespace OpenMind\FindBox;
 
 
 class SmartESL
 class SmartESL
 {
 {

+ 3 - 2
src/OpenMind/System/ErrorHandlers.php

@@ -44,6 +44,7 @@ class ErrorHandlers
    */
    */
   function WriteLog($logMessage, $traceNumber = 1)
   function WriteLog($logMessage, $traceNumber = 1)
   {
   {
+    Global $System;
     $trace = debug_backtrace();
     $trace = debug_backtrace();
 
 
     if (count($trace) > 1) {
     if (count($trace) > 1) {
@@ -53,11 +54,11 @@ class ErrorHandlers
       $class = isset($trace['class']) ? $trace['class'] . ':' : '';
       $class = isset($trace['class']) ? $trace['class'] . ':' : '';
       $line = isset($trace['line']) ? $trace['line'] . ':' : '';
       $line = isset($trace['line']) ? $trace['line'] . ':' : '';
       //$userAgent = '(' . join(', ', $UA) . ')';
       //$userAgent = '(' . join(', ', $UA) . ')';
-      System::getLogger()->write("{$line}{$class}{$method} " . str_replace(array("\r", "\n"), '', $logMessage));
+      $System->getLogger()->write("{$line}{$class}{$method} " . str_replace(array("\r", "\n"), '', $logMessage));
       return;
       return;
     }
     }
 
 
-    System::getLogger()->write($logMessage);
+    $System->getLogger()->write($logMessage);
   }
   }
 
 
 }
 }

+ 11 - 5
src/OpenMind/System/OMUtils.php

@@ -28,16 +28,22 @@ class OMUtils
    */
    */
   public function PluginLoader(string $path)
   public function PluginLoader(string $path)
   {
   {
+    Global $System;
+    $System = new System();  // we need System Base class first, so will force to load as first
     $Directory = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
     $Directory = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
     $Iterator = new RecursiveIteratorIterator($Directory, RecursiveIteratorIterator::CHILD_FIRST);
     $Iterator = new RecursiveIteratorIterator($Directory, RecursiveIteratorIterator::CHILD_FIRST);
 
 
-    foreach($Iterator as $item) {
+    foreach ($Iterator as $item) {
       if (is_file($item->getPathname()))
       if (is_file($item->getPathname()))
         continue;
         continue;
-      $moduleInitPath = "{$item->getPathname()}/{$item->getFilename()}.php";
-      $className = str_replace('/', '\\', ltrim("{$item->getPathname()}/{$item->getFilename()}", $path));
-      if (file_exists($moduleInitPath)) {
-        $className::Init();
+      $moduleName = $item->getFilename();
+      $moduleInitPath = "{$item->getPathname()}/{$moduleName}.php";
+      $className = str_replace('/', '\\', ltrim("{$item->getPathname()}/{$moduleName}", $path));
+      if (file_exists($moduleInitPath)) { // If already imported, skip
+        if (!isset($$moduleName)) {
+          Global $$moduleName;  // Declare visibility to Global
+          $$moduleName = new $className(); // Instantiate the Module, all init procedure must reside in __constructor() method
+        }
       }
       }
     }
     }
   }
   }

+ 26 - 7
src/OpenMind/System/PluginStrategy.php

@@ -15,11 +15,29 @@ namespace OpenMind\System;
  */
  */
 interface IPluginStrategy
 interface IPluginStrategy
 {
 {
+  public function __construct();
+
+  /**
+   * Class version
+   * @return string
+   */
   public function getVersion(): string;
   public function getVersion(): string;
 
 
+  /**
+   * Class name
+   * @return string
+   */
   public function getName(): string;
   public function getName(): string;
 
 
-  public static function Init();
+  /**
+   * Set method route
+   *
+   * @param array|string $pattern
+   * @param string $handler
+   * @return mixed
+   */
+  public function AddRoute($pattern, string $handler);
+
 }
 }
 
 
 /**
 /**
@@ -30,6 +48,11 @@ interface IPluginStrategy
  */
  */
 class PluginStrategy implements IPluginStrategy
 class PluginStrategy implements IPluginStrategy
 {
 {
+  public function __construct()
+  {
+    throw new \Exception("Plugin " . $this->getName() . ' doesn\'t have a __constructor() function. Please provide one.');
+  }
+
   /**
   /**
    * Return default version for plugins that doesn't have one
    * Return default version for plugins that doesn't have one
    *
    *
@@ -50,13 +73,9 @@ class PluginStrategy implements IPluginStrategy
     return get_class($this);
     return get_class($this);
   }
   }
 
 
-  /**
-   * Main function
-   */
-  public static function Init()
+  public function AddRoute($pattern, string $handler)
   {
   {
-    $className = get_called_class();
-    die("Plugin " . $className . ' doesn\'t have an Init() function. Please provide one.');
+    \F3::route($pattern, $handler, 0);  // TTL 60s
   }
   }
 
 
 }
 }

+ 24 - 12
src/OpenMind/System/System.php

@@ -10,19 +10,14 @@ namespace OpenMind\System;
 
 
 class System extends PluginStrategy
 class System extends PluginStrategy
 {
 {
-  private static $Logger;
+  private $Logger;
+  private $cache;
 
 
-  /**
-   * @return mixed
-   */
-  public static function getLogger()
+  public function __construct()
   {
   {
-    return self::$Logger;
-  }
+    $this->cache = \Cache::instance();
 
 
-  public static function Init()
-  {
-    self::$Logger = new \Log('Site.log');
+    $this->Logger = new \Log('Site.log');
 
 
     \F3::set('DB',
     \F3::set('DB',
       new \DB\SQL(
       new \DB\SQL(
@@ -35,8 +30,25 @@ class System extends PluginStrategy
         ))
         ))
     );
     );
 
 
-    \F3::config('labels.ini', true);
+    \F3::set('ONERROR', __NAMESPACE__ . '\ErrorHandlers->Handler');
+  }
+
+  /**
+   * @return \Log
+   */
+  public function getLogger(): \Log
+  {
+    return $this->Logger;
+  }
 
 
-    \F3::set('ONERROR', '\OpenMind\System\ErrorHandlers->Handler');
+  /**
+   * @return \Cache
+   */
+  public function getCache(): \Cache
+  {
+    return $this->cache;
   }
   }
 }
 }
+
+/** @var System $System **/
+Global $System;

+ 53 - 0
src/OpenMind/System/User.php

@@ -0,0 +1,53 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: giancarlo
+ * Date: 28/06/2018
+ * Time: 20:01
+ */
+
+namespace OpenMind\System;
+
+class User
+{
+  private $p_id;
+  private $p_username;
+
+  /**
+   * @param int $p_id
+   */
+  public function setId(int $p_id)
+  {
+    $this->p_id = $p_id;
+  }
+
+  /**
+   * @return int
+   */
+  public function getId(): int
+  {
+    return $this->p_id;
+  }
+
+  /**
+   * @return string
+   */
+  public function getUsername(): string
+  {
+    return $this->p_username;
+  }
+
+  public function __construct(int $id, string $username)
+  {
+    $this->p_id = $id;
+    $this->p_username = $username;
+  }
+
+  public static function Load() {
+    return \F3::get('SESSION.user');
+  }
+
+  public function Save() {
+    \F3::set('SESSION.user', $this);
+  }
+}

+ 0 - 96
src/OpenMind/Web/BaseController.php

@@ -1,96 +0,0 @@
-<?php
-/**
- * @author Open Mind
- * @date 09/04/2018
- * @time 16:15
- */
-
-namespace OpenMind\Web;
-
-class BaseController
-{
-  protected $dbHandle;
-  protected $userId;
-  private $sanitizedPostRequest;
-
-  public function __construct($f3)
-  {
-    $this->sanitizedPostRequest = $f3->clean($f3->get('POST'));
-
-    $this->dbHandle = $f3->get('DB');
-
-    $this->userId = $this->checkLogin($f3->get('COOKIE.username'), $f3->get('COOKIE.password'));
-    $f3->set('USERID', $this->userId);
-
-    if (!is_null($this->userId))
-      return;
-
-    $f3->clear('COOKIE.username');
-    $f3->clear('COOKIE.password');
-    $f3->clear('COOKIE.id');
-
-    if (!in_array($f3->get('PATTERN'), ['/login', '/']))
-      $f3->reroute('/');
-
-    return;
-  }
-
-  /**
-   * Check if login is valid
-   * @param $username
-   * @param $password
-   * @return int|null
-   */
-  private function checkLogin($username, $password): ?int
-  {
-    $accounts = \F3::get('users.PASSWORD');
-    foreach($accounts as $index => $account) {
-      $exist = password_verify("{$username}|{$password}", $account);
-      if ($exist)
-        return $index;
-    }
-    return null;
-  }
-
-  /**
-   * Check if username and password are correct and set cookie
-   *
-   * @param $f3
-   */
-  public function Login($f3)
-  {
-    $accountData = $this->getSanitizedPostRequest();
-
-    $userId = $this->checkLogin($accountData['username'], $accountData['password']);
-
-    if (is_null($userId)) {
-      http_response_code(500);
-      echo "Dati di accesso non corretti";
-      return;
-    }
-
-    $f3->set('COOKIE.username', $accountData['username']);
-    $f3->set('COOKIE.password', $accountData['password']);
-    $f3->set('COOKIE.id', $userId);
-    //http_response_code(200);
-    $f3->reroute('/homemenu');
-  }
-
-  /**
-   * Return the sanitized POST parameters
-   *
-   * @return mixed
-   */
-  public function getSanitizedPostRequest()
-  {
-    return $this->sanitizedPostRequest;
-  }
-
-  public function Logout($f3)
-  {
-    $f3->clear('COOKIE.username');
-    $f3->clear('COOKIE.password');
-    $f3->clear('COOKIE.id');
-    $f3->reroute('/');
-  }
-}

+ 50 - 0
src/OpenMind/Web/Controller.php

@@ -0,0 +1,50 @@
+<?php
+/**
+ * @author Open Mind
+ * @date 09/04/2018
+ * @time 16:15
+ */
+
+namespace OpenMind\Web;
+
+use OpenMind\System\User;
+
+class Controller
+{
+  protected $dbHandle;
+
+  /**
+   * Sanitized POST request, usefull if sanitized POST is need
+   * @var array $sanitizedPostRequest
+   */
+  private $sanitizedPostRequest;
+
+  public function __construct($f3)
+  {
+    $this->sanitizedPostRequest = $f3->clean($f3->get('POST'));
+    $this->dbHandle = $f3->get('DB');
+
+    if (!$f3->exists('SESSION.user_id') && !in_array($f3->get('PATTERN'), ['/loginform', '/'])) {
+      $f3->reroute('/');
+      return;
+    }
+
+    if ($f3->exists('SESSION.user_id')) {
+      $f3->set('USERID', $f3->get('SESSION.user_id'));
+      \F3::get('SESSION.user')->setId(1123);
+      $user = User::Load();
+    }
+
+    return;
+  }
+
+  /**
+   * Return the sanitized POST parameters
+   *
+   * @return mixed
+   */
+  public function getSanitizedPostRequest()
+  {
+    return $this->sanitizedPostRequest;
+  }
+}

+ 79 - 0
src/OpenMind/Web/Login.php

@@ -0,0 +1,79 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: giancarlo
+ * Date: 28/06/2018
+ * Time: 16:52
+ */
+
+namespace OpenMind\Web;
+
+use OpenMind\System\User;
+
+class Login extends Controller
+{
+  public function Login($f3)
+  {
+    if ($f3->exists('SESSION.user_id')) {
+      $f3->reroute('/homemenu');
+      return;
+    }
+
+    $f3->clear('SESSION');
+    $f3->clear('COOKIE.username');
+
+    $f3->set('CONTENT', 'login.tpl');
+    echo \Template::instance()->render('masterpage.tpl');
+  }
+
+  /**
+   * Check if login is valid
+   *
+   * @param string $username
+   * @param string $password
+   * @return int|null
+   */
+  private function checkLogin(string $username, string $password): ?int
+  {
+    $accounts = \F3::get('users.PASSWORD');
+    foreach ($accounts as $index => $account) {
+      $exist = password_verify("{$username}|{$password}", $account);
+      if ($exist)
+        return $index;
+    }
+    return null;
+  }
+
+  /**
+   * Check if username and password are correct
+   *
+   * @param $f3
+   */
+  public function LoginForm($f3)
+  {
+    $accountData = $this->getSanitizedPostRequest();
+
+    $userId = $this->checkLogin($accountData['username'], $accountData['password']);
+
+    if (is_null($userId)) {
+      http_response_code(500);
+      echo "Dati di accesso non corretti";
+      return;
+    }
+
+    $f3->set('SESSION.user_id', $userId);
+    $user = new User($userId, $accountData['username']);
+    $user->Save();
+    $f3->set('USERID', $userId);
+    $f3->set('COOKIE.username', $accountData['username']);
+
+    $f3->reroute('/homemenu');
+  }
+
+  public function Logout($f3)
+  {
+    $f3->clear('SESSION');
+    $f3->clear('COOKIE.username');
+    $f3->reroute('/');
+  }
+}

+ 7 - 3
src/OpenMind/Web/Web.php

@@ -11,10 +11,14 @@ use OpenMind\System\PluginStrategy;
 
 
 class Web extends PluginStrategy
 class Web extends PluginStrategy
 {
 {
-  public static function Init()
+  public function __construct()
   {
   {
     // Services
     // Services
-    \F3::route("POST /login", __NAMESPACE__ . '\BaseController->Login');
-    \F3::route("GET /logout", __NAMESPACE__ . '\BaseController->Logout');
+    $this->AddRoute('GET /', __NAMESPACE__ . '\Login->Login');
+    $this->AddRoute("POST /loginform", __NAMESPACE__ . '\Login->LoginForm');
+    $this->AddRoute("GET /logout", __NAMESPACE__ . '\Login->Logout');
   }
   }
 }
 }
+
+/** @var \OpenMind\Web\Web $Web */
+Global $Web;

+ 7 - 46
ui/custom.css

@@ -1,51 +1,12 @@
-html, body {
-  height: 100%;
-}
+/**
+ * Child CSS file
+ *
+ * @author Open Mind
+ * @date 27/06/2018
+ * @time 17:42
+ */
 
 
 body {
 body {
   background-color: #1c1c1c !important;
   background-color: #1c1c1c !important;
   color: #ffd242 !important;
   color: #ffd242 !important;
-  font-family: 'Century Gothic';
-}
-
-.error_body {
-  background-image: url('ui/images/error_bg.png');
-  background-repeat: no-repeat;
-  background-size: cover;
-}
-
-.error_body .card {
-  opacity: 0.9;
-}
-
-input[type="text"], input[type="password"] {
-  background-color: #484848 !important;
-  border-color: #C5AC0F !important;
-}
-
-input[type="text"]:focus, input[type="password"]:focus {
-  border-color: #C5AC0F !important;
-  color: #ffd242 !important;
-}
-
-.form-control {
-  background-color: #484848 !important;
-  color: #ffd242 !important;
-}
-
-.form-control:focus {
-  border-color: #c5ac0f !important;
-  box-shadow: 0 0 0 0.2rem rgba(197, 172, 15, 0.25) !important;
-}
-
-.debugborder {
-  border: 1px solid red !important;
-}
-
-.bg-dark {
-  background-color: #686f75 !important;
-}
-
-.disablebutton {
-  opacity: 0.4;
 }
 }

+ 8 - 7
ui/custom.js

@@ -1,7 +1,8 @@
-$(function(){
-  $('form').on('submit', function () {
-    setTimeout(function () {
-      $('form input,select').prop('disabled', true);
-    }, 500);
-  });
-});
+/**
+ * Child CSS file
+ *
+ * @author Open Mind
+ * @date 27/06/2018
+ * @time 17:42
+ */
+

+ 6 - 6
ui/errors.tpl

@@ -8,16 +8,16 @@
 </head>
 </head>
 <body class="bg-light error_body">
 <body class="bg-light error_body">
 
 
-<div class="container">
-    <div class="row">
-        <div class="col-md-12" style="font-family: verdana, arial, sans serif; font-size: 8pt; text-align: center">
-            <div class="text-left card bg-white m-1 p-2">
+<div class="container-fluid h-100">
+    <div class="row h-100">
+        <div class="col-md-12 d-flex justify-content-center">
+            <div class="card bg-white m-1 p-2">
                 <h1 class="text-center text-info">{{@ERROR.code}} {{@ERROR.status}}</h1>
                 <h1 class="text-center text-info">{{@ERROR.code}} {{@ERROR.status}}</h1>
                 <br/>
                 <br/>
                 <h3 class="text-success">Dettaglio errore:</h3>
                 <h3 class="text-success">Dettaglio errore:</h3>
-                <pre style="font-size: 1rem">{{@ERROR.text}}</pre>
+                <p style="color: black">{{@ERROR.text | raw}}</p>
                 <h3 class="text-success">Debug Trace:</h3>
                 <h3 class="text-success">Debug Trace:</h3>
-                <pre style="font-size: 1rem">{{@ERROR.trace}}</pre>
+                <pre style="font-size: 0.8rem">{{@ERROR.trace | raw}}</pre>
             </div>
             </div>
         </div>
         </div>
     </div>
     </div>

BIN
ui/fonts/Roboto-Regular.ttf


+ 1 - 1
ui/login.tpl

@@ -1,6 +1,6 @@
 <div class="text-center mx-auto col-md-7 mt-5">
 <div class="text-center mx-auto col-md-7 mt-5">
     <img src="{{@BASEURL}}/ui/images/logo.png" alt="" class="img-fluid">
     <img src="{{@BASEURL}}/ui/images/logo.png" alt="" class="img-fluid">
-    <form enctype="multipart/form-data" action="login" method="POST">
+    <form enctype="multipart/form-data" action="loginform" method="POST">
         <h1 class="mb-4" style="font-size: 4vw">Login</h1>
         <h1 class="mb-4" style="font-size: 4vw">Login</h1>
         <label for="username" class="sr-only">username</label>
         <label for="username" class="sr-only">username</label>
         <input type="text" name="username" id="username" class="form-control mb-1" placeholder="Username" required autofocus autocomplete="false">
         <input type="text" name="username" id="username" class="form-control mb-1" placeholder="Username" required autofocus autocomplete="false">

+ 66 - 0
ui/omlink.css

@@ -0,0 +1,66 @@
+/**
+ * Main CSS file
+ *
+ * @author Open Mind
+ * @date 27/06/2018
+ * @time 17:42
+ */
+
+html, body {
+  height: 100%;
+}
+
+/* latin */
+@font-face {
+  font-family: 'Roboto';
+  font-style: normal;
+  font-weight: 400;
+  src: local('Roboto'), local('Roboto-Regular'), url('ui/fonts/Roboto-Regular.ttf') format('truetype');
+  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+
+body {
+  font-family: 'Roboto';
+}
+
+.error_body {
+  background-image: url('ui/images/error_bg.png');
+  background-repeat: no-repeat;
+  background-size: cover;
+}
+
+.error_body .card {
+  opacity: 0.9;
+}
+
+input[type="text"], input[type="password"] {
+  background-color: #484848 !important;
+  border-color: #C5AC0F !important;
+}
+
+input[type="text"]:focus, input[type="password"]:focus {
+  border-color: #C5AC0F !important;
+  color: #ffd242 !important;
+}
+
+.form-control {
+  background-color: #484848 !important;
+  color: #ffd242 !important;
+}
+
+.form-control:focus {
+  border-color: #c5ac0f !important;
+  box-shadow: 0 0 0 0.2rem rgba(197, 172, 15, 0.25) !important;
+}
+
+.debugborder {
+  border: 1px solid red !important;
+}
+
+.bg-dark {
+  background-color: #686f75 !important;
+}
+
+.disablebutton {
+  opacity: 0.4;
+}

+ 15 - 0
ui/omlink.js

@@ -0,0 +1,15 @@
+/**
+ * Main Javascript file
+ *
+ * @author Open Mind
+ * @date 27/06/2018
+ * @time 17:42
+ */
+
+$(function(){
+  $('form').on('submit', function () {
+    setTimeout(function () {
+      $('form input,select').prop('disabled', true);
+    }, 500);
+  });
+});