diff --git a/.gitignore b/.gitignore index 3b1a7ff1..63717e04 100644 --- a/.gitignore +++ b/.gitignore @@ -1,202 +1,3 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -build/ -bld/ -[Bb]in/ -[Oo]bj/ - -# Visual Studo 2015 cache/options directory -.vs/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding addin-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config - -# Windows Azure Build Output -csx/ -*.build.csdef - -# Windows Store app package directory -AppPackages/ - -# Others -*.[Cc]ache -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - /bower_components /vendor /.release -/composer.phar -/composer.lock diff --git a/Grocy.php b/Grocy.php deleted file mode 100644 index 0cfbc580..00000000 --- a/Grocy.php +++ /dev/null @@ -1,148 +0,0 @@ -setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - if ($doMigrations === true) - { - Grocy::ExecuteDbStatement($pdo, "CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))"); - GrocyDbMigrator::MigrateDb($pdo); - - if (self::IsDemoInstallation()) - { - GrocyDemoDataGenerator::PopulateDemoData($pdo); - } - } - - self::$DbConnectionRaw = $pdo; - } - - return self::$DbConnectionRaw; - } - - private static $DbConnection; - /** - * @return LessQL\Database - */ - public static function GetDbConnection($doMigrations = false) - { - if ($doMigrations === true) - { - self::$DbConnection = null; - } - - if (self::$DbConnection == null) - { - self::$DbConnection = new LessQL\Database(self::GetDbConnectionRaw($doMigrations)); - } - - return self::$DbConnection; - } - - /** - * @return boolean - */ - public static function ExecuteDbStatement(PDO $pdo, string $sql) - { - if ($pdo->exec($sql) === false) - { - throw new Exception($pdo->errorInfo()); - } - - return true; - } - - /** - * @return boolean|PDOStatement - */ - public static function ExecuteDbQuery(PDO $pdo, string $sql) - { - if (self::ExecuteDbStatement($pdo, $sql) === true) - { - return $pdo->query($sql); - } - - return false; - } - - /** - * @return boolean - */ - public static function IsDemoInstallation() - { - return file_exists(__DIR__ . '/data/demo.txt'); - } - - private static $InstalledVersion; - /** - * @return string - */ - public static function GetInstalledVersion() - { - if (self::$InstalledVersion == null) - { - self::$InstalledVersion = preg_replace("/\r|\n/", '', file_get_contents(__DIR__ . '/version.txt')); - } - - return self::$InstalledVersion; - } - - /** - * @return boolean - */ - public static function IsValidSession($sessionKey) - { - if ($sessionKey === null || empty($sessionKey)) - { - return false; - } - else - { - return file_exists(__DIR__ . "/data/sessions/$sessionKey.txt"); - } - } - - /** - * @return string - */ - public static function CreateSession() - { - if (!file_exists(__DIR__ . '/data/sessions')) - { - mkdir(__DIR__ . '/data/sessions'); - } - - $now = time(); - foreach (new FilesystemIterator(__DIR__ . '/data/sessions') as $file) - { - if ($now - $file->getCTime() >= 2678400) //31 days - { - unlink(__DIR__ . '/data/sessions/' . $file->getFilename()); - } - } - - $newSessionKey = uniqid() . uniqid() . uniqid(); - file_put_contents(__DIR__ . "/data/sessions/$newSessionKey.txt", ''); - return $newSessionKey; - } - - public static function RemoveSession($sessionKey) - { - unlink(__DIR__ . "/data/sessions/$sessionKey.txt"); - } -} diff --git a/GrocyDbMigrator.php b/GrocyDbMigrator.php index 81dc9e61..3c80565f 100644 --- a/GrocyDbMigrator.php +++ b/GrocyDbMigrator.php @@ -190,11 +190,11 @@ class GrocyDbMigrator private static function ExecuteMigrationWhenNeeded(PDO $pdo, int $migrationId, string $sql) { - $rowCount = Grocy::ExecuteDbQuery($pdo, 'SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); + $rowCount = DatabaseService::ExecuteDbQuery($pdo, 'SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); if (intval($rowCount) === 0) { - Grocy::ExecuteDbStatement($pdo, $sql); - Grocy::ExecuteDbStatement($pdo, 'INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); + DatabaseService::ExecuteDbStatement($pdo, $sql); + DatabaseService::ExecuteDbStatement($pdo, 'INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); } } } diff --git a/GrocyDemoDataGenerator.php b/GrocyDemoDataGenerator.php index c35de379..81d8de7e 100644 --- a/GrocyDemoDataGenerator.php +++ b/GrocyDemoDataGenerator.php @@ -4,7 +4,7 @@ class GrocyDemoDataGenerator { public static function PopulateDemoData(PDO $pdo) { - $rowCount = Grocy::ExecuteDbQuery($pdo, 'SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn(); + $rowCount = DatabaseService::ExecuteDbQuery($pdo, 'SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn(); if (intval($rowCount) === 0) { $sql = " @@ -45,38 +45,38 @@ class GrocyDemoDataGenerator INSERT INTO migrations (migration) VALUES (-1); "; - Grocy::ExecuteDbStatement($pdo, $sql); + DatabaseService::ExecuteDbStatement($pdo, $sql); - GrocyLogicStock::AddProduct(3, 5, date('Y-m-d', strtotime('+180 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(4, 5, date('Y-m-d', strtotime('+180 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(5, 5, date('Y-m-d', strtotime('+20 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(6, 5, date('Y-m-d', strtotime('+600 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(7, 5, date('Y-m-d', strtotime('+800 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(8, 5, date('Y-m-d', strtotime('+900 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(9, 5, date('Y-m-d', strtotime('+14 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(10, 5, date('Y-m-d', strtotime('+21 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(11, 5, date('Y-m-d', strtotime('+10 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(12, 5, date('Y-m-d', strtotime('+2 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(13, 5, date('Y-m-d', strtotime('-2 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(14, 5, date('Y-m-d', strtotime('+2 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddProduct(15, 5, date('Y-m-d', strtotime('-2 days')), GrocyLogicStock::TRANSACTION_TYPE_PURCHASE); - GrocyLogicStock::AddMissingProductsToShoppingList(); + StockService::AddProduct(3, 5, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(4, 5, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(5, 5, date('Y-m-d', strtotime('+20 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(6, 5, date('Y-m-d', strtotime('+600 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(7, 5, date('Y-m-d', strtotime('+800 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(8, 5, date('Y-m-d', strtotime('+900 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(9, 5, date('Y-m-d', strtotime('+14 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(10, 5, date('Y-m-d', strtotime('+21 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(11, 5, date('Y-m-d', strtotime('+10 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(12, 5, date('Y-m-d', strtotime('+2 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(13, 5, date('Y-m-d', strtotime('-2 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(14, 5, date('Y-m-d', strtotime('+2 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddProduct(15, 5, date('Y-m-d', strtotime('-2 days')), StockService::TRANSACTION_TYPE_PURCHASE); + StockService::AddMissingProductsToShoppingList(); - GrocyLogicHabits::TrackHabit(1, date('Y-m-d H:i:s', strtotime('-5 days'))); - GrocyLogicHabits::TrackHabit(1, date('Y-m-d H:i:s', strtotime('-10 days'))); - GrocyLogicHabits::TrackHabit(1, date('Y-m-d H:i:s', strtotime('-15 days'))); - GrocyLogicHabits::TrackHabit(2, date('Y-m-d H:i:s', strtotime('-10 days'))); - GrocyLogicHabits::TrackHabit(2, date('Y-m-d H:i:s', strtotime('-20 days'))); + HabitsService::TrackHabit(1, date('Y-m-d H:i:s', strtotime('-5 days'))); + HabitsService::TrackHabit(1, date('Y-m-d H:i:s', strtotime('-10 days'))); + HabitsService::TrackHabit(1, date('Y-m-d H:i:s', strtotime('-15 days'))); + HabitsService::TrackHabit(2, date('Y-m-d H:i:s', strtotime('-10 days'))); + HabitsService::TrackHabit(2, date('Y-m-d H:i:s', strtotime('-20 days'))); - GrocyLogicBatteries::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-200 days'))); - GrocyLogicBatteries::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-150 days'))); - GrocyLogicBatteries::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-100 days'))); - GrocyLogicBatteries::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-50 days'))); - GrocyLogicBatteries::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-200 days'))); - GrocyLogicBatteries::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-150 days'))); - GrocyLogicBatteries::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-100 days'))); - GrocyLogicBatteries::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-50 days'))); - GrocyLogicBatteries::TrackChargeCycle(3, date('Y-m-d H:i:s', strtotime('-65 days'))); + BatteriesService::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-200 days'))); + BatteriesService::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-150 days'))); + BatteriesService::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-100 days'))); + BatteriesService::TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-50 days'))); + BatteriesService::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-200 days'))); + BatteriesService::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-150 days'))); + BatteriesService::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-100 days'))); + BatteriesService::TrackChargeCycle(2, date('Y-m-d H:i:s', strtotime('-50 days'))); + BatteriesService::TrackChargeCycle(3, date('Y-m-d H:i:s', strtotime('-65 days'))); } } @@ -84,7 +84,7 @@ class GrocyDemoDataGenerator { unlink(__DIR__ . '/data/grocy.db'); - $db = Grocy::GetDbConnectionRaw(true); + $db = DatabaseService::GetDbConnectionRaw(true); self::PopulateDemoData($db); } } diff --git a/composer.lock b/composer.lock new file mode 100644 index 00000000..b61967df --- /dev/null +++ b/composer.lock @@ -0,0 +1,461 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "content-hash": "bf75d2487343249c600746a03f63cfd2", + "packages": [ + { + "name": "container-interop/container-interop", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/container-interop/container-interop.git", + "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/container-interop/container-interop/zipball/79cbf1341c22ec75643d841642dd5d6acd83bdb8", + "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8", + "shasum": "" + }, + "require": { + "psr/container": "^1.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Interop\\Container\\": "src/Interop/Container/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Promoting the interoperability of container objects (DIC, SL, etc.)", + "homepage": "https://github.com/container-interop/container-interop", + "time": "2017-02-14T19:40:03+00:00" + }, + { + "name": "morris/lessql", + "version": "v0.3.5", + "source": { + "type": "git", + "url": "https://github.com/morris/lessql.git", + "reference": "338966185fc052e7ee769360d19950cf90c0fd42" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/morris/lessql/zipball/338966185fc052e7ee769360d19950cf90c0fd42", + "reference": "338966185fc052e7ee769360d19950cf90c0fd42", + "shasum": "" + }, + "require": { + "php": ">=5.3.4" + }, + "require-dev": { + "codeclimate/php-test-reporter": "dev-master", + "phpunit/phpunit": "~4.6" + }, + "type": "library", + "autoload": { + "psr-0": { + "": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Morris Brodersen", + "homepage": "https://morrisbrodersen.de" + } + ], + "description": "LessQL: The agile PHP ORM alternative", + "homepage": "https://github.com/morris/lessql", + "keywords": [ + "database", + "notorm", + "orm", + "pdo", + "sql" + ], + "time": "2018-01-27T13:18:21+00:00" + }, + { + "name": "nikic/fast-route", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/181d480e08d9476e61381e04a71b34dc0432e812", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + }, + "type": "library", + "autoload": { + "psr-4": { + "FastRoute\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ], + "time": "2018-02-13T20:26:39+00:00" + }, + { + "name": "pavlakis/slim-cli", + "version": "1.0.4", + "source": { + "type": "git", + "url": "https://github.com/pavlakis/slim-cli.git", + "reference": "603933a54e391b3c70c573206cce543b75d8b1db" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pavlakis/slim-cli/zipball/603933a54e391b3c70c573206cce543b75d8b1db", + "reference": "603933a54e391b3c70c573206cce543b75d8b1db", + "shasum": "" + }, + "require": { + "php": "^5.5|^5.6|^7.0|^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^4.0", + "slim/slim": "^3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "pavlakis\\cli\\tests\\": "tests/phpunit", + "pavlakis\\cli\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Antonis Pavlakis", + "email": "adoni@pavlakis.info", + "homepage": "http://pavlakis.info" + } + ], + "description": "Making a mock GET request through the CLI and enabling the same application entry point on CLI scripts.", + "homepage": "http://github.com/pavlakis/slim-cli", + "keywords": [ + "cli", + "framework", + "middleware", + "slim" + ], + "time": "2017-01-30T22:50:06+00:00" + }, + { + "name": "pimple/pimple", + "version": "v3.2.3", + "source": { + "type": "git", + "url": "https://github.com/silexphp/Pimple.git", + "reference": "9e403941ef9d65d20cba7d54e29fe906db42cf32" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/silexphp/Pimple/zipball/9e403941ef9d65d20cba7d54e29fe906db42cf32", + "reference": "9e403941ef9d65d20cba7d54e29fe906db42cf32", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "psr/container": "^1.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2.x-dev" + } + }, + "autoload": { + "psr-0": { + "Pimple": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Pimple, a simple Dependency Injection Container", + "homepage": "http://pimple.sensiolabs.org", + "keywords": [ + "container", + "dependency injection" + ], + "time": "2018-01-21T07:42:36+00:00" + }, + { + "name": "psr/container", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "time": "2017-02-14T16:28:37+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "slim/php-view", + "version": "2.2.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/PHP-View.git", + "reference": "122ed121a8d9cf91a94020814d2a3ee6c836754f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/PHP-View/zipball/122ed121a8d9cf91a94020814d2a3ee6c836754f", + "reference": "122ed121a8d9cf91a94020814d2a3ee6c836754f", + "shasum": "" + }, + "require": { + "psr/http-message": "^1.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8", + "slim/slim": "^3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Slim\\Views\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Glenn Eggleton", + "email": "geggleto@gmail.com" + } + ], + "description": "Render PHP view scripts into a PSR-7 Response object.", + "keywords": [ + "framework", + "php", + "phtml", + "renderer", + "slim", + "template", + "view" + ], + "time": "2016-10-11T07:43:08+00:00" + }, + { + "name": "slim/slim", + "version": "3.9.2", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim.git", + "reference": "4086d0106cf5a7135c69fce4161fe355a8feb118" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/4086d0106cf5a7135c69fce4161fe355a8feb118", + "reference": "4086d0106cf5a7135c69fce4161fe355a8feb118", + "shasum": "" + }, + "require": { + "container-interop/container-interop": "^1.2", + "nikic/fast-route": "^1.0", + "php": ">=5.5.0", + "pimple/pimple": "^3.0", + "psr/container": "^1.0", + "psr/http-message": "^1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0", + "squizlabs/php_codesniffer": "^2.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Slim\\": "Slim" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + } + ], + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "homepage": "https://slimframework.com", + "keywords": [ + "api", + "framework", + "micro", + "router" + ], + "time": "2017-11-26T19:13:09+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/index.php b/index.php index 89fbd2b8..d7296d7b 100644 --- a/index.php +++ b/index.php @@ -6,12 +6,14 @@ use Slim\Views\PhpRenderer; require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/data/config.php'; -require_once __DIR__ . '/Grocy.php'; +require_once __DIR__ . '/services/ApplicationService.php'; +require_once __DIR__ . '/services/DatabaseService.php'; +require_once __DIR__ . '/services/SessionService.php'; require_once __DIR__ . '/GrocyDbMigrator.php'; require_once __DIR__ . '/GrocyDemoDataGenerator.php'; -require_once __DIR__ . '/GrocyLogicStock.php'; -require_once __DIR__ . '/GrocyLogicHabits.php'; -require_once __DIR__ . '/GrocyLogicBatteries.php'; +require_once __DIR__ . '/services/StockService.php'; +require_once __DIR__ . '/services/HabitsService.php'; +require_once __DIR__ . '/services/BatteriesService.php'; require_once __DIR__ . '/GrocyPhpHelper.php'; $app = new \Slim\App; @@ -33,14 +35,14 @@ if (PHP_SAPI === 'cli') $app->add(new \pavlakis\cli\CliRequest()); } -if (!Grocy::IsDemoInstallation()) +if (!ApplicationService::IsDemoInstallation()) { $sessionMiddleware = function(Request $request, Response $response, callable $next) { $route = $request->getAttribute('route'); $routeName = $route->getName(); - if ((!isset($_COOKIE['grocy_session']) || !Grocy::IsValidSession($_COOKIE['grocy_session'])) && $routeName !== 'login') + if ((!isset($_COOKIE['grocy_session']) || !SessionService::IsValidSession($_COOKIE['grocy_session'])) && $routeName !== 'login') { $response = $response->withRedirect('/login'); } @@ -55,11 +57,11 @@ if (!Grocy::IsDemoInstallation()) $app->add($sessionMiddleware); } -$db = Grocy::GetDbConnection(); +$db = DatabaseService::GetDbConnection(); $app->get('/login', function(Request $request, Response $response) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Login', 'contentPage' => 'login.php' ]); @@ -72,7 +74,7 @@ $app->post('/login', function(Request $request, Response $response) { if ($postParams['username'] === HTTP_USER && $postParams['password'] === HTTP_PASSWORD) { - $sessionKey = Grocy::CreateSession(); + $sessionKey = SessionService::CreateSession(); setcookie('grocy_session', $sessionKey, time()+2592000); //30 days return $response->withRedirect('/'); @@ -90,52 +92,52 @@ $app->post('/login', function(Request $request, Response $response) $app->get('/logout', function(Request $request, Response $response) { - Grocy::RemoveSession($_COOKIE['grocy_session']); + SessionService::RemoveSession($_COOKIE['grocy_session']); return $response->withRedirect('/'); }); $app->get('/', function(Request $request, Response $response) use($db) { - $db = Grocy::GetDbConnection(true); //For database schema migration + $db = DatabaseService::GetDbConnection(true); //For database schema migration return $response->withRedirect('/stockoverview'); }); $app->get('/stockoverview', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Stock overview', 'contentPage' => 'stockoverview.php', 'products' => $db->products(), 'quantityunits' => $db->quantity_units(), - 'currentStock' => GrocyLogicStock::GetCurrentStock(), - 'missingProducts' => GrocyLogicStock::GetMissingProducts() + 'currentStock' => StockService::GetCurrentStock(), + 'missingProducts' => StockService::GetMissingProducts() ]); }); $app->get('/habitsoverview', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Habits overview', 'contentPage' => 'habitsoverview.php', 'habits' => $db->habits(), - 'currentHabits' => GrocyLogicHabits::GetCurrentHabits(), + 'currentHabits' => HabitsService::GetCurrentHabits(), ]); }); $app->get('/batteriesoverview', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Batteries overview', 'contentPage' => 'batteriesoverview.php', 'batteries' => $db->batteries(), - 'current' => GrocyLogicBatteries::GetCurrent(), + 'current' => BatteriesService::GetCurrent(), ]); }); $app->get('/purchase', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Purchase', 'contentPage' => 'purchase.php', 'products' => $db->products() @@ -144,7 +146,7 @@ $app->get('/purchase', function(Request $request, Response $response) use($db) $app->get('/consume', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Consume', 'contentPage' => 'consume.php', 'products' => $db->products() @@ -153,7 +155,7 @@ $app->get('/consume', function(Request $request, Response $response) use($db) $app->get('/inventory', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Inventory', 'contentPage' => 'inventory.php', 'products' => $db->products() @@ -162,19 +164,19 @@ $app->get('/inventory', function(Request $request, Response $response) use($db) $app->get('/shoppinglist', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Shopping list', 'contentPage' => 'shoppinglist.php', 'listItems' => $db->shopping_list(), 'products' => $db->products(), 'quantityunits' => $db->quantity_units(), - 'missingProducts' => GrocyLogicStock::GetMissingProducts() + 'missingProducts' => StockService::GetMissingProducts() ]); }); $app->get('/habittracking', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Habit tracking', 'contentPage' => 'habittracking.php', 'habits' => $db->habits() @@ -183,7 +185,7 @@ $app->get('/habittracking', function(Request $request, Response $response) use($ $app->get('/batterytracking', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Battery tracking', 'contentPage' => 'batterytracking.php', 'batteries' => $db->batteries() @@ -192,7 +194,7 @@ $app->get('/batterytracking', function(Request $request, Response $response) use $app->get('/products', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Products', 'contentPage' => 'products.php', 'products' => $db->products(), @@ -203,7 +205,7 @@ $app->get('/products', function(Request $request, Response $response) use($db) $app->get('/locations', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Locations', 'contentPage' => 'locations.php', 'locations' => $db->locations() @@ -212,7 +214,7 @@ $app->get('/locations', function(Request $request, Response $response) use($db) $app->get('/quantityunits', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Quantity units', 'contentPage' => 'quantityunits.php', 'quantityunits' => $db->quantity_units() @@ -221,7 +223,7 @@ $app->get('/quantityunits', function(Request $request, Response $response) use($ $app->get('/habits', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Habits', 'contentPage' => 'habits.php', 'habits' => $db->habits() @@ -230,7 +232,7 @@ $app->get('/habits', function(Request $request, Response $response) use($db) $app->get('/batteries', function(Request $request, Response $response) use($db) { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Batteries', 'contentPage' => 'batteries.php', 'batteries' => $db->batteries() @@ -242,7 +244,7 @@ $app->get('/product/{productId}', function(Request $request, Response $response, { if ($args['productId'] == 'new') { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Create product', 'contentPage' => 'productform.php', 'locations' => $db->locations(), @@ -252,7 +254,7 @@ $app->get('/product/{productId}', function(Request $request, Response $response, } else { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Edit product', 'contentPage' => 'productform.php', 'product' => $db->products($args['productId']), @@ -267,7 +269,7 @@ $app->get('/location/{locationId}', function(Request $request, Response $respons { if ($args['locationId'] == 'new') { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Create location', 'contentPage' => 'locationform.php', 'mode' => 'create' @@ -275,7 +277,7 @@ $app->get('/location/{locationId}', function(Request $request, Response $respons } else { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Edit location', 'contentPage' => 'locationform.php', 'location' => $db->locations($args['locationId']), @@ -288,7 +290,7 @@ $app->get('/quantityunit/{quantityunitId}', function(Request $request, Response { if ($args['quantityunitId'] == 'new') { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Create quantity unit', 'contentPage' => 'quantityunitform.php', 'mode' => 'create' @@ -296,7 +298,7 @@ $app->get('/quantityunit/{quantityunitId}', function(Request $request, Response } else { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Edit quantity unit', 'contentPage' => 'quantityunitform.php', 'quantityunit' => $db->quantity_units($args['quantityunitId']), @@ -309,20 +311,20 @@ $app->get('/habit/{habitId}', function(Request $request, Response $response, $ar { if ($args['habitId'] == 'new') { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Create habit', 'contentPage' => 'habitform.php', - 'periodTypes' => GrocyPhpHelper::GetClassConstants('GrocyLogicHabits'), + 'periodTypes' => GrocyPhpHelper::GetClassConstants('HabitsService'), 'mode' => 'create' ]); } else { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Edit habit', 'contentPage' => 'habitform.php', 'habit' => $db->habits($args['habitId']), - 'periodTypes' => GrocyPhpHelper::GetClassConstants('GrocyLogicHabits'), + 'periodTypes' => GrocyPhpHelper::GetClassConstants('HabitsService'), 'mode' => 'edit' ]); } @@ -332,7 +334,7 @@ $app->get('/battery/{batteryId}', function(Request $request, Response $response, { if ($args['batteryId'] == 'new') { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Create battery', 'contentPage' => 'batteryform.php', 'mode' => 'create' @@ -340,7 +342,7 @@ $app->get('/battery/{batteryId}', function(Request $request, Response $response, } else { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Edit battery', 'contentPage' => 'batteryform.php', 'battery' => $db->batteries($args['batteryId']), @@ -353,7 +355,7 @@ $app->get('/shoppinglistitem/{itemId}', function(Request $request, Response $res { if ($args['itemId'] == 'new') { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Add shopping list item', 'contentPage' => 'shoppinglistform.php', 'products' => $db->products(), @@ -362,7 +364,7 @@ $app->get('/shoppinglistitem/{itemId}', function(Request $request, Response $res } else { - return $this->renderer->render($response, '/layout.php', [ + return $this->renderer->render($response, 'layout/default.php', [ 'title' => 'Edit shopping list item', 'contentPage' => 'shoppinglistform.php', 'listItem' => $db->shopping_list($args['itemId']), @@ -416,13 +418,13 @@ $app->group('/api', function() use($db) $bestBeforeDate = $request->getQueryParams()['bestbeforedate']; } - $transactionType = GrocyLogicStock::TRANSACTION_TYPE_PURCHASE; + $transactionType = StockService::TRANSACTION_TYPE_PURCHASE; if (isset($request->getQueryParams()['transactiontype']) && !empty($request->getQueryParams()['transactiontype'])) { $transactionType = $request->getQueryParams()['transactiontype']; } - echo json_encode(array('success' => GrocyLogicStock::AddProduct($args['productId'], $args['amount'], $bestBeforeDate, $transactionType))); + echo json_encode(array('success' => StockService::AddProduct($args['productId'], $args['amount'], $bestBeforeDate, $transactionType))); }); $this->get('/stock/consume-product/{productId}/{amount}', function(Request $request, Response $response, $args) @@ -433,13 +435,13 @@ $app->group('/api', function() use($db) $spoiled = true; } - $transactionType = GrocyLogicStock::TRANSACTION_TYPE_CONSUME; + $transactionType = StockService::TRANSACTION_TYPE_CONSUME; if (isset($request->getQueryParams()['transactiontype']) && !empty($request->getQueryParams()['transactiontype'])) { $transactionType = $request->getQueryParams()['transactiontype']; } - echo json_encode(array('success' => GrocyLogicStock::ConsumeProduct($args['productId'], $args['amount'], $spoiled, $transactionType))); + echo json_encode(array('success' => StockService::ConsumeProduct($args['productId'], $args['amount'], $spoiled, $transactionType))); }); $this->get('/stock/inventory-product/{productId}/{newAmount}', function(Request $request, Response $response, $args) @@ -450,22 +452,22 @@ $app->group('/api', function() use($db) $bestBeforeDate = $request->getQueryParams()['bestbeforedate']; } - echo json_encode(array('success' => GrocyLogicStock::InventoryProduct($args['productId'], $args['newAmount'], $bestBeforeDate))); + echo json_encode(array('success' => StockService::InventoryProduct($args['productId'], $args['newAmount'], $bestBeforeDate))); }); $this->get('/stock/get-product-details/{productId}', function(Request $request, Response $response, $args) { - echo json_encode(GrocyLogicStock::GetProductDetails($args['productId'])); + echo json_encode(StockService::GetProductDetails($args['productId'])); }); $this->get('/stock/get-current-stock', function(Request $request, Response $response) { - echo json_encode(GrocyLogicStock::GetCurrentStock()); + echo json_encode(StockService::GetCurrentStock()); }); $this->get('/stock/add-missing-products-to-shoppinglist', function(Request $request, Response $response) { - GrocyLogicStock::AddMissingProductsToShoppingList(); + StockService::AddMissingProductsToShoppingList(); echo json_encode(array('success' => true)); }); @@ -477,12 +479,12 @@ $app->group('/api', function() use($db) $trackedTime = $request->getQueryParams()['tracked_time']; } - echo json_encode(array('success' => GrocyLogicHabits::TrackHabit($args['habitId'], $trackedTime))); + echo json_encode(array('success' => HabitsService::TrackHabit($args['habitId'], $trackedTime))); }); $this->get('/habits/get-habit-details/{habitId}', function(Request $request, Response $response, $args) { - echo json_encode(GrocyLogicHabits::GetHabitDetails($args['habitId'])); + echo json_encode(HabitsService::GetHabitDetails($args['habitId'])); }); $this->get('/batteries/track-charge-cycle/{batteryId}', function(Request $request, Response $response, $args) @@ -493,12 +495,12 @@ $app->group('/api', function() use($db) $trackedTime = $request->getQueryParams()['tracked_time']; } - echo json_encode(array('success' => GrocyLogicBatteries::TrackChargeCycle($args['batteryId'], $trackedTime))); + echo json_encode(array('success' => BatteriesService::TrackChargeCycle($args['batteryId'], $trackedTime))); }); $this->get('/batteries/get-battery-details/{batteryId}', function(Request $request, Response $response, $args) { - echo json_encode(GrocyLogicBatteries::GetBatteryDetails($args['batteryId'])); + echo json_encode(BatteriesService::GetBatteryDetails($args['batteryId'])); }); })->add(function($request, $response, $next) { @@ -510,7 +512,7 @@ $app->group('/cli', function() { $this->get('/recreatedemo', function(Request $request, Response $response) { - if (Grocy::IsDemoInstallation()) + if (ApplicationService::IsDemoInstallation()) { GrocyDemoDataGenerator::RecreateDemo(); } diff --git a/services/ApplicationService.php b/services/ApplicationService.php new file mode 100644 index 00000000..2e80a031 --- /dev/null +++ b/services/ApplicationService.php @@ -0,0 +1,26 @@ +fetchAll(PDO::FETCH_OBJ); + return DatabaseService::ExecuteDbQuery(DatabaseService::GetDbConnectionRaw(), $sql)->fetchAll(PDO::FETCH_OBJ); } public static function GetNextChargeTime(int $batteryId) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $battery = $db->batteries($batteryId); - $batteryLastLogRow = Grocy::ExecuteDbQuery(Grocy::GetDbConnectionRaw(), "SELECT * from batteries_current WHERE battery_id = $batteryId LIMIT 1")->fetch(PDO::FETCH_OBJ); + $batteryLastLogRow = DatabaseService::ExecuteDbQuery(DatabaseService::GetDbConnectionRaw(), "SELECT * from batteries_current WHERE battery_id = $batteryId LIMIT 1")->fetch(PDO::FETCH_OBJ); if ($battery->charge_interval_days > 0) { @@ -29,7 +29,7 @@ class GrocyLogicBatteries public static function GetBatteryDetails(int $batteryId) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $battery = $db->batteries($batteryId); $batteryChargeCylcesCount = $db->battery_charge_cycles()->where('battery_id', $batteryId)->count(); @@ -44,7 +44,7 @@ class GrocyLogicBatteries public static function TrackChargeCycle(int $batteryId, string $trackedTime) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $logRow = $db->battery_charge_cycles()->createRow(array( 'battery_id' => $batteryId, diff --git a/services/DatabaseService.php b/services/DatabaseService.php new file mode 100644 index 00000000..ff21d4da --- /dev/null +++ b/services/DatabaseService.php @@ -0,0 +1,82 @@ +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + if ($doMigrations === true) + { + self::ExecuteDbStatement($pdo, "CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))"); + GrocyDbMigrator::MigrateDb($pdo); + + if (ApplicationService::IsDemoInstallation()) + { + GrocyDemoDataGenerator::PopulateDemoData($pdo); + } + } + + self::$DbConnectionRaw = $pdo; + } + + return self::$DbConnectionRaw; + } + + private static $DbConnection; + /** + * @return LessQL\Database + */ + public static function GetDbConnection($doMigrations = false) + { + if ($doMigrations === true) + { + self::$DbConnection = null; + } + + if (self::$DbConnection == null) + { + self::$DbConnection = new LessQL\Database(self::GetDbConnectionRaw($doMigrations)); + } + + return self::$DbConnection; + } + + /** + * @return boolean + */ + public static function ExecuteDbStatement(PDO $pdo, string $sql) + { + if ($pdo->exec($sql) === false) + { + throw new Exception($pdo->errorInfo()); + } + + return true; + } + + /** + * @return boolean|PDOStatement + */ + public static function ExecuteDbQuery(PDO $pdo, string $sql) + { + if (self::ExecuteDbStatement($pdo, $sql) === true) + { + return $pdo->query($sql); + } + + return false; + } +} diff --git a/GrocyLogicHabits.php b/services/HabitsService.php similarity index 73% rename from GrocyLogicHabits.php rename to services/HabitsService.php index 0e978d3c..39e08ba8 100644 --- a/GrocyLogicHabits.php +++ b/services/HabitsService.php @@ -1,6 +1,6 @@ fetchAll(PDO::FETCH_OBJ); + return DatabaseService::ExecuteDbQuery(DatabaseService::GetDbConnectionRaw(), $sql)->fetchAll(PDO::FETCH_OBJ); } public static function GetNextHabitTime(int $habitId) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $habit = $db->habits($habitId); - $habitLastLogRow = Grocy::ExecuteDbQuery(Grocy::GetDbConnectionRaw(), "SELECT * from habits_current WHERE habit_id = $habitId LIMIT 1")->fetch(PDO::FETCH_OBJ); + $habitLastLogRow = DatabaseService::ExecuteDbQuery(DatabaseService::GetDbConnectionRaw(), "SELECT * from habits_current WHERE habit_id = $habitId LIMIT 1")->fetch(PDO::FETCH_OBJ); switch ($habit->period_type) { @@ -31,7 +31,7 @@ class GrocyLogicHabits public static function GetHabitDetails(int $habitId) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $habit = $db->habits($habitId); $habitTrackedCount = $db->habits_log()->where('habit_id', $habitId)->count(); @@ -46,7 +46,7 @@ class GrocyLogicHabits public static function TrackHabit(int $habitId, string $trackedTime) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $logRow = $db->habits_log()->createRow(array( 'habit_id' => $habitId, diff --git a/services/SessionService.php b/services/SessionService.php new file mode 100644 index 00000000..257e25d0 --- /dev/null +++ b/services/SessionService.php @@ -0,0 +1,48 @@ +getCTime() >= 2678400) //31 days + { + unlink(__DIR__ . '/../data/sessions/' . $file->getFilename()); + } + } + + $newSessionKey = uniqid() . uniqid() . uniqid(); + file_put_contents(__DIR__ . "/../data/sessions/$newSessionKey.txt", ''); + return $newSessionKey; + } + + public static function RemoveSession($sessionKey) + { + unlink(__DIR__ . "/../data/sessions/$sessionKey.txt"); + } +} diff --git a/GrocyLogicStock.php b/services/StockService.php similarity index 91% rename from GrocyLogicStock.php rename to services/StockService.php index a6fc533f..ae61bbe7 100644 --- a/GrocyLogicStock.php +++ b/services/StockService.php @@ -1,6 +1,6 @@ fetchAll(PDO::FETCH_OBJ); + return DatabaseService::ExecuteDbQuery(DatabaseService::GetDbConnectionRaw(), $sql)->fetchAll(PDO::FETCH_OBJ); } public static function GetMissingProducts() { $sql = 'SELECT * from stock_missing_products'; - return Grocy::ExecuteDbQuery(Grocy::GetDbConnectionRaw(), $sql)->fetchAll(PDO::FETCH_OBJ); + return DatabaseService::ExecuteDbQuery(DatabaseService::GetDbConnectionRaw(), $sql)->fetchAll(PDO::FETCH_OBJ); } public static function GetProductDetails(int $productId) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $product = $db->products($productId); $productStockAmount = $db->stock()->where('product_id', $productId)->sum('amount'); @@ -43,7 +43,7 @@ class GrocyLogicStock { if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_PURCHASE || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $stockId = uniqid(); $logRow = $db->stock_log()->createRow(array( @@ -69,7 +69,7 @@ class GrocyLogicStock } else { - throw new Exception("Transaction type $transactionType is not valid (GrocyLogicStock.AddProduct)"); + throw new Exception("Transaction type $transactionType is not valid (StockService.AddProduct)"); } } @@ -77,7 +77,7 @@ class GrocyLogicStock { if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_PURCHASE || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $productStockAmount = $db->stock()->where('product_id', $productId)->sum('amount'); $potentialStockEntries = $db->stock()->where('product_id', $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); //First expiring first, then first in first out @@ -138,13 +138,13 @@ class GrocyLogicStock } else { - throw new Exception("Transaction type $transactionType is not valid (GrocyLogicStock.ConsumeProduct)"); + throw new Exception("Transaction type $transactionType is not valid (StockService.ConsumeProduct)"); } } public static function InventoryProduct(int $productId, int $newAmount, string $bestBeforeDate) { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $productStockAmount = $db->stock()->where('product_id', $productId)->sum('amount'); if ($newAmount > $productStockAmount) @@ -163,7 +163,7 @@ class GrocyLogicStock public static function AddMissingProductsToShoppingList() { - $db = Grocy::GetDbConnection(); + $db = DatabaseService::GetDbConnection(); $missingProducts = self::GetMissingProducts(); foreach ($missingProducts as $missingProduct) diff --git a/views/batteriesoverview.php b/views/batteriesoverview.php index 54aa507b..aca6ca2f 100644 --- a/views/batteriesoverview.php +++ b/views/batteriesoverview.php @@ -13,7 +13,7 @@
-