### Complete Database Operations Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Demonstrates a full workflow including connecting to the database, checking installation status, fetching single and multiple rows, performing aggregations, executing transactions, and accessing the PDO object. ```php // Connessione $db = Database::getConnection(); if (!$db->isConnected()) { die("Errore connessione database"); } if (!$db->isInstalled()) { echo "Installare OpenSTAManager"; exit; } // Query singola $user = $db->fetchRow( 'SELECT * FROM zz_utenti WHERE id_utente = :id', [':id' => 1] ); // Query multipla $users = $db->fetchArray( 'SELECT id_utente, nome FROM zz_utenti ORDER BY nome' ); // Aggregazione $count = $db->fetchOne( 'SELECT COUNT(*) FROM zz_utenti' ); // Transazione $db->transaction(function () use ($db) { $db->query('UPDATE zz_utenti SET updated_at = NOW()'); $db->query('INSERT INTO zz_logs VALUES (?, ?)'); }); // Accesso diretto PDO $pdo = $db->getPDO(); $stmt = $pdo->prepare('SELECT * FROM zz_utenti'); $stmt->execute(); ``` -------------------------------- ### Quick Installation with Git and Yarn Source: https://github.com/devcode-it/openstamanager/blob/master/README.md Clone the repository and install dependencies using Yarn for development. ```bash git clone https://github.com/devcode-it/openstamanager.git cd openstamanager # Download di composer da https://getcomposer.org/download/ yarn develop-OSM ``` -------------------------------- ### Quick Start with Included MySQL Source: https://github.com/devcode-it/openstamanager/blob/master/docker/README.md Download the docker-compose.yml file and start the OpenSTAManager and MySQL containers. Access the application at http://localhost:8080 and configure database connection details. ```bash # Download file for Docker compose wget https://raw.githubusercontent.com/devcode-it/openstamanager/refs/heads/master/docker/docker-compose.yml # Avvio docker compose up -d # se non funziona, esegui docker-compose up -d ``` -------------------------------- ### Docker Container Setup Source: https://github.com/devcode-it/openstamanager/blob/master/README.md Build and run a Docker container with Apache and MySQL for development. ```bash docker compose up --build -d ``` -------------------------------- ### Check Database Installation Status Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Determine if the database has been installed by checking for the presence of the 'zz_modules' table. Essential for initial setup checks. ```php public function isInstalled(): bool ``` ```php if (!database()->isInstalled()) { echo "OpenSTAManager non è installato"; // Mostra pagina di installazione } ``` -------------------------------- ### Complete Example: Fetching Active Customers Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/APIManager.md A full example demonstrating how to retrieve active customers with specific filters, sorting, pagination, and decoding the JSON response. It shows how to access total count and customer details. ```php // Recupera clienti attivi con paginazione $manager = new API\Manager('anagrafiche', 'retrieve', 'v1'); $request = [ 'display' => '[id,ragione_sociale,email,telefono]', 'filter[enabled]' => '[1]', 'filter[tipo]' => '[Cliente]', 'order' => '[ragione_sociale|asc]', 'limit' => 50, 'offset' => 0, ]; $json_response = $manager->retrieve($request); $data = json_decode($json_response, true); echo "Totale clienti: " . $data['total']; echo "Pagina 1 di " . ceil($data['total'] / 50); foreach ($data['data'] as $cliente) { echo $cliente['ragione_sociale'] . " - " . $cliente['email']; } ``` -------------------------------- ### isInstalled() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Verifies if the database has been installed by checking for the initial schema, specifically the `zz_modules` table. ```APIDOC ## isInstalled() ### Description Verifica se il database è stato installato (schema iniziale creato). Controlla l'esistenza della tabella `zz_modules` come indicatore di installazione. ### Return Type `bool` ### Example ```php if (!database()->isInstalled()) { echo "OpenSTAManager non è installato"; // Mostra pagina di installazione } ``` ``` -------------------------------- ### Example REST API GET Request Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/README.md An example of a GET request to the API for retrieving 'anagrafiche' (records) with filtering and ordering. ```http GET /api/v1/anagrafiche?filter[enabled]=[1]&order=[ragione_sociale] ``` -------------------------------- ### Singleton Pattern Examples Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/INDICE.md Demonstrates how to access singleton instances for core components like authentication, database connections, and application configuration. ```php // AuthOSM - Autenticazione $auth = auth_osm(); $auth = AuthOSM::getInstance(); // Database - Connessione $db = database(); $db = Database::getConnection(); // App - Configurazione $config = App::getConfig(); ``` -------------------------------- ### OpenSTAManager .env.example Configuration Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Example environment variables for OpenSTAManager, covering application settings, database connection, mail configuration, and caching/session drivers. ```bash APP_NAME=OpenSTAManager APP_ENV=production # 'local', 'production' APP_DEBUG=false # true/false APP_LOG_LEVEL=warning # error, warning, info, debug DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=openstamanager DB_USERNAME=root DB_PASSWORD=password MAIL_DRIVER=mail MAIL_HOST=smtp.mailtrap.io MAIL_PORT=465 MAIL_USERNAME= MAIL_PASSWORD= CACHE_DRIVER=file SESSION_DRIVER=file REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 ``` -------------------------------- ### Example Backup Information Extraction Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/types.md Shows how to parse a backup filename to extract structured information such as date, time, and a unique code. ```php $info = Backup::readName('OSM backup 2024-6-27 14_30_45 ABC1234.sql.gz'); // [ // 'date' => '2024-6-27', // 'time' => '14_30_45', // 'code' => 'ABC1234', // 'datetime' => '2024-06-27 14:30:45', // ] ``` -------------------------------- ### Build Dependencies with Composer and Yarn Source: https://github.com/devcode-it/openstamanager/blob/master/README.md Install PHP dependencies using Composer and frontend assets using Yarn and Gulp. ```bash php composer.phar install yarn global add gulp yarn install gulp ``` -------------------------------- ### Quick Start without MySQL Source: https://github.com/devcode-it/openstamanager/blob/master/docker/README.md Run the OpenSTAManager Docker image directly without an integrated database. This requires you to set up your own MySQL container separately. ```bash docker run -d \ -p 8080:80 \ --name openstamanager \ devcodesrl/openstamanager:latest ``` -------------------------------- ### Get Database Instance Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Returns the singleton instance of the database connection. This is a shortcut for getConnection(). ```php $db = Database::getInstance(); // Equivalente a: $db = database(); ``` -------------------------------- ### Example Select Result Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/types.md An example of how the 'results' and 'recordsFiltered' fields are populated in a select query response. ```php [ 'results' => [ ['id' => '1', 'text' => 'Mario Rossi'], ['id' => '2', 'text' => 'Anna Bianchi'], ], 'recordsFiltered' => 2, ] ``` -------------------------------- ### Complete Backup Operations Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Demonstrates how to check if a daily backup is complete, create a daily backup if not, list available backups, read backup information, create a manual backup excluding specific tables, clean up old backups, and restore a database from a backup file. ```php // Verifica stato backup giornaliero if (!Backup::isDailyComplete()) { echo "Creazione backup giornaliero..."; Backup::daily(); echo "Completato"; } // Elenco backup disponibili $backups = Backup::getList(); echo "Backup disponibili: " . count($backups); foreach ($backups as $backup) { $info = Backup::readName($backup); echo "- " . $info['datetime'] . " (" . $info['code'] . ")"; } // Crea backup manuale escludendo log if (Backup::create([ 'tabelle' => ['zz_logs', 'zz_emails_log'] ])) { echo "Backup manuale creato"; // Pulisci backup vecchi Backup::cleanup(); echo "Backup obsoleti eliminati"; } // Ripristina backup (con conferma) if ($_POST['action'] === 'restore') { $backup_file = $_POST['backup_file']; if (file_exists(Backup::getDirectory() . '/' . $backup_file)) { if (Backup::restore(Backup::getDirectory() . '/' . $backup_file)) { echo "Database ripristinato con successo"; } else { echo "Errore ripristino"; } } } ``` -------------------------------- ### Authentication Helpers Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/INDICE.md Use `auth_osm()` to get the AuthOSM instance and `auth_osm()->check()` to verify if a user is authenticated. ```php // Autenticazione auth_osm() → Ottieni istanza AuthOSM auth_osm()->check() → Verifica se autenticato ``` -------------------------------- ### Database Connection Parameters Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Configure the database connection details. Ensure these match your MySQL/MariaDB server setup. ```php $db_host = 'localhost:3306'; // Host:porta $db_username = 'root'; // Username database $db_password = 'password'; // Password database $db_name = 'openstamanager'; // Nome database $port = '3306'; // Porta (opzionale, override) ``` ```php $config = App::getConfig(); echo $config['db_host']; echo $config['db_username']; echo $config['db_name']; ``` -------------------------------- ### Throw and Handle ResourceNotFound Exception Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/errors.md Example of throwing a ResourceNotFound exception when a resource is empty and how to catch it to return a 404 HTTP response. ```php // api/Manager.php:45-49 if (empty($object)) { throw new ResourceNotFound(); } ``` ```php try { $api = new API\Manager('nonexistent', 'retrieve', 'v1'); } catch (ResourceNotFound $e) { http_response_code(404); echo json_encode(['error' => 'Risorsa non trovata']); } ``` -------------------------------- ### Ensure Config File Compilation on Installation Source: https://github.com/devcode-it/openstamanager/blob/master/KNOWN-ISSUES.md Fixes an issue where the config file was not compiled during installation if it was absent. This solution involves modifying the index.php file. ```php if ($dbo->isConnected()) { try { $microsoft = $dbo->selectOne('zz_oauth2', '*', ['nome' => 'Microsoft', 'enabled' => 1, 'is_login' => 1]); } catch (QueryException $e) { } } ``` -------------------------------- ### Alternative Build Command with Yarn Source: https://github.com/devcode-it/openstamanager/blob/master/README.md A single command to build project dependencies, requiring Git and Yarn to be installed globally. ```bash yarn run develop-OSM ``` -------------------------------- ### API Response Usage Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/types.md Demonstrates how to instantiate and populate the APIResponse object, then encode it as JSON. This is a common pattern for returning structured data from an API. ```php $response = new Response(); $response->status = 'success'; $response->data = ['id' => 1, 'name' => 'Test']; $response->message = 'Operazione completata'; echo json_encode($response); ``` -------------------------------- ### API Request Examples for Bad Request Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/APIManager.md Illustrates examples of invalid API request parameters that would result in a bad request error. This includes malformed filter fields and invalid ordering directions. ```php // Parametri non validi ?filter[invalid_field]=[value] // Ritorna errore ?order=[nonexistent|invalid_direction] // Ritorna errore ``` -------------------------------- ### API Reference File Header Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/README.md This is the standard header format for each API reference file, including class name, description, namespace, file path, and parent class. ```markdown # Nome Classe Descrizione brevissima **Namespace:** ... **File:** src/path/to/file.php **Extends:** Parent class ``` -------------------------------- ### PHP Class Property Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/README.md Illustrates the format for defining protected properties within a PHP class, including type hinting and a description. ```php protected Type $property; // Descrizione ``` -------------------------------- ### Mounting Volumes for Files and Backups (docker run) Source: https://github.com/devcode-it/openstamanager/blob/master/docker/README.md Start the OpenSTAManager container and mount local directories for persistent storage of files and backups. This ensures data is saved on the host machine. ```bash docker run -d \ -p 8080:80 \ --name openstamanager \ -v ./percorso-locale-files:/var/www/html/files \ -v ./percorso-locale-backup:/var/www/html/backup \ devcodesrl/openstamanager:latest ``` -------------------------------- ### Get First Navigable Module Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Retrieves the first module that the user can navigate to. Equivalent to auth_osm()->getFirstModule(). ```php public static function firstModule(): ?string ``` -------------------------------- ### Get Database Connection Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Retrieves the singleton database connection instance. Optionally creates a new connection with provided configuration data. ```php // Ottieni la connessione singolone $db = Database::getConnection(); // Crea una nuova connessione con parametri diversi $db_new = Database::getConnection(true, [ 'db_host' => 'localhost', 'db_username' => 'root', 'db_password' => 'password', 'db_name' => 'mydb' ]); ``` -------------------------------- ### File Logging Configuration Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/errors.md Provides an example of configuring file logging in a Laravel application via the .env file, specifying the log channel and the minimum log level to record. ```dotenv LOG_CHANNEL=stack LOG_LEVEL=warning ``` -------------------------------- ### Parameter Table Format Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/README.md Defines the markdown table structure used to detail method parameters, including name, type, requirement, default value, and description. ```markdown | Parametro | Tipo | Obbligatorio | Default | Descrizione | |-----------|------|:------------:|---------|-------------| | $param | string | Si | — | Descrizione | ``` -------------------------------- ### Get List of Backup Files Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Scans the backup directory and returns an array of available backup filenames. An optional pattern can be provided to filter the results. ```php public static function getList(?string $pattern = null): array ``` ```php // Ottieni tutti i backup $backups = Backup::getList(); echo "Backup disponibili: " . count($backups); foreach ($backups as $backup) { echo "- $backup"; } // Filtra per pattern custom $monthly_backups = Backup::getList('OSM backup YYYY-m-d H_i_s *'); ``` -------------------------------- ### Implement Pagination with limit and offset Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/APIManager.md Control the number of records returned per page using 'limit' and specify the starting record for the current page using 'offset'. This enables efficient handling of large datasets. ```php // Sintassi ?limit=100 // Record per pagina ?offset=0 // Primo record (0-based) ``` ```php $page = 1; $limit = 50; $offset = ($page - 1) * $limit; // Page 1: offset 0 (record 0-49) // Page 2: offset 50 (record 50-99) // Page 3: offset 100 (record 100-149) ``` ```json { "data": [...], "total": 245, // Totale record "limit": 50, // Record per pagina "offset": 100, // Primo record "page": 3, // Pagina attuale "pages": 5 // Numero pagine } ``` -------------------------------- ### Get All GET Data Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Retrieve all processed and sanitized GET data. This method caches the data internally after loading and sanitizing it once. ```php $get_data = Filter::getGET(); // Esempio URL: ?page=2&filter=active echo $get_data['page']; // "2" echo $get_data['filter']; // "active" ``` -------------------------------- ### Get Specific GET Parameter Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Quickly access a single GET parameter. Returns an empty string if the parameter is not found. The 'raw' option bypasses sanitization. ```php // URL: ?module=anagrafiche&id_record=5 $module = Filter::get('module'); // "anagrafiche" $id = Filter::get('id_record'); // "5" // URL: ?search=Mario Rossi $search = Filter::get('search'); // "Mario Rossi" ``` -------------------------------- ### Get User Input Value (POST/GET) Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Retrieve a specific user input parameter, prioritizing POST over GET by default. Use the 'post' or 'get' method to specify the source, or set raw to true to bypass sanitization. ```php // Leggi parametro da POST o GET (priorità POST) $nome = Filter::getValue('nome'); // Leggi solo da POST $email = Filter::getValue('email', 'post'); // Leggi valore grezzo (non sanitizzato) $raw_html = Filter::getValue('content', null, true); // Leggi solo da GET $page = Filter::getValue('page', 'get'); ``` -------------------------------- ### Configuration and Translation Helpers Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/INDICE.md Retrieve base paths, directories, URLs, and translation instances using `base_path()`, `base_dir()`, `base_url()`, and `trans_osm()` respectively. ```php // Configurazione base_path() → Percorso base base_dir() → Directory assoluta base_url() → URL base trans_osm() → Gestore traduzione ``` -------------------------------- ### create() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Creates a manual database backup with optional configuration for table exclusions. This method allows users to initiate a backup on demand and specify which tables should be ignored. ```APIDOC ## create() ### Description Creates a manual database backup with optional configuration for table exclusions. ### Method `static public function create(array $ignores = [])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **$ignores** (array) - Optional - An array of tables to exclude from the backup. Can specify tables by name or by pattern. ### Request Example ```php // Full backup if (Backup::create()) { echo "Backup created successfully"; } // Selective backup excluding log tables if (Backup::create([ 'tabelle' => ['zz_logs', 'zz_emails_log'] ])) { echo "Selective backup created"; } ``` ### Response #### Success Response (bool) * **true** - Indicates the backup was created successfully. #### Response Example ```php true ``` ### Throws * **Exception** - If the backup fails. ``` -------------------------------- ### Input Handling Helpers Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/INDICE.md Sanitize and retrieve input parameters using `filter($key)`, `post($key)` for POST data, and `get($key)` for GET data. ```php // Input filter($key) → Get + sanitizza parametro post($key) → Leggi da POST get($key) → Leggi da GET ``` -------------------------------- ### Accessing Database Configuration Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/types.md Demonstrates how to retrieve database configuration values after they have been loaded by the application. ```php $config = App::getConfig(); $host = $config['db_host']; $db_name = $config['db_name']; ``` -------------------------------- ### getCurrentStatus() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Gets the status of the most recent login attempt. ```APIDOC ## getCurrentStatus() ### Description Returns the status of the most recent login attempt. ### Method `getCurrentStatus(): string` ### Parameters None ### Response #### Success Response (string) - Returns a string indicating the status. Possible values are: 'success', 'failed', 'disabled', 'unauthorized', 'already_logged_in'. ### Example ```php $auth = auth_osm(); $auth->attempt('user@example.com', 'pwd'); $status = $auth->getCurrentStatus(); if ($status === 'failed') { echo "Credenziali non valide"; } ``` ``` -------------------------------- ### Create Daily Backup Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/README.md Initiate a daily backup process using the Backup::daily() method. ```php Backup::daily(); ``` -------------------------------- ### Configure Automatic Backups Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Set up automatic daily backups, including the time of execution, data retention period, and compression. Specify the directory where backups will be stored. ```php $backup = [ 'daily' => true, // Abilita backup giornaliero 'time' => '03:00', // Orario backup (HH:MM) 'retention' => 7, // Giorni di retention 'compression' => true, // Compressione gzip ]; $backup_dir = DOCROOT . '/backups'; // Directory backup ``` -------------------------------- ### Access System Path Constants Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Demonstrates how to access and echo the defined system path constants. This shows the resolved values for DOCROOT, ROOTDIR, and BASEURL. ```php echo DOCROOT; // /var/www/html/openstamanager echo ROOTDIR; // /openstamanager echo BASEURL; // https://example.com/openstamanager ``` -------------------------------- ### User Login Workflow Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/INDICE.md Illustrates the sequence of operations for user authentication, session creation, and redirection upon successful login. ```text Filter.md → Ricevi credenziali POST ↓ AuthOSM.md → Autentica utente ↓ AuthOSM.md → Crea sessione ↓ App.md → Reindirizza al primo modulo ``` -------------------------------- ### Filter::getGET() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Retrieves all processed and sanitized GET data. This method caches the data after the first call. ```APIDOC ## Filter::getGET() ### Description Retrieves all processed and sanitized data from the GET request. The data is loaded and sanitized only once. ### Method Signature `public static function getGET(): array` ### Parameters None ### Request Example ```php $get_data = Filter::getGET(); // Example URL: ?page=2&filter=active echo $get_data['page']; // "2" echo $get_data['filter']; // "active" ``` ### Response #### Success Response - **Return Value** (array) - An associative array containing the sanitized GET data. ``` -------------------------------- ### Creating a Database Log Entry Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/errors.md Shows how to create a new log entry in the database, capturing user actions like failed logins, associated table, record ID, and client IP address. ```php Log::create([ 'id_utente' => auth_osm()->getUser()->id_utente, 'action' => 'login_failed', 'table' => 'zz_utenti', 'id_record' => 0, 'ip' => get_client_ip(), ]); ``` -------------------------------- ### Get MySQL/MariaDB Version Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Retrieve the version string of the MySQL or MariaDB server. Useful for compatibility checks and feature detection. ```php public function getMySQLVersion(): string ``` ```php $version = database()->getMySQLVersion(); if (version_compare($version, '8.0', '>=')) { echo "MySQL 8.0 o superiore"; } ``` -------------------------------- ### getInstance() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Provides a shortcut to `getConnection()`, returning the singleton instance of the database connection. It is equivalent to calling `database()`. ```APIDOC ## `getInstance` Database::getInstance ### Description Returns the singleton instance of the connection. This is a shortcut for `getConnection()` and is equivalent to calling `database()`. ### Method `public static function getInstance(): Database` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Response #### Success Response - Returns an instance of `Database`. ### Request Example ```php $db = Database::getInstance(); // Equivalent to: $db = database(); ``` ``` -------------------------------- ### Filter::get() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Provides quick access to a specific GET parameter's value. It can return the raw value if requested. ```APIDOC ## Filter::get() ### Description Retrieves the value of a specific parameter from the GET data. Allows fetching the raw, unsanitized value. ### Method Signature `public static function get(string $property, bool $raw = false): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters - **$property** (string) - Required - The name of the GET parameter. - **$raw** (bool) - Optional - If true, returns the raw, unsanitized value. Defaults to false. ### Request Example ```php // URL: ?module=anagrafiche&id_record=5 $module = Filter::get('module'); // "anagrafiche" $id = Filter::get('id_record'); // "5" // URL: ?search=Mario Rossi $search = Filter::get('search'); // "Mario Rossi" ``` ### Response #### Success Response - **Return Value** (string) - The value of the GET parameter or an empty string if not found. ``` -------------------------------- ### Get All POST Data Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Retrieve all processed and sanitized POST data. This method caches the data internally after loading and sanitizing it once. ```php $post_data = Filter::getPOST(); foreach ($post_data as $key => $value) { echo "$key = $value"; } // Accesso diretto if (isset($post_data['username'])) { $username = $post_data['username']; } ``` -------------------------------- ### Backup::daily() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Initiates the creation of a daily full database backup. It ensures no duplicate backups are made on the same day. ```APIDOC ## Backup::daily() ### Description Creates a full daily database backup. This method automatically checks if a backup for the current day already exists to prevent duplicates. It compresses the SQL file into a .gz format and saves it in the backup directory. ### Method `public static function daily(): bool` ### Return Type `bool` - `true` if the backup was created successfully, `false` if a backup for the current day already exists. ### Throws - `Exception` - If the backup process fails. ### Example ```php try { if (Backup::daily()) { echo "Daily backup created"; } else { echo "Daily backup already exists"; } } catch (Exception $e) { echo "Backup error: " . $e->getMessage(); } ``` ``` -------------------------------- ### Get Authenticated User Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Retrieves the currently authenticated user object. Returns null if no user is logged in. Equivalent to auth_osm()->getUser(). ```php $user = AuthOSM::user(); ``` -------------------------------- ### Restore Backup with File Existence Check (PHP) Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/errors.md Attempts to restore a backup file after verifying its existence. Throws an exception if the file is not found, which is then caught and reported. ```php try { $backup_file = Backup::getDirectory() . '/' . $_POST['backup']; if (!file_exists($backup_file)) { throw new Exception('Backup non trovato'); } Backup::restore($backup_file); } catch (Exception $e) { echo "Errore: " . $e->getMessage(); } ``` -------------------------------- ### Daily Backup Workflow Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/INDICE.md Describes the steps involved in performing a daily backup, including verification, creation, database dumping, compression, archiving, and cleanup of old backups. ```text Backup.md → Verifica backup odierno ↓ Backup.md → Se non esiste, crea backup ↓ Database.md → Dump database ↓ Backup.md → Comprimi e archivia ↓ Backup.md → Pulisci backup vecchi ``` -------------------------------- ### Create Manual Database Backup Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Initiates a manual database backup. Supports excluding specific tables or patterns from the backup process. Returns true on success. ```php if (Backup::create()) { echo "Backup creato con successo"; } ``` ```php if (Backup::create([ 'tabelle' => ['zz_logs', 'zz_emails_log'] ])) { echo "Backup selettivo creato"; } ``` -------------------------------- ### Get Query Builder Instance Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Access the Eloquent Query Builder instance for constructing dynamic database queries. Enables fluent query construction. ```php public function getQueryBuilder(): Builder ``` ```php $db = database(); $users = $db->getQueryBuilder() ->from('zz_utenti') ->where('enabled', 1) ->orderBy('nome') ->get(); ``` -------------------------------- ### Application Configuration Structure Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Outlines the structure of the complete application configuration array, detailing settings for database, language, formatting, debugging, assets, backup, and authentication. ```php [ // Database 'db_host' => string, 'db_username' => string, 'db_password' => string, 'db_name' => string, 'port' => ?string, 'db_options' => array, // Lingua 'lang' => string, // 'it_IT', 'en_US' // Formattazione 'formatter' => [ 'timestamp' => 'd/m/Y H:i', 'date' => 'd/m/Y', 'time' => 'H:i', 'number' => [ 'decimals' => ',', 'thousands' => '.', ], ], // Debug 'debug' => bool, // Asset 'assets' => [ 'css' => [], 'print' => [], 'js' => [], ], // Backup 'backup' => [ 'daily' => bool, 'time' => string, // 'HH:MM' 'retention' => int, 'compression' => bool, ], // Autenticazione 'password_options' => [], 'brute_options' => [], ] ``` -------------------------------- ### Get PDO Object Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Database.md Retrieve the native PHP PDO object for complex queries. Useful for direct database interaction when the Query Builder is insufficient. ```php public function getPDO(): PDO ``` ```php $db = database(); $pdo = $db->getPDO(); $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); $stmt->execute([1]); $result = $stmt->fetch(PDO::FETCH_ASSOC); ``` -------------------------------- ### Get Intended URL Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Retrieves the previously saved intended URL. Use this to redirect users to their desired page after login if the URL is valid and accessible. ```php public function getIntendedUrl(): ?string ``` ```php $intended = auth_osm()->getIntendedUrl(); if ($intended && auth_osm()->canAccessIntendedUrl()) { header("Location: $intended"); } ``` -------------------------------- ### Retrieve List of Enabled Modules Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Shows how to access the list of enabled modules from the database using the Modules::getList() method and iterate through them. ```php // Accesso da codice $modules = Modules::getList(); // Array di moduli foreach ($modules as $module) { if ($module['enabled']) { echo $module['title']; } } ``` -------------------------------- ### Backup Configuration Settings Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Shows essential configuration parameters for automated backups, including enabling daily backups, setting the execution time, defining retention policies, and enabling compression. Also includes the directory for storing backups and database credentials for mysqldump. ```php // Backup automatico 'backup' => [ 'daily' => true, // Abilita backup giornaliero 'time' => '03:00', // Orario esecuzione 'retention' => 7, // Giorni di retention 'compression' => true, // Compressione .gz ], // Directory backup 'backup_dir' => DOCROOT . '/backups', // Credenziali database per mysqldump 'db_host' => 'localhost', 'db_username' => 'root', 'db_password' => 'password', ``` -------------------------------- ### Get Backup Directory Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Retrieves the absolute path to the directory where backup files are stored. Typically this is a subdirectory named 'backups' within the document root. ```php public static function getDirectory(): string ``` ```php $backup_dir = Backup::getDirectory(); echo $backup_dir; // /var/www/html/openstamanager/backups // Elenco file backup $files = scandir(Backup::getDirectory()); ``` -------------------------------- ### OpenSTAManager Directory Structure Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Illustrates the standard directory layout for OpenSTAManager, showing the location of configuration files, source code, modules, plugins, assets, backups, storage, public-facing files, and database migration files. ```text {DOCROOT}/ ├── config.inc.php ← File configurazione ├── bootstrap/ │ ├── app.php ← Bootstrap Laravel │ └── providers.php ← Service providers ├── src/ ← Codice principale ├── modules/ ← Moduli funzionali ├── plugins/ ← Plugin aggiuntivi ├── assets/ │ └── dist/ ← Asset compilati │ ├── css/ │ ├── js/ │ └── img/ ├── backups/ ← Backup database ├── storage/ │ ├── logs/ ← Log applicazione │ └── cache/ ← Cache file ├── public/ ← Web root │ ├── index.php ← Entry point │ └── uploads/ ← File caricati └── database/ └── migrations/ ← Migrazioni Laravel ``` -------------------------------- ### Get Brute-Force Timeout Seconds Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Returns the number of seconds remaining before the brute-force protection timeout expires. This is useful for informing the user how long they need to wait. ```php $seconds = AuthOSM::getBruteTimeout(); echo "Riprova tra $seconds secondi"; ``` -------------------------------- ### Get Specific POST Parameter Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Quickly access a single POST parameter. Returns an empty string if the parameter is not found. The 'raw' option bypasses sanitization. ```php // Leggi parametro POST $username = Filter::post('username'); // Leggi valore non processato $html_content = Filter::post('content', true); // Con controllo if (!empty(Filter::post('email'))) { $email = Filter::post('email'); } // Alternativa: getValue() $username = Filter::getValue('username', 'post'); ``` -------------------------------- ### select() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AJAX.md Finds selection options for a requested resource. It supports searching, pagination, and generating links for selected items. ```APIDOC ## select() ### Description Locates selection options starting from the requested resource. ### Method `public static function select(string $resource, array|string $elements = [], ?string $search = null, int $page = 0, int $length = 100, array $options = []): array` ### Parameters #### Path Parameters * `resource` (string) - Required - Name of the resource (e.g., 'anagrafica', 'articolo'). * `elements` (array|string) - Optional - Array or comma-separated string of IDs. * `search` (?string) - Optional - Search term for filtering. * `page` (int) - Optional - Page number for pagination. Defaults to 0. * `length` (int) - Optional - Number of results per page. Defaults to 100. * `options` (array) - Optional - Additional options (links, filters, etc.). Defaults to []. ### Return Type `array` ### Response Structure ```php [ 'results' => [ 0 => [ 'id' => '1', 'text' => 'Mario Rossi', 'link' => 'http://example.com/?id=1', // If link option is set ], // ... ], 'recordsFiltered' => 45, // Total records (with filters) ] ``` ### Available Options ```php [ 'link' => 'page=:id&action=edit', // Link template 'filters' => ['enabled' => 1], // Additional filters 'order' => 'nome', // Sorting field ] ``` ### Details Loads `ajax_select.php` and `ajax/select.php` to process the resource. ### Example ```php // Select contacts $results = AJAX::select('anagrafica', [], 'mario', 0, 100); foreach ($results['results'] as $item) { echo $item['text']; // Contact name } // With generated link $results = AJAX::select( 'anagrafica', [], null, 0, 100, ['link' => '?module=contacts&id_record=:id'] ); // With filters $results = AJAX::select( 'article', [], 'engine', 0, 50, ['filters' => ['enabled' => 1]] ); ``` ``` -------------------------------- ### Get Available Status Codes Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Retrieves a list of available status codes used within the authentication system. This can be helpful for understanding or debugging different authentication states. ```php $statuses = AuthOSM::getStatus(); // [ // 'success' => 1, // 'failed' => 0, // 'disabled' => 2, // 'unauthorized' => 5, // 'already_logged_in' => 6, // ] ``` -------------------------------- ### Authentication Status Usage Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/types.md Example of checking the current authentication status against the defined constants. This pattern is used to conditionally execute logic based on login success or failure. ```php $status = auth_osm()->getCurrentStatus(); if ($status === 'success') { // Login riuscito } ``` -------------------------------- ### firstModule() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Retrieves the first navigable module. ```APIDOC ## firstModule() ### Description Retrieves the first navigable module. ### Method `public static function firstModule(): ?string` ### Return Type `string|null` ### Equivalent to `auth_osm()->getFirstModule()` ``` -------------------------------- ### HTMLPurifier Sanitization Example Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/errors.md Demonstrates how HTMLPurifier removes non-whitelisted tags and attributes to prevent XSS attacks. By default, it sanitizes content to prevent potentially harmful HTML. ```php $content = ''; $safe = Filter::purify($content); // Risultato: "" (vuoto - tag rimosso) ``` -------------------------------- ### database() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Performs a database backup and saves it to a specified file path. This method utilizes `mysqldump` to create a raw SQL dump of the database. ```APIDOC ## database() ### Description Performs a database backup and saves it to a specified file path using `mysqldump`. ### Method `static public function database(string $filepath): bool` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **$filepath** (string) - Required - The output file path for the database backup. ### Request Example ```php $backup_file = '/backups/manual_backup.sql'; if (Backup::database($backup_file)) { echo "Database dump completed"; // Compress the file shell_exec("gzip $backup_file"); echo "File compressed"; } ``` ### Response #### Success Response (bool) * **true** - Indicates the database dump was successful. #### Response Example ```php true ``` ### Throws * **Exception** - If the dump fails. ``` -------------------------------- ### Configure OpenSTAManager Settings Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md This PHP code defines essential configuration parameters for OpenSTAManager, including database connection details, language, date/time formatting, debug mode, and automatic backup settings. Ensure these are correctly set for your environment. ```php 'd/m/Y H:i', 'date' => 'd/m/Y', 'time' => 'H:i', 'number' => [ 'decimals' => ',', 'thousands' => '.', ], ]; // Modalità debug (disabilitata in produzione) $debug = false; // Asset aggiuntivi $assets = [ 'css' => [], 'print' => [], 'js' => [], ]; // Configurazione backup automatico $backup = [ 'daily' => true, 'time' => '03:00', 'retention' => 7, 'compression' => true, ]; // Opzioni database PDO $db_options = [ PDO::ATTR_TIMEOUT => 30, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; ``` -------------------------------- ### Reading Database Log Entries Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/errors.md Demonstrates how to query the database logs to retrieve specific entries, such as failed login attempts from a particular IP address within the last 5 minutes. ```php $logs = Log::where('action', 'login_failed') ->where('ip', get_client_ip()) ->where('created_at', '>', now()->subMinutes(5)) ->get(); ``` -------------------------------- ### Backup::getList() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Backup.md Fetches a list of available backup files from the backup directory. Supports filtering by a custom pattern. ```APIDOC ## Backup::getList() ### Description Fetches a list of available backup files from the backup directory. Supports filtering by a custom pattern. If no pattern is provided, it uses the default `PATTERN` constant. ### Method `public static function getList(?string $pattern = null): array` ### Parameters #### Query Parameters - **`$pattern`** (string | null) - Optional - A pattern to filter the backup files. Defaults to `null`, which uses the `PATTERN` constant. ### Return Type `array` - An array of backup filenames, ordered by date in descending order. ### Example ```php // Get all backups $backups = Backup::getList(); echo "Available backups: " . count($backups); foreach ($backups as $backup) { echo "- $backup"; } // Filter by custom pattern $monthly_backups = Backup::getList('OSM backup YYYY-m-d H_i_s *'); ``` ``` -------------------------------- ### Get Last Login Timestamp Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/AuthOSM.md Retrieves the timestamp of the user's last login in 'YYYY-MM-DD HH:MM:SS' format. Use to display last login information to the user. ```php public function getLastLogin(): ?string ``` ```php $last = auth_osm()->getLastLogin(); echo "Ultimo accesso: " . $last; ``` -------------------------------- ### Instantiate API Manager Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/APIManager.md Instantiate the API Manager with the resource, type of operation, and API version. Catches ResourceNotFound exception if the resource does not exist. ```php try { $manager = new API\Manager('anagrafiche', 'retrieve', 'v1'); } catch (ResourceNotFound $e) { echo "Risorsa non trovata"; } ``` -------------------------------- ### Filter::getValue() Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/Filter.md Retrieves a parameter value from user inputs (POST or GET). It prioritizes POST requests unless a specific method is specified. It can also return the raw, unsanitized value. ```APIDOC ## Filter::getValue() ### Description Retrieves the value of a parameter from user inputs (POST or GET), with options to specify the method and whether to return the raw value. ### Method Signature `public static function getValue(string $property, ?string $method = null, bool $raw = false): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters - **$property** (string) - Required - The name of the parameter to retrieve. - **$method** (?string) - Optional - The input method to use ('post', 'get', or null for auto-detection with POST priority). Defaults to null. - **$raw** (bool) - Optional - If true, returns the raw, unsanitized value. Defaults to false. ### Request Example ```php // Read parameter from POST or GET (POST priority) $nome = Filter::getValue('nome'); // Read only from POST $email = Filter::getValue('email', 'post'); // Read raw value (unsanitized) $raw_html = Filter::getValue('content', null, true); // Read only from GET $page = Filter::getValue('page', 'get'); ``` ### Response #### Success Response - **Return Value** (string) - The value of the parameter or an empty string if not found. ``` -------------------------------- ### API Manager Constructor Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/api-reference/APIManager.md Initializes the API Manager with resource, type, and version. It loads resource configuration and validates parameters. Throws ResourceNotFound if the resource does not exist. ```APIDOC ## Constructor ### Description Loads the resource configuration from the database and validates the parameters. ### Parameters #### Path Parameters - **$resource** (string) - Required - Name of the resource ('anagrafiche', 'articoli') - **$type** (string) - Required - Operation type ('retrieve', 'create', 'update', 'delete') - **$version** (string) - Required - API version ('v1', 'v2') ### Return Type - **Manager** - Manager instance ### Throws - **ResourceNotFound** - If the resource does not exist ### Example ```php try { $manager = new API\Manager('anagrafiche', 'retrieve', 'v1'); } catch (ResourceNotFound $e) { echo "Risorsa non trovata"; } ``` ``` -------------------------------- ### Manage Backup Operations Source: https://github.com/devcode-it/openstamanager/blob/master/_autodocs/configuration.md Check the status of daily backups and initiate a backup if it hasn't been completed. Access configuration settings like daily backup status, time, and retention using App::getConfig(). ```php // Verifica configurazione $config = App::getConfig(); $backup_enabled = $config['backup']['daily']; $backup_time = $config['backup']['time']; $retention = $config['backup']['retention']; // Giorni // Operazioni backup if (!Backup::isDailyComplete()) { Backup::daily(); } ```