Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ data/config.php
data/users.db
/vendor/
.idea
/.devDocker/
/.run/Dev Docker.run.xml
/data/logs/
53 changes: 38 additions & 15 deletions api/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
require_once __DIR__ . "/../incl/db.inc.php";
require_once __DIR__ . "/../incl/processing.inc.php";
require_once __DIR__ . "/../incl/config.inc.php";
require_once __DIR__ . "/../incl/logging.inc.php";

//removes Get parameters
$requestedUrl = strtok($_SERVER["REQUEST_URI"], '?');
Expand All @@ -37,11 +38,12 @@
$api->checkIfAuthorized();
$api->execute($requestedUrl);


class BBuddyApi {

private $routes = array();

private \Monolog\Logger $logger;

/**
* Checks if authorized
* @return bool True if authorized, or dies if not
Expand All @@ -60,11 +62,13 @@ function checkIfAuthorized(): bool {
$apiKey = $_GET["apikey"];

if ($apiKey == "")
$procLog->error("Unauthorized API call. No API key provided.");
self::sendUnauthorizedAndDie();

if (DatabaseConnection::getInstance()->isValidApiKey($apiKey))
return true;
else
$procLog->error("Unauthorized API call. Invalid API key provided.");
self::sendUnauthorizedAndDie();
return false;
}
Expand All @@ -77,11 +81,14 @@ static function sendUnauthorizedAndDie(): void {
function execute(string $url): void {
global $CONFIG;

$this->logger->debug("API call: " . $url, ['class' => __CLASS__, 'function' => __FUNCTION__]);

//Turn off all error reporting, as it could cause problems with parsing json clientside
if (!$CONFIG->IS_DEBUG)
error_reporting(0);

if (!isset($this->routes[$url])) {
$this->logger->warning("API call not found: " . $url);
self::sendResult(self::createResultArray(null, "API call not found", 404), 404);
} else {
$this->routes[$url]->execute();
Expand All @@ -90,6 +97,8 @@ function execute(string $url): void {


function __construct() {
$this->logger = bb_logger('api');
$this->logger->info("Barcode Buddy Version " . BB_VERSION_READABLE);
$this->initRoutes();
}

Expand All @@ -115,32 +124,43 @@ function addRoute(ApiRoute $route): void {
}

private function initRoutes(): void {

$this->addRoute(new ApiRoute("/action/scan", function () {
$barcode = "";
if (isset($_GET["text"]))
if (isset($_GET["text"])) {
$barcode = $_GET["text"];
if (isset($_GET["add"]))
}

if (isset($_GET["add"])) {
$barcode = $_GET["add"];
if (isset($_POST["barcode"]))
}

if (isset($_POST["barcode"])) {
$barcode = $_POST["barcode"];
if ($barcode == "")
}

if ($barcode == "") {
$this->logger->warning("No barcode supplied");
return self::createResultArray(null, "No barcode supplied", 400);
else {
} else {
$bestBefore = null;
$price = null;
if (isset($_POST["bestBeforeInDays"]) && $_POST["bestBeforeInDays"] != null) {
if (is_numeric($_POST["bestBeforeInDays"]))
if (is_numeric($_POST["bestBeforeInDays"])) {
$bestBefore = $_POST["bestBeforeInDays"];
else
} else {
$this->logger->warning("Invalid parameter bestBeforeInDays: needs to be type int");
return self::createResultArray(null, "Invalid parameter bestBeforeInDays: needs to be type int", 400);
}
}
if (isset($_POST["price"]) && $_POST["price"] != null) {
if (is_numeric($_POST["price"]))
if (is_numeric($_POST["price"])) {
$price = $_POST["price"];
else
} else {
$this->logger->warning("Invalid parameter price: needs to be type float");
return self::createResultArray(null, "Invalid parameter price: needs to be type float", 400);
}
}
$this->logger->debug(sprintf("Scanning barcode: %s with bestBefore: %d days, price: %.2f", $barcode, $bestBefore, $price), ['class' => __CLASS__, 'function' => __FUNCTION__]);
$result = processNewBarcode(sanitizeString($barcode), $bestBefore, $price);
return self::createResultArray(array("result" => sanitizeString($result)));
}
Expand All @@ -159,10 +179,12 @@ private function initRoutes(): void {
else if (isset($_POST["state"]))
$state = $_POST["state"];

//Also check if value is a valid range (STATE_CONSUME the lowest and STATE_CONSUME_ALL the highest value)
if (!is_numeric($state) || $state < STATE_CONSUME || $state > STATE_CONSUME_ALL)
//Also check if value is a valid range (STATE_CONSUME the lowest and STATE_TXFR the highest value)
if (!is_numeric($state) || $state < STATE_CONSUME || $state > STATE_TXFR) {
$this->logger->warning("Invalid state provided");
return self::createResultArray(null, "Invalid state provided", 400);
else {
} else {
$this->logger->debug("Setting transaction mode to " . $state, ['class' => __CLASS__, 'function' => __FUNCTION__]);
DatabaseConnection::getInstance()->setTransactionState(intval($state));
return self::createResultArray();
}
Expand All @@ -178,7 +200,8 @@ private function initRoutes(): void {
"BARCODE_GS" => $config["BARCODE_GS"],
"BARCODE_Q" => $config["BARCODE_Q"],
"BARCODE_AS" => $config["BARCODE_AS"],
"BARCODE_CA" => $config["BARCODE_CA"]
"BARCODE_CA" => $config["BARCODE_CA"],
"BARCODE_TXFR" => $config["BARCODE_TXFR"],
));
}));

Expand Down
102 changes: 102 additions & 0 deletions barcodes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

/**
* Barcode Buddy for Grocy
*
* PHP version 8
*
* LICENSE: This source file is subject to version 3.0 of the GNU General
* Public License v3.0 that is attached to this project.
*
* @author Marc Ole Bulling
* @copyright 2019 Marc Ole Bulling
* @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU GPL v3.0
* @since File available since Release 1.8.1.9
*/

require_once __DIR__ . "/incl/configProcessing.inc.php";
require_once __DIR__ . "/incl/db.inc.php";
require_once __DIR__ . "/incl/webui.inc.php";
require_once __DIR__ . "/incl/api.inc.php";

const MODE_QUANTITY = 'qty';
const MODE_LOCATION = 'loc';

$CONFIG->checkIfAuthenticated(true, true);

// Get mode and validate it
$mode = MODE_LOCATION;
if (isset($_GET)) {
if (isset($_GET["mode"])) {
$mode = $_GET["mode"];
}
}
if (!in_array($mode, [MODE_QUANTITY, MODE_LOCATION])) {
die("Invalid mode");
}

// Generate the page
$webUi = new WebUiGenerator(MENU_GENERIC);

$webUi->addBaseHeader(
null,
false,
true,
"<script src=\"/incl/js/JsBarcode.all.min.js\"></script>\n<script src=\"/incl/js/scripts_barcodes.js\"></script>");

switch ($mode) {
case MODE_QUANTITY:
getHtmlQuantityTable($webUi);
break;
case MODE_LOCATION:
getHtmlLocationTable($webUi);
break;
}

$webUi->printHtml();


function getHtmlLocationTable(WebUiGenerator $webUi): void
{
$config = BBConfig::getInstance();
$locations = API::getLocations();

// Generate the HTML
$html = new UiEditor(true, null, "barcodes");
$html->addHtml("<div id=\"location-barcodes\" class=\"flex-settings\" data-locations='" . json_encode($locations) . "' data-barcode='" . $config['BARCODE_TXFR'] . "'>");

foreach ($locations as $location) {
$html->addDiv("<img id=\"location-$location->id\" alt=\"$location->id\"/>", null, "flex-settings-child");

}

$html->addHtml('</div>');
$webUi->addHtml($html->getHtml());

// Generate the JS
$webUi->addScript("generateLocationBarcodes();");
}


function getHtmlQuantityTable(WebUiGenerator $webUi): void
{
$config = BBConfig::getInstance();

// Get quantity start and end
$startQty = isset($_GET['startQty']) ? intval($_GET['startQty']) : 1;
$endQty = isset($_GET['endQty']) ? intval($_GET['endQty']) : 10;

// Generate the HTML
$html = new UiEditor(true, null, "barcodes");
$html->addHtml("<div id=\"quantity-barcodes\" class=\"flex-settings\" data-start-qty='$startQty' data-end-qty='$endQty' data-barcode='" . $config['BARCODE_Q'] . "'>");

for ($i = $startQty; $i <= $endQty; $i++) {
$html->addDiv("<img id=\"quantity-$i\" alt=\"$i\"/>", null, "flex-settings-child");
}

$html->addHtml('</div>');
$webUi->addHtml($html->getHtml());

// Generate the JS
$webUi->addScript("generateQuantityBarcodes();");
}
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"require": {
"ext-redis": "*",
"ext-sockets": "*",
"ext-curl": "*"
"ext-curl": "*",
"monolog/monolog": "^2.9"
}
}
Loading