Laravel API server with auth PoC

This commit is contained in:
Matteo Gheza 2023-02-19 01:40:12 +01:00
parent 3e4c6779ef
commit 65031a750a
86 changed files with 9378 additions and 4270 deletions

18
backend/.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

58
backend/.env.example Normal file
View File

@ -0,0 +1,58 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
backend/.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

27
backend/.gitignore vendored
View File

@ -1,8 +1,19 @@
vendor
dist-frontend
tmp/*
!tmp/.gitkeep
uploads/*
!uploads/.gitkeep
keys/*
!keys/gen.ps1
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
.phpunit.result.cache
/.fleet
/.idea
/.vscode

View File

@ -1,15 +1,36 @@
RewriteEngine on
# Go to https://gist.github.com/MatteoGheza/17a63a6b27e1b1d37aa62cdba7d7f2b1 for more information
# This is the .htaccess used in production where you can't use a custom root folder
<IfModule mod_rewrite.c>
#https://stackoverflow.com/a/26791450
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
<IfModule mod_negotiation.c>
#Thanks u/IZEN_R!
RewriteCond %{REQUEST_URI} !^(.*)dist-frontend/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ dist-frontend/$1
RewriteRule ^(.*)api/(.*) router.php [L]
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Send Requests To Front Controller...
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Redirect everything that isn't not an existing file or directory to:
# - dist-frontend (try to serve the file from it)
# - using index.php if the requests contains api/*
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dist-frontend/$1
RewriteRule ^(.*)api/(.*) index.php [L]
# Redirect anything else to index.php, so files like .env or cache files aren't served
RewriteRule (.*) index.php [L]
</IfModule>
DirectoryIndex dist-frontend/index.html
ErrorDocument 404 router.php

66
backend/README.md Normal file
View File

@ -0,0 +1,66 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Cubet Techno Labs](https://cubettech.com)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[Many](https://www.many.co.uk)**
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
- **[DevSquad](https://devsquad.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
- **[OP.GG](https://op.gg)**
- **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)**
- **[Lendio](https://lendio.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

View File

@ -1,415 +0,0 @@
<?php
require_once 'utils.php';
final class NoChiefAvailableException extends Exception {}
final class NoDriverAvailableException extends Exception {}
final class NotEnoughAvailableUsersException extends Exception {}
function callsList($type) {
global $db;
$crew = [];
if($db->selectValue("SELECT COUNT(id) FROM `".DB_PREFIX."_profiles` WHERE `available` = 1") < 2) {
throw new NotEnoughAvailableUsersException();
return;
}
$chief_result = $db->selectRow("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0 AND `available` = 1 AND `chief` = 1 ORDER BY services ASC, trainings DESC, availability_minutes ASC, name ASC LIMIT 1");
if(is_null($chief_result)) {
throw new NoChiefAvailableException();
return;
}
$crew[] = $chief_result;
if($chief_result["driver"]) {
$result = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0 AND `available` = 1 ORDER BY chief ASC, services ASC, trainings DESC, availability_minutes ASC, name ASC");
foreach ($result as $row) {
if(!in_array($row["id"], array_column($crew, 'id'))) {
$crew[] = $row;
}
}
} else {
$driver_result = $db->selectRow("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0 AND `available` = 1 AND `driver` = 1 ORDER BY chief ASC, services ASC, trainings DESC, availability_minutes ASC, name ASC");
if(is_null($driver_result)) {
throw new NoDriverAvailableException();
return;
}
foreach ($driver_result as $row) {
if(!in_array($row["id"], array_column($crew, 'id'))) {
$crew[] = $row;
}
}
}
if ($type == 'full') {
$result = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0 AND `available` = 1 ORDER BY chief ASC, services ASC, trainings DESC, availability_minutes ASC, name ASC");
foreach ($result as $row) {
if(!in_array($row["id"], array_column($crew, 'id'))) {
$crew[] = $row;
}
}
}
return $crew;
}
function loadCrewMemberData($input) {
global $db;
$result = $db->selectRow("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `id` = ?", [$input["id"]]);
if(is_null($result)) {
throw new Exception("Crew member not found");
return;
}
return array_merge($input, $result);
}
function updateAlertMessages($alert, $crew=null, $alertDeleted = false) {
global $Bot, $users, $db;
if(is_null($Bot)) initializeBot(NONE);
if(is_null($crew)) {
$crew = json_decode($alert["crew"], true);
}
$notification_messages = json_decode($alert["notification_messages"], true);
$notification_text = generateAlertReportMessage($alert["type"], $crew, $alert["enabled"], $alert["notes"], $alert["created_by"], $alertDeleted);
foreach($notification_messages as $chat_id => $message_id) {
try {
$Bot->editMessageText([
"chat_id" => $chat_id,
"message_id" => $message_id,
"text" => $notification_text
]);
} catch(skrtdev\Telegram\BadRequestException) {
//
}
}
if($alertDeleted) {
foreach($crew as &$member) {
$message_id = $member["telegram_message_id"];
$chat_id = $member["telegram_chat_id"];
if(!is_null($message_id) && !is_null($chat_id)) {
$Bot->sendMessage([
"chat_id" => $chat_id,
"text" => "Allerta rimossa.\nPartecipazione non più richiesta.",
"reply_to_message_id" => $message_id
]);
try {
$Bot->editMessageReplyMarkup([
"chat_id" => $chat_id,
"message_id" => $message_id,
"reply_markup" => [
'inline_keyboard' => [
]
]
]);
} catch(skrtdev\Telegram\BadRequestException) {
//
}
}
}
return;
}
$available_users_count = 0;
$drivers_count = 0;
$chiefs_count = 0;
foreach($crew as &$member) {
if($member["response"] === true) {
$user = $users->getUserById($member["id"]);
$available_users_count++;
if($user["driver"]) $drivers_count++;
if($user["chief"]) $chiefs_count++;
}
}
if(
($alert["type"] === "support" && $available_users_count >= 2 && $chiefs_count >= 1 && $drivers_count >= 1) ||
($alert["type"] === "full" && $available_users_count >= 5 && $chiefs_count >= 1 && $drivers_count >= 1)
) {
$db->update(
DB_PREFIX."_alerts",
[
"enabled" => 0
],
[
"id" => $alert["id"]
]
);
$notification_text = generateAlertReportMessage($alert["type"], $crew, false, $alert["notes"], $alert["created_by"], $alertDeleted);
foreach($notification_messages as $chat_id => $message_id) {
try {
$Bot->editMessageText([
"chat_id" => $chat_id,
"message_id" => $message_id,
"text" => $notification_text
]);
} catch(skrtdev\Telegram\BadRequestException) {
//
}
}
foreach($crew as &$member) {
$message_id = $member["telegram_message_id"];
$chat_id = $member["telegram_chat_id"];
if((!is_null($message_id) || !is_null($chat_id)) && $member["response"] === "waiting") {
$Bot->sendMessage([
"chat_id" => $chat_id,
"text" => "Numero minimo vigili richiesti raggiunto.\nPartecipazione non più richiesta.",
"reply_to_message_id" => $message_id
]);
try {
$Bot->editMessageReplyMarkup([
"chat_id" => $chat_id,
"message_id" => $message_id,
"reply_markup" => [
'inline_keyboard' => [
]
]
]);
} catch(skrtdev\Telegram\BadRequestException) {
//
}
}
}
}
}
function setAlertResponse($response, $userId, $alertId) {
global $db, $users, $Bot;
if(is_null($Bot)) initializeBot(NONE);
$alert = $db->selectRow(
"SELECT * FROM `".DB_PREFIX."_alerts` WHERE `id` = ?", [$alertId]
);
if(!$alert["enabled"]) return;
$crew = json_decode($alert["crew"], true);
$messageText = $response ? "🟢 Partecipazione accettata." : "🔴 Partecipazione rifiutata.";
foreach($crew as &$member) {
if($member["id"] == $userId) {
if($member["response"] === $response) return;
$message_id = $member["telegram_message_id"];
$chat_id = $member["telegram_chat_id"];
if(!is_null($message_id) || !is_null($chat_id)) {
$Bot->sendMessage([
"chat_id" => $chat_id,
"text" => $messageText,
"reply_to_message_id" => $message_id
]);
try {
$Bot->editMessageReplyMarkup([
"chat_id" => $chat_id,
"message_id" => $message_id,
"reply_markup" => [
'inline_keyboard' => [
]
]
]);
} catch(skrtdev\Telegram\BadRequestException) {
//
}
}
$member["response"] = $response;
$member["response_time"] = get_timestamp();
}
}
$db->update(
DB_PREFIX."_alerts",
[
"crew" => json_encode($crew)
],
[
"id" => $alertId
]
);
updateAlertMessages($alert, $crew);
}
function alertsRouter (FastRoute\RouteCollector $r) {
$r->addRoute(
'GET',
'',
function ($vars) {
global $db, $users;
requireLogin();
$alerts = $db->select("SELECT * FROM `".DB_PREFIX."_alerts` WHERE `enabled` = 1");
if(is_null($alerts)) $alerts = [];
foreach($alerts as &$alert) {
if(isset($_GET["load_less"])) {
$alert = [
"id" => $alert["id"],
"created_at" => $alert["created_at"]
];
} else {
$alert["crew"] = json_decode($alert["crew"], true);
$alert["crew"] = array_map(function($crew_member) {
return loadCrewMemberData($crew_member);
}, $alert["crew"]);
}
}
apiResponse($alerts);
}
);
$r->addRoute(
'POST',
'',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
if(!$users->hasRole(Role::SUPER_EDITOR)) {
apiResponse(["status" => "error", "message" => "Access denied"]);
return;
}
try {
$crew_members = callsList($_POST["type"]);
} catch (NoChiefAvailableException) {
apiResponse(["status" => "error", "message" => "Nessun caposquadra disponibile. Contattare i vigili manualmente."]);
return;
} catch (NoDriverAvailableException) {
apiResponse(["status" => "error", "message" => "Nessun autista disponibile. Contattare i vigili manualmente."]);
return;
} catch (NotEnoughAvailableUsersException) {
apiResponse(["status" => "error", "message" => "Nessun utente disponibile. Distaccamento non operativo."]);
return;
}
$crew = [];
foreach($crew_members as $member) {
$crew[] = [
"id" => $member["id"],
"response" => "waiting"
];
}
$notifications = sendAlertReportMessage($_POST["type"], $crew, true, "", $users->auth->getUserId());
$db->insert(
DB_PREFIX."_alerts",
[
"crew" => json_encode($crew),
"type" => $_POST["type"],
"created_at" => get_timestamp(),
"created_by" => $users->auth->getUserId(),
"notification_messages" => json_encode($notifications)
]
);
$alertId = $db->getLastInsertId();
foreach($crew as &$member) {
[$member["telegram_message_id"], $member["telegram_chat_id"]] = sendAlertRequestMessage($_POST["type"], $member["id"], $alertId, "", $users->auth->getUserId());
}
$db->update(
DB_PREFIX."_alerts",
[
"crew" => json_encode($crew)
],
[
"id" => $alertId
]
);
apiResponse([
"crew" => $crew,
"id" => $alertId
]);
}
);
$r->addRoute(
'GET',
'/{id:\d+}',
function ($vars) {
global $db;
requireLogin();
$alert = $db->selectRow("SELECT * FROM `".DB_PREFIX."_alerts` WHERE `id` = :id", [":id" => $vars["id"]]);
if(is_null($alert)) {
apiResponse(["error" => "alert not found"]);
return;
}
$alert["crew"] = json_decode($alert["crew"], true);
$alert["crew"] = array_map(function($crew_member) {
return loadCrewMemberData($crew_member);
}, $alert["crew"]);
apiResponse($alert);
}
);
$r->addRoute(
'POST',
'/{id:\d+}/settings',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
if(!$users->hasRole(Role::SUPER_EDITOR)) {
apiResponse(["status" => "error", "message" => "Access denied"]);
return;
}
$db->update(
DB_PREFIX."_alerts",
[
"notes" => $_POST["notes"]
],
[
"id" => $vars["id"]
]
);
$alert = $db->selectRow(
"SELECT * FROM `".DB_PREFIX."_alerts` WHERE `id` = :id",
[
":id" => $vars["id"]
]
);
updateAlertMessages($alert);
}
);
$r->addRoute(
'DELETE',
'/{id:\d+}',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
if(!$users->hasRole(Role::SUPER_EDITOR)) {
apiResponse(["status" => "error", "message" => "Access denied"]);
return;
}
$db->update(
DB_PREFIX."_alerts",
[
"enabled" => 0
],
[
"id" => $vars["id"]
]
);
$alert = $db->selectRow(
"SELECT * FROM `".DB_PREFIX."_alerts` WHERE `id` = :id",
[
":id" => $vars["id"]
]
);
updateAlertMessages($alert, null, true);
}
);
}

View File

@ -1,486 +0,0 @@
<?php
require_once 'utils.php';
require_once 'telegramBotRouter.php';
require_once 'cronRouter.php';
require_once 'alerts.php';
function apiRouter (FastRoute\RouteCollector $r) {
$r->addGroup('/cron', function (FastRoute\RouteCollector $r) {
cronRouter($r);
});
$r->addGroup('/alerts', function (FastRoute\RouteCollector $r) {
alertsRouter($r);
});
$r->addRoute(
['GET', 'POST'],
'/bot/telegram',
function ($vars) {
telegramBotRouter();
}
);
$r->addRoute(
'GET',
'/owner_image',
function ($vars) {
if(get_option("use_custom_owner_image", false)) {
$owner_image = get_option("owner_image", false);
if($owner_image) {
header('Cache-control: max-age='.(60*60*24*31));
header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*31));
header('Content-Type: image/png');
readfile($owner_image);
} else {
statusCode(404);
}
} else {
header('Cache-control: max-age='.(60*60*24*31));
header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*31));
header('Content-Type: image/png');
readfile("dist-frontend/assets/img/owner.png");
}
}
);
$r->addRoute(
'GET',
'/place_image',
function ($vars) {
header('Cache-control: max-age='.(60*60*24*31));
header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*31));
header('Content-Type: image/png');
readfile("tmp/".md5($_GET["lat"].";".$_GET["lng"]).".jpg");
}
);
$r->addRoute(
'GET',
'/healthcheck',
function ($vars) {
apiResponse(["state" => "SUCCESS", "description" => ""]);
}
);
$r->addRoute(
['GET', 'POST'],
'/debug/request',
function ($vars) {
apiResponse(["get" => $_GET, "post" => $_POST, "server" => $_SERVER]);
}
);
$r->addRoute(
['GET', 'POST'],
'/debug/token',
function ($vars) {
global $users;
$token = isset($_GET['token']) ? $_GET['token'] : $_POST['token'];
$token_parsed = $users->auth->parseToken($token);
$claims = $token_parsed !== false ? $token_parsed->claims() : null;
$jti = isset($claims) ? $claims->get('jti') : null;
$exp = isset($claims) ? $claims->get('exp') : null;
$iat = isset($claims) ? $claims->get('iat') : null;
$nbf = isset($claims) ? $claims->get('nbf') : null;
$user_info = isset($claims) ? $claims->get('user_info') : null;
apiResponse([
"user_info" => $user_info,
"jti" => $jti,
"exp" => $exp,
"iat" => $iat,
"nbf" => $nbf,
"valid" => $users->auth->isTokenValid($token_parsed),
]);
}
);
$r->addRoute(
['GET'],
'/list',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
if($users->hasRole(Role::SUPER_EDITOR)) {
$response = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0 ORDER BY available DESC, chief DESC, services ASC, trainings DESC, availability_minutes ASC, name ASC");
} else {
$response = $db->select("SELECT `id`, `chief`, `online_time`, `available`, `availability_minutes`, `name`, `driver`, `services` FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0 ORDER BY available DESC, chief DESC, services ASC, trainings DESC, availability_minutes ASC, name ASC");
}
apiResponse(
!is_null($response) ? $response : []
);
}
);
$r->addRoute(
['GET'],
'/logs',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
$response = $db->select("SELECT * FROM `".DB_PREFIX."_log` ORDER BY `timestamp` DESC");
if(!is_null($response)) {
foreach($response as &$row) {
$row['changed'] = $users->getName($row['changed']);
$row['editor'] = $users->getName($row['editor']);
}
} else {
$response = [];
}
apiResponse($response);
}
);
$r->addRoute(
['GET'],
'/services',
function ($vars) {
global $services, $users;
requireLogin();
$users->online_time_update();
apiResponse($services->list());
}
);
$r->addRoute(
['POST'],
'/services',
function ($vars) {
global $services, $users;
requireLogin();
$users->online_time_update();
apiResponse(["response" => $services->add($_POST["start"], $_POST["end"], $_POST["code"], $_POST["chief"], $_POST["drivers"], $_POST["crew"], $_POST["place"], $_POST["notes"], $_POST["type"], $users->auth->getUserId())]);
}
);
$r->addRoute(
['GET'],
'/services/{id}',
function ($vars) {
global $services, $users;
requireLogin();
$users->online_time_update();
apiResponse($services->get($vars['id']));
}
);
$r->addRoute(
['DELETE'],
'/services/{id}',
function ($vars) {
global $services, $users;
requireLogin();
$users->online_time_update();
apiResponse(["response" => $services->delete($vars["id"])]);
}
);
$r->addRoute(
['GET'],
'/place_details',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
$response = $db->selectRow("SELECT * FROM `".DB_PREFIX."_places_info` WHERE `lat` = ? and `lng` = ? LIMIT 0,1;", [$_GET["lat"], $_GET["lng"]]);
apiResponse(!is_null($response) ? $response : []);
}
);
$r->addRoute(
['GET'],
'/trainings',
function ($vars) {
global $db, $users;
requireLogin();
$users->online_time_update();
$response = $db->select("SELECT * FROM `".DB_PREFIX."_trainings` ORDER BY date DESC, beginning desc");
apiResponse(
!is_null($response) ? $response : []
);
}
);
$r->addRoute(
['GET'],
'/users',
function ($vars) {
global $users, $users;
requireLogin();
$users->online_time_update();
apiResponse($users->get_users());
}
);
$r->addRoute(
['POST'],
'/users',
function ($vars) {
global $users;
requireLogin();
if(!$users->hasRole(Role::SUPER_EDITOR)){
exit;
}
apiResponse(["userId" => $users->add_user($_POST["email"], $_POST["name"], $_POST["username"], $_POST["password"], $_POST["phone_number"], $_POST["birthday"], $_POST["chief"], $_POST["driver"], $_POST["hidden"], $_POST["disabled"], "unknown")]);
}
);
$r->addRoute(
['GET'],
'/users/{userId}',
function ($vars) {
global $users;
requireLogin();
if(!$users->hasRole(Role::SUPER_EDITOR) && $_POST["id"] !== $users->auth->getUserId()){
exit;
}
apiResponse($users->getUserById($vars["userId"]));
}
);
$r->addRoute(
['DELETE'],
'/users/{userId}',
function ($vars) {
global $users;
requireLogin();
if(!$users->hasRole(Role::SUPER_EDITOR) && $_POST["id"] !== $users->auth->getUserId()){
exit;
}
$users->remove_user($vars["userId"], "unknown");
apiResponse(["status" => "success"]);
}
);
$r->addRoute(
['GET'],
'/availability',
function ($vars) {
global $users, $db;
requireLogin();
$users->online_time_update();
$row = $db->selectRow(
"SELECT `available`, `manual_mode` FROM `".DB_PREFIX."_profiles` WHERE `id` = ?",
[$users->auth->getUserId()]
);
apiResponse([
"available" => $row["available"],
"manual_mode" => $row["manual_mode"]
]);
}
);
$r->addRoute(
['POST'],
'/availability',
function ($vars) {
global $users, $availability;
requireLogin();
$users->online_time_update();
if(!$users->hasRole(Role::SUPER_EDITOR) && (int) $_POST["id"] !== $users->auth->getUserId()){
statusCode(401);
apiResponse(["status" => "error", "message" => "You don't have permission to change other users availability", "t" => $users->auth->getUserId()]);
return;
}
$user_id = is_numeric($_POST["id"]) ? $_POST["id"] : $users->auth->getUserId();
apiResponse([
"response" => $availability->change($_POST["available"], $user_id, true),
"updated_user" => $user_id,
"updated_user_name" => $users->getName($user_id)
]);
}
);
$r->addRoute(
"POST",
"/manual_mode",
function ($vars) {
global $users, $availability;
requireLogin();
$users->online_time_update();
$availability->change_manual_mode($_POST["manual_mode"]);
apiResponse(["status" => "success"]);
}
);
$r->addRoute(
['GET'],
'/schedules',
function ($vars) {
global $users, $schedules;
requireLogin();
$users->online_time_update();
apiResponse($schedules->get());
}
);
$r->addRoute(
['POST'],
'/schedules',
function ($vars) {
global $users, $schedules;
requireLogin();
$users->online_time_update();
$new_schedules = !is_string($_POST["schedules"]) ? json_encode($_POST["schedules"]) : $_POST["schedules"];
apiResponse([
"response" => $schedules->update($new_schedules)
]);
}
);
$r->addRoute(
['GET'],
'/service_types',
function ($vars) {
global $users, $db;
requireLogin();
$users->online_time_update();
$response = $db->select("SELECT * FROM `".DB_PREFIX."_type`");
apiResponse(is_null($response) ? [] : $response);
}
);
$r->addRoute(
['POST'],
'/service_types',
function ($vars) {
global $users, $db;
requireLogin();
$users->online_time_update();
$response = $db->insert(DB_PREFIX."_type", ["name" => $_POST["name"]]);
apiResponse($response);
}
);
$r->addRoute(
['GET'],
'/places/search',
function ($vars) {
global $places;
requireLogin();
apiResponse($places->search($_GET["q"]));
}
);
$r->addRoute(
['POST'],
'/telegram_login_token',
function ($vars) {
global $users, $db;
requireLogin();
$users->online_time_update();
$token = bin2hex(random_bytes(16));
apiResponse([
"response" => $db->insert(
DB_PREFIX.'_bot_telegram',
[
'user' => $users->auth->getUserId(),
'tmp_login_token' => $token
]
),
"start_link" => "https://t.me/".BOT_TELEGRAM_USERNAME."?start=".$token,
"token" => $token
]);
}
);
$r->addRoute(
['POST'],
'/login',
function ($vars) {
global $users;
try {
$token = $users->loginAndReturnToken($_POST["username"], $_POST["password"]);
logger("Login effettuato");
apiResponse(["status" => "success", "access_token" => $token]);
}
catch (\Delight\Auth\InvalidEmailException $e) {
statusCode(401);
apiResponse(["status" => "error", "message" => "Wrong email address"]);
}
catch (\Delight\Auth\InvalidPasswordException $e) {
statusCode(401);
apiResponse(["status" => "error", "message" => "Wrong password"]);
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
statusCode(401);
apiResponse(["status" => "error", "message" => "Email not verified"]);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
statusCode(401);
apiResponse(["status" => "error", "message" => "Wrong username"]);
}
catch (\Delight\Auth\TooManyRequestsException $e) {
statusCode(401);
apiResponse(["status" => "error", "message" => "Too many requests"]);
}
catch (Exception $e) {
statusCode(401);
apiResponse(["status" => "error", "message" => "Unknown error", "error" => $e]);
}
}
);
$r->addRoute(
['POST'],
'/impersonate',
function ($vars) {
global $users;
requireLogin();
if(!$users->hasRole(Role::SUPER_ADMIN)) {
statusCode(401);
apiResponse(["status" => "error", "message" => "You don't have permission to impersonate"]);
return;
}
try {
$token = $users->loginAsUserIdAndReturnToken($_POST["user_id"]);
apiResponse(["status" => "success", "access_token" => $token]);
}
catch (\Delight\Auth\UnknownIdException $e) {
statusCode(400);
apiResponse(["status" => "error", "message" => "Wrong user ID"]);
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
statusCode(400);
apiResponse(["status" => "error", "message" => "Email not verified"]);
}
catch (Exception $e) {
statusCode(400);
apiResponse(["status" => "error", "message" => "Unknown error", "error" => $e]);
}
}
);
$r->addRoute(
['POST'],
'/stop_impersonating',
function ($vars) {
global $users;
requireLogin();
if(array_key_exists("impersonating_user", $users->auth->user_info) && array_key_exists("precedent_user_id", $users->auth->user_info)) {
$precedent_user_id = $users->auth->user_info["precedent_user_id"];
$users->auth->logOut();
$token = $users->loginAsUserIdAndReturnToken($precedent_user_id);
apiResponse(["status" => "success", "access_token" => $token, "user_id" => $users->auth->getUserId()]);
}
}
);
$r->addRoute(
['GET', 'POST'],
'/refreshToken',
function ($vars) {
global $users;
requireLogin(false);
apiResponse([
"token" => $users->generateToken()
]);
}
);
$r->addRoute(
['GET', 'POST'],
'/validateToken',
function ($vars) {
global $users;
$token = isset($_GET['token']) ? $_GET['token'] : $_POST['token'];
$token_parsed = $users->auth->parseToken($token);
apiResponse([
"valid" => $users->auth->isTokenValid($token_parsed),
]);
}
);
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
'user' => $user
]);
}
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function me(Request $request)
{
return $request->user();
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*/
protected function configureRateLimiting(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}

53
backend/artisan Normal file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
backend/bootstrap/app.php Normal file
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
backend/bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -1,38 +1,66 @@
{
"name": "allerta-vvf/allerta-vvf",
"description": "Un software di allertamento per i vvf",
"name": "laravel/laravel",
"type": "project",
"repositories": [
{
"type": "vcs",
"no-api": true,
"url": "https://github.com/allerta-vvf/PHP-Auth-JWT"
}
],
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"delight-im/auth": "dev-master",
"ulrichsg/getopt-php": "4.0.1",
"nikic/fast-route": "^2.0@dev",
"spatie/array-to-xml": "3.1.1",
"ezyang/htmlpurifier": "4.14.0",
"brick/phonenumber": "0.4.0",
"sentry/sdk": "3.1.1",
"azuyalabs/yasumi": "2.5.0",
"ministryofweb/php-osm-tiles": "2.0.0",
"delight-im/db": "1.3.1",
"phpfastcache/phpfastcache": "9.0.1",
"skrtdev/novagram": "1.10",
"league/mime-type-detection": "1.9.0"
"php": "^8.1",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^10.0",
"laravel/sanctum": "^3.2",
"laravel/tinker": "^2.8"
},
"license": "GPL-3.0-or-later",
"authors": [
{
"name": "Matteo Gheza",
"email": "me@matteogheza.it"
}
],
"minimum-stability": "stable",
"require-dev": {
"pheromone/phpcs-security-audit": "2.0.1"
}
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.18",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^7.0",
"phpunit/phpunit": "^10.0",
"spatie/laravel-ignition": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

7934
backend/composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +0,0 @@
<?php
// ** Database settings ** //
/* The name of the database for Allerta-vvf */
define('DB_NAME', '@@db@@');
/* Database username */
define('DB_USER', '@@user@@');
/* Database password */
define('DB_PASSWORD', '@@password@@');
/* Database hostname */
define('DB_HOST', '@@host@@');
/* Database hostname */
define('DB_PREFIX', '@@prefix@@');
/* JWT Keys */
define('JWT_PUBLIC_KEY', '@@public_key@@');
define('JWT_PRIVATE_KEY', '@@private_key@@');
/* Telegram bot options */
define('BOT_TELEGRAM_API_KEY', '');
define('BOT_TELEGRAM_USERNAME', '');
define('BOT_TELEGRAM_DEBUG_USER', null);
/* Sentry options */
define('SENTRY_CSP_REPORT_URI', '');
define('SENTRY_ENABLED', false);
define('SENTRY_DSN', '');
define('SENTRY_ENV', 'prod');
//define('BASE_PATH', 'allerta/');

215
backend/config/app.php Normal file
View File

@ -0,0 +1,215 @@
<?php
use Illuminate\Support\Facades\Facade;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', '/'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
])->toArray(),
];

115
backend/config/auth.php Normal file
View File

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

View File

@ -0,0 +1,70 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

110
backend/config/cache.php Normal file
View File

@ -0,0 +1,110 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
backend/config/cors.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

151
backend/config/database.php Normal file
View File

@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

View File

@ -0,0 +1,76 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been set up for each driver as an example of the required values.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

View File

@ -0,0 +1,52 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 10),
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 65536,
'threads' => 1,
'time' => 4,
],
];

122
backend/config/logging.php Normal file
View File

@ -0,0 +1,122 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

124
backend/config/mail.php Normal file
View File

@ -0,0 +1,124 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2"
| "postmark", "log", "array", "failover"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
// 'client' => [
// 'timeout' => 5,
// ],
],
'postmark' => [
'transport' => 'postmark',
// 'client' => [
// 'timeout' => 5,
// ],
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

93
backend/config/queue.php Normal file
View File

@ -0,0 +1,93 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

View File

@ -0,0 +1,69 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. If this value is null, personal access tokens do
| not expire. This won't tweak the lifetime of first-party sessions.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],
'prefix' => 'api',
];

View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
'scheme' => 'https',
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

201
backend/config/session.php Normal file
View File

@ -0,0 +1,201 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
];

36
backend/config/view.php Normal file
View File

@ -0,0 +1,36 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

View File

@ -1,215 +0,0 @@
<?php
require_once 'utils.php';
$executed_actions = [];
function job_reset_availability() {
global $db, $executed_actions;
if(
(int) date("j") === 1 &&
(int) date("H") === 0 &&
(int) date("i") - 5 < 0
) {
$profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles`");
if(!is_null($profiles) && count($profiles) > 0) {
$list = [];
foreach($profiles as $profile){
$list[] = [$profile["id"] => $profile["availability_minutes"]];
}
$db->insert(
DB_PREFIX."_minutes",
["month" => date("m"), "year" => date("Y"), "list"=> json_encode($list)]
);
$db->exec("UPDATE `".DB_PREFIX."_profiles` SET `availability_minutes` = 0");
$output = $list;
$output_status = "ok";
} else {
$output = ["profiles array empty"];
$output_status = "error";
}
} else {
$output = ["not time to reset"];
$output_status = "ok";
}
$executed_actions[] = [
"title" => "Reset availability minutes",
"description" => "Reset availability minutes for all profiles",
"output" => $output,
"output_status" => $output_status
];
}
function job_increment_availability() {
global $db, $executed_actions;
$profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `available` = 1");
if(!is_null($profiles) && count($profiles) > 0) {
$output = [];
$output[] = $profiles;
$output_status = "ok";
$queries = [];
foreach ($profiles as $row) {
$value = (int)$row["availability_minutes"]+5;
$id = $row["id"];
$increment[$id] = $value;
$count = $db->update(
DB_PREFIX."_profiles",
["availability_minutes" => $value],
["id" => $id]
);
$tmp = $id . " - " . $value . " ";
$tmp .= $count == 1 ? "success" : "fail";
$queries[] = $tmp;
}
$output[] = $queries;
} else {
$output = ["profiles array empty"];
$output_status = "ok";
}
$executed_actions[] = [
"title" => "Increment availability minutes",
"description" => "Increment availability minutes for all available profiles",
"output" => $output,
"output_status" => $output_status
];
}
function job_schedule_availability() {
global $availability, $db, $executed_actions;
$result = $db->select("SELECT * FROM `".DB_PREFIX."_schedules`;");
$schedules_check = [];
$schedules_users = [];
$schedules_check["schedules"] = [];
$schedules_check["users"] = [];
if(!empty($result)){
foreach ($result as $key => $value) {
$result[$key]["schedules"] = json_decode($result[$key]["schedules"], true);
}
$schedules_check["table"] = $result;
foreach ($result as $row) {
if(!is_null($row["last_exec"])){
$last_exec = [
"day" => (int) explode(";",$row["last_exec"])[0],
"hour" => (int) explode(":",explode(";",$row["last_exec"])[1])[0],
"minutes" => (int) explode(":",$row["last_exec"])[1]
];
} else {
$last_exec = null;
}
$id = $row["id"];
$user_id = $row["user"];
/*
$selected_holidays = json_decode($row["holidays"]);
$selected_holidays_dates = [];
foreach ($selected_holidays as $holiday){
$selected_holidays_dates[] = $user->holidays->getHoliday($holiday)->format('Y-m-d');
}
*/
foreach ($row["schedules"] as $value) {
$schedule = [
"day" => (int) $value["day"]+1,
"hour" => (int) explode(":",$value["hour"])[0],
"minutes" => (int) explode(":",$value["hour"])[1]
];
$now = [
"day" => (int) date("N"),
"hour" => (int) date("H"),
"minutes" => (int) date("i")
];
$manual_mode = $db->selectValue("SELECT `manual_mode` FROM `".DB_PREFIX."_profiles` WHERE `id` = ?", [$user_id]);
if(
$manual_mode == 0 &&
$schedule["day"] == $now["day"] &&
$schedule["hour"] == $now["hour"] &&
$schedule["minutes"] <= $now["minutes"] &&
$now["minutes"] - $schedule["minutes"] <= 30
){
if(!in_array($user_id,$schedules_users)) $schedules_users[] = $user_id;
$last_exec_new = $schedule["day"].";".sprintf("%02d", $schedule["hour"]).":".sprintf("%02d", $schedule["minutes"]);
$db->update(
DB_PREFIX."_schedules",
["last_exec" => $last_exec_new],
["id" => $id]
);
$availability->change(1, $user_id, false);
$schedules_check["schedules"][] = [
"schedule" => $schedule,
"now" => $now,
"last_exec" => $last_exec,
"last_exec_new" => $last_exec_new,
];
}
}
}
$schedules_check["users"] = $schedules_users;
$profiles = $db->select("SELECT id FROM `".DB_PREFIX."_profiles` WHERE `manual_mode` = 0");
foreach ($profiles as $profile) {
if(!in_array($profile["id"],$schedules_users)){
$availability->change(0, $profile["id"], false);
}
}
$output = $schedules_check;
$output_status = "ok";
} else {
$output = ["schedules array empty"];
$output_status = "ok";
}
$executed_actions[] = [
"title" => "Schedule availability",
"description" => "Update availability for all users based on schedules",
"output" => $output,
"output_status" => $output_status
];
}
function job_send_notification_if_manual_mode() {
global $db, $executed_actions;
if(
(int) date("H") === 7 &&
(int) date("i") - 5 < 0
) {
$profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `manual_mode` = 1");
$notified_users = [];
foreach ($profiles as $profile) {
$notified_users[] = $profile["id"];
$stato = $profile["available"] ? "disponibile" : "non disponibile";
sendTelegramNotificationToUser("⚠️ Attenzione! La tua disponibilità <b>non segue la programmazione oraria</b>.\nAttualmente sei <b>{$stato}</b>.\nScrivi \"/programma\" se vuoi ripristinare la programmazione.", $profile["id"]);
}
$output = $notified_users;
$output_status = "ok";
} else {
$output = ["notification not sent"];
$output_status = "ok";
}
$executed_actions[] = [
"title" => "Send notification if manual mode",
"description" => "Send notification to users at 7:00 if they are in manual mode",
"output" => $output,
"output_status" => $output_status
];
}
function cronRouter (FastRoute\RouteCollector $r) {
$r->addRoute(
'POST',
'/execute',
function ($vars) {
global $db, $executed_actions;
$cron_job_allowed = get_option("cron_job_enabled", false) && ((isset($_POST['cron']) && $_POST['cron'] == "cron_job-".get_option("cron_job_code")) || (isset($_SERVER['HTTP_CRON']) && $_SERVER['HTTP_CRON'] == "cron_job-".get_option("cron_job_code")));
if(!$cron_job_allowed) {
statusCode(403);
exit();
}
job_schedule_availability();
job_reset_availability();
job_increment_availability();
job_send_notification_if_manual_mode();
apiResponse(["excuted_actions" => $executed_actions]);
}
);
}

1
backend/database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,40 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* @return $this
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('sessions');
}
};

View File

@ -0,0 +1,22 @@
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// \App\Models\User::factory(10)->create();
// \App\Models\User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
}
}

55
backend/index.php Normal file
View File

@ -0,0 +1,55 @@
<?php
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/
if (file_exists($maintenance = __DIR__.'/storage/framework/maintenance.php')) {
require $maintenance;
}
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/
require __DIR__.'/vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/
$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = $kernel->handle(
$request = Request::capture()
)->send();
$kernel->terminate($request, $response);

View File

@ -1,25 +0,0 @@
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
$Public = Get-Content server.crt
$Private = Get-Content key.pem
Write-Output "" ""
Write-Output "" ""
Write-Output "Public Key"
Write-Output $Public
Write-Output "" ""
Write-Output "Private Key"
Write-Output $Private
Write-Output "" ""
Write-Output "" ""
$PublicBytes = [System.Text.Encoding]::Unicode.GetBytes($Public)
$EncodedPublic = [Convert]::ToBase64String($PublicBytes)
$PrivateBytes = [System.Text.Encoding]::Unicode.GetBytes($Private)
$EncodedPrivate = [Convert]::ToBase64String($PrivateBytes)
Write-Output "/* JWT Keys */"
Write-Output "define('JWT_PUBLIC_KEY', '$EncodedPublic');"
Write-Output "define('JWT_PRIVATE_KEY', '$EncodedPrivate');"

21
backend/public/.htaccess Normal file
View File

@ -0,0 +1,21 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

55
backend/public/index.php Normal file
View File

@ -0,0 +1,55 @@
<?php
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = $kernel->handle(
$request = Request::capture()
)->send();
$kernel->terminate($request, $response);

View File

@ -0,0 +1 @@
import './bootstrap';

32
backend/resources/js/bootstrap.js vendored Normal file
View File

@ -0,0 +1,32 @@
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// import Pusher from 'pusher-js';
// window.Pusher = Pusher;
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: import.meta.env.VITE_PUSHER_APP_KEY,
// cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
// wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
// wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
// wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
// forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
// enabledTransports: ['ws', 'wss'],
// });

File diff suppressed because one or more lines are too long

View File

@ -1,226 +0,0 @@
<?php
require 'utils.php';
require 'apiRouter.php';
use Spatie\ArrayToXml\ArrayToXml;
$MIMEdetector = new League\MimeTypeDetection\ExtensionMimeTypeDetector();
$dispatcher = FastRoute\simpleDispatcher(
function (FastRoute\RouteCollector $r) {
$r->addGroup('/api', function (FastRoute\RouteCollector $r) {
apiRouter($r);
});
$r->addRoute(
'GET',
'/',
function ($vars) {
header("Content-type: text/html");
plainResponse(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . "dist-frontend" . DIRECTORY_SEPARATOR . "index.html"));
}
);
$r->addRoute(
'GET',
'/{file:.+}',
function ($vars) {
global $MIMEdetector;
$filePath = __DIR__ . DIRECTORY_SEPARATOR . "dist-frontend" . DIRECTORY_SEPARATOR . $vars['file'];
if (!file_exists($filePath)) {
notFoundErrorHandler();
} else {
header("Content-type: " . $MIMEdetector->detectMimeTypeFromFile($filePath));
plainResponse(file_get_contents($filePath));
}
}
);
}
);
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
if(defined('BASE_PATH')){
$uri = str_replace(BASE_PATH, "", $uri);
}
$uri = str_replace("index.php", "", $uri);
$uri = str_replace("///", "/", $uri);
$uri = str_replace("//", "/", $uri);
$uri = "/" . trim($uri, "/");
// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
$statusCode = 200;
function statusCode($code)
{
global $statusCode;
$statusCode = $code;
}
function apiResponse($content)
{
global $uri, $responseFormat, $statusCode;
// Get response format
if (isset($_GET["xml"])) {
$responseFormat = "xml";
$responseFormatType = "application/xml";
} else if (isset($_GET["json"])) {
$responseFormat = "json";
$responseFormatType = "application/json";
} else if (false !== strpos($uri, 'xml')) {
$responseFormat = "xml";
$responseFormatType = "application/xml";
$uri = str_replace(".xml", "", $uri);
} else if (false !== strpos($uri, 'json')) {
$responseFormat = "json";
$responseFormatType = "application/json";
$uri = str_replace(".json", "", $uri);
} else {
$responseFormat = "json";
$responseFormatType = "application/json";
}
http_response_code($statusCode);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Max-Age: *");
header("Content-type: " . $responseFormatType);
if ($responseFormat == "json") {
echo (json_encode($content));
} else {
echo (ArrayToXml::convert($content));
}
}
//https://gist.github.com/wildiney/b0be69ff9960642b4f7d3ec2ff3ffb0b
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
function getBearerToken() {
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
function requireLogin($validate_token_version=true)
{
global $users;
$token = getBearerToken();
if($users->auth->isTokenValid($token)) {
$users->auth->authenticateWithToken($token);
if($users->auth->hasRole(\Delight\Auth\Role::CONSULTANT)) {
//Migrate to new user roles
$users->auth->admin()->removeRoleForUserById($users->auth->getUserId(), \Delight\Auth\Role::CONSULTANT);
$users->auth->admin()->addRoleForUserById($users->auth->getUserId(), Role::SUPER_EDITOR);
$users->auth->authenticateWithToken($token);
}
if($validate_token_version) {
if(!array_key_exists("v", $users->auth->user_info)) {
statusCode(400);
apiResponse(["status" => "error", "message" => "JWT client version is not supported", "type" => "jwt_update_required"]);
exit();
}
if((int) $users->auth->user_info["v"] !== 2) {
statusCode(400);
apiResponse(["status" => "error", "message" => "JWT client version ".$users->auth->user_info["v"]." is not supported", "type" => "jwt_update_required"]);
exit();
}
}
if(defined('SENTRY_LOADED')) {
\Sentry\configureScope(function (\Sentry\State\Scope $scope) use ($users): void {
$scope->setUser([
'id' => $users->auth->getUserId(),
'username' => $users->auth->getUserName(),
'name' => $users->getName(),
'email' => $users->auth->getEmail(),
'ip_address' => get_ip()
]);
});
}
return;
}
statusCode(401);
apiResponse(["status" => "error", "message" => "Access denied"]);
exit();
}
function plainResponse($content)
{
global $statusCode;
http_response_code($statusCode);
echo ($content);
}
function notFoundErrorHandler()
{
global $uri;
if (false !== strpos($uri, 'api')) {
statusCode(404);
apiResponse(["status" => "error", "message" => "Resource not found"]);
} else {
statusCode(404);
header("Content-type: text/html");
plainResponse(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . "dist-frontend" . DIRECTORY_SEPARATOR . "index.html"));
}
}
if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
exit();
}
try {
if(defined('SENTRY_LOADED')) {
\Sentry\configureScope(function (\Sentry\State\Scope $scope) use ($uri): void {
$scope->setTag('page.route', $uri);
});
}
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
notFoundErrorHandler();
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
statusCode(405);
apiResponse(["status" => "error", "message" => "Method not allowed", "usedMethod" => $_SERVER['REQUEST_METHOD']]);
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
$handler($vars);
break;
}
} catch (\Throwable $exception) {
\Sentry\captureException($exception);
}

23
backend/routes/api.php Normal file
View File

@ -0,0 +1,23 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->get('/me', function (Request $request) {
return $request->user();
});

View File

@ -0,0 +1,18 @@
<?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});

View File

@ -0,0 +1,19 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

18
backend/routes/web.php Normal file
View File

@ -0,0 +1,18 @@
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});

3
backend/storage/app/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*
!public/
!.gitignore

2
backend/storage/app/public/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

9
backend/storage/framework/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

View File

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
backend/storage/logs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -1,388 +0,0 @@
<?php
use skrtdev\NovaGram\Bot;
use skrtdev\Telegram\Message;
use skrtdev\Telegram\CallbackQuery;
require_once 'utils.php';
define('NONE', 0);
define('WEBHOOK', 1);
$Bot = null;
function initializeBot($mode = WEBHOOK) {
global $Bot;
if (is_null($Bot)) {
if(defined("BASE_PATH")){
$base_path = "/".BASE_PATH."api/bot/telegram";
} else {
$base_path = "/api/bot/telegram";
}
$_SERVER['SCRIPT_URL'] = $base_path;
$NovagramConfig = [
"disable_ip_check" => true, //TODO: fix NovaGram ip check and enable it again
"parse_mode" => "HTML",
"mode" => $mode
];
if(defined("BOT_TELEGRAM_DEBUG_USER")){
$NovagramConfig["debug"] = BOT_TELEGRAM_DEBUG_USER;
}
$Bot = new Bot(BOT_TELEGRAM_API_KEY, $NovagramConfig);
}
}
function getUserIdByFrom($from_id)
{
global $db;
return $db->selectValue("SELECT user FROM `".DB_PREFIX."_bot_telegram` WHERE `chat_id` = ?", [$from_id]);
}
function getUserIdByMessage(Message $message)
{
return getUserIdByFrom($message->from->id);
}
function requireBotLogin(Message $message)
{
global $users;
$userId = getUserIdByMessage($message);
if ($userId === null) {
$message->reply(
"Non hai ancora collegato il tuo account Allerta al bot.".
"\nPer farlo, premere su <strong>\"Collega l'account al bot Telegram\"</strong>."
);
exit();
} else {
if($users->auth->hasRole(\Delight\Auth\Role::CONSULTANT)) {
//Migrate to new user roles
$users->auth->admin()->removeRoleForUserById($users->auth->getUserId(), \Delight\Auth\Role::CONSULTANT);
$users->auth->admin()->addRoleForUserById($users->auth->getUserId(), Role::SUPER_EDITOR);
}
}
}
function sendTelegramNotification($message, $do_not_send_if_same=true)
{
global $Bot, $db;
if(is_null($Bot)) initializeBot(NONE);
$sentMessages = [];
//TODO: implement different types of notifications
//TODO: add command for subscribing to notifications
$chats = $db->select("SELECT * FROM `".DB_PREFIX."_bot_telegram_notifications`");
if(!is_null($chats)) {
foreach ($chats as $chat) {
if($do_not_send_if_same && urldecode($chat['last_notification']) === $message) continue;
$chat = $chat['chat_id'];
$sendMessage = $Bot->sendMessage([
"chat_id" => $chat,
"text" => $message
]);
$db->update(
DB_PREFIX."_bot_telegram_notifications",
["last_notification" => urlencode($message)],
["chat_id" => $chat]
);
$sentMessages[$chat] = $sendMessage->message_id;
}
}
return $sentMessages;
}
function sendTelegramNotificationToUser($message, $userId, $options = [])
{
global $Bot, $db;
if(is_null($Bot)) initializeBot(NONE);
$chat = $db->selectValue("SELECT `chat_id` FROM `".DB_PREFIX."_bot_telegram` WHERE `user` = ?", [$userId]);
if(!is_null($chat)) {
$message_response = $Bot->sendMessage(array_merge([
"chat_id" => $chat,
"text" => $message
], $options));
return [$message_response->message_id, $chat];
}
}
function generateAlertMessage($alertType, $alertEnabled, $alertNotes, $alertCreatedBy, $alertDeleted=false) {
global $users;
$message =
"<b><i><u>".($alertEnabled ? "Allertamento in corso" : ($alertDeleted ? "Allertamento completato" : "Allerta rimossa")).":</u></i></b> ".
($alertType === "full" ? "Richiesta <b>squadra completa 🚒</b>" : "<b>Supporto 🧯</b>\n");
if(!is_null($alertNotes) && $alertNotes !== "") {
$message .= "Note:\n<b>".$alertNotes."</b>\n";
}
if(!is_null($alertCreatedBy)) {
$message .= "Lanciata da: <b>".$users->getName($alertCreatedBy)."</b>\n";
}
return $message;
}
function generateAlertReportMessage($alertType, $crew, $alertEnabled, $alertNotes, $alertCreatedBy, $alertDeleted=false) {
global $users;
$message = generateAlertMessage($alertType, $alertEnabled, $alertNotes, $alertCreatedBy);
$message .= "\nSquadra:\n";
foreach($crew as $member) {
if((!$alertEnabled || $alertDeleted) && $member["response"] === "waiting") continue;
$user = $users->getUserById($member['id']);
$message .= "<i>".$user["name"]."</i> ";
if($user["chief"]) $message .= "CS";
if($user["driver"]) $message .= "🚒";
$message .= "- ";
if($member["response"] === "waiting") {
$message .= "In attesa 🟡";
} else if($member["response"] === true) {
$message .= "Presente 🟢";
} else if($member["response"] === false) {
$message .= "Assente 🔴";
}
$message .= "\n";
}
return $message;
}
function sendAlertReportMessage($alertType, $crew, $alertEnabled, $alertNotes, $alertCreatedBy, $alertDeleted = false) {
$message = generateAlertReportMessage($alertType, $crew, $alertEnabled, $alertNotes, $alertCreatedBy, $alertDeleted);
return sendTelegramNotification($message, false);
}
function sendAlertRequestMessage($alertType, $userId, $alertId, $alertNotes, $alertCreatedBy, $alertDeleted = false) {
return sendTelegramNotificationToUser(generateAlertMessage($alertType, true, $alertNotes, $alertCreatedBy, $alertDeleted), $userId, [
'reply_markup' => [
'inline_keyboard' => [
[
[
'text' => '✅ Partecipo',
'callback_data' => "alert_yes_".$alertId
],
[
'text' => 'Non partecipo ❌',
'callback_data' => "alert_no_".$alertId
]
]
]
]
]);
}
function yesOrNo($value)
{
return ($value === 1 || $value) ? '<b>SI</b>' : '<b>NO</b>';
}
function sendLongMessage($text, $userId) {
global $Bot;
if(strlen($text) > 4096) {
$message_json = wordwrap($text, 4096, "<@MESSAGE_SEPARATOR@>", true);
$message_json = explode("<@MESSAGE_SEPARATOR@>", $message_json);
foreach($message_json as $segment) {
sendLongMessage($segment, $userId);
}
} else {
$Bot->sendMessage($userId, $text);
}
}
function telegramBotRouter() {
global $Bot;
define("running_telegram_bot_webhook", true);
initializeBot();
$Bot->addErrorHandler(function ($e) {
print('Caught '.get_class($e).' exception from general handler'.PHP_EOL);
print($e.PHP_EOL);
});
$Bot->onCommand('start', function (Message $message, array $args = []) {
global $db;
if(isset($args[0])) {
$registered_chats = $db->select("SELECT * FROM `".DB_PREFIX."_bot_telegram` WHERE `chat_id` = ?", [$message->from->id]);
if(!is_null($registered_chats) && count($registered_chats) > 1) {
$message->chat->sendMessage(
"⚠️ Questo account Allerta è già associato ad un'altro utente Telegram.".
"\nContattare un amministratore."
);
return;
}
$response = $db->update(
DB_PREFIX.'_bot_telegram',
['chat_id' => $message->from->id],
['tmp_login_token' => $args[0]]
);
if($response === 1) {
logger("Utente collegato ad account telegram (".$message->from->id.")");
$message->chat->sendMessage(
"✅ Login avvenuto con successo!".
"\nPer ottenere informazioni sul profilo, utilizzare il comando /info".
"\nPer ricevere informazioni sui comandi, utilizzare il comando /help o visualizzare il menu dei comandi da Telegram"
);
} else {
$message->chat->sendMessage(
"⚠️ Chiave di accesso non valida, impossibile eseguire il login.".
"\nRiprovare o contattare un amministratore."
);
}
} else {
$message->chat->sendMessage(
"Per iniziare, è necessario collegare l'account di Allerta con Telegram.".
"\nPer farlo, premere su <strong>\"Collega l'account al bot Telegram\"</strong>."
);
}
});
$Bot->onCommand('help', function (Message $message, array $args = []) {
$message->chat->sendMessage(
" Elenco dei comandi disponibili:".
"\n/info - Ottieni informazioni sul profilo connesso".
"\n/help - Ottieni informazioni sui comandi".
"\n/attiva - Modifica la tua disponibilità in \"reperibile\"".
"\n/disattiva - Modifica la tua disponibilità in \"non reperibile\"".
"\n/programma - Abilita programmazione oraria".
"\n/disponibili - Mostra un elenco dei vigili attualmente disponibili".
"\n/stato - Mostra lo stato della disponibilità della squadra"
);
});
$Bot->onCommand('debug_userid', function (Message $message) {
global $Bot;
$messageText = "🔎 ID utente Telegram: <b>".$message->from->id."</b>";
if(isset($message->from->username)) {
$messageText .= "\n💬 Username: <b>".$message->from->username."</b>";
}
if(isset($message->from->first_name)) {
$messageText .= "\n🔎 Nome: <b>".$message->from->first_name."</b>";
}
if(isset($message->from->last_name)) {
$messageText .= "\n🔎 Cognome: <b>".$message->from->last_name."</b>";
}
if(isset($message->from->language_code)) {
$messageText .= "\n🌐 Lingua: <b>".$message->from->language_code."</b>";
}
if(isset($message->from->is_bot)) {
$messageText .= "\n🤖 Bot: <b>".yesOrNo($message->from->is_bot)."</b>";
}
$message->reply($messageText);
if(defined("BOT_TELEGRAM_DEBUG_USER") && BOT_TELEGRAM_DEBUG_USER !== $message->from->id){
$messageText .= "\n\n🔎 JSON del messaggio:";
$Bot->sendMessage(BOT_TELEGRAM_DEBUG_USER, $messageText);
$message_json = json_encode($message, JSON_PRETTY_PRINT);
sendLongMessage($message_json, BOT_TELEGRAM_DEBUG_USER);
}
});
$Bot->onCommand('info', function (Message $message) {
global $users;
$user_id = getUserIdByMessage($message);
if(is_null($user_id)) {
$message->chat->sendMessage('⚠️ Questo account Telegram non è associato a nessun utente di Allerta.');
} else {
$user = $users->getUserById($user_id);
$message->chat->sendMessage(
" Informazioni sul profilo:".
"\n<i>Nome:</i> <b>".$user["name"]."</b>".
"\n<i>Disponibile:</i> ".yesOrNo($user["available"]).
"\n<i>Caposquadra:</i> ".yesOrNo($user["chief"] === 1).
"\n<i>Autista:</i> ".yesOrNo($user["driver"] === 1).
"\n<i>Interventi svolti:</i> <b>".$user["services"]."</b>".
"\n<i>Esercitazioni svolte:</i> <b>".$user["trainings"]."</b>".
"\n<i>Minuti di disponibilità:</i> <b>".$user["availability_minutes"]."</b>"
);
}
});
//Too difficult and "spaghetti to explain it here in comments, please use https://regexr.com/
//Jokes apart, checks if text contains something like "Attiva", "attiva", "Disponibile", "disponibile" but not "Non ", "non ", "Non_", "non_", "Dis" or "dis"
$Bot->onText("/\/?(Sono |sono |Io sono |Io sono )?(?<!non( |_))(?<!dis)(?<!Non( |_))(?<!Dis)(Attiva|Attivami|Attivo|Disponibile|Operativo|attiva|attivami|attivo|disponibile|operativo)/", function (Message $message, $matches = []) {
global $Bot, $availability;
requireBotLogin($message);
if(count(explode(" ", $message->text)) > 3) return;
$user_id = getUserIdByMessage($message);
$availability->change(1, $user_id, true);
$Bot->sendMessage($message->from->id, "Disponibilità aggiornata con successo.\nOra sei <b>operativo</b>.");
});
$Bot->onText("/\/?(Io |Io sono )?(Disattiva|Disattivo|Disattivami|Non( |_)attivo|Non( |_)(Sono |sono )?disponibile|Non( |_)(Sono |sono )?operativo|disattiva|disattivo|sisattivami|non( |_)(Sono |sono )?attivo|non( |_)(Sono |sono )?disponibile|non( |_)(Sono |sono )?operativo)/", function (Message $message, $matches = []) {
global $Bot, $availability;
requireBotLogin($message);
if(count(explode(" ", $message->text)) > 4) return;
$user_id = getUserIdByMessage($message);
$availability->change(0, $user_id, true);
$Bot->sendMessage($message->from->id, "Disponibilità aggiornata con successo.\nOra sei <b>non operativo</b>.");
});
$Bot->onText("/\/?(Abilita( |_)|abilita( |_)|Attiva( |_)|attiva( |_))?(Programma|Programmazione|programmazione|Programmazione( |_)oraria|programma|programmazione( |_)oraria)/", function (Message $message, $matches = []) {
global $Bot, $availability;
requireBotLogin($message);
if(count(explode(" ", $message->text)) > 3) return;
$userId = getUserIdByMessage($message);
$availability->change_manual_mode(0, $userId);
$Bot->sendMessage($message->from->id, "Programmazione oraria <b>abilitata</b>.\nPer disabilitarla (e tornare in modalità manuale), cambiare la disponbilità usando i comandi \"/attiva\" e \"/disattiva\"");
});
$Bot->onText("/\/?(Stato|stato)( |_)?(Distaccamento|distaccamento)?/", function (Message $message, $matches = []) {
global $db;
requireBotLogin($message);
if(count(explode(" ", $message->text)) > 2) return;
$available_users_count = $db->selectValue("SELECT COUNT(id) FROM `".DB_PREFIX."_profiles` WHERE `available` = 1 AND `hidden` = 0");
if($available_users_count >= 5) {
$message->reply("🚒 Distaccamento operativo con squadra completa");
} else if($available_users_count >= 2) {
$message->reply("🧯 Distaccamento operativo per supporto");
} else if($available_users_count >= 0) {
$message->reply("⚠️ Distaccamento non operativo");
}
});
$Bot->onText("/\/?(Elenco|elenco|Elenca|elenca)?(_| )?(Disponibili|disponibili)/", function (Message $message, $matches = []) {
global $db, $users;
requireBotLogin($message);
if(count(explode(" ", $message->text)) > 2) return;
$result = $db->select("SELECT `chief`, `driver`, `available`, `name` FROM `".DB_PREFIX."_profiles` WHERE available = 1 and hidden = 0 ORDER BY chief DESC, services ASC, trainings DESC, availability_minutes DESC, name ASC");
if(!is_null($result) && count($result) > 0) {
$msg = " Vigili attualmente disponibili:";
foreach($result as $user) {
$msg .= "\n<b>".$user["name"]."</b>";
if($user["driver"]) $msg .= " 🚒";
if($user["chief"]) {
$msg .= " CS";
}
}
} else {
$msg = "⚠️ Nessun vigile disponibile.";
}
$message->reply($msg);
});
$Bot->onCallbackQuery(function (CallbackQuery $callback_query) use ($Bot) {
$user = $callback_query->from;
$message = $callback_query->message;
$chat = $message->chat;
if(strpos($callback_query->data, 'alert_') === 0) {
$data = explode("_", str_replace("alert_", "", $callback_query->data));
$alert_id = $data[1];
setAlertResponse($data[0] === "yes", getUserIdByFrom($user->id), $alert_id);
return;
}
});
$Bot->start();
}

View File

@ -0,0 +1,21 @@
<?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Application;
trait CreatesApplication
{
/**
* Creates the application.
*/
public function createApplication(): Application
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Tests\Feature;
// use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}

View File

@ -0,0 +1,16 @@
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_that_true_is_true(): void
{
$this->assertTrue(true);
}
}

View File

@ -1,735 +0,0 @@
<?php
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key\InMemory;
use Phpfastcache\CacheManager;
use Phpfastcache\Config\ConfigurationOption;
require_once("vendor/autoload.php");
require("config.php");
if(!defined('SENTRY_LOADED')) {
if(!defined(SENTRY_ENABLED)) define(SENTRY_ENABLED, false);
if(SENTRY_ENABLED) {
\Sentry\init([
'dsn' => SENTRY_DSN,
'environment' => SENTRY_ENV,
'integrations' => [
new \Sentry\Integration\ModulesIntegration(),
]
]);
define('SENTRY_LOADED', true);
}
}
$db = \Delight\Db\PdoDatabase::fromDsn(
new \Delight\Db\PdoDsn(
"mysql:host=".DB_HOST.";dbname=".DB_NAME,
DB_USER,
DB_PASSWORD
)
);
try {
CacheManager::setDefaultConfig(new ConfigurationOption([
'path' => realpath(dirname(__FILE__).'/tmp')
]));
$cache = CacheManager::getInstance('files');
} catch(Exception $e) {
$cache = null;
}
$options = new Options($db, $cache);
function get_option($name, $default=null) {
global $options;
try {
return $options->get($name);
} catch(Exception $e) {
return $default;
}
}
function get_ip()
{
if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
if(get_option("check_cf_ip", false)) {
if(!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
}
return $ip;
}
$JWTconfig = Configuration::forAsymmetricSigner(
new Signer\Rsa\Sha256(),
InMemory::base64Encoded(JWT_PRIVATE_KEY),
InMemory::base64Encoded(JWT_PUBLIC_KEY)
);
$auth = new \Delight\Auth\Auth($db, $JWTconfig, get_ip(), DB_PREFIX."_");
final class Role
{
const EDITOR = \Delight\Auth\Role::EDITOR;
const SUPER_EDITOR = \Delight\Auth\Role::SUPER_EDITOR;
const DEVELOPER = \Delight\Auth\Role::DEVELOPER;
const GUEST = \Delight\Auth\Role::SUBSCRIBER;
const EXTERNAL_VIEWER = \Delight\Auth\Role::REVIEWER;
const ADMIN = \Delight\Auth\Role::ADMIN;
const SUPER_ADMIN = \Delight\Auth\Role::SUPER_ADMIN;
public function __construct()
{
}
}
function get_timestamp() {
return round(microtime(true) * 1000);
}
function logger($action, $changed=null, $editor=null, $timestamp=null, $source_type="api")
{
global $db, $users;
//timestamp added by default in DB
if(is_null($changed)){
$changed = $users->auth->getUserId();
}
if(is_null($editor)){
$editor = $changed;
}
if(!$users->isHidden($editor)){
if(get_option("log_save_ip", true)){
$ip = get_ip();
} else {
$ip = null;
}
if(defined("running_telegram_bot_webhook")) {
$source_type = "telegram";
}
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? mb_strimwidth($_SERVER['HTTP_USER_AGENT'], 0, 200, "...") : null;
$db->insert(
DB_PREFIX."_log",
["action" => $action, "changed" => $changed, "editor" => $editor, "timestamp" => $timestamp, "ip" => $ip, "source_type" => $source_type, "user_agent" => $user_agent]
);
}
}
class Options
{
protected $db;
protected $cache;
public $options = [];
public $optionsCache;
public function __construct($db, $cache, $bypassCache=false){
$this->db = $db;
$this->cache = $cache;
if(!$bypassCache){
try {
$this->optionsCache = $this->cache->getItem("options");
if (is_null($this->optionsCache->get())) {
$this->optionsCache->set($db->select("SELECT * FROM `".DB_PREFIX."_options` WHERE `enabled` = 1"))->expiresAfter(60*60*24*7);
$this->cache->save($this->optionsCache);
}
$this->options = $this->optionsCache->get();
} catch(Exception $e) {
$this->options = $db->select("SELECT * FROM `".DB_PREFIX."_options` WHERE `enabled` = 1");
}
} else {
$this->options = $db->select("SELECT * FROM `".DB_PREFIX."_options` WHERE `enabled` = 1");
}
if(is_null($this->options)){
$this->options = [];
}
}
public function get($name)
{
if(defined($name)) {
return constant($name);
} else {
foreach($this->options as $option){
if($name == $option["name"]) {
return empty($option["value"]) ? false : $option["value"];
}
}
throw new \Exception("Option not found: ".$name);
}
}
}
class Users
{
private $db = null;
public $auth = null;
public $holidays = null;
public function __construct($db, $auth)
{
$this->db = $db;
$this->auth = $auth;
//$this->holidays = Yasumi\Yasumi::create(get_option("holidays_provider") ?: "USA", date("Y"), get_option("holidays_language") ?: "en_US");
}
public function add_user($email, $name, $username, $password, $phone_number, $birthday, $chief, $driver, $hidden, $disabled, $inserted_by)
{
//TODO: save birthday in db
$userId = $this->auth->admin()->createUserWithUniqueUsername($email, $password, $username);
if($userId) {
$hidden = $hidden ? 1 : 0;
$disabled = $disabled ? 1 : 0;
$chief = $chief ? 1 : 0;
$driver = $driver ? 1 : 0;
$this->db->insert(
DB_PREFIX."_profiles",
["hidden" => $hidden, "disabled" => $disabled, "name" => $name, "phone_number" => $phone_number, "chief" => $chief, "driver" => $driver]
);
if($chief == 1) {
$this->auth->admin()->addRoleForUserById($userId, Role::SUPER_EDITOR);
}
logger("User added", $userId, $inserted_by);
return $userId;
} else {
return false;
}
}
public function get_users()
{
return $this->db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `hidden` = 0");
}
public function getUserById($id)
{
return $this->db->selectRow("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `id` = ?", [$id]);
}
public function remove_user($id, $removed_by)
{
$this->db->delete(
DB_PREFIX."_users",
["id" => $id]
);
$this->db->delete(
DB_PREFIX."_profiles",
["id" => $id]
);
logger("User removed", null, $removed_by);
}
public function online_time_update($id=null){
if(is_null($id)) $id = $this->auth->getUserId();
$time = time();
$this->db->update(
DB_PREFIX."_profiles",
["online_time" => $time],
["id" => $id]
);
}
public function generateToken($precedent_user_id = null)
{
$token_params = [
"roles" => $this->auth->getRoles(),
"name" => $this->getName(),
"v" => 2
];
if(!is_null($precedent_user_id)) {
$token_params["impersonating_user"] = true;
$token_params["precedent_user_id"] = $precedent_user_id;
}
$token = $this->auth->generateJWTtoken($token_params);
return $token;
}
public function loginAndReturnToken($username, $password)
{
$this->auth->loginWithUsername($username, $password);
if($this->auth->hasRole(\Delight\Auth\Role::CONSULTANT)) {
//Migrate to new user roles
$this->auth->admin()->removeRoleForUserById($this->auth->getUserId(), \Delight\Auth\Role::CONSULTANT);
$this->auth->admin()->addRoleForUserById($this->auth->getUserId(), Role::SUPER_EDITOR);
$this->auth->loginWithUsername($username, $password);
}
return $this->generateToken();
}
public function loginAsUserIdAndReturnToken($userId)
{
$precedent_user_id = null;
if(!is_null($this->auth->getUserId())) {
if((int) $userId === (int) $this->auth->getUserId()) {
return $this->generateToken();
}
$precedent_user_id = $this->auth->getUserId();
$this->auth->logOut();
}
$this->auth->admin()->logInAsUserById($userId);
if($this->auth->hasRole(\Delight\Auth\Role::CONSULTANT)) {
//Migrate to new user roles
$this->auth->admin()->removeRoleForUserById($this->auth->getUserId(), \Delight\Auth\Role::CONSULTANT);
$this->auth->admin()->addRoleForUserById($this->auth->getUserId(), Role::SUPER_EDITOR);
$this->auth->admin()->logInAsUserById($userId);
}
return $this->generateToken($precedent_user_id);
}
public function isHidden($id=null)
{
if(is_null($id)) $id = $this->auth->getUserId();
if(is_null($id)) return true;
return $this->db->selectValue("SELECT hidden FROM `".DB_PREFIX."_profiles` WHERE `id` = ?", [$id]);
}
public function getName($id=null)
{
if(is_null($id)) $id = $this->auth->getUserId();
return $this->db->selectValue("SELECT name FROM `".DB_PREFIX."_profiles` WHERE `id` = ?", [$id]);
}
public function hasRole($role, $adminGranted=true)
{
return $this->auth->hasRole($role) || ($adminGranted && ($this->auth->hasRole(Role::ADMIN) || $this->auth->hasRole(Role::SUPER_ADMIN)));
}
}
class Availability {
private $db = null;
private $users = null;
public function __construct($db, $users)
{
$this->db = $db;
$this->users = $users;
}
public function change_manual_mode($manual_mode, $user_id = null) {
global $db, $users;
if(is_null($user_id)) $user_id = $users->auth->getUserId();
$db->update(
DB_PREFIX."_profiles",
[
"manual_mode" => $manual_mode
],
[
"id" => $user_id
]
);
}
public function change($availability, $user_id, $is_manual_mode=true)
{
if($is_manual_mode) logger("Disponibilità cambiata in ".($availability ? '"disponibile"' : '"non disponibile"'), $user_id, $this->users->auth->getUserId());
$change_values = ["available" => $availability];
if($is_manual_mode) $change_values["manual_mode"] = 1;
$response = $this->db->update(
DB_PREFIX."_profiles",
$change_values,
["id" => $user_id]
);
if(!$this->users->isHidden($user_id)) {
$available_users_count = $this->db->selectValue("SELECT COUNT(id) FROM `".DB_PREFIX."_profiles` WHERE `available` = 1 AND `hidden` = 0");
if($available_users_count === 5) {
sendTelegramNotification("🚒 Distaccamento operativo con squadra completa");
} else if($available_users_count < 2) {
sendTelegramNotification("⚠️ Distaccamento non operativo");
} else if($available_users_count < 5) {
sendTelegramNotification("🧯 Distaccamento operativo per supporto");
}
}
return $response;
}
}
class Services {
private $db = null;
private $users = null;
private $places = null;
public function __construct($db, $users, $places)
{
$this->db = $db;
$this->users = $users;
$this->places = $places;
}
public function list() {
$response = $this->db->select("SELECT ".DB_PREFIX."_services.*, place.id as place_id, place.lat as lat, place.lng as lng, place.place_name as place_name, place.country as country, place.country_code as country_code, place.postcode as postcode, place.state as state, place.municipality as municipality, place.village as village, place.hamlet as hamlet, place.road as road, place.building_service_name as building_service_name, place.house_number as house_number FROM `".DB_PREFIX."_services` JOIN ".DB_PREFIX."_places_info place ON ".DB_PREFIX."_services.place_reverse = place.id ORDER BY start DESC");
$response = is_null($response) ? [] : $response;
foreach($response as &$service) {
$service["chief"] = $this->users->getName($service["chief"]);
$drivers = explode(";", $service["drivers"]);
foreach($drivers as &$driver) {
$driver = $this->users->getName($driver);
}
$service["drivers"] = implode(", ", $drivers);
$crew = explode(";", $service["crew"]);
foreach($crew as &$member) {
$member = $this->users->getName($member);
}
$service["crew"] = implode(", ", $crew);
$service["type"] = $this->db->selectValue("SELECT name FROM `".DB_PREFIX."_type` WHERE `id` = ?", [$service["type"]]);
}
return $response;
}
public function get($id) {
$response = $this->db->selectRow("SELECT ".DB_PREFIX."_services.*, place.id as place_id, place.lat as lat, place.lng as lng, place.place_name as place_name, place.country as country, place.country_code as country_code, place.postcode as postcode, place.state as state, place.municipality as municipality, place.village as village, place.hamlet as hamlet, place.road as road, place.building_service_name as building_service_name, place.house_number as house_number FROM `".DB_PREFIX."_services` JOIN ".DB_PREFIX."_places_info place ON ".DB_PREFIX."_services.place_reverse = place.id WHERE ".DB_PREFIX."_services.id = ? ORDER BY start DESC", [$id]);
if(is_null($response)) return [];
return $response;
$response["chief"] = $this->users->getName($response["chief"]);
$response = explode(";", $response["drivers"]);
foreach($response as &$driver) {
$driver = $this->users->getName($driver);
}
$response["drivers"] = implode(", ", $response);
$crew = explode(";", $response["crew"]);
foreach($crew as &$member) {
$member = $this->users->getName($member);
}
$response["crew"] = implode(", ", $crew);
$response["type"] = $this->db->selectValue("SELECT name FROM `".DB_PREFIX."_type` WHERE `id` = ?", [$response["type"]]);
return $response;
}
public function increment_counter($increment)
{
$increment = implode(",", array_unique(explode(",", str_replace(";", ",", $increment))));
$this->db->exec(
"UPDATE `".DB_PREFIX."_profiles` SET `services`= services + 1 WHERE id IN ($increment)"
);
}
public function decrement_counter($decrement)
{
$decrement = implode(",", array_unique(explode(",", str_replace(";", ",", $decrement))));
$this->db->exec(
"UPDATE `".DB_PREFIX."_profiles` SET `services`= services - 1 WHERE id IN ($decrement)"
);
}
public function get_selected_users($id)
{
$response = $this->db->selectRow(
"SELECT `chief`, `drivers`, `crew` FROM `".DB_PREFIX."_services` WHERE `id` = :id",
["id" => $id]
);
return $response["chief"].";".$response["drivers"].";".$response["crew"];
}
public function add($start, $end, $code, $chief, $drivers, $crew, $place, $notes, $type, $inserted_by)
{
$this->db->insert(
DB_PREFIX."_services",
["start" => $start, "end" => $end, "code" => $code, "chief" => $chief, "drivers" => $drivers, "crew" => $crew, "place" => $place, "place_reverse" => $this->places->save_place_reverse(explode(";", $place)[0], explode(";", $place)[1]), "notes" => $notes, "type" => $type, "inserted_by" => $inserted_by]
);
$serviceId = $this->db->getLastInsertId();
$this->increment_counter($chief.",".$drivers.",".$crew);
logger("Service added");
return $serviceId;
}
public function delete($id)
{
$service = $this->db->selectRow(
"SELECT `chief`, `drivers`, `crew` FROM `".DB_PREFIX."_services` WHERE `id` = :id",
["id" => $id]
);
$this->decrement_counter($service["chief"].";".$service["drivers"].";".$service["crew"]);
$this->db->delete(
DB_PREFIX."_services",
["id" => $id]
);
logger("Intervento eliminato");
return true;
}
}
function curl_call($url, $is_response_json=true)
{
$useragent = "Allerta-VVF (https://github.com/allerta-vvf/allerta-vvf) place search proxy (see utils.php class Places)";
try {
$hostname = gethostname();
if(!is_null($hostname) && $hostname != "") $useragent .= " - server hostname: ".$hostname;
} catch (Exception $e) {
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$response = curl_exec($ch);
if($is_response_json) $response = json_decode($response, true);
curl_close($ch);
return $response;
}
class Places {
private $cache;
private $users;
private $db;
private $placesCache;
public function __construct($cache, $users, $db)
{
$this->cache = $cache;
$this->users = $users;
$this->db = $db;
}
public function search($query)
{
$this->placesCache = $this->cache->getItem("place_".md5($query));
$cache_element = $this->placesCache->get();
if (is_null($cache_element)) {
$place_response = curl_call("https://nominatim.openstreetmap.org/search?format=json&limit=6&q=".urlencode($query));
if(is_null($place_response)) {
$place_response = [];
}
$this->placesCache->set($place_response)->expiresAfter(60*60*24*365);
$this->cache->save($this->placesCache);
return $place_response;
} else {
return $cache_element;
}
}
public function save_place_reverse($lat, $lng)
{
$this->save_static_map_image($lat, $lng);
$response = curl_call("https://nominatim.openstreetmap.org/reverse?format=json&lat=".$lat."&lon=".$lng);
if(is_null($response) || empty($response)) {
$response = "{}";
$place_name = "";
$address = [];
} else {
$place_name = $response["display_name"];
$address = $response["address"];
}
$row = ["lat" => $lat, "lng" => $lng, "place_name" => $place_name, "place" => json_encode($response)];
if(isset($address["country"])) $row["country"] = $address["country"];
if(isset($address["country_code"])) $row["country_code"] = $address["country_code"];
if(isset($address["postcode"])) $row["postcode"] = $address["postcode"];
if(isset($address["region"])) $row["state"] = $address["region"];
if(isset($address["state"])) $row["state"] = $address["state"];
if(isset($address["municipality"])) $row["municipality"] = $address["municipality"];
if(isset($address["village"])) $row["village"] = $address["village"];
if(isset($address["hamlet"])) $row["hamlet"] = $address["hamlet"];
if(isset($address["road"])) $row["road"] = $address["road"];
if(isset($address["tourism"])) $row["building_service_name"] = $address["tourism"];
if(isset($address["croft"])) $row["building_service_name"] = $address["croft"];
if(isset($address["isolated_dwelling"])) $row["building_service_name"] = $address["isolated_dwelling"];
if(isset($address["amenity"])) $row["building_service_name"] = $address["amenity"];
if(isset($address["building"])) $row["building_service_name"] = $address["building"];
if(isset($address["house_number"])) $row["house_number"] = $address["house_number"];
$this->db->insert(
DB_PREFIX."_places_info",
$row
);
return $this->db->getLastInsertId();
}
function save_static_map_image($lat, $lng)
{
if(get_option("use_static_map_image_generator", false)) {
$url = get_option("static_map_image_generator_url", "");
$url = str_replace("{{lat}}", $lat, $url);
$url = str_replace("{{lng}}", $lng, $url);
} else {
$tile_x = floor($lng / 360 * pow(2, get_option("static_map_image_zoom", 18)));
$tile_y = floor(log(tan((90 + $lat) * pi() / 360)) / pi() * pow(2, get_option("static_map_image_zoom", 18)));
$url = "https://a.tile.openstreetmap.org/".get_option("static_map_image_zoom", 18)."/".$tile_x."/".$tile_y.".png";
}
$image = curl_call($url, false);
$image_path = "tmp/".md5($lat.";".$lng).".jpg";
file_put_contents($image_path, $image);
}
}
class Schedules {
private $db = null;
private $users = null;
public function __construct($db, $users)
{
$this->db = $db;
$this->users = $users;
}
public function get($profile="default") {
$response = $this->db->selectRow("SELECT * FROM `".DB_PREFIX."_schedules` WHERE `user` = ? AND `profile_name` = ?", [$this->users->auth->getUserId(), $profile]);
if(!is_null($response)) {
$response["schedules"] = json_decode($response["schedules"], true);
return $response;
}
return [];
}
public function update($schedules, $profile="default") {
//TODO implement multiple profiles
//TODO implement holidays
logger("Aggiornata programmazione orari disponibilità");
if(empty($this->get($profile))) {
return $this->db->insert(
DB_PREFIX."_schedules",
["user" => $this->users->auth->getUserId(), "schedules" => $schedules, "profile_name" => $profile]
);
} else {
return $this->db->update(
DB_PREFIX."_schedules",
["schedules" => $schedules, "last_update" => null],
["user" => $this->users->auth->getUserId(), "profile_name" => $profile]
);
}
}
}
class Translations
{
public $loaded_languages = ["en", "it"];
public $default_language = "en";
public $language = null;
public $client_languages = ["en"];
public $loaded_translations = [];
public function client_languages()
{
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$client_languages = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
} else {
$client_languages = "en-US;q=0.5,en;q=0.3";
}
if(strpos($client_languages, ';') == false) {
if(strpos($client_languages, '-') !== false) {
return [substr($client_languages, 0, 5)];
} else {
return [substr($client_languages, 0, 2)];
}
} else {
$client_languages = explode(",", $client_languages);
$tmp_languages = [];
foreach($client_languages as $language){
if(strpos($language, ';') == false) {
$tmp_languages[$language] = 1;
} else {
$tmp_languages[explode(";q=", $language)[0]] = (float) explode(";q=", $language)[1];
}
}
arsort($tmp_languages);
return array_keys($tmp_languages);
}
}
public function __construct($force_language = false)
{
$this->client_languages = $this->client_languages();
if(isset($_COOKIE["forceLanguage"]) && in_array($_COOKIE["forceLanguage"], $this->loaded_languages)){
$this->language = $_COOKIE["forceLanguage"];
} else if($force_language && in_array($force_language, $this->loaded_languages)){
$this->language = $force_language;
} else {
foreach($this->client_languages as $language){
if(in_array($language, $this->loaded_languages) && $this->language == null) {
$this->language = $language;
}
}
if($this->language == null) {
$this->language = "en";
}
}
foreach($this->loaded_languages as $language) {
$filename = "translations/".$language.".php";
if (file_exists($filename)) {
$this->loaded_translations[$language] = require($filename);
} else {
throw new Exception("Language file not found");
}
}
}
public function translate($string, $language=null, $returnStringIfNotFound=false)
{
if(is_null($language)) {
$language = $this->language;
}
if(get_option("force_language", false)) {
$language = get_option("force_language", false);
if(!in_array($language, $this->loaded_languages)) {
$language = $this->default_language;
}
}
if(strpos($string, ".") !== false) {
$string = explode(".", $string);
if (!array_key_exists($string[1], $this->loaded_translations[$language][$string[0]])) {
if($returnStringIfNotFound) {
return $string;
}
throw new Exception('string does not exist');
}
return $this->loaded_translations[$language][$string[0]][$string[1]];
} else {
if (!array_key_exists($string, $this->loaded_translations[$language])) {
if($returnStringIfNotFound) {
return $string;
}
throw new Exception('string does not exist');
}
return $this->loaded_translations[$language][$string];
}
}
public function setLanguage($language)
{
if(in_array($language, $this->loaded_languages)) {
$this->language = $language;
}
}
}
$users = new Users($db, $auth);
$availability = new Availability($db, $users);
$places = new Places($cache, $users, $db);
$services = new Services($db, $users, $places);
$schedules = new Schedules($db, $users);