allerta-vvf/server/core.php

684 lines
24 KiB
PHP
Raw Normal View History

2020-04-27 23:27:39 +02:00
<?php
require_once 'vendor/autoload.php';
use Tracy\Debugger;
2020-04-27 23:27:39 +02:00
2020-07-03 12:10:41 +02:00
if(!file_exists("config.php") && !file_exists("../../config.php")) header('Location: install/install.php');
require_once 'config.php';
session_start();
date_default_timezone_set('Europe/Rome');
class tools{
2020-06-17 12:05:10 +02:00
public $check_cf_ip;
public function __construct($check_cf_ip){
$this->check_cf_ip = $check_cf_ip;
}
2020-05-29 12:13:33 +02:00
public function validate_form_data($data, $noempty=true, $value=null){
if(!is_array($data) && isset($data) && !empty($data)){
if(substr($data, 0, 6) == '$post-'){
$data = substr($data, 6);
if(isset($_POST[$data])){
$data = $_POST[$data];
}
}
}
if(is_array($data)){
if(empty($data)){
2020-05-29 12:13:33 +02:00
$continue = false;
return false;
} else {
2020-05-29 12:13:33 +02:00
$continue = true;
}
2020-05-29 12:13:33 +02:00
if($continue){
foreach($data as $key=>$value){
if(!is_array($value) && isset($value) && !empty($value)){
if(substr($value, 0, 6) == '$post-'){
$value = substr($value, 6);
if(isset($_POST[$value])){
$value = $_POST[$value];
}
}
}
2020-05-29 12:13:33 +02:00
if($continue){
if(!is_array($value)){
bdump($value);
bdump("_");
2020-05-29 12:13:33 +02:00
$validazione = $this->validate_form_data($value, $noempty, $value);
if(!$validazione){
2020-05-29 12:13:33 +02:00
$continue = false;
return false;
}
}
}
}
2020-05-29 12:13:33 +02:00
if($continue){
return true;
}
}
} else if(isset($data)) {
if(!empty($data)){
2020-05-29 12:13:33 +02:00
if(!is_null($value)){
return $value == $data;
} else {
bdump($data);
return true;
}
} else {
return false;
}
} else {
return false;
}
}
public 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'];
}
2020-06-17 12:05:10 +02:00
if($this->check_cf_ip){
if(!empty($_SERVER['HTTP_CF_CONNECTING_IP'])){
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
}
return $ip;
}
public function get_page_url(){
if(!empty($_SERVER["HTTPS"])){
if($_SERVER["HTTPS"] == "on"){
$protocol = "https";
} else {
$protocol = "http";
}
} else {
$protocol = "http";
}
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
}
public function redirect($url){
if (!headers_sent()){
header('Location: '.$url);
exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>';
}
}
function extract_unique($data){
$array2=[];
foreach($data as $arr){
if(is_array($arr)){
$tmp = $this->extract_unique($arr);
foreach($tmp as $temp){
if(!is_array($temp)){
if(!in_array($temp, $array2)){
$array2[] = $temp;
}
}
}
} else {
if(!in_array($arr, $array2)){
$array2[] = $arr;
}
}
}
return $array2;
}
2020-07-12 10:57:02 +02:00
public function createKey($hashCode=false, $lenght=128){
$code = str_replace(".", "", bin2hex(random_bytes(10)).base64_encode(openssl_random_pseudo_bytes(30)));
if($hashCode){
$code = $code.".".hash("sha256", $code);
}
return $code;
}
public function sanitize($string, $htmlAllowed=false, $htmlPurifierOptions=[]){
if($htmlAllowed){
$config = HTMLPurifier_Config::createDefault();
foreach ($htmlPurifierOptions as $key => $value) {
$config->set($key, $value);
}
$purifier = new HTMLPurifier($config);
$string = $purifier->purify($string);
} else {
$string = htmlspecialchars($string);
}
return $string;
}
2020-04-27 23:27:39 +02:00
}
class database{
protected $db_host = DB_HOST;
protected $db_dbname = DB_NAME;
protected $db_username = DB_USER;
protected $db_password = DB_PASSWORD;
2020-05-20 22:49:36 +02:00
public $connection = null;
public $query = null;
public $stmt = null;
public $load_from_file = true;
public $options = [];
public $options_cache_file = null;
2020-05-29 12:13:33 +02:00
public function connect(){
try {
2020-05-20 22:49:36 +02:00
$this->connection = new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_dbname, $this->db_username, $this->db_password);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
exit($e->getMessage());
}
}
2020-06-05 17:56:22 +02:00
public function isOptionsEmpty(){
2020-06-05 21:03:13 +02:00
return empty($this->exec("SELECT * FROM `%PREFIX%_options`;", true));
2020-06-05 17:56:22 +02:00
}
public function __construct(){
2020-05-29 12:13:33 +02:00
$this->connect();
2020-06-05 21:03:13 +02:00
if($this->isOptionsEmpty()){
2020-06-05 17:56:22 +02:00
header('Location: install/install.php');
}
$file_infos = pathinfo(array_reverse(debug_backtrace())[0]['file']);
2020-09-27 00:57:37 +02:00
if(strpos($file_infos['dirname'], 'resources') !== false) {
$this->options_cache_file = "../../options.txt";
} else {
$this->options_cache_file = "options.txt";
}
if($this->load_from_file){
if(file_exists($this->options_cache_file)/* && time()-@filemtime($this->options_cache_file) < 604800*/){
$this->options = unserialize(file_get_contents($this->options_cache_file), ['allowed_classes' => false]);
} else {
$this->options = $this->exec("SELECT * FROM `%PREFIX%_options` WHERE `enabled` = 1", true);
file_put_contents($this->options_cache_file, serialize( $this->options ));
}
}
}
public function close(){
2020-05-20 22:49:36 +02:00
$this->connection = null;
}
public function exec($sql1, $fetch=false, $param=null, ...$others_params){
try{
//$this->connection->beginTransaction();
array_unshift($others_params,$sql1);
bdump($others_params);
$toReturn = [];
foreach($others_params as $sql){
$sql = str_replace("%PREFIX%", DB_PREFIX, $sql);
bdump($sql);
$this->stmt = $this->connection->prepare($sql);
if(!is_null($param)){
$this->query = $this->stmt->execute($param);
} else {
$this->query = $this->stmt->execute();
}
bdump($this->query);
if($fetch == true){
if(count($others_params) > 1) {
$toReturn[] = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$toReturn = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
}
//$this->connection->commit();
//$this->stmt->closeCursor();
return $toReturn;
} catch (PDOException $e) {
2020-05-29 12:13:33 +02:00
print "Error!: " . $e->getMessage() . "<br/>";
//$this->connection->rollBack();
die();
}
}
2020-05-29 12:13:33 +02:00
public function exists($table, $id){
2020-07-03 12:10:41 +02:00
$risultato = $this->exec("SELECT :table FROM `%PREFIX%_services` WHERE id = :id;", true, [":table" => $table, ":id" => $id]);
return !empty($risultato);
}
2020-06-06 18:58:37 +02:00
public function getOption($name){
if(defined($name)){
return constant($name);
} else {
//$option = $this->exec("SELECT `value` FROM `%PREFIX%_options` WHERE `name` = :name AND `enabled` = 1;", true, [":name" => $name]);
//return empty($option) ? "" : $option[0]["value"];
foreach($this->options as $option){
if($name == $option["name"]){
return empty($option["value"]) ? "" : $option["value"];
}
}
2020-06-06 18:58:37 +02:00
}
}
2020-09-27 00:57:37 +02:00
public function increment($increment){
bdump($increment);
$sql = "UPDATE `%PREFIX%_profiles` SET `services`= services + 1 WHERE id IN ($increment);";
2020-06-07 13:56:12 +02:00
$this->exec($sql, false);
}
2020-09-27 00:57:37 +02:00
public function getIncrement($id){
bdump($id);
2020-09-27 00:57:37 +02:00
$sql = "SELECT `increment` FROM `%PREFIX%_services` WHERE `id` = :id";
$increment = $this->exec($sql, true, [":id" => $id])[0]['increment'];
bdump($increment);
return $increment;
}
2020-09-27 00:57:37 +02:00
public function decrease($id){
$sql = "UPDATE `%PREFIX%_profiles` SET `services`= services - 1 WHERE id IN ({$this->getIncrement($id)});";
$this->exec($sql, false);
}
2020-09-27 00:57:37 +02:00
public function increment_trainings($increment){
bdump($increment);
$sql = "UPDATE `%PREFIX%_profiles` SET `trainings`= trainings + 1 WHERE id IN ($increment);";
2020-07-01 21:00:53 +02:00
$this->exec($sql, false);
}
2020-09-27 00:57:37 +02:00
public function getIncrement_trainings($id){
2020-07-01 21:00:53 +02:00
bdump($id);
2020-09-27 00:57:37 +02:00
$sql = "SELECT `increment` FROM `%PREFIX%_trainings` WHERE `id` = :id";
$increment = $this->exec($sql, true, [":id" => $id])[0]['increment'];
bdump($increment);
return $increment;
2020-07-01 21:00:53 +02:00
}
2020-09-27 00:57:37 +02:00
public function decrease_trainings($id){
$sql = "UPDATE `%PREFIX%_profiles` SET `trainings`= trainings - 1 WHERE id IN ({$this->getIncrement_trainings($id)});";
2020-07-01 21:00:53 +02:00
$this->exec($sql, false);
}
2020-09-27 00:57:37 +02:00
public function add_service($data, $codice, $uscita, $rientro, $capo, $autisti, $personale, $luogo, $note, $tipo, $increment, $inserted_by){
$autisti = implode(",", $autisti);
bdump($autisti);
$personale = implode(",", $personale);
bdump($personale);
2020-09-27 00:57:37 +02:00
$increment = implode(",", $increment);
bdump($increment);
$sql = "INSERT INTO `%PREFIX%_services` (`id`, `data`, `codice`, `uscita`, `rientro`, `capo`, `autisti`, `personale`, `luogo`, `note`, `tipo`, `increment`, `inserted_by`) VALUES (NULL, :data, :codice, :uscita, :rientro, :capo, :autisti, :personale, :luogo, :note, :tipo, :increment, :inserted_by);";
$this->exec($sql, false, [":data" => $data, ":codice" => $codice, "uscita" => $uscita, ":rientro" => $rientro, ":capo" => $capo, ":autisti" => $autisti, ":personale" => $personale, ":luogo" => $luogo, ":note" => $note, ":tipo" => $tipo, ":increment" => $increment, ":inserted_by" => $inserted_by]);
$this->increment($increment);
}
2020-07-03 12:10:41 +02:00
public function remove_service($id){
2020-09-27 00:57:37 +02:00
$this->decrease($id);
2020-07-03 12:10:41 +02:00
$this->exec("DELETE FROM `%PREFIX%_services` WHERE `id` = :id", true, [":id" => $id]);
}
2020-09-27 00:57:37 +02:00
public function change_service($id, $data, $codice, $uscita, $rientro, $capo, $autisti, $personale, $luogo, $note, $tipo, $increment, $inserted_by){
2020-07-03 12:10:41 +02:00
$this->remove_service($id); // TODO: update, instead of removing and re-adding (with another id)
2020-09-27 00:57:37 +02:00
$this->add_service($data, $codice, $uscita, $rientro, $capo, $autisti, $personale, $luogo, $note, $tipo, $increment, $inserted_by);
}
2020-07-01 21:00:53 +02:00
2020-09-27 00:57:37 +02:00
public function add_training($data, $name, $start_time, $end_time, $capo, $personale, $luogo, $note, $increment, $inserted_by){
2020-07-01 21:00:53 +02:00
$personale = implode(",", $personale);
bdump($personale);
2020-09-27 00:57:37 +02:00
$increment = implode(",", $increment);
bdump($increment);
$sql = "INSERT INTO `%PREFIX%_trainings` (`id`, `data`, `name`, `inizio`, `fine`, `capo`, `personale`, `luogo`, `note`, `increment`, `inserted_by`) VALUES (NULL, :data, :name, :start_time, :end_time, :capo, :personale, :luogo, :note, :increment, :inserted_by);";
$this->exec($sql, false, [":data" => $data, ":name" => $name, "start_time" => $start_time, ":end_time" => $end_time, ":capo" => $capo, ":personale" => $personale, ":luogo" => $luogo, ":note" => $note, ":increment" => $increment, ":inserted_by" => $inserted_by]);
$this->increment_trainings($increment);
2020-07-01 21:00:53 +02:00
}
2020-07-03 12:10:41 +02:00
public function remove_training($id){
2020-09-27 00:57:37 +02:00
$this->decrease_trainings($id);
2020-07-01 21:00:53 +02:00
bdump($id);
2020-07-03 12:10:41 +02:00
$this->exec("DELETE FROM `%PREFIX%_trainings` WHERE `id` = :id", true, [":id" => $id]);
2020-07-01 21:00:53 +02:00
}
2020-09-27 00:57:37 +02:00
public function change_training($id, $data, $name, $start_time, $end_time, $capo, $personale, $luogo, $note, $increment, $inserted_by){
2020-07-03 12:10:41 +02:00
$this->remove_training($id); // TODO: update, instead of removing and re-adding (with another id)
2020-07-01 21:00:53 +02:00
bdump("removed");
2020-09-27 00:57:37 +02:00
$this->add_training($data, $name, $start_time, $end_time, $capo, $personale, $luogo, $note, $increment, $inserted_by);
2020-07-01 21:00:53 +02:00
}
}
final class Role {
//https://github.com/delight-im/PHP-Auth/blob/master/src/Role.php
const GUEST = \Delight\Auth\Role::AUTHOR;
const BASIC_VIEWER = \Delight\Auth\Role::COLLABORATOR;
const FULL_VIEWER = \Delight\Auth\Role::CONSULTANT;
const EDITOR = \Delight\Auth\Role::CONSUMER;
const SUPER_EDITOR = \Delight\Auth\Role::CONTRIBUTOR;
const DEVELOPER = \Delight\Auth\Role::DEVELOPER;
const TESTER = \Delight\Auth\Role::CREATOR;
const EXTERNAL_VIEWER = \Delight\Auth\Role::REVIEWER;
const ADMIN = \Delight\Auth\Role::ADMIN;
const SUPER_ADMIN = \Delight\Auth\Role::SUPER_ADMIN;
public function __construct() {}
}
class user{
private $database = null;
private $tools = null;
public $auth = null;
2020-09-13 13:38:18 +02:00
public $authenticated = false;
public function __construct($database, $tools){
$this->database = $database;
$this->tools = $tools;
2020-06-17 22:08:59 +02:00
$this->auth = new \Delight\Auth\Auth($database->connection, $tools->get_ip(), DB_PREFIX."_", false);
2020-09-13 13:38:18 +02:00
$this->authenticated = $this->auth->isLoggedIn();
}
2020-05-29 12:13:33 +02:00
public function authenticated(){
2020-09-13 13:38:18 +02:00
return $this->authenticated;
}
2020-05-20 22:49:36 +02:00
public function requirelogin(){
2020-05-29 12:13:33 +02:00
if(!$this->authenticated()){
2020-06-06 18:58:37 +02:00
if($this->database->getOption("intrusion_save")){
if($this->database->getOption("intrusion_save_info")){
2020-09-27 00:57:37 +02:00
$params = [":page" => $this->tools->get_page_url(), ":ip" => $this->tools->get_ip(), ":data" => date("d/m/Y"), ":ora" => date("H:i.s"), ":servervar" => json_encode($_SERVER)];
} else {
2020-09-27 00:57:37 +02:00
$params = [":page" => $this->tools->get_page_url(), ":ip" => "redacted", ":data" => date("d/m/Y"), ":ora" => date("H:i.s"), ":servervar" => json_encode(["redacted" => "true"])];
}
2020-09-27 00:57:37 +02:00
$sql = "INSERT INTO `%PREFIX%_intrusions` (`id`, `page`, `data`, `ora`, `ip`, `servervar`) VALUES (NULL, :page, :data, :ora, :ip, :servervar)";
2020-05-29 12:13:33 +02:00
$this->database->exec($sql, false, $params);
}
2020-06-06 18:58:37 +02:00
$this->tools->redirect($this->database->getOption("web_url"));
}
}
2020-05-28 23:33:10 +02:00
public function requireRole($role, $adminGranted=true){
2020-09-03 22:57:04 +02:00
return $this->auth->hasRole($role) || $adminGranted && $role !== Role::DEVELOPER && $this->auth->hasRole(Role::ADMIN) || $role !== Role::DEVELOPER && $this->auth->hasRole(Role::SUPER_ADMIN);
}
public function name($replace=false){
if(isset($_SESSION['_user_name'])){
2020-10-02 20:52:10 +02:00
$return_name = $_SESSION['_user_name'];
} else {
$check_name = $this->nameById($this->auth->getUserId());
if($check_name){
$return_name = $check_name;
} else {
2020-10-02 20:52:10 +02:00
$return_name = "not authenticated";
}
2020-10-02 20:52:10 +02:00
}
if($replace){
return str_replace(" ", "_", $return_name);
} else {
2020-10-02 20:52:10 +02:00
return $return_name;
}
}
public function nameById($id){
2020-05-29 12:13:33 +02:00
$profiles = $this->database->exec("SELECT `name` FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $id]);
if(!empty($profiles)){
if(!is_null($profiles[0]["name"])){
return(s($profiles[0]["name"],false));
} else {
2020-05-29 12:13:33 +02:00
$user = $this->database->exec("SELECT `username` FROM `%PREFIX%_users` WHERE id = :id;", true, [":id" => $id]);
if(!empty($user)){
if(!is_null($user[0]["username"])){
return(s($user[0]["username"],false));
} else {
return false;
}
} else {
return false;
}
}
} else {
return false;
}
}
public function hidden(){
2020-05-29 12:13:33 +02:00
$profiles = $this->database->exec("SELECT `name` FROM `%PREFIX%_profiles` WHERE hidden = 1;", true);
return $profiles;
}
2020-07-03 11:38:41 +02:00
public function available($name){
$user = $this->database->exec("SELECT available FROM `%PREFIX%_users` WHERE name = :name;", true, [":name" => $name]);
2020-05-20 22:49:36 +02:00
if(empty($user)){
return false;
} else {
2020-07-03 11:38:41 +02:00
return $user[0]["available"];
}
}
public function info(){
2020-09-03 22:57:04 +02:00
return array("autenticated" => $this->authenticated(), "id" => $this->auth->getUserId(), "name" => $this->name(), "full_viewer" => $this->requireRole(Role::FULL_VIEWER), "tester" => $this->requireRole(Role::TESTER), "developer" => $this->requireRole(Role::DEVELOPER));
}
2020-09-26 22:46:04 +02:00
public function login($name, $password, $remember_me, $twofa=null){
if(!empty($name)){
if(!empty($password)){
try {
2020-09-26 22:46:04 +02:00
if ($remember_me) {
// keep logged in for one year
$rememberDuration = (int) (60 * 60 * 24 * 365.25);
} else {
// do not keep logged in after session ends
$rememberDuration = null;
}
$this->auth->loginWithUsername($name, $password, $rememberDuration);
}
catch (\Delight\Auth\InvalidEmailException $e) {
return ["status" => "error", "code" => 010, "text" => "Wrong email address"];
die('Wrong email address');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
return ["status" => "error", "code" => 011, "text" => "Wrong password"];
die('Wrong password');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
return ["status" => "error", "code" => 012, "text" => "Email not verified"];
die('Email not verified');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
return ["status" => "error", "code" => 020, "text" => "Too many requests"];
die('Too many requests');
}
if($this->auth->isLoggedIn()){
2020-05-30 13:22:52 +02:00
$this->log("Login", $this->auth->getUserId(), $this->auth->getUserId(), date("d/m/Y"), date("H:i.s"));
2020-05-29 12:13:33 +02:00
$user = $this->database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $this->auth->getUserId()]);
if(!empty($user)){
if(is_null($user[0]["name"])){
$_SESSION['_user_name'] = $this->auth->getUsername();
} else {
$_SESSION['_user_name'] = $user[0]["name"];
}
$_SESSION['_user_hidden'] = $user[0]["hidden"];
$_SESSION['_user_disabled'] = $user[0]["disabled"];
2020-09-27 13:23:37 +02:00
$_SESSION['_user_chief'] = $user[0]["chief"];
return true;
}
}
} else {
return ["status" => "error", "code" => 002];
}
} else {
return ["status" => "error", "code" => 001];
}
}
2020-05-29 14:57:13 +02:00
public function log($action, $changed, $editor, $date, $time){
$params = [":action" => $action, ":changed" => $changed, ":editor" => $editor, ":date" => $date, ":time" => $time];
$sql = "INSERT INTO `%PREFIX%_log` (`id`, `action`, `changed`, `editor`, `date`, `time`) VALUES (NULL, :action, :changed, :editor, :date, :time)";
2020-05-29 12:13:33 +02:00
$this->database->exec($sql, false, $params);
}
public function logout(){
try {
2020-10-02 20:52:10 +02:00
$this->auth->logOut();
$this->auth->destroySession();
2020-10-02 20:52:10 +02:00
$this->log("Logout", $this->auth->getUserId(), $this->auth->getUserId(), date("d/m/Y"), date("H:i.s"));
}
catch (\Delight\Auth\NotLoggedInException $e) {
die('Not logged in');
}
2020-04-28 11:09:38 +02:00
}
2020-06-17 22:08:59 +02:00
2020-09-27 00:57:37 +02:00
public function add_user($email, $name, $username, $password, $birthday, $capo, $autista, $hidden, $disabled, $inserted_by){
2020-06-17 22:24:14 +02:00
$userId = $this->auth->admin()->createUserWithUniqueUsername($email, $password, $username);
if($userId){
2020-09-24 23:46:00 +02:00
$hidden = $hidden ? 1 : 0;
$disabled = $disabled ? 1 : 0;
$capo = $capo ? 1 : 0;
$autista = $autista ? 1 : 0;
2020-09-27 13:23:37 +02:00
$sql = "INSERT INTO `%PREFIX%_profiles` (`hidden`, `disabled`, `name`, `chief`, `autista`) VALUES (:hidden, :disabled, :name, :chief, :autista)";
$this->database->exec($sql, false, [":hidden" => $hidden, ":disabled" => $disabled, ":name" => $name, ":chief" => $capo, ":autista" => $autista]);
if($capo == 1){
$this->auth->admin()->addRoleForUserById($userId, Role::FULL_VIEWER);
}
2020-09-27 00:57:37 +02:00
$this->log("User created", $userId, $inserted_by, date("d/m/Y"), date("H:i.s"));
return $userId;
} else {
return $false;
2020-06-17 22:24:14 +02:00
}
2020-06-17 22:08:59 +02:00
}
2020-09-27 00:57:37 +02:00
public function remove_user($id, $removed_by){
$this->database->exec("DELETE FROM `%PREFIX%_users` WHERE `id` = :id", true, [":id" => $id], "DELETE FROM `%PREFIX%_profiles` WHERE `id` = :id");
2020-09-27 00:57:37 +02:00
$this->log("User removed", null, $removed_by, date("d/m/Y"), date("H:i.s"));
}
2020-04-27 23:27:39 +02:00
}
2020-07-02 21:45:45 +02:00
class translations{
public $loaded_languages = ["en", "it"];
2020-07-02 21:45:45 +02:00
public $default_language = "en";
public $language = null;
2020-07-02 21:45:45 +02:00
public $client_languages = ["en"];
public $loaded_translations = [];
public $filename = "";
public function client_languages() {
2020-09-02 16:57:56 +02:00
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
2020-09-04 22:50:08 +02:00
$client_languages = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
2020-09-02 16:57:56 +02:00
} else {
2020-09-04 22:50:08 +02:00
$client_languages = "en-US;q=0.5,en;q=0.3";
2020-09-02 16:57:56 +02:00
}
2020-07-02 21:45:45 +02:00
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 $key=>$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(){
$this->client_languages = $this->client_languages();
foreach($this->client_languages as $language){
if(in_array($language, $this->loaded_languages) && $this->language == null){
2020-07-02 21:45:45 +02:00
$this->language = $language;
}
}
if($this->language == null){
$this->language = "en";
}
2020-09-01 12:27:32 +02:00
$file_infos = pathinfo(array_reverse(debug_backtrace())[0]['file']);
2020-09-27 00:57:37 +02:00
if(strpos($file_infos['dirname'], 'resources') !== false) {
2020-09-01 12:27:32 +02:00
$this->filename = "../../translations/".$this->language."/".$file_infos['basename'];
} else {
$this->filename = "translations/".$this->language."/".$file_infos['basename'];
}
if (file_exists($this->filename)){
$this->loaded_translations = array_merge(require("translations/".$this->language."/base.php"),require($this->filename));
} else {
try{
$this->loaded_translations = require("translations/".$this->language."/base.php");
} catch(Exception $e) {
$this->loaded_translations = require("../../translations/".$this->language."/base.php");
}
}
2020-07-02 21:45:45 +02:00
}
public function translate($string){
2020-07-02 23:49:41 +02:00
bdump($string);
2020-07-02 21:45:45 +02:00
try {
if (!array_key_exists($string, $this->loaded_translations))
2020-07-02 21:45:45 +02:00
throw new Exception ('string does not exist');
return $this->loaded_translations[$string];
} catch (\Exception $e) {
2020-07-02 23:49:41 +02:00
bdump($this->filename);
bdump($e, $string);
2020-07-02 21:45:45 +02:00
return $string;
}
}
}
function init_class($enableDebugger=true, $headers=true){
2020-07-02 21:45:45 +02:00
global $tools, $database, $user, $translations;
if(!isset($tools) && !isset($database) && !isset($translations)){
$database = new database();
2020-06-17 12:05:10 +02:00
$tools = new tools($database->getOption("check_cf_ip"));
$user = new user($database, $tools);
2020-07-02 21:45:45 +02:00
$translations = new translations();
}
if($headers){
2020-10-02 20:52:10 +02:00
$csp = "default-src 'self' data: *.tile.openstreetmap.org nominatim.openstreetmap.org; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: *.tile.openstreetmap.org; object-src; style-src 'self' 'unsafe-inline'; require-trusted-types-for 'style';";
2020-09-30 22:35:22 +02:00
header("Content-Security-Policy: $csp");
header("X-Content-Security-Policy: $csp");
header("X-WebKit-CSP: $csp");
header("X-XSS-Protection: 1; mode=block");
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Feature-Policy: autoplay 'none'; camera 'none'; microphone 'none'; payment 'none'");
}
2020-09-13 13:41:55 +02:00
//var_dump($user);
//exit();
2020-10-02 20:52:10 +02:00
if($enableDebugger){
2020-09-13 13:18:54 +02:00
//if($user->requireRole(Role::DEVELOPER)){
2020-09-03 22:57:04 +02:00
Debugger::enable(Debugger::DEVELOPMENT, __DIR__ . '/error-log');
2020-09-13 13:18:54 +02:00
//} else {
//Debugger::enable(Debugger::PRODUCTION, __DIR__ . '/error-log');
//}
2020-10-02 20:52:10 +02:00
}
2020-09-01 12:27:32 +02:00
bdump(get_included_files());
bdump($translations->loaded_translations);
2020-07-02 23:49:41 +02:00
}
function t($string, $echo=true){
global $translations;
if($echo){
echo $translations->translate($string);
} else {
return $translations->translate($string);
}
}
function s($string, $echo=true, $htmlAllowed=false, $htmlPurifierOptions=[]){
global $tools;
if($echo){
echo $tools->sanitize($string, $htmlAllowed, $htmlPurifierOptions);
} else {
return $tools->sanitize($string, $htmlAllowed, $htmlPurifierOptions);
}
}