Servidor Api RestFull – EDAS3 – Archivo Electrónico

Esta es otra versión del proyecto EDAS. Prácticamente es una copia de la versión EDAS2, pero lo más importante y relevante, es que se le ha añadido un Api RestFull para que otros sistemas, mediante este API, pueda gestionar el 100% de las funcionalidades de la aplicación.

Objetivo

A la funcionalidad que tiene el aplicativo EDAS se le ha añadido un Api RestFull (server) para que los sistemas que dispongan de las credenciales para conectarse puedan realizar el 100% de la funcionalidad del aplicativo.

Técnicamente, tiene como objetivo el poder facilitar un API RestFull a cualquier aplicativo desarrollado en PHPRunner. Uno de sus puntos importantes es la identificación de las credenciales de usuario de acceso y el mantenimiento de estos datos para todas las acciones que se hagan.

DEMO: https://fhumanes.com/edas3/

Usuario/Password:  admin/admin o user1/user1 o user2/user2

API RestFullPOST/PUT/GET  http://fhumanes.com/edas3/restapi/v1/{acción}

Solución Técnica

En este artículo se explica cómo se ha realizado el API, para conocer cómo se ha hecho la aplicación, por favor, consultar el artículo de EDAS

El desarrollo del servidor del API RestFull se ha realizado utilizando el Framework SLIM 4.0. En la codificación se reutiliza la conexión de la base de datos de PHPRunner y su API de acceso a as bases de datos, pero todo el resto del código es PHP. Desde mi punto de vista muy fácil de leer y entender y muy accesible para aquellos que sepan leer bien código PHP fuera de PHPRunner.

Se ha desarrollado y testeado utilizando Microsoft Visual Studio (PHP) y para las funciones de testeo del cliente del Api, he utilizado Postman.

En el proyecto, la programación del server Api RestFull está:

Los ficheros que hay que personalizar/codificar son:

Todas las peticiones acceden a index.php y es el director de todo el proceso o lógica del sistema

index.php
<?php

/**
 *
 * @About:      API Interface
 * @File:       index.php
 * @Date:       $Date:$ Agosot0 -2022
 * @Version:    $Rev:$ 1.0
 * @Developer:  Federico Guzman || Modificado por Fernando Humanes para PHP 8.1
 **/

/* Los headers permiten acceso desde otro dominio (CORS) a nuestro REST API o desde un cliente remoto via HTTP
 * Removiendo las lineas header() limitamos el acceso a nuestro RESTfull API a el mismo dominio
 * Nótese los métodos permitidos en Access-Control-Allow-Methods. Esto nos permite limitar los métodos de consulta a nuestro RESTfull API
 * Mas información: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
 **/

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: text/html; charset=utf-8');
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');

session_cache_limiter(false);

include_once '../include/Config.php';

require_once("../../include/dbcommon.php"); // DataBase PHPRunner
global $conn; // Connection data base of PHPRunner

// Debug
$debugCode = true;
custom_error(1,"URL ejecutada: ".$_SERVER["REQUEST_URI"]); // To debug

// use App\Models\Db;  // Utilizamos la conexión de PHPRunner
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Selective\BasePath\BasePathMiddleware;
use Slim\Factory\AppFactory;

require_once __DIR__ . '/../libs/autoload.php';

$app = AppFactory::create();
$app->addBodyParsingMiddleware();

$app->addRoutingMiddleware();
// $app->add(new BasePathMiddleware($app)); // No usar si se ejecuta en subdirectorio
$app->addErrorMiddleware(true, true, true);


$app->setBasePath(SCRIPTS_DIR);


// --------------------------------------------------------------------------------------

/* Usando POST para Crear la autenticación de los usuarios */

$app->post('/login', function(Request $request, Response $response) {
    global $errorMessages;
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';
    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // check for required params
    $param = $request->getParsedBody();
    $verify = verifyRequiredParams(array('login', 'password'), $param, $request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    $data = $request->getParsedBody();

    $responseBody = array();
    $param = array();
    //capturamos los parametros recibidos y los almacenamos como un nuevo array
    $param['login']  = $data['login'];
    $param['password'] = $data['password'];
    
    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();

    /* Podemos crear un metodo que almacene el nuevo auto, por ejemplo: */
    $login = $db->createSession($param, $request, $response);

    if ( is_array($login) ) {
        $responseBody["error"] = false;
        $responseBody["message_num"] = '001';
        $responseBody["message"] = $errorMessages['001'];
        $responseBody["token"] = $login['uuid'];
        $response->getBody()->write(json_encode($responseBody));

        session_write_close();  // Save Session

        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    } else {
        $responseBody["error"] = true;
        $responseBody["message_num"] = '002';
        $responseBody["message"] = $errorMessages['002'];
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
});

// --------------------------------------------------------------------------------------

/* Usando POST para consultar Directorios */

$app->post('/dir', function(Request $request, Response $response) {
    global $errorMessages;
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';   

    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verify Token of Access
    $verify = controlSession($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // check for required params
    $param = $request->getParsedBody();
    $verify = verifyRequiredParams(array('path'), $param, $request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();

    $responseBody = array();

    $verify = $db->pathDirectory($param, $request, $response); // Control del path enviado
    
    if ($verify['error']) { // Si ha habido error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }

    /* Analizar directorio y obtener directorios y ficheros */
    $arr_row = $db->listDirectory($verify,$request, $response);


    $responseBody["error"] = false;
    $responseBody["message_num"] = '000';
    $responseBody["message"] = $arr_row; 
    $response->getBody()->write(json_encode($responseBody));

    return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(200);

});
// --------------------------------------------------------------------------------------

/* Usando POST para Añadir  Documentos del directorio posicionado */

$app->post('/documentAdd', function(Request $request, Response $response) {

    global $errorMessages;
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';   

    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verify Token of Access
    $verify = controlSession($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // check for required params
    $param = $request->getParsedBody();

    $verify = verifyRequiredParams(array('code', 'name', 'locked'), $param, $request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }

    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();

    $USER_PRIV = $db->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory

    // Recuperar directorio y ficheros del último directorio
    $selectDirectory = $USER_PRIV['selectedDirectory'];

    $error = $db->accessDocumentWrite($param,$request, $response );   // Control acceso la directorio para escribir

    $responseBody = array();
    if ( $error <> '000') { // Si no es '000'' es que es error.
        $responseBody["error"] = true;
        $responseBody["message_num"] = $error;
        $responseBody["message"] =str_replace("{1}",$selectDirectory,$errorMessages[$error]);
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
    $error = $db->addDocument($param, $request, $response);  // Add row of Document

    $code = $param['code'];
    if ( !is_array($error)) { // Si no es '000'' es que es error.
        $responseBody["error"] = true;
        $responseBody["message_num"] = $error;
        $responseBody["message"] =str_replace("{1}",$code,$errorMessages[$error]);
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
    $lastID = $error['lastID'];    // last document INSERT
    // All OK
    $responseBody["error"] = false;
    $responseBody["message_num"] = '000';
    $responseBody["message"] =  array("documentCreated" => $lastID);
    $response->getBody()->write(json_encode($responseBody));

    return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(200);

  
});
// --------------------------------------------------------------------------------------

/* Usando POST para view,update y delete ..... Documentos del directorio posicionado */

$app->put('/document/{action}/{id_document}', function(Request $request, Response $response, array $args) {

    global $errorMessages;
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';   

    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verify Token of Access
    $verify = controlSession($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // check for required params
    $param = array();
    $param['action'] = $args['action'];
    $param['id_document'] = $args['id_document'];

    $verify = verifyRequiredParams(array('action','id_document'), $param, $request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verificación de los valores de los parámetros || attributes
    if( !in_array($param['action'],array('view','update','delete')) || !is_numeric($param['id_document']))  { // Si la acción es correcta y el id es un número
        $responseBody["error"] = true;
        $responseBody["message_num"] = '013';
        $responseBody["message"] = $errorMessages['013'];
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
  
    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();

    $data = $db->accessDocument($param,$request, $response );   // Control acceso la directorio y documento

    $id_document = $param['id_document'];     // CODE of File
    $responseBody = array();
    if ( !is_array($data)) { // Si no es array es que es error y si es array son los datos del documento
        $responseBody["error"] = true;
        $responseBody["message_num"] = $data;
        $responseBody["message"] = str_replace("{1}",$id_document,$errorMessages[$data]);
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
    
// --------------------------------------------------- VIEW -------------------------------------------------------
    if ( $param['action'] == 'view' ) { // VIEW

        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] = $data; 
        $response->getBody()->write(json_encode($responseBody));

        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    } 
// -------------------------------------------------- DELETE ---------------------------------------------------------
    if ( $param['action'] == 'delete' ) { // DELETE

        $db->deleteDocument($param); 

        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] =  str_replace("{1}",$id_document,$errorMessages['014']);
        $response->getBody()->write(json_encode($responseBody));

        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    }
// -------------------------------------------------- UPDATE -----------------------------------------------------------
    if ( $param['action'] == 'update' ) { // UPDATE
        // check for required params
        $param2 = $request->getParsedBody();
        $verify = verifyRequiredParams(array('code', 'name', 'locked'), $param2, $request, $response);
        if (is_array($verify)) { // Si es una array, es que hay error
            $response->getBody()->write(json_encode($verify));
            return $response
                ->withHeader('content-type', 'application/json')
                ->withStatus(400);
        }
        $param2['id_document'] =  $id_document;
        $error = $db->updateDocument($param2, $request, $response);  // Update row of Document

        if ($error <> '000') { // ha habido error en la actualziación
            $responseBody["error"] = true;
            $responseBody["message_num"] = $error;
            $responseBody["message"] = str_replace("{1}",$param['code'],$errorMessages[$error]);
            $response->getBody()->write(json_encode($responseBody));
            return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);    
        }
   
        // All OK
        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] =  str_replace("{1}",$id_document,$errorMessages['017']);
        $response->getBody()->write(json_encode($responseBody));

        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);

    }
});
// --------------------------------------------------------------------------------------
/* Usando POST para list, add, view, update y delete ..... ficheros de un Documento del directorio posicionado */

$app->put('/document/{id_document}/file/{action}', function(Request $request, Response $response, array $args) {

    global $errorMessages;
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';   

    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verify Token of Access
    $verify = controlSession($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // check for required params
    $param = array();
    $param['action'] = $args['action'];
    $param['id_document'] = $args['id_document'];

    $verify = verifyRequiredParams(array('action','id_document'), $param, $request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verificación de los valores de los parámetros || attributes
    if( !in_array($param['action'],array('list','add','view','update','delete')) || !is_numeric($param['id_document']))  { // Si la acción es correcta y el id es un número
        $responseBody["error"] = true;
        $responseBody["message_num"] = '013';
        $responseBody["message"] = $errorMessages['013'];
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
  
    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();

    $data = $db->accessDocument($param,$request, $response );   // Control acceso la directorio y documento

    $id_document = $param['id_document'];     // CODE of File
    $responseBody = array();
    if ( !is_array($data)) { // Si no es array es que es error y si es array son los datos del documento
        $responseBody["error"] = true;
        $responseBody["message_num"] = $data;
        $responseBody["message"] = str_replace("{1}",$id_document,$errorMessages[$data]);
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
        // check for required params
        $param = $request->getParsedBody();

// --------------------------------------------------- LIST -------------------------------------------------------
if ( $args['action'] == 'list' ) { 
    $data = $db->listFile($param, $request, $response, $args );

    $id_document = $args['id_document'];
    if (!is_array($data)) { // Error 
        $responseBody["error"] = true;
        $responseBody["message_num"] = $data;
        $responseBody["message"] = str_replace("{1}",$id_document,$errorMessages[$data]);;
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
    $responseBody["error"] = false;
    $responseBody["message_num"] = '000';
    $responseBody["message"] = $data; 
    $response->getBody()->write(json_encode($responseBody));

    return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(200);
} 

// --------------------------------------------------- ADD -------------------------------------------------------
if ( $args['action'] == 'add' ) { 
    $verify = verifyRequiredParams(array('usrName','type','base64File'), $param, $request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    $data = $db->addFile($param, $request, $response, $args );
    $id_document = $args['id_document'];
    $usrName = $param['usrName'];

    if (!is_array($data)) { // Error 
        $responseBody["error"] = true;
        $responseBody["message_num"] = $data;
        $responseBody["message"] = str_replace("{2}",$usrName,str_replace("{1}",$id_document,$errorMessages[$data]));
        $response->getBody()->write(json_encode($responseBody));
        return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(400);
    }
    $responseBody["error"] = false;
    $responseBody["message_num"] = '000';
    $responseBody["message"] = $data; 
    $response->getBody()->write(json_encode($responseBody));

    return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(200);
}  

// --------------------------------------------------- VIEW -------------------------------------------------------
    if ( $args['action'] == 'view' ) { 
        $verify = verifyRequiredParams(array('usrName'), $param, $request, $response);
        if (is_array($verify)) { // Si es una array, es que hay error
            $response->getBody()->write(json_encode($verify));
            return $response
                ->withHeader('content-type', 'application/json')
                ->withStatus(400);
        }
        $data = $db->viewFile($param, $request, $response, $args );
        $id_document = $args['id_document'];
        $usrName = $param['usrName'];

        if (!is_array($data)) { // Error 
            $responseBody["error"] = true;
            $responseBody["message_num"] = $data;
            $responseBody["message"] = str_replace("{2}",$usrName,str_replace("{1}",$id_document,$errorMessages[$data]));
            $response->getBody()->write(json_encode($responseBody));
            return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
        }
        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] = $data; 
        $response->getBody()->write(json_encode($responseBody));
    
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    }  
// -------------------------------------------------- DELETE ---------------------------------------------------------
    if ( $args['action'] == 'delete' ) { // DELETE
        $verify = verifyRequiredParams(array('usrName'), $param, $request, $response);
        if (is_array($verify)) { // Si es una array, es que hay error
            $response->getBody()->write(json_encode($verify));
            return $response
                ->withHeader('content-type', 'application/json')
                ->withStatus(400);
        }
        $data = $db->deleteFile($param, $request, $response, $args );
        $id_document = $args['id_document'];
        $usrName = $param['usrName'];

        if (!is_array($data)) { // Error 
            $responseBody["error"] = true;
            $responseBody["message_num"] = $data;
            $responseBody["message"] = str_replace("{2}",$usrName,str_replace("{1}",$id_document,$errorMessages[$data]));
            $response->getBody()->write(json_encode($responseBody));
            return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
        }
        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] = $data; 
        $response->getBody()->write(json_encode($responseBody));
    
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    }  
// -------------------------------------------------- UPDATE -----------------------------------------------------------
    if ( $args['action'] == 'update' ) { // UPDATE
        $verify = verifyRequiredParams(array('usrName','type','base64File'), $param, $request, $response);
        if (is_array($verify)) { // Si es una array, es que hay error
            $response->getBody()->write(json_encode($verify));
            return $response
                ->withHeader('content-type', 'application/json')
                ->withStatus(400);
        }
        $data = $db->updateFile($param, $request, $response, $args );
        $id_document = $args['id_document'];
        $usrName = $param['usrName'];
    
        if (!is_array($data)) { // Error 
            $responseBody["error"] = true;
            $responseBody["message_num"] = $data;
            $responseBody["message"] = str_replace("{2}",$usrName,str_replace("{1}",$id_document,$errorMessages[$data]));
            $response->getBody()->write(json_encode($responseBody));
            return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
        }
        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] = $data; 
        $response->getBody()->write(json_encode($responseBody));
    
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
    } 
});

// --------------------------------------------------------------------------------------
/* Usando POST para las variablers de session */

$app->post('/session', function(Request $request, Response $response) {
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';   

    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verify Token of Access
    $verify = controlSession($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();
    $USER_PRIV = $db->restoreUser($request, $response);

    $responseBody = array();

    $responseBody["error"] = false;
    $responseBody["message_num"] = '000';
    // $responseBody["_SESSION"] =  $_SESSION; 
    $responseBody["USER_PRIV"] =  $USER_PRIV; 
    $response->getBody()->write(json_encode($responseBody));

    return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(200);
// --------------------------------------------------------------------------------------
});
// --------------------------------------------------------------------------------------
/* Usando GET para obtener la información del usuario conectado */

$app->get('/user', function(Request $request, Response $response) {
    /* Include functions required for the execution of the actions */
    include_once '../include/Function.php';   

    // Verify Token Authenticate Security
    $verify = authenticate($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    // Verify Token of Access
    $verify = controlSession($request, $response);
    if (is_array($verify)) { // Si es una array, es que hay error
        $response->getBody()->write(json_encode($verify));
        return $response
            ->withHeader('content-type', 'application/json')
            ->withStatus(400);
    }
    /* Podemos inicializar la conexion a la base de datos si queremos hacer uso de esta para procesar los parametros con DB */
    require_once '../include/DbEdas.php';
    $db = new DbEdas();
    $USER_PRIV = $db->restoreUser($request, $response);

    $responseBody = array();

    $responseBody["error"] = false;
    $responseBody["message_num"] = '000';
    $responseBody["message"] =  $USER_PRIV['dataUser']; 
    $response->getBody()->write(json_encode($responseBody));

    return $response
        ->withHeader('content-type', 'application/json')
        ->withStatus(200);
// --------------------------------------------------------------------------------------
});

/* corremos la aplicación */
$app->run();

/*********************** USEFULL FUNCTIONS **************************************/

El fichero Config.php, como de su nombre se deduce, es el fichero de configuración de URL de ubicación de los archivos, del Api de Autorización y de los mensajes que utiliza para comunicar los problemas.

Config.php
<?php

//
//  Database configuration
//

//
//  URI raíz de la aplicación
//

define('SCRIPTS_DIR', '/edas3/restapi/v1'); 

// Path root of Directory files in File System or Disc
define('FILES_DIR', 'C:/Apache24/htdocs/edas3/files'); 
define('FILES_ROOT', 'C:/Apache24/htdocs/edas3'); 

// In Server Linux
// define('FILES_DIR', '/home/u637977917/public_html/edas3/files'); 
// define('FILES_ROOT', '/home/u637977917/public_html/edas3'); 
 

//referencia generado con MD5(uniqueid(<some_string>, true))
define('API_KEY','3d524a53c110e4c22463b10ed32cef9d');

/**
 * API Response HTTP CODE
 * Used as reference for API REST Response Header
 *
 */
/*
200 	OK
201 	Created
304 	Not Modified
400 	Bad Request
401 	Unauthorized
403 	Forbidden
404 	Not Found
422 	Unprocessable Entity
500 	Internal Server Error
*/

// Error messages to facilitate their translation

$errorMessages = array(
    "001" => "Usuario identificado correctamente!",
    "002" => "Error al identificación de usuario. Por favor intenta nuevamente.",
    "003" => "Required field(s) or attribute(s) {1} is missing or empty",
    "004" => "Email address is not valid",
    "005" => "Acceso denegado. Token inválido",
    "006" => "Falta token de autorización",
    "007" => "Token Expirado. Token inválido",
    "008" => "{1} directory does not exist",
    "009" => "Directory {1} has no access",
    "010" => "document {1} not found in current directory",
    "011" => "Dcoument {1} not access",
    "012" => "The work directory has not been set",
    "013" => "The attribute action is incorrect or the ID is not a number",
    "014" => "Document {1} Deleted.",
    "015" => "One or more of the types of the variables are not correct",
    "016" => "New Code {1} already exists in this directory",
    "017" => "Document {1} Updated.",
    "018" => "Directory {1} has been eliminated",
    "019" => "In the document {1}, the file {2} has not been found",
    "020" => "In the document {1}, the file {2} already exists",
    "021" => "In the document {1}, the file {2} has been inserted",
    "022" => "change",
    "023" => "change",
    "024" => "change",
    "025" => "change",
    "026" => "change"

);

?>

El fichero Function.php contiene funciones PHP, que no acceden a base de datos y que se utilizan directamente desde el fichero index.php

Function.php
<?php
/*********************** USEFULL FUNCTIONS **************************************/

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Selective\BasePath\BasePathMiddleware;
use Slim\Factory\AppFactory;


/**
 * Verificando los parametros requeridos en el método
 */
function verifyRequiredParams($required_fields, $request_params,  Request  $request, Response $response)
{
    global $errorMessages;
    $error = false;
    $error_fields = "";

    // $request_params = $request->getParsedBody();

    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }

    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $responseBody = array();
        $responseBody["error"] = true;
        $responseBody["message_num"] = '003';
        $responseBody["message"] = str_replace("{1}",substr($error_fields, 0, -2),$errorMessages['003']); 

        return $responseBody;
    }
    return true;
}

/**
 * Validando parametro email si necesario; un Extra ;)
 */
function validateEmailRest($email, Request $request, Response $response)
{
    global $errorMessages;
    $responseBody = array();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $responseBody["error"] = true;
        $responseBody["message_num"] = '004';
        $responseBody["message"] = $errorMessages['004']; 
        return $responseBody;
    }
    return true;
}

/**
 * Revisa si la consulta contiene un Header "Authorization" para validar
 */
function authenticate(Request $request, Response $response)
{
    global $errorMessages;
    // Getting request headers
    $headers = $request->getHeaders();
    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        // get the api key
        $token = $headers['Authorization'];

        // validating api key
        if (!($token[0] == API_KEY)) { //API_KEY declarada en Config.php

            // api key is not present in users table
            $responseBody["error"] = true;
            $responseBody["message_num"] = '005';
            $responseBody["message"] = $errorMessages['005']; 
            // Error 401
            return $responseBody;
        } else {
            //procede utilizar el recurso o metodo del llamado
            return true;
        }
    } else {
        // api key is missing in header
        $responseBody["error"] = true;
        $responseBody["message_num"] = '006';
        $responseBody["message"] = $errorMessages['006']; 
        // error 400
        return $responseBody;
    }
}

/**
 * Revisa si la consulta contiene un Header "token-user" para validar y recuperar session
 */
function controlSession(Request $request, Response $response)
{
    global $errorMessages;
    // Getting request headers
    $headers = $request->getHeaders();
    // Debug
    custom_error(2,"Header: ".json_encode($headers, true)); // To debug
    // Verifying Authorization Header
    if (isset($headers['token-user'])) {
        // get the api key
        $token = $headers['token-user'];
        $token = $token[0];
        $rs = DB::Query("SELECT * FROM edas_session_api WHERE uuid = '$token'");
        $data = $rs->fetchAssoc();
        if (!$data)
        {
            // Token is not present in control session table
            $responseBody["error"] = true;
            $responseBody["message_num"] = '005';
            $responseBody["message"] = $errorMessages['005']; 
            // Error 401
            return $responseBody;
        }

        // validating token
        if ($data['dateOfExpiry'] < now()) { // Expiry

            // Expiry
            $responseBody["error"] = true;
            $responseBody["message_num"] = '007';
            $responseBody["message"] = $errorMessages['007']; 
            // Error 401
            return $responseBody;
        } else {
            //procede utilizar el recurso o metodo del llamado
            
            // Update date of Expiry the Token
            $data2 = array();
            $keyvalues2 = array();
            $data2["dateOfExpiry"] = date('Y-m-d H:i:s', strtotime('3 hour'));
            $keyvalues2["id_edas_session_api"] = $data["id_edas_session_api"];
            DB::Update("edas_session_api", $data2, $keyvalues2 );
            // Restore Session of the User
            //  $session_id = $data['session'];  // Restaura la session
            // session_destroy();
            // session_id($session_id);
            // session_start();

            return true;
        }
    } else {
        // api key is missing in header
        $responseBody["error"] = true;
        $responseBody["message_num"] = '006';
        $responseBody["message"] = $errorMessages['006']; 
        // error 400
        return $responseBody;
    }
}
?>

Y el fichero DbEdas.php es una clase de PHP que contiene todas las funciones que requieren de la información de la base de datos.

DbEdas.php
<?php

/**
 *
 * @About:      Gestión de EDAS
 * @File:       DbEdas.php
 * @Date:       $Date:$ ADec. 2022
 * @Version:    $Rev:$ 1.0
 * @Developer:  fernando humanes
 **/

    use Psr\Http\Message\ResponseInterface as Response;
    use Psr\Http\Message\ServerRequestInterface as Request;
    use Selective\BasePath\BasePathMiddleware;
    use Slim\Factory\AppFactory;

class DbEdas
{

    private $connDB;

    function __construct()
    {
        global $conn; // Connection data base of PHPRunner
        $this->connDB = $conn;
    }

    public function createSession($param, Request $request, Response $response)
    {   
        global $conn; // Connection data base of PHPRunner
        $login = $param['login'];
        $password = $param['password'];
        // $password = MD5($password );
        // Delete session expired
        $now = now();
        DB::Delete("edas_session_api", "dateOfExpiry < '$now'" );
        // Check User and password
        $sql = "SELECT * FROM edas_user WHERE login = '$login' AND password= '$password' AND active = 1";
        $rs = DB::Query($sql);
        $data = $rs->fetchAssoc();
        if (!is_array($data)) {
            return false;
        }
        // Delete field "password"
        unset($data['password']);
        // Create enviroment of Session
        // session_regenerate_id(true);  // Init SESSION.
        // $session_id = session_id();
        $USER_PRIV = array();
        $USER_PRIV['dataUser']=$data; // Save info of User identified
        $uuid = $this->guidv4();
        // Save session in Data Base
        $data2 = array();
        $data2["uuid"] = $uuid;
        $data2["session"]  = session_id();
        $data2["creationDate"]  = now();
        $data2["dateOfExpiry"]  = date('Y-m-d H:i:s', strtotime('3 hour'));
        $data2['sessionVariables'] = json_encode($USER_PRIV,true);
        DB::Insert("edas_session_api", $data2 );
        
        return array("uuid"=>$uuid);
    }

    /**
     * Analiza el path de Directorios solicitado y crea estructura en variables de entorno
     */
    public function pathDirectory( array $param, Request $request, Response $response)
    {
        global $errorMessages;

        $document = $param['path'];  // New pathdirectory
        $arr_document = explode('/',$document);

        $arr_new_path = array();
        // Initial array
        $arr_new_path[0]['code'] =  '.' ;
        $arr_new_path[0]['url'] =  "edas_nav_directory_list.php?path=0";
        $arr_new_path[0]['id'] =  NULL ;

        $USER_PRIV = $this->restoreUser($request, $response);

        if ($arr_document[1] <> '' ) { // para contemplar el directorio raíz

            $parent = NULL; 
            for ($i=1 ;$i< count($arr_document) ;$i++){ // First element ignore
                $code = $arr_document[$i];
                if ($parent == NULL) {
                    $sql = "SELECT id_edas_directory, edas_parent_directory_id, code, owners, reading_groups, writing_groups FROM edas_directory where code = '$code' and edas_parent_directory_id is null";
                } else {
                    $sql = "SELECT id_edas_directory, edas_parent_directory_id, code, owners, reading_groups, writing_groups FROM edas_directory where code = '$code' and edas_parent_directory_id = $parent";
                }
                $rs = DB::Query($sql);
                if ($rs->value("id_edas_directory") == NULL ) {
                    // No existe el Directorio
                    $responseBody["error"] = true;
                    $responseBody["message_num"] = '008';
                    $responseBody["message"] =str_replace("{1}",$code,$errorMessages['008']);
                    // Error 401
                    return $responseBody;
                }
                
                $parent = $rs->value('id_edas_directory'); 

                // Function "IsInSet()" this in APPSETTING
                // Access control
                $isOwner = IsInSet($rs->value('owners'), $USER_PRIV['dataUser']['id_edas_user']); // Owner?
                $isRead =  IsInSet($rs->value('reading_groups') , $USER_PRIV['dataUser']['belongingGroups']); // Read?
                $isWrite =  IsInSet($rs->value('writing_groups'), $USER_PRIV['dataUser']['belongingGroups']); // write?
                if ( !$isOwner && !$isRead  ) {  
                    //  No access the Directory
                    $responseBody["error"] = true;
                    $responseBody["message_num"] = '009';
                    $responseBody["message"] =str_replace("{1}",$code,$errorMessages['009']);
                    // Error 401
                    return $responseBody;
                }
                $x = $i;
                $arr_new_path[$x]['code'] = $rs->value("code");
                $arr_new_path[$x]['url'] = "edas_nav_directory_list.php?path=".$x;
                $arr_new_path[$x]['id'] = $rs->value("id_edas_directory");
            }
        }

        $responseBody["error"] = false;
        $responseBody["message_num"] = '000';
        $responseBody["message"] = '';
        $responseBody['pathDirectory'] = $arr_new_path;
        $responseBody['selectedDirectory'] = $responseBody['pathDirectory'][count($arr_new_path)-1]['id']; // Last Directory
        // $responseBody['searchDocument'] = $arr_document[count($arr_document)-1]; // Document
        return  $responseBody;

    }
    /*
    ** Listado de los directorios y ficheros del direcotrio posicionado (sólo los que el usuario tiene acceso)
    */
    public function listDirectory($verify,Request $request, Response $response)
    {   
        global $conn; // Connection data base of PHPRunner

        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $verify['selectedDirectory'];
        if ($selectDirectory <> NULL) {
            $sql = <<<EOT
            select * from (
            SELECT 'dir' type, `id_edas_directory` id, `edas_parent_directory_id` edas_parent, `code`, `name`, `locked`, `owners`, `reading_groups`, `writing_groups` FROM edas_directory
                where edas_parent_directory_id = $selectDirectory
            union
            SELECT 'file' type, `id_edas_file`, `edas_directory_id`, `code`, `name`, `locked`, `owners`, `reading_groups`, `writing_groups` FROM edas_file
                where edas_directory_id = $selectDirectory)
            T1  order by 1,4
EOT;
        } else {
            $sql = <<<EOT
            select * from (
            SELECT 'dir' type, `id_edas_directory` id, `edas_parent_directory_id` edas_parent, `code`, `name`, `locked`, `owners`, `reading_groups`, `writing_groups` FROM edas_directory
                    where edas_parent_directory_id is NULL
            union
            SELECT 'file' type, `id_edas_file`, `edas_directory_id`, `code`, `name`, `locked`, `owners`, `reading_groups`, `writing_groups` FROM edas_file
                    where edas_directory_id is NULL)
            T1  order by 1,4
EOT;       
        }
        $arr_row = array();
        $rs = DB::Query($sql);
        $USER_PRIV = $this->restoreUser($request, $response);
        $USER_PRIV['pathDirectory'] = $verify['pathDirectory'];
        $USER_PRIV['selectedDirectory'] = $verify['selectedDirectory'];
        $status = $this->saveUser($USER_PRIV,$request, $response); // Save SESSION User, Path directory and ID of last directory

        while( $data = $rs->fetchAssoc() )
        {
            // Function "IsInSet()" this in APPSETTING
            // Access control
            $isOwner = IsInSet($data['owners'], $USER_PRIV['dataUser']['id_edas_user']); // Owner?
            $isRead =  IsInSet($data['reading_groups'] ,$USER_PRIV['dataUser']['belongingGroups']); // Read?
            $isWrite =  IsInSet($data['writing_groups'],$USER_PRIV['dataUser']['belongingGroups']); // write?
            if ( $isOwner || $isRead  ) {  
                //  Ok access the Directory or file
                $arr_row[] = $data;
            }
        }
        return  $arr_row;
    }
    /*
    ** Verificación de si está posicionado en el directorio adecuado y dispone de acceso al documento solicitado
    */
    public function accessDocument($param ,Request $request, Response $response)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
                            
        $id_document = $param['id_document'];     // CODE of File

        if(  $USER_PRIV ['selectedDirectory'] == NULL ) { // No se ha fijado el directorio por defecto
            return '012';
        }
        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];
        if ($selectDirectory <> NULL) {
            $sql = "SELECT * FROM edas_file WHERE  edas_directory_id  = $selectDirectory AND id_edas_file = $id_document";
        } else {
            $sql = "SELECT * FROM edas_file WHERE  edas_directory_id  is NULL AND id_edas_file = $id_document";
        }

        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No recuperado datos, Documento no existe
            return '010';
        }
    
        // Function "IsInSet()" this in APPSETTING
        // Access control
        $isOwner = IsInSet($data['owners'], $USER_PRIV['dataUser']['id_edas_user']); // Owner?
        $isRead =  IsInSet($data['reading_groups'] ,$USER_PRIV['dataUser']['belongingGroups']); // Read?
        $isWrite =  IsInSet($data['writing_groups'],$USER_PRIV['dataUser']['belongingGroups']); // write?
        if ($isOwner || $isRead) { //  Ok access
            $data['files'] = str_replace('\\','',$data['files']);

        } else {
                return '011';
        }
        return  $data;

    }
    /*
    ** Verificación de si está posicionado en el directorio adecuado y dispone de acceso para crear un documento
    */
    public function accessDocumentWrite($param ,Request $request, Response $response)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
                            

        if(  $USER_PRIV ['selectedDirectory'] == NULL ) { // No se ha fijado el directorio por defecto
            return '012';
        }
        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];
        if ($selectDirectory <> NULL) {
            $sql = "SELECT * FROM edas_directory WHERE  id_edas_directory  = $selectDirectory";
        }

        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No recuperado datos, Documento no existe
            return '018';
        }
    
        // Function "IsInSet()" this in APPSETTING
        // Access control
        $isOwner = IsInSet($data['owners'], $USER_PRIV['dataUser']['id_edas_user']); // Owner?
        $isRead =  IsInSet($data['reading_groups'] ,$USER_PRIV['dataUser']['belongingGroups']); // Read?
        $isWrite =  IsInSet($data['writing_groups'],$USER_PRIV['dataUser']['belongingGroups']); // write?
        if (!($isOwner || $isWrite)) { //  KO access
                return '009';
        }
        return  '000';

    }
    /*
    ** DELETE del documento
    */
    public function deleteDocument($param)
    {
        $id_document = $param['id_document'];     // CODE of File
        $sql = "delete from edas_file where id_edas_file = $id_document";
        DB::Exec($sql);                                 // Delete record in database

        $directory_rm = FILES_DIR."/$id_document";
        $files = glob($directory_rm .'/*');             // get all file names
        foreach($files as $file){                       // iterate files
          if(is_file($file)) {
            unlink($file);                              // delete file
          }
        }
        $error_rm = rmdir($directory_rm);               // Delete files of Document
        return $error_rm;

    }
    /*
    ** UPDATE del documento
    */
    public function updateDocument($param, Request $request, Response $response)
    {
        $id_document = $param['id_document'];     // CODE of File
        $code = $param['code'];
        $name = $param['name'];
        $locked = $param['locked'];
        if ( !is_string($code) || !is_string($name) || !( $locked == 0 || $locked == 1)) { // Type of variables
            return '015'; // Error 015
        }
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory

        if(  $USER_PRIV ['selectedDirectory'] == NULL ) { // No se ha fijado el directorio por defecto
            return '012';
        }
        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];
        $code = RemoveSpecialChar($code);   // Function in APPSETTING . Delecte charaters specials
        $sql = "SELECT code, name, locked,  lastModificationDate, userLastModification FROM edas_file where edas_directory_id = $selectDirectory and id_edas_file <> $id_document and code = '$code'"; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data <> NULL) { // Recuperado datos, Duplicado "code"
            return '016';
        }  
        $data = array();
        $keyvalues = array();
        $data["code"] = $code;
        $data["name"]  = $name;
        $data["locked"] = $locked;
        $keyvalues["id_edas_file"] = $id_document;
        DB::Update("edas_file", $data, $keyvalues );  // UPDATE Database
        return '000';
    }  
 
    /*
    ** Add del documento
    */
    public function addDocument($param, Request $request, Response $response)
    {
        $code = $param['code'];
        $name = $param['name'];
        $locked = $param['locked'];
        if ( !is_string($code) || !is_string($name) || !( $locked == 0 || $locked == 1)) { // Type of variables
            return '015'; // Error 015
        }
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory

        if(  $USER_PRIV ['selectedDirectory'] == NULL ) { // No se ha fijado el directorio por defecto
            return '012';
        }
        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];
        $code = RemoveSpecialChar($code);   // Function in APPSETTING . Delecte charaters specials
        $sql = "SELECT code, name, locked,  lastModificationDate, userLastModification FROM edas_file where edas_directory_id = $selectDirectory and code = '$code'"; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data <> NULL) { // Recuperado datos, Duplicado "code"
            return '016';
        } 
        $sql = "SELECT * FROM edas_directory  WHERE id_edas_directory =  $selectDirectory"; 
        $rs = DB::Query($sql);

        $dataDir = $rs->fetchAssoc(); 
        $data = array();
        // edas_directory_id , code , name , locked , files , owners , reading_groups , writing_groups , 
        // creationDate , lastModificationDate , userCreation , userLastModification
        $data["code"] = $code;
        $data["name"]  = $name;
        $data["locked"] = $locked;
        $data["edas_directory_id"] = $selectDirectory  ;
        $data["creationDate"] = now()  ;
        $data["lastModificationDate"] = now()  ;
        $data["userCreation"] = $USER_PRIV['dataUser']['login']   ;
        $data["userLastModification"] = $USER_PRIV['dataUser']['login']    ;
        $data["owners"] = $dataDir['owners']    ;
        $data["reading_groups"] = $dataDir['reading_groups']     ;
        $data["writing_groups"] = $dataDir['writing_groups']     ;

        DB::Insert("edas_file", $data );  // INSERT Database

        $lastID = DB::LastId();
        return array('error'=>'000','lastID'=>$lastID);
    } 

    /*
    ** LIST File del documento
    */
    public function listFile($param, Request $request, Response $response, array $args)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
        $action = $args['action'];
        $id_document = $args['id_document'];

        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];

        $sql = "SELECT files FROM edas_file where id_edas_file = $id_document "; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No existe el documento
            return '010';
        }
        $files = array();
        $files_arr = json_decode($data['files'], true);

        foreach ($files_arr as &$file) {
               $files[] = array("usrName"=>$file['usrName'],"size"=>$file["size"],"type"=>$file["type"]);
            }

        return $files;
    }
    /*
    ** View File del documento
    */
    public function viewFile($param, Request $request, Response $response, array $args)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
        $action = $args['action'];
        $id_document = $args['id_document'];
        $usrName = $param["usrName"];

        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];

        $sql = "SELECT files FROM edas_file where id_edas_file = $id_document "; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No existe el documento
            return '010';
        }
        $files = array();
        $files_arr = json_decode($data['files'], true);

        foreach ($files_arr as &$file) {
            if ($file['usrName'] == $usrName){
                $pathFile = FILES_ROOT."/".$file['name'];
                $contentFile = file_get_contents($pathFile);   
                // Encode the image string data into base64
                $dataFile = base64_encode($contentFile);
                $files[] = array("usrName"=>$file['usrName'],"size"=>$file["size"],"type"=>$file["type"],"base64File"=>$dataFile);
            }
        }
        iF (count($files) == 0) { // no ha encontrado el archivo
            return '019';
        }
        return $files;
    }
    /*
    ** Delete File del documento
    */
    public function deleteFile($param, Request $request, Response $response, array $args)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
        $action = $args['action'];
        $id_document = $args['id_document'];
        $usrName = $param["usrName"];

        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];

        $sql = "SELECT files FROM edas_file where id_edas_file = $id_document "; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No existe el documento
            return '010';
        }
        $files = array();
        $files_arr = json_decode($data['files'], true);

        foreach ($files_arr as &$file) {
            if ($file['usrName'] <> $usrName){
                $files[] = $file;
            }
        }
        if (count($files) == count($files_arr)) { // no ha encontrado el archivo
            return '019';
        }

        $files = json_encode($files, true);

        $data = array();
        $data["files"] = $files;
        $keyvalues["id_edas_file"] = $id_document;
        DB::Update("edas_file", $data, $keyvalues );

        return array("id_document"=>$id_document,"usrName"=>$usrName);
    }
    /*
    ** Add File del documento
    */
    public function addFile($param, Request $request, Response $response, array $args)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
        $action = $args['action'];
        $id_document = $args['id_document'];
        $usrName = $param["usrName"];

        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];

        $sql = "SELECT files FROM edas_file where id_edas_file = $id_document "; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No existe el documento
            return '010';
        }
        $files = array();
        $files_arr = json_decode($data['files'], true);

        foreach ($files_arr as &$file) {
            if ($file['usrName'] == $usrName){
                $files[] = array("usrName"=>$file['usrName']);
            }
        }
        iF (count($files) <> 0) { // Se ha encontrado un fichero igual
            return '020';
        }
        $pathDir = FILES_DIR."/".$id_document;
        $pathFile = FILES_DIR."/".$id_document."/".$this->RemoveSpecialCharFile($usrName);
        if (!file_exists($pathDir)) { // Directorio existe?
            mkdir($pathDir, 0755);
        }

        $fp = fopen($pathFile, "wb");
        fwrite($fp,base64_decode($param['base64File'])); // Escribe fichero en FileSystem
        fclose($fp);
        $size = filesize($pathFile);
        $nameFile_arr = explode('/',$pathFile); 
        $x = count($nameFile_arr)-3;  // son 3 partículas
        $name = $nameFile_arr[$x].'/'.$nameFile_arr[$x+1].'/'.$nameFile_arr[$x+2];
        
        $files_arr[] = array("name"=>$name,"usrName"=>$usrName,"size"=>$size,"type"=>$param["type"]);
     
        $files = json_encode($files_arr, true);

        $data["files"] = $files;
        $keyvalues["id_edas_file"] = $id_document;
        DB::Update("edas_file", $data, $keyvalues );

        return array("id_document"=>$id_document,"usrName"=>$usrName);
    }
    /*
    ** Update File del documento
    */
    public function updateFile($param, Request $request, Response $response, array $args)
    {
        $USER_PRIV = $this->restoreUser($request, $response);  // Restauramos los campos del USER and data of Directory
        $action = $args['action'];
        $id_document = $args['id_document'];
        $usrName = $param["usrName"];

        // Recuperar directorio y ficheros del último directorio
        $selectDirectory = $USER_PRIV['selectedDirectory'];

        $sql = "SELECT files FROM edas_file where id_edas_file = $id_document "; 
        $rs = DB::Query($sql);

        $data = $rs->fetchAssoc();
        if(  $data == NULL) { // No existe el documento
            return '010';
        }
        $files = array();
        $files_arr = json_decode($data['files'], true);
        $files_arr2 = array();

        foreach ($files_arr as &$file) {
            if ($file['usrName'] == $usrName){
                $files[] = array("usrName"=>$file['usrName']);
            } else {
                $files_arr2[]=$file;  // Save all files diferent
            }
        }
        iF (count($files) == 0) { // No se ha encontrado un fichero igual
            return '019';
        }
        $pathDir = FILES_DIR."/".$id_document;
        $pathFile = FILES_DIR."/".$id_document."/".$this->RemoveSpecialCharFile($usrName);
        if (!file_exists($pathDir)) { // Directorio existe?
            mkdir($pathDir, 0755);
        }
        unlink($pathFile);          // Delete file old
        $fp = fopen($pathFile, "wb");
        fwrite($fp,base64_decode($param['base64File'])); // Escribe fichero en FileSystem
        fclose($fp);
        $size = filesize($pathFile);
        $nameFile_arr = explode('/',$pathFile); 
        $x = count($nameFile_arr)-3;  // son 3 partículas
        $name = $nameFile_arr[$x].'/'.$nameFile_arr[$x+1].'/'.$nameFile_arr[$x+2];
        
        $files_arr2[] = array("name"=>$name,"usrName"=>$usrName,"size"=>$size,"type"=>$param["type"]);
     
        $files = json_encode($files_arr2, true);

        $data["files"] = $files;
        $keyvalues["id_edas_file"] = $id_document;
        DB::Update("edas_file", $data, $keyvalues );

        return array("id_document"=>$id_document,"usrName"=>$usrName);
    }

    /**
     * Recuperar los datos del usuario de la sesion
     */
    public function restoreUser( Request $request, Response $response)
    {
        global $errorMessages;
        // Getting request headers
        $headers = $request->getHeaders();    
        // get the api key
        $token = $headers['token-user'];
        $token = $token[0];
        $rs = DB::Query("SELECT * FROM edas_session_api WHERE uuid = '$token'");
        $data = $rs->fetchAssoc();
        return json_decode($data['sessionVariables'],true);
    }

    /**
     * Save los datos del usuario de la sesion y data Directory of Path
     */
    public function saveUser( array $USER_PRIV,Request $request, Response $response)
    {
        global $errorMessages;
        // Getting request headers
        $headers = $request->getHeaders();    
        // get the api key
        $token = $headers['token-user'];
        $token = $token[0];
        $data = array();
        $keyvalues = array();
        $data["sessionVariables"] =json_encode($USER_PRIV,true);
        $keyvalues["uuid"] = $token;
        DB::Update("edas_session_api", $data, $keyvalues );

        return true;
    }

    private function guidv4($data = null) {
        // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
        $data = $data ?? random_bytes(16);
        assert(strlen($data) == 16);
    
        // Set version to 0100
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set bits 6-7 to 10
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    
        // Output the 36 character UUID.
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    } 

    private function RemoveSpecialCharFile($str) // To normalize filer name
{
    $res = preg_replace('([^A-Za-z0-9_. ])', ' ', $str);
    $res = str_replace(' ','_',$res);
    return $res;
}

}

Como siempre, os dejo el proyecto de PHPRunner y el código del server de Api RestFull, así como un backup de la ase de datos, un zip con los ficheros del directorio files del directorio de ejecución y en este caso, los comandos de Postman, para que lo puedas importar y probar en tu equipo.

Si quieres probar los comandos de Postman con mi Linux de pruebas tienes que cambiar de la URL’s la parte de “http://localhost”, por “https://fhumanes.com”.

Recuerda que el primer paso es la acción de login, si todo va bien te facilita una variable nombrada con token cuyo valor tienes que facilitar en la variable de cabecera token-user

Acciones del server de Api RestFull:

Acción: Login POST: http://localhost/edas3/restapi/v1/login
Identificación en la aplicación
Head Body Response
Autorization: login:
password:
token-user:

 

Acción: Sesión POST: http://localhost/edas3/restapi/v1/session
Obtención de las variables de sesión
Head Body Response
Autorization:

token-user:

  Información del directorio posicionado y otras informaciones

 

Acción: Usuario GET: http://localhost/edas3/restapi/v1/user
Obtención de los datos del usuario identificado en el server
Head Body Response
Autorization:

token-user:

  Información del usuario logado

 

Acción: Directorio POST: http://localhost/edas3/restapi/v1/dir
Posicionamiento en el directorio informado y facilita los directorios y ficheros de ese Dir.
Head Body Response
Autorization:

token-user:

Path: /Home/Departament_1/Expedient_EXP1 Directorios y Ficheros del directorio

 

Acción: Documento PUT: http://localhost/edas3/restapi/v1/document/{accion}/{id_document}
Acciones sobre un documento concreto del directorio posicionado. Acciones=(view, update, delete)
Head Body Response
Autorization:

token-user:

Dependiendo de la acción.

code:

name:

locked:

Dependiendo de la acción

 

Acción: Documento POST: http://localhost/edas3/restapi/v1/documentAdd
Añadir un nuevo documento en el directorio posicionado
Head Body Response
Autorization:

token-user:

code:

name:

locked:

ID, del documento insertado

 

Acción: List. Files PUT: http://localhost/edas3/restapi/v1/document/{id_document}/file/list
Mostrar todos los ficheros del documento identificado por su ID.
Head Body Response
Autorization:

token-user:

  Lista de los ficheros de ese documento.

 

Acción: Acción sobre File PUT:

http://localhost/edas3/restapi/v1/document/{id_document}/file/{acción}

Acción sobre un fichero concreto del documento identificado por ID.

Acciones= view, add, update, delete

Head Body Response
Autorization:

token-user:

Dependiendo de la acción.

usrName:

type:

base64File:

Lista de los ficheros de ese documento.

 

Para lo que necesites, puedes contactar conmigo en [email protected].

Adjuntos

Archivo Tamaño de archivo Descargas
zip Backup de base de datos 12 KB 108
zip PHPRunner 10.8 4 MB 128
zip Directorio "files" 862 KB 118
zip Comandos de TEST de los servicios en formato POSTMAN 9 KB 102

Blog personal para facilitar soporte gratuito a usuarios de PHPRunner