From bfe56a0820b11ed0e56bad5e129a8721d43474eb Mon Sep 17 00:00:00 2001 From: Damien <damien.burel@maarch.org> Date: Thu, 8 Nov 2018 11:24:16 +0100 Subject: [PATCH] FEAT #8750 Create and get signatures --- rest/index.php | 34 +- sql/data_fr.sql | 2 + sql/structure.sql | 14 +- .../controllers/DocserverController.php | 399 +----- src/app/docserver/models/DocserverModel.php | 15 + .../resource/controllers/ResController.php | 633 ---------- .../resource/controllers/StoreController.php | 352 ------ src/app/resource/models/ResModel.php | 19 - src/app/resource/models/ResModelAbstract.php | 450 ------- src/app/user/controllers/UserController.php | 1118 +---------------- src/app/user/models/UserModel.php | 114 +- src/app/user/models/UserModelAbstract.php | 96 -- src/app/user/models/UserSignatureModel.php | 19 - .../models/UserSignatureModelAbstract.php | 118 -- .../controllers/PreparedClauseController.php | 240 ---- src/core/models/CurlModel.php | 184 --- 16 files changed, 200 insertions(+), 3607 deletions(-) delete mode 100755 src/app/resource/controllers/ResController.php delete mode 100644 src/app/resource/controllers/StoreController.php delete mode 100644 src/app/resource/models/ResModel.php delete mode 100644 src/app/resource/models/ResModelAbstract.php delete mode 100644 src/app/user/models/UserModelAbstract.php delete mode 100644 src/app/user/models/UserSignatureModel.php delete mode 100644 src/app/user/models/UserSignatureModelAbstract.php delete mode 100644 src/core/controllers/PreparedClauseController.php delete mode 100644 src/core/models/CurlModel.php diff --git a/rest/index.php b/rest/index.php index 1d43e2168b..9faeae19da 100755 --- a/rest/index.php +++ b/rest/index.php @@ -24,11 +24,9 @@ require_once("src/core/lang/lang-{$language}.php"); $app = new \Slim\App(['settings' => ['displayErrorDetails' => true, 'determineRouteBeforeAppMiddleware' => true]]); -$GLOBALS['login'] = 'jjane'; //Authentication -/*$app->add(function (\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next) { +$app->add(function (\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next) { $login = \SrcCore\controllers\AuthenticationController::authentication(); - if (!empty($login)) { $GLOBALS['login'] = $login; $response = $next($request, $response); @@ -36,7 +34,7 @@ $GLOBALS['login'] = 'jjane'; } else { return $response->withStatus(401)->withJson(['errors' => 'Authentication Failed']); } -});*/ +}); //Attachments @@ -46,30 +44,8 @@ $app->get('/attachments/{id}', \Attachment\controllers\AttachmentController::cla $app->get('/documents', \Document\controllers\DocumentController::class . ':get'); $app->get('/documents/{id}', \Document\controllers\DocumentController::class . ':getById'); - -////Users -//$app->get('/users', \User\controllers\UserController::class . ':get'); -//$app->post('/users', \User\controllers\UserController::class . ':create'); -//$app->get('/users/{id}/details', \User\controllers\UserController::class . ':getDetailledById'); -//$app->put('/users/{id}', \User\controllers\UserController::class . ':update'); -//$app->put('/users/{id}/password', \User\controllers\UserController::class . ':resetPassword'); -//$app->get('/users/{userId}/status', \User\controllers\UserController::class . ':getStatusByUserId'); -//$app->put('/users/{id}/status', \User\controllers\UserController::class . ':updateStatus'); -//$app->delete('/users/{id}', \User\controllers\UserController::class . ':delete'); -//$app->post('/users/{id}/groups', \User\controllers\UserController::class . ':addGroup'); -//$app->put('/users/{id}/groups/{groupId}', \User\controllers\UserController::class . ':updateGroup'); -//$app->delete('/users/{id}/groups/{groupId}', \User\controllers\UserController::class . ':deleteGroup'); -//$app->post('/users/{id}/entities', \User\controllers\UserController::class . ':addEntity'); -//$app->put('/users/{id}/entities/{entityId}', \User\controllers\UserController::class . ':updateEntity'); -//$app->put('/users/{id}/entities/{entityId}/primaryEntity', \User\controllers\UserController::class . ':updatePrimaryEntity'); -//$app->get('/users/{id}/entities/{entityId}', \User\controllers\UserController::class . ':isEntityDeletable'); -//$app->delete('/users/{id}/entities/{entityId}', \User\controllers\UserController::class . ':deleteEntity'); -//$app->post('/users/{id}/signatures', \User\controllers\UserController::class . ':addSignature'); -//$app->get('/users/{id}/signatures/{signatureId}/content', \User\controllers\UserController::class . ':getImageContent'); -//$app->put('/users/{id}/signatures/{signatureId}', \User\controllers\UserController::class . ':updateSignature'); -//$app->delete('/users/{id}/signatures/{signatureId}', \User\controllers\UserController::class . ':deleteSignature'); -//$app->post('/users/{id}/redirectedBaskets', \User\controllers\UserController::class . ':setRedirectedBaskets'); -//$app->delete('/users/{id}/redirectedBaskets/{basketId}', \User\controllers\UserController::class . ':deleteRedirectedBaskets'); -//$app->put('/users/{id}/baskets', \User\controllers\UserController::class . ':updateBasketsDisplay'); +//Users +$app->post('/users/{id}/signatures', \User\controllers\UserController::class . ':createSignature'); +$app->get('/users/{id}/signatures', \User\controllers\UserController::class . ':getSignatures'); $app->run(); diff --git a/sql/data_fr.sql b/sql/data_fr.sql index a7f4e105b6..270298d894 100755 --- a/sql/data_fr.sql +++ b/sql/data_fr.sql @@ -12,6 +12,8 @@ INSERT INTO docservers (type, label, is_readonly, size_limit_number, actual_size VALUES ('DOC', 'Documents principaux', 'N', 50000000000, 0, '/opt/maarchparapheur/docservers/documents/', CURRENT_TIMESTAMP); INSERT INTO docservers (type, label, is_readonly, size_limit_number, actual_size_number, path, creation_date) VALUES ('ATTACH', 'Documents joints', 'N', 50000000000, 0, '/opt/maarchparapheur/docservers/attachments/', CURRENT_TIMESTAMP); +INSERT INTO docservers (type, label, is_readonly, size_limit_number, actual_size_number, path, creation_date) +VALUES ('SIGNATURE', 'Signatures utilisateurs', 'N', 50000000000, 0, '/opt/maarchparapheur/docservers/signatures/', CURRENT_TIMESTAMP); ------------ --STATUS diff --git a/sql/structure.sql b/sql/structure.sql index e22f64eb54..6e97a22b47 100755 --- a/sql/structure.sql +++ b/sql/structure.sql @@ -86,7 +86,6 @@ CREATE TABLE docservers size_limit_number bigint NOT NULL DEFAULT (0)::bigint, actual_size_number bigint NOT NULL DEFAULT (0)::bigint, path character varying(255) NOT NULL, - creation_date timestamp without time zone NOT NULL, CONSTRAINT docservers_pkey PRIMARY KEY (id), CONSTRAINT docservers_type_key UNIQUE (type) ) @@ -120,16 +119,15 @@ CREATE TABLE adr_attachments ) WITH (OIDS=FALSE); -DROP TABLE IF EXISTS users_signatures; -CREATE TABLE users_signatures +DROP TABLE IF EXISTS signatures; +CREATE TABLE signatures ( id serial NOT NULL, user_id integer NOT NULL, - label character varying(255) DEFAULT NULL::character varying, - path character varying(255) DEFAULT NULL::character varying, - filename character varying(255) DEFAULT NULL::character varying, - fingerprint character varying(255) DEFAULT NULL::character varying, - CONSTRAINT user_signatures_pkey PRIMARY KEY (id) + path character varying(255) NOT NULL, + filename character varying(255) NOT NULL, + fingerprint character varying(255) NOT NULL, + CONSTRAINT signatures_pkey PRIMARY KEY (id) ) WITH (OIDS=FALSE); diff --git a/src/app/docserver/controllers/DocserverController.php b/src/app/docserver/controllers/DocserverController.php index 104f2b451f..69e4c68c8d 100644 --- a/src/app/docserver/controllers/DocserverController.php +++ b/src/app/docserver/controllers/DocserverController.php @@ -14,210 +14,24 @@ namespace Docserver\controllers; -use Docserver\models\DocserverTypeModel; -use Group\models\ServiceModel; -use History\controllers\HistoryController; -use Resource\controllers\StoreController; -use Respect\Validation\Validator; -use Slim\Http\Request; -use Slim\Http\Response; use SrcCore\models\ValidatorModel; use Docserver\models\DocserverModel; class DocserverController { - public function get(Request $request, Response $response) - { - if (!ServiceModel::hasService(['id' => 'admin_docservers', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $sortedDocservers = []; - $docservers = DocserverModel::get(); - foreach ($docservers as $docserver) { - $sortedDocservers[$docserver['docserver_type_id']][] = DocserverController::getFormattedDocserver(['docserver' => $docserver]); - } - - $docserversTypes = DocserverTypeModel::get(['select' => ['docserver_type_id', 'docserver_type_label'], 'orderBy' => ['docserver_type_label']]); - - return $response->withJson(['docservers' => $sortedDocservers, 'types' => $docserversTypes]); - } - - public function getById(Request $request, Response $response, array $aArgs) - { - if (!ServiceModel::hasService(['id' => 'admin_docservers', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $docserver = DocserverModel::getById(['id' => $aArgs['id']]); - if (empty($docserver)) { - return $response->withStatus(400)->withJson(['errors' => 'Docserver not found']); - } - - return $response->withJson($docserver); - } - - public function create(Request $request, Response $response) - { - if (!ServiceModel::hasService(['id' => 'admin_docservers', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } + const FINGERPRINT_MODE = 'sha512'; - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['docserver_id']) && preg_match("/^[\w-]*$/", $data['docserver_id']) && (strlen($data['docserver_id']) <= 32); - $check = $check && Validator::stringType()->notEmpty()->validate($data['docserver_type_id']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['device_label']); - $check = $check && Validator::intVal()->notEmpty()->validate($data['size_limit_number']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['path_template']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['coll_id']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $existingDocserver = DocserverModel::getByDocserverId(['docserverId' => $data['docserver_id'], 'select' => ['1']]); - if (!empty($existingDocserver)) { - return $response->withStatus(400)->withJson(['errors' => _ID. ' ' . _ALREADY_EXISTS]); - } - $existingDocserverType = DocserverTypeModel::get(['select' => ['1'], 'where' => ['docserver_type_id = ?'], 'data' => [$data['docserver_type_id']]]); - if (empty($existingDocserverType)) { - return $response->withStatus(400)->withJson(['errors' => 'Docserver type does not exist']); - } - if (!DocserverController::isPathAvailable(['path' => $data['path_template']])) { - return $response->withStatus(400)->withJson(['errors' => _PATH_OF_DOCSERVER_UNAPPROACHABLE]); - } - - $existingCurrentDocserver = DocserverModel::getCurrentDocserver([ - 'select' => ['1'], - 'typeId' => $data['docserver_type_id'], - 'collId' => $data['coll_id'] - ]); - $data['is_readonly'] = empty($existingCurrentDocserver) ? 'N' : 'Y'; - - if (substr($data['path_template'], -1) != DIRECTORY_SEPARATOR) { - $data['path_template'] .= "/"; - } - - $id = DocserverModel::create($data); - HistoryController::add([ - 'tableName' => 'docservers', - 'recordId' => $data['docserver_id'], - 'eventType' => 'ADD', - 'info' => _DOCSERVER_ADDED . " : {$data['docserver_id']}", - 'moduleId' => 'docserver', - 'eventId' => 'docserverCreation', - ]); - - return $response->withJson(['docserver' => $id]); - } - - public function update(Request $request, Response $response, array $aArgs) + public static function storeResourceOnDocServer(array $args) { - if (!ServiceModel::hasService(['id' => 'admin_docservers', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['device_label']); - $check = $check && Validator::intVal()->notEmpty()->validate($data['size_limit_number']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['path_template']); - $check = $check && Validator::boolType()->validate($data['is_readonly']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } + ValidatorModel::notEmpty($args, ['encodedFile', 'docserverType', 'format']); + ValidatorModel::stringType($args, ['docserverType', 'format']); - $docserver = DocserverModel::getById(['id' => $aArgs['id'], 'select' => ['docserver_type_id', 'coll_id']]); - if (empty($docserver)) { - return $response->withStatus(400)->withJson(['errors' => 'Docserver not found']); - } - if (!DocserverController::isPathAvailable(['path' => $data['path_template']])) { - return $response->withStatus(400)->withJson(['errors' => _PATH_OF_DOCSERVER_UNAPPROACHABLE]); - } - if (!$data['is_readonly']) { - $existingCurrentDocserver = DocserverModel::getCurrentDocserver([ - 'select' => ['id'], - 'typeId' => $docserver['docserver_type_id'], - 'collId' => $docserver['coll_id'] - ]); - if (!empty($existingCurrentDocserver) && $existingCurrentDocserver['id'] != $aArgs['id']) { - return $response->withStatus(400)->withJson(['errors' => _DOCSERVER_ACTIVATED_EXISTS]); - } - } - - if (substr($data['path_template'], -1) != DIRECTORY_SEPARATOR) { - $data['path_template'] .= "/"; - } - - $updateData = [ - 'id' => $aArgs['id'], - 'device_label' => $data['device_label'], - 'size_limit_number' => $data['size_limit_number'], - 'path_template' => $data['path_template'], - 'is_readonly' => empty($data['is_readonly']) ? 'N' : 'Y' - ]; - - DocserverModel::update($updateData); - HistoryController::add([ - 'tableName' => 'docservers', - 'recordId' => $aArgs['id'], - 'eventType' => 'UP', - 'info' => _DOCSERVER_UPDATED . " : {$data['device_label']}", - 'moduleId' => 'docserver', - 'eventId' => 'docserverModification', - ]); - - $docserver = DocserverModel::getById(['id' => $aArgs['id']]); - - return $response->withJson(['docserver' => DocserverController::getFormattedDocserver(['docserver' => $docserver])]); - } - - public function delete(Request $request, Response $response, array $aArgs) - { - if (!ServiceModel::hasService(['id' => 'admin_docservers', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $docserver = DocserverModel::getById(['id' => $aArgs['id']]); - if (empty($docserver)) { - return $response->withStatus(400)->withJson(['errors' => 'Docserver does not exist']); - } - - DocserverModel::delete(['id' => $aArgs['id']]); - HistoryController::add([ - 'tableName' => 'docservers', - 'recordId' => $aArgs['id'], - 'eventType' => 'DEL', - 'info' => _DOCSERVER_DELETED . " : {$aArgs['id']}", - 'moduleId' => 'docserver', - 'eventId' => 'docserverSuppression', - ]); - - return $response->withJson(['success' => 'success']); - } - - public static function storeResourceOnDocServer(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['collId', 'docserverTypeId', 'fileInfos']); - ValidatorModel::stringType($aArgs, ['collId', 'docserverTypeId']); - ValidatorModel::arrayType($aArgs, ['fileInfos']); - ValidatorModel::notEmpty($aArgs['fileInfos'], ['tmpDir', 'tmpFileName']); - ValidatorModel::stringType($aArgs['fileInfos'], ['tmpDir', 'tmpFileName']); - - if (!is_dir($aArgs['fileInfos']['tmpDir'])) { - return ['errors' => '[storeRessourceOnDocserver] FileInfos.tmpDir does not exist']; - } - if (!file_exists($aArgs['fileInfos']['tmpDir'] . $aArgs['fileInfos']['tmpFileName'])) { - return ['errors' => '[storeRessourceOnDocserver] FileInfos.tmpFileName does not exist ' - . $aArgs['fileInfos']['tmpDir'] . $aArgs['fileInfos']['tmpFileName']]; - } - - $docserver = DocserverModel::getCurrentDocserver(['collId' => $aArgs['collId'], 'typeId' => $aArgs['docserverTypeId']]); + $docserver = DocserverModel::getByType(['type' => $args['docserverType'], 'select' => ['id', 'path', 'actual_size_number']]); if (empty($docserver)) { return ['errors' => '[storeRessourceOnDocserver] No available Docserver']; } - $pathOnDocserver = DocserverController::createPathOnDocServer(['path' => $docserver['path_template']]); + $pathOnDocserver = DocserverController::createPathOnDocServer(['path' => $docserver['path']]); if (!empty($pathOnDocserver['errors'])) { return ['errors' => '[storeRessourceOnDocserver] ' . $pathOnDocserver['errors']]; } @@ -226,38 +40,24 @@ class DocserverController if (!empty($docinfo['errors'])) { return ['errors' => '[storeRessourceOnDocserver] ' . $docinfo['errors']]; } - $pathInfoOnTmp = pathinfo($aArgs['fileInfos']['tmpDir'] . $aArgs['fileInfos']['tmpFileName']); - $docinfo['fileDestinationName'] .= '.' . strtolower($pathInfoOnTmp['extension']); - - $docserverTypeObject = DocserverTypeModel::getById(['id' => $docserver['docserver_type_id']]); - $copyResult = DocserverController::copyOnDocServer([ - 'sourceFilePath' => $aArgs['fileInfos']['tmpDir'] . $aArgs['fileInfos']['tmpFileName'], - 'destinationDir' => $docinfo['destinationDir'], - 'fileDestinationName' => $docinfo['fileDestinationName'], - 'docserverSourceFingerprint' => $docserverTypeObject['fingerprint_mode'], - ]); - if (!empty($copyResult['errors'])) { - return ['errors' => '[storeRessourceOnDocserver] ' . $copyResult['errors']]; - } + $docinfo['fileDestinationName'] .= ".{$args['format']}"; - $destinationDir = substr($copyResult['copyOnDocserver']['destinationDir'], strlen($docserver['path_template'])) . '/'; - $destinationDir = str_replace(DIRECTORY_SEPARATOR, '#', $destinationDir); + $file = base64_decode($args['encodedFile']); + file_put_contents($docinfo['destinationDir'] . $docinfo['fileDestinationName'], $file); + chmod($docinfo['destinationDir'] . $docinfo['fileDestinationName'], 0770); DocserverModel::update([ - 'id' => $docserver['id'], - 'actual_size_number' => $docserver['actual_size_number'] + $aArgs['fileInfos']['size'] + 'set' => [ + 'actual_size_number' => $docserver['actual_size_number'] + filesize($docinfo['destinationDir'] . $docinfo['fileDestinationName']) + ], + 'where' => ['id = ?'], + 'data' => [$docserver['id']] ]); return [ - 'path_template' => $docserver['path_template'], - 'destination_dir' => $destinationDir, - 'docserver_id' => $docserver['docserver_id'], - 'file_destination_name' => $copyResult['copyOnDocserver']['fileDestinationName'], - 'fileSize' => $copyResult['copyOnDocserver']['fileSize'], - 'fingerPrint' => StoreController::getFingerPrint([ - 'filePath' => $docinfo['destinationDir'] . $docinfo['fileDestinationName'], - 'mode' => $docserverTypeObject['fingerprint_mode'] - ]) + 'path' => substr($docinfo['destinationDir'], strlen($docserver['path'])), + 'filename' => $docinfo['fileDestinationName'], + 'fingerprint' => DocserverController::getFingerPrint(['path' => ($docinfo['destinationDir'] . $docinfo['fileDestinationName'])]) ]; } @@ -294,17 +94,6 @@ class DocserverController } $pathToDS = $monthPath; - if (!empty($GLOBALS['wb'])) { - $pathToDS = "{$monthPath}BATCH/{$GLOBALS['wb']}/"; - if (!is_dir($pathToDS)) { - mkdir($pathToDS, 0770, true); - if (DIRECTORY_SEPARATOR == '/' && !empty($GLOBALS['apacheUserAndGroup'])) { - exec('chown ' . escapeshellarg($GLOBALS['apacheUserAndGroup']) . ' ' . escapeshellarg($monthPath)); - } - umask(0022); - chmod($monthPath, 0770); - } - } return ['pathToDocServer' => $pathToDS]; } @@ -324,13 +113,6 @@ class DocserverController array_shift($aFiles); // Remove . line array_shift($aFiles); // Remove .. line - if (file_exists($aArgs['pathOnDocserver'] . '/package_information')) { - unset($aFiles[array_search('package_information', $aFiles)]); - } - if (is_dir($aArgs['pathOnDocserver'] . '/BATCH')) { - unset($aFiles[array_search('BATCH', $aFiles)]); - } - $filesNb = count($aFiles); if ($filesNb == 0) { $zeroOnePath = $aArgs['pathOnDocserver'] . '0001/'; @@ -390,148 +172,11 @@ class DocserverController } } - public static function copyOnDocServer(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['destinationDir', 'fileDestinationName', 'sourceFilePath']); - ValidatorModel::stringType($aArgs, ['destinationDir', 'fileDestinationName', 'sourceFilePath']); - - if (file_exists($aArgs['destinationDir'] . $aArgs['fileDestinationName'])) { - return ['errors' => '[copyOnDocserver] File already exists: ' . $aArgs['destinationDir'] . $aArgs['fileDestinationName']]; - } - - if (!file_exists($aArgs['sourceFilePath'])) { - return ['errors' => '[copyOnDocserver] File does not exist']; - } - - error_reporting(0); - $aArgs['sourceFilePath'] = str_replace('\\\\', '\\', $aArgs['sourceFilePath']); - - if (!is_dir($aArgs['destinationDir'])) { - mkdir($aArgs['destinationDir'], 0770, true); - if (DIRECTORY_SEPARATOR == '/' && !empty($GLOBALS['apacheUserAndGroup'])) { - exec('chown ' . escapeshellarg($GLOBALS['apacheUserAndGroup']) . ' ' . escapeshellarg($aArgs['destinationDir'])); - } - umask(0022); - chmod($aArgs['destinationDir'], 0770); - } - - if (!copy($aArgs['sourceFilePath'], $aArgs['destinationDir'] . $aArgs['fileDestinationName'])) { - return ['errors' => '[copyOnDocserver] Copy on the docserver failed']; - } - if (DIRECTORY_SEPARATOR == '/' && !empty($GLOBALS['apacheUserAndGroup'])) { - exec('chown ' . escapeshellarg($GLOBALS['apacheUserAndGroup']) . ' ' . escapeshellarg($aArgs['destinationDir'] . $aArgs['fileDestinationName'])); - } - umask(0022); - chmod($aArgs['destinationDir'] . $aArgs['fileDestinationName'], 0770); - - $fingerprintControl = StoreController::controlFingerPrint([ - 'pathInit' => $aArgs['sourceFilePath'], - 'pathTarget' => $aArgs['destinationDir'] . $aArgs['fileDestinationName'], - 'fingerprintMode' => $aArgs['docserverSourceFingerprint'], - ]); - if (!empty($fingerprintControl['errors'])) { - return ['errors' => '[copyOnDocserver] ' . $fingerprintControl['errors']]; - } - - if (!empty($GLOBALS['currentStep'])) { // For batch like life cycle - $aArgs['destinationDir'] = str_replace($GLOBALS['docservers'][$GLOBALS['currentStep']]['docserver']['path_template'], '', $aArgs['destinationDir']); - } - $aArgs['destinationDir'] = str_replace(DIRECTORY_SEPARATOR, '#', $aArgs['destinationDir']); - - $dataToReturn = [ - 'copyOnDocserver' => - [ - 'destinationDir' => $aArgs['destinationDir'], - 'fileDestinationName' => $aArgs['fileDestinationName'], - 'fileSize' => filesize(str_replace('#', '/', $aArgs['destinationDir']) . $aArgs['fileDestinationName']), - ] - ]; - - if (!empty($GLOBALS['TmpDirectory'])) { - DocserverController::directoryWasher(['path' => $GLOBALS['TmpDirectory']]); - } - - return $dataToReturn; - } - - private static function getFormattedDocserver(array $aArgs) + public static function getFingerPrint(array $args) { - ValidatorModel::notEmpty($aArgs, ['docserver']); - ValidatorModel::arrayType($aArgs, ['docserver']); - - $docserver = $aArgs['docserver']; - - $docserver['is_readonly'] = ($docserver['is_readonly'] == 'Y'); - $docserver['actual_size_number'] = DocserverController::getDocserverSize(['path' => $docserver['path_template']]); - if ($docserver['actual_size_number'] > 1000000000) { - $docserver['actualSizeFormatted'] = round($docserver['actual_size_number'] / 1000000000, 3) . ' Go'; - } else { - $docserver['actualSizeFormatted'] = round($docserver['actual_size_number'] / 1000000, 3) . ' Mo'; - } - $docserver['limitSizeFormatted'] = round($docserver['size_limit_number'] / 1000000000, 3); // Giga - $docserver['percentage'] = round($docserver['actual_size_number'] / $docserver['size_limit_number'] * 100, 2); - - return $docserver; - } - - private static function getDocserverSize(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['path']); - ValidatorModel::stringType($aArgs, ['path']); - - $size = 0; - - if (DocserverController::isPathAvailable(['path' => $aArgs['path']])) { - $exec = shell_exec("du -s -b {$aArgs['path']}"); - $execPlode = explode("\t", $exec); - if (isset($execPlode[0]) && is_numeric($execPlode[0])) { - $size = $execPlode[0]; - } - } - - return (int)$size; - } - - private static function isPathAvailable(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['path']); - ValidatorModel::stringType($aArgs, ['path']); - - if (!is_dir($aArgs['path'])) { - return false; - } - if (!is_readable($aArgs['path'])) { - return false; - } - if (!is_writable($aArgs['path'])) { - return false; - } - - return true; - } - - private static function directoryWasher(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['path']); - ValidatorModel::stringType($aArgs, ['path']); - - if (!is_dir($aArgs['path'])) { - return ['errors' => '[directoryWasher] Path does not exist']; - } - - $aFiles = scandir($aArgs['path']); - foreach ($aFiles as $file) { - if ($file != '.' && $file != '..') { - if (filetype($aArgs['path'] . '/' . $file) == 'dir') { - DocserverController::directoryWasher(['path' => $aArgs['path'] . '/' . $file]); - } else { - unlink($aArgs['path'] . '/' . $file); - } - } - } - - reset($aFiles); + ValidatorModel::notEmpty($args, ['path']); + ValidatorModel::stringType($args, ['path']); - return true; + return hash_file(self::FINGERPRINT_MODE, $args['path']); } } diff --git a/src/app/docserver/models/DocserverModel.php b/src/app/docserver/models/DocserverModel.php index 9871e4f3d7..1c24386e33 100644 --- a/src/app/docserver/models/DocserverModel.php +++ b/src/app/docserver/models/DocserverModel.php @@ -37,4 +37,19 @@ class DocserverModel return $aDocserver[0]; } + + public static function update(array $aArgs) + { + ValidatorModel::notEmpty($aArgs, ['set', 'where', 'data']); + ValidatorModel::arrayType($aArgs, ['set', 'where', 'data']); + + DatabaseModel::update([ + 'table' => 'docservers', + 'set' => $aArgs['set'], + 'where' => $aArgs['where'], + 'data' => $aArgs['data'] + ]); + + return true; + } } diff --git a/src/app/resource/controllers/ResController.php b/src/app/resource/controllers/ResController.php deleted file mode 100755 index d0c0261d91..0000000000 --- a/src/app/resource/controllers/ResController.php +++ /dev/null @@ -1,633 +0,0 @@ -<?php - -/** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ - -/** -* @brief Resource Controller -* @author dev@maarch.org -*/ - -namespace Resource\controllers; - -use Attachment\models\AttachmentModel; -use Basket\models\BasketModel; -use Basket\models\GroupBasketModel; -use Convert\controllers\ConvertPdfController; -use Convert\controllers\ConvertThumbnailController; -use Convert\models\AdrModel; -use Docserver\controllers\DocserverController; -use Docserver\models\DocserverModel; -use Docserver\models\ResDocserverModel; -use Entity\models\ListInstanceModel; -use Group\controllers\GroupController; -use Group\models\GroupModel; -use Group\models\ServiceModel; -use History\controllers\HistoryController; -use Note\models\NoteModel; -use Resource\models\ChronoModel; -use Resource\models\ResModel; -use Respect\Validation\Validator; -use setasign\Fpdi\TcpdfFpdi; -use Slim\Http\Request; -use Slim\Http\Response; -use SrcCore\controllers\PreparedClauseController; -use SrcCore\models\CoreConfigModel; -use SrcCore\models\ValidatorModel; -use Status\models\StatusModel; -use User\models\UserModel; - -class ResController -{ - //***************************************************************************************** - //LOG ONLY LOG FOR DEBUG - // $file = fopen('storeResourceLogs.log', 'a'); - // fwrite($file, '[' . date('Y-m-d H:i:s') . '] new request' . PHP_EOL); - // foreach ($data as $key => $value) { - // if ($key <> 'encodedFile') { - // fwrite($file, '[' . date('Y-m-d H:i:s') . '] ' . $key . ' : ' . $value . PHP_EOL); - // } - // } - // fclose($file); - // ob_flush(); - // ob_start(); - // print_r($data); - // file_put_contents("storeResourceLogs.log", ob_get_flush()); - //END LOG FOR DEBUG ONLY - //***************************************************************************************** - public function create(Request $request, Response $response) - { - if (!ServiceModel::hasService(['id' => 'index_mlb', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'menu'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $data = $request->getParams(); - - $check = Validator::notEmpty()->validate($data['encodedFile']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['fileFormat']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['status']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['collId']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['table']); - $check = $check && Validator::arrayType()->notEmpty()->validate($data['data']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $mandatoryColumns = []; - if ($data['table'] == 'res_letterbox') { - $mandatoryColumns[] = 'type_id'; - } - - foreach ($data['data'] as $value) { - foreach ($mandatoryColumns as $columnKey => $column) { - if ($column == $value['column'] && !empty($value['value'])) { - unset($mandatoryColumns[$columnKey]); - } - } - } - if (!empty($mandatoryColumns)) { - return $response->withStatus(400)->withJson(['errors' => 'Data array needs column(s) [' . implode(', ', $mandatoryColumns) . ']']); - } - - $resId = StoreController::storeResource($data); - - if (empty($resId) || !empty($resId['errors'])) { - return $response->withStatus(500)->withJson(['errors' => '[ResController create] ' . $resId['errors']]); - } - - HistoryController::add([ - 'tableName' => 'res_letterbox', - 'recordId' => $resId, - 'eventType' => 'ADD', - 'info' => _DOC_ADDED, - 'moduleId' => 'res', - 'eventId' => 'resadd', - ]); - - return $response->withJson(['resId' => $resId]); - } - - public function createExt(Request $request, Response $response) - { - if (!ServiceModel::hasService(['id' => 'index_mlb', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'menu'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $data = $request->getParams(); - - $check = Validator::intVal()->notEmpty()->validate($data['resId']); - $check = $check && Validator::arrayType()->notEmpty()->validate($data['data']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $document = ResModel::getById(['resId' => $data['resId'], 'select' => ['1']]); - if (empty($document)) { - return $response->withStatus(404)->withJson(['errors' => 'Document does not exist']); - } - $documentExt = ResModel::getExtById(['resId' => $data['resId'], 'select' => ['1']]); - if (!empty($documentExt)) { - return $response->withStatus(400)->withJson(['errors' => 'Document already exists in mlb_coll_ext']); - } - - $formatedData = StoreController::prepareExtStorage(['resId' => $data['resId'], 'data' => $data['data']]); - - $check = Validator::stringType()->notEmpty()->validate($formatedData['category_id']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - ResModel::createExt($formatedData); - - return $response->withJson(['status' => true]); - } - - public function updateStatus(Request $request, Response $response) - { - $data = $request->getParams(); - - if (empty($data['status'])) { - $data['status'] = 'COU'; - } - if (empty(StatusModel::getById(['id' => $data['status']]))) { - return $response->withStatus(400)->withJson(['errors' => _STATUS_NOT_FOUND]); - } - if (empty($data['historyMessage'])) { - $data['historyMessage'] = _UPDATE_STATUS; - } - - $check = Validator::arrayType()->notEmpty()->validate($data['chrono']) || Validator::arrayType()->notEmpty()->validate($data['resId']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['status']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['historyMessage']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $identifiers = !empty($data['chrono']) ? $data['chrono'] : $data['resId']; - foreach ($identifiers as $id) { - if (!empty($data['chrono'])) { - $document = ResModel::getResIdByAltIdentifier(['altIdentifier' => $id]); - } else { - $document = ResModel::getById(['resId' => $id, 'select' => ['res_id']]); - } - if (empty($document)) { - return $response->withStatus(400)->withJson(['errors' => _DOCUMENT_NOT_FOUND]); - } - if (!ResController::hasRightByResId(['resId' => $document['res_id'], 'userId' => $GLOBALS['userId']])) { - return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']); - } - - ResModel::update(['set' => ['status' => $data['status']], 'where' => ['res_id = ?'], 'data' => [$document['res_id']]]); - - HistoryController::add([ - 'tableName' => 'res_letterbox', - 'recordId' => $document['res_id'], - 'eventType' => 'UP', - 'info' => $data['historyMessage'], - 'moduleId' => 'apps', - 'eventId' => 'resup', - ]); - } - - return $response->withJson(['success' => 'success']); - } - - public function getFileContent(Request $request, Response $response, array $aArgs) - { - if (!Validator::intVal()->validate($aArgs['resId']) || !ResController::hasRightByResId(['resId' => $aArgs['resId'], 'userId' => $GLOBALS['userId']])) { - return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']); - } - - $document = ResModel::getById(['select' => ['docserver_id', 'path', 'filename'], 'resId' => $aArgs['resId']]); - $extDocument = ResModel::getExtById(['select' => ['category_id', 'alt_identifier'], 'resId' => $aArgs['resId']]); - if (empty($document) || empty($extDocument)) { - return $response->withStatus(400)->withJson(['errors' => 'Document does not exist']); - } - - if ($extDocument['category_id'] == 'outgoing') { - $attachment = AttachmentModel::getOnView([ - 'select' => ['res_id', 'res_id_version', 'docserver_id', 'path', 'filename'], - 'where' => ['res_id_master = ?', 'attachment_type = ?', 'status not in (?)'], - 'data' => [$aArgs['resId'], 'outgoing_mail', ['DEL', 'OBS']], - 'limit' => 1 - ]); - if (!empty($attachment[0])) { - $attachmentTodisplay = $attachment[0]; - $id = (empty($attachmentTodisplay['res_id']) ? $attachmentTodisplay['res_id_version'] : $attachmentTodisplay['res_id']); - $isVersion = empty($attachmentTodisplay['res_id']); - if ($isVersion) { - $collId = "attachments_version_coll"; - } else { - $collId = "attachments_coll"; - } - $convertedDocument = ConvertPdfController::getConvertedPdfById(['select' => ['docserver_id', 'path', 'filename'], 'resId' => $id, 'collId' => $collId, 'isVersion' => $isVersion]); - if (empty($convertedDocument['errors'])) { - $attachmentTodisplay = $convertedDocument; - } - $document['docserver_id'] = $attachmentTodisplay['docserver_id']; - $document['path'] = $attachmentTodisplay['path']; - $document['filename'] = $attachmentTodisplay['filename']; - } - } else { - $convertedDocument = ConvertPdfController::getConvertedPdfById(['select' => ['docserver_id', 'path', 'filename'], 'resId' => $aArgs['resId'], 'collId' => 'letterbox_coll', 'isVersion' => false]); - - if (empty($convertedDocument['errors'])) { - $documentTodisplay = $convertedDocument; - $document['docserver_id'] = $documentTodisplay['docserver_id']; - $document['path'] = $documentTodisplay['path']; - $document['filename'] = $documentTodisplay['filename']; - } - } - - $docserver = DocserverModel::getByDocserverId(['docserverId' => $document['docserver_id'], 'select' => ['path_template']]); - if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) { - return $response->withStatus(400)->withJson(['errors' => 'Docserver does not exist']); - } - - $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $document['path']) . $document['filename']; - - if (!file_exists($pathToDocument)) { - return $response->withStatus(404)->withJson(['errors' => 'Document not found on docserver']); - } - - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/features.xml']); - if ($loadedXml) { - $watermark = (array)$loadedXml->FEATURES->watermark; - if ($watermark['enabled'] == 'true') { - - $text = "watermark by {$GLOBALS['userId']}"; - if (!empty($watermark['text'])) { - $text = $watermark['text']; - preg_match_all('/\[(.*?)\]/i', $watermark['text'], $matches); - - foreach ($matches[1] as $value) { - $tmp = ''; - if ($value == 'date_now') { - $tmp = date('d-m-Y'); - } elseif ($value == 'hour_now') { - $tmp = date('H:i'); - } elseif($value == 'alt_identifier'){ - $tmp = $extDocument['alt_identifier']; - } else { - $backFromView = ResModel::getOnView(['select' => $value, 'where' => ['res_id = ?'], 'data' => [$aArgs['resId']]]); - if (!empty($backFromView[0][$value])) { - $tmp = $backFromView[0][$value]; - } - } - $text = str_replace("[{$value}]", $tmp, $text); - } - } - - $color = ['192', '192', '192']; //RGB - if (!empty($watermark['text_color'])) { - $rawColor = explode(',', $watermark['text_color']); - $color = count($rawColor) == 3 ? $rawColor : $color; - } - - $font = ['helvetica', '10']; //Familly Size - if (!empty($watermark['font'])) { - $rawFont = explode(',', $watermark['font']); - $font = count($rawFont) == 2 ? $rawFont : $font; - } - - $position = [30, 35, 0, 0.5]; //X Y Angle Opacity - if (!empty($watermark['position'])) { - $rawPosition = explode(',', $watermark['position']); - $position = count($rawPosition) == 4 ? $rawPosition : $position; - } - - try { - $pdf = new TcpdfFpdi('P', 'pt'); - $nbPages = $pdf->setSourceFile($pathToDocument); - $pdf->setPrintHeader(false); - for ($i = 1; $i <= $nbPages; $i++) { - $page = $pdf->importPage($i); - $size = $pdf->getTemplateSize($page); - $pdf->AddPage($size['orientation'], $size); - $pdf->useImportedPage($page); - $pdf->SetFont($font[0], '', $font[1]); - $pdf->SetTextColor($color[0], $color[1], $color[2]); - $pdf->SetAlpha($position[3]); - $pdf->Rotate($position[2]); - $pdf->Text($position[0], $position[1], $text); - } - $fileContent = $pdf->Output('', 'S'); - } catch (\Exception $e) { - $fileContent = null; - } - } - } - - if (empty($fileContent)) { - $fileContent = file_get_contents($pathToDocument); - } - if ($fileContent === false) { - return $response->withStatus(404)->withJson(['errors' => 'Document not found on docserver']); - } - - $finfo = new \finfo(FILEINFO_MIME_TYPE); - $mimeType = $finfo->buffer($fileContent); - $pathInfo = pathinfo($pathToDocument); - - $response->write($fileContent); - $response = $response->withAddedHeader('Content-Disposition', "inline; filename=maarch.{$pathInfo['extension']}"); - - HistoryController::add([ - 'tableName' => 'res_letterbox', - 'recordId' => $aArgs['resId'], - 'eventType' => 'VIEW', - 'info' => _DOC_DISPLAYING . " : {$aArgs['resId']}", - 'moduleId' => 'res', - 'eventId' => 'resview', - ]); - - return $response->withHeader('Content-Type', $mimeType); - } - - public function getThumbnailContent(Request $request, Response $response, array $aArgs) - { - if (!Validator::intVal()->validate($aArgs['resId'])) { - return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']); - } - - $pathToThumbnail = 'apps/maarch_entreprise/img/noThumbnail.png'; - if (ResController::hasRightByResId(['resId' => $aArgs['resId'], 'userId' => $GLOBALS['userId']])) { - $tnlAdr = AdrModel::getTypedDocumentAdrByResId([ - 'select' => ['docserver_id', 'path', 'filename'], - 'resId' => $aArgs['resId'], - 'type' => 'TNL' - ]); - if (empty($tnlAdr)) { - $extDocument = ResModel::getExtById(['select' => ['category_id'], 'resId' => $aArgs['resId']]); - if ($extDocument['category_id'] == 'outgoing') { - $attachment = AttachmentModel::getOnView([ - 'select' => ['res_id', 'res_id_version'], - 'where' => ['res_id_master = ?', 'attachment_type = ?', 'status not in (?)'], - 'data' => [$aArgs['resId'], 'outgoing_mail', ['DEL', 'OBS']], - 'limit' => 1 - ]); - if (!empty($attachment[0])) { - ConvertThumbnailController::convert([ - 'collId' => 'letterbox_coll', - 'resId' => $aArgs['resId'], - 'outgoingId' => empty($attachment[0]['res_id']) ? $attachment[0]['res_id_version'] : $attachment[0]['res_id'], - 'isOutgoingVersion' => empty($attachment[0]['res_id']) - ]); - } - } else { - ConvertThumbnailController::convert(['collId' => 'letterbox_coll', 'resId' => $aArgs['resId']]); - } - $tnlAdr = AdrModel::getTypedDocumentAdrByResId([ - 'select' => ['docserver_id', 'path', 'filename'], - 'resId' => $aArgs['resId'], - 'type' => 'TNL' - ]); - } - - if (!empty($tnlAdr)) { - $docserver = DocserverModel::getByDocserverId(['docserverId' => $tnlAdr['docserver_id'], 'select' => ['path_template']]); - if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) { - return $response->withStatus(400)->withJson(['errors' => 'Docserver does not exist']); - } - - $pathToThumbnail = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $tnlAdr['path']) . $tnlAdr['filename']; - } - } - - $fileContent = file_get_contents($pathToThumbnail); - if ($fileContent === false) { - return $response->withStatus(404)->withJson(['errors' => 'Thumbnail not found on docserver']); - } - - $finfo = new \finfo(FILEINFO_MIME_TYPE); - $mimeType = $finfo->buffer($fileContent); - $pathInfo = pathinfo($pathToThumbnail); - - $response->write($fileContent); - $response = $response->withAddedHeader('Content-Disposition', "inline; filename=maarch.{$pathInfo['extension']}"); - - return $response->withHeader('Content-Type', $mimeType); - } - - public function getResourcesByBasket(Request $request, Response $response, array $aArgs) - { - $data = $request->getQueryParams(); - - if (empty($data['offset']) || !is_numeric($data['offset'])) { - $data['offset'] = 0; - } - if (empty($data['limit']) || !is_numeric($data['limit'])) { - $data['limit'] = 0; - } - - $group = GroupModel::getById(['id' => $aArgs['groupSerialId'], 'select' => ['group_id']]); - $basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause', 'basket_res_order']]); - if (empty($group) || empty($basket)) { - return $response->withStatus(400)->withJson(['errors' => 'Group or basket does not exist']); - } - - $groups = UserModel::getGroupsByUserId(['userId' => $GLOBALS['userId']]); - $groupFound = false; - foreach ($groups as $value) { - if ($value['id'] == $aArgs['groupSerialId']) { - $groupFound = true; - } - } - if (!$groupFound) { - return $response->withStatus(400)->withJson(['errors' => 'Group is not linked to this user']); - } - - $isBasketLinked = GroupBasketModel::get(['select' => [1], 'where' => ['basket_id = ?', 'group_id = ?'], 'data' => [$aArgs['basketId'], $group['group_id']]]); - if (empty($isBasketLinked)) { - return $response->withStatus(400)->withJson(['errors' => 'Group is not linked to this basket']); - } - - $whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $GLOBALS['userId']]); - $resources = ResModel::getForList([ - 'clause' => $whereClause, - 'orderBy' => ["{$basket['basket_res_order']} DESC"], - 'offset' => (int)$data['offset'], - 'limit' => (int)$data['limit'], - ]); - $allResources = ResModel::getOnView([ - 'select' => [1], - 'where' => [$whereClause], - ]); - - return $response->withJson(['resources' => $resources, 'number' => count($allResources)]); - } - - public function updateExternalInfos(Request $request, Response $response) - { - $data = $request->getParams(); - - if (empty($data['externalInfos'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - if (empty($data['status'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - foreach ($data['externalInfos'] as $mail) { - if(!Validator::intType()->validate($mail['res_id'])){ - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: invalid res_id']); - } - if(!Validator::StringType()->notEmpty()->validate($mail['external_id'])){ - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: invalid external_id for element : '.$mail['res_id']]); - } - if(!Validator::StringType()->notEmpty()->validate($mail['external_link'])){ - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: invalid external_link for element'.$mail['res_id']]); - } - } - - foreach ($data['externalInfos'] as $mail) { - $document = ResModel::getById(['resId' => $mail['res_id'], 'select' => ['res_id']]); - if (empty($document)) { - return $response->withStatus(400)->withJson(['errors' => _DOCUMENT_NOT_FOUND]); - } - if (!ResController::hasRightByResId(['resId' => $document['res_id'], 'userId' => $GLOBALS['userId']])) { - return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']); - } - ResModel::update(['set' => ['external_id' => $mail['external_id'] , 'external_link' => $mail['external_link'], 'status' => $data['status']], 'where' => ['res_id = ?'], 'data' => [$document['res_id']]]); - } - - return $response->withJson(['success' => 'success']); - } - - public function isLock(Request $request, Response $response, array $aArgs) - { - return $response->withJson(ResModel::isLock(['resId' => $aArgs['resId'], 'userId' => $GLOBALS['userId']])); - } - - public function getNotesCountForCurrentUserById(Request $request, Response $response, array $aArgs) - { - return $response->withJson(NoteModel::countByResId(['resId' => $aArgs['resId'], 'userId' => $GLOBALS['userId']])); - } - - public static function hasRightByResId(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId', 'userId']); - ValidatorModel::stringType($aArgs, ['userId']); - ValidatorModel::intVal($aArgs, ['resId']); - - if ($aArgs['userId'] == 'superadmin') { - return true; - } - $groups = UserModel::getGroupsByUserId(['userId' => $aArgs['userId']]); - $groupsClause = ''; - foreach ($groups as $key => $group) { - if (!empty($group['where_clause'])) { - $groupClause = PreparedClauseController::getPreparedClause(['clause' => $group['where_clause'], 'userId' => $aArgs['userId']]); - if ($key > 0) { - $groupsClause .= ' or '; - } - $groupsClause .= "({$groupClause})"; - } - } - - if (!empty($groupsClause)) { - $res = ResModel::getOnView(['select' => [1], 'where' => ['res_id = ?', "({$groupsClause})"], 'data' => [$aArgs['resId']]]); - if (!empty($res)) { - return true; - } - } - - $baskets = BasketModel::getBasketsByUserId(['userId' => $aArgs['userId'], 'unneededBasketId' => ['IndexingBasket']]); - $basketsClause = ''; - foreach ($baskets as $key => $basket) { - if (!empty($basket['basket_clause'])) { - $basketClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'userId' => $aArgs['userId']]); - if ($key > 0) { - $basketsClause .= ' or '; - } - $basketsClause .= "({$basketClause})"; - } - } - - if (!empty($basketsClause)) { - try { - $res = ResModel::getOnView(['select' => [1], 'where' => ['res_id = ?', "({$basketsClause})"], 'data' => [$aArgs['resId']]]); - if (!empty($res)) { - return true; - } - } catch (\Exception $e) { - return false; - } - } - - return false; - } - - public function getList(Request $request, Response $response) - { - $data = $request->getParams(); - - if (!Validator::stringType()->notEmpty()->validate($data['select'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: select is not valid']); - } - if (!Validator::stringType()->notEmpty()->validate($data['clause'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: clause is not valid']); - } - if (!empty($data['withFile'])) { - if(!Validator::boolType()->validate($data['withFile'])){ - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: withFile parameter is not a boolean']); - } - } - - if (!empty($data['orderBy'])) { - if (!Validator::arrayType()->notEmpty()->validate($data['orderBy'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: orderBy parameter not valid']); - } - } - - if (!empty($data['limit'])) { - if (!Validator::intType()->validate($data['limit'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request: limit parameter not valid']); - } - } - $select = explode(',', $data['select']); - - if (!PreparedClauseController::isRequestValid(['select' => $select, 'clause' => $data['clause'], 'orderBy' => $data['orderBy'], 'limit' => $data['limit'], 'userId' => $GLOBALS['userId']])) { - return $response->withStatus(400)->withJson(['errors' => _INVALID_REQUEST]); - } - - $where = [$data['clause']]; - if ($GLOBALS['userId'] != 'superadmin') { - $groupsClause = GroupController::getGroupsClause(['userId' => $GLOBALS['userId']]); - if (empty($groupsClause)) { - return $response->withStatus(400)->withJson(['errors' => 'User has no groups']); - } - $where[] = "({$groupsClause})"; - } - - if ($data['withFile'] === true) { - $select[] = 'res_id'; - } - - $resources = ResModel::getOnView(['select' => $select, 'where' => $where, 'orderBy' => $data['orderBy'], 'limit' => $data['limit']]); - if ($data['withFile'] === true) { - foreach ($resources as $key => $res) { - $path = ResDocserverModel::getSourceResourcePath(['resId' => $res['res_id'], 'resTable' => 'res_letterbox', 'adrTable' => 'null']); - $file = file_get_contents($path); - $base64Content = base64_encode($file); - $resources[$key]['fileBase64Content'] = $base64Content; - } - } - - return $response->withJson(['resources' => $resources, 'count' => count($resources)]); - } - - public function getCategories(Request $request, Response $response) - { - return $response->withJson(['categories' => ResModel::getCategories()]); - } - - public function getNatures(Request $request, Response $response) - { - return $response->withJson(['natures' => ResModel::getNatures()]); - } -} diff --git a/src/app/resource/controllers/StoreController.php b/src/app/resource/controllers/StoreController.php deleted file mode 100644 index 26b2548cdc..0000000000 --- a/src/app/resource/controllers/StoreController.php +++ /dev/null @@ -1,352 +0,0 @@ -<?php - -/** - * Copyright Maarch since 2008 under licence GPLv3. - * See LICENCE.txt file at the root folder for more details. - * This file is part of Maarch software. - * - */ - -/** - * @brief Store Controller - * @author dev@maarch.org - * @ingroup core - */ - -namespace Resource\controllers; - -use Attachment\models\AttachmentModel; -use Contact\models\ContactModel; -use Convert\controllers\ConvertThumbnailController; -use Convert\controllers\ConvertPdfController; -use Docserver\controllers\DocserverController; -use Resource\models\ChronoModel; -use SrcCore\models\ValidatorModel; -use Entity\models\EntityModel; -use Resource\models\ResModel; -use SrcCore\models\CoreConfigModel; -use User\models\UserModel; - -class StoreController -{ - public static function storeResource(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['encodedFile', 'data', 'collId', 'table', 'fileFormat', 'status']); - ValidatorModel::stringType($aArgs, ['collId', 'table', 'fileFormat', 'status']); - ValidatorModel::arrayType($aArgs, ['data']); - - if (!in_array($aArgs['table'], ['res_letterbox', 'res_attachments'])) { - return ['errors' => '[storeResource] Table not valid']; - } - - try { - $fileContent = base64_decode(str_replace(['-', '_'], ['+', '/'], $aArgs['encodedFile'])); - $fileName = 'tmp_file_' . rand() . '.' . $aArgs['fileFormat']; - $tmpFilepath = CoreConfigModel::getTmpPath() . $fileName; - - $file = fopen($tmpFilepath, 'w'); - fwrite($file, $fileContent); - fclose($file); - - $storeResult = DocserverController::storeResourceOnDocServer([ - 'collId' => $aArgs['collId'], - 'docserverTypeId' => 'DOC', - 'fileInfos' => [ - 'tmpDir' => CoreConfigModel::getTmpPath(), - 'tmpFileName' => $fileName - ] - ]); - if (!empty($storeResult['errors'])) { - return ['errors' => '[storeResource] ' . $storeResult['errors']]; - } - unlink($tmpFilepath); - - $data = StoreController::prepareStorage([ - 'data' => $aArgs['data'], - 'docserverId' => $storeResult['docserver_id'], - 'status' => $aArgs['status'], - 'fileName' => $storeResult['file_destination_name'], - 'fileFormat' => $aArgs['fileFormat'], - 'fileSize' => $storeResult['fileSize'], - 'path' => $storeResult['destination_dir'], - 'fingerPrint' => $storeResult['fingerPrint'] - ]); - - $resId = false; - if ($aArgs['table'] == 'res_letterbox') { - $resId = ResModel::create($data); - } elseif ($aArgs['table'] == 'res_attachments') { - $resId = AttachmentModel::create($data); - } - - return $resId; - } catch (\Exception $e) { - return ['errors' => '[storeResource] ' . $e->getMessage()]; - } - } - - public static function controlFingerPrint(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['pathInit', 'pathTarget']); - ValidatorModel::stringType($aArgs, ['pathInit', 'pathTarget', 'fingerprintMode']); - - if (!file_exists($aArgs['pathInit'])) { - return ['errors' => '[controlFingerprint] PathInit does not exist']; - } - if (!file_exists($aArgs['pathTarget'])) { - return ['errors' => '[controlFingerprint] PathTarget does not exist']; - } - - $fingerprint1 = StoreController::getFingerPrint(['filePath' => $aArgs['pathInit'], 'mode' => $aArgs['fingerprintMode']]); - $fingerprint2 = StoreController::getFingerPrint(['filePath' => $aArgs['pathTarget'], 'mode' => $aArgs['fingerprintMode']]); - - if ($fingerprint1 != $fingerprint2) { - return ['errors' => '[controlFingerprint] Fingerprints do not match: ' . $aArgs['pathInit'] . ' and ' . $aArgs['pathTarget']]; - } - - return true; - } - - public static function getFingerPrint(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['filePath']); - ValidatorModel::stringType($aArgs, ['filePath', 'mode']); - - if (empty($aArgs['mode']) || $aArgs['mode'] == 'NONE') { - return '0'; - } - - return hash_file(strtolower($aArgs['mode']), $aArgs['filePath']); - } - - public static function prepareStorage(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['data', 'docserverId', 'fileName', 'fileFormat', 'fileSize', 'path', 'fingerPrint']); - ValidatorModel::stringType($aArgs, ['docserverId', 'status', 'fileName', 'fileFormat', 'path', 'fingerPrint']); - ValidatorModel::arrayType($aArgs, ['data']); - ValidatorModel::intVal($aArgs, ['fileSize']); - - $statusFound = false; - $typistFound = false; - $toAddressFound = false; - $userPrimaryEntity = false; - - foreach ($aArgs['data'] as $key => $value) { - $aArgs['data'][$key]['column'] = strtolower($value['column']); - } - - foreach ($aArgs['data'] as $key => $value) { - if (strtolower($value['type']) == 'integer' || strtolower($value['type']) == 'float') { - if (empty($value['value'])) { - $aArgs['data'][$key]['value'] = '0'; - } - } elseif (strtolower($value['type']) == 'string') { - $aArgs['data'][$key]['value'] = str_replace(';', '', $value['value']); - $aArgs['data'][$key]['value'] = str_replace('--', '', $value['value']); - } - - if ($value['column'] == 'status') { - $statusFound = true; - } elseif ($value['column'] == 'typist') { - $typistFound = true; - } elseif ($value['column'] == 'custom_t10') { - $theString = str_replace('>', '', $value['value']); - $mail = explode("<", $theString); - $user = UserModel::getByEmail(['mail' => $mail[count($mail) -1], 'select' => ['user_id']]); - if (!empty($user[0]['user_id'])) { - $toAddressFound = true; - $destUser = $user[0]['user_id']; - $entity = EntityModel::getByUserId(['userId' => $destUser, 'select' => ['entity_id']]); - if (!empty($entity[0]['entity_id'])) { - $userEntity = $entity[0]['entity_id']; - $userPrimaryEntity = true; - } - } else { - $entity = EntityModel::getByEmail(['email' => $mail[count($mail) -1], 'select' => ['entity_id']]); - if (!empty($entity[0]['entity_id'])) { - $userPrimaryEntity = true; - } - } - } - } - - $destUser = empty($destUser) ? '' : $destUser; - $userEntity = empty($userEntity) ? '' : $userEntity; - - if (!$typistFound && !$toAddressFound) { - $aArgs['data'][] = [ - 'column' => 'typist', - 'value' => 'auto', - 'type' => 'string' - ]; - } - if (!$statusFound) { - $aArgs['data'][] = [ - 'column' => 'status', - 'value' => $aArgs['status'], - 'type' => 'string' - ]; - } - if ($toAddressFound) { - $aArgs['data'][] = [ - 'column' => 'dest_user', - 'value' => $destUser, - 'type' => 'string' - ]; - if (!$typistFound) { - $aArgs['data'][] = [ - 'column' => 'typist', - 'value' => $destUser, - 'type' => 'string' - ]; - } - } - if ($userPrimaryEntity) { - $destinationFound = false; - $initiatorFound = false; - foreach ($aArgs['data'] as $key => $value) { - if ($value['column'] == 'destination') { - if (empty($value['value'])) { - $aArgs['data'][$key]['value'] = $userEntity; - } - $destinationFound = true; - } elseif ($value['column'] == 'initiator') { - if (empty($value['value'])) { - $aArgs['data'][$key]['value'] = $userEntity; - } - $initiatorFound = true; - } - } - if (!$destinationFound) { - $aArgs['data'][] = [ - 'column' => 'destination', - 'value' => $userEntity, - 'type' => 'string' - ]; - } - if (!$initiatorFound) { - $aArgs['data'][] = [ - 'column' => 'initiator', - 'value' => $userEntity, - 'type' => 'string' - ]; - } - } - - $aArgs['data'][] = [ - 'column' => 'docserver_id', - 'value' => $aArgs['docserverId'], - 'type' => 'string' - ]; - $aArgs['data'][] = [ - 'column' => 'creation_date', - 'value' => 'CURRENT_TIMESTAMP', - 'type' => 'function' - ]; - $aArgs['data'][] = [ - 'column' => 'path', - 'value' => $aArgs['path'], - 'type' => 'string' - ]; - $aArgs['data'][] = [ - 'column' => 'fingerprint', - 'value' => $aArgs['fingerPrint'], - 'type' => 'string' - ]; - $aArgs['data'][] = [ - 'column' => 'filename', - 'value' => $aArgs['fileName'], - 'type' => 'string' - ]; - $aArgs['data'][] = [ - 'column' => 'format', - 'value' => $aArgs['fileFormat'], - 'type' => 'string' - ]; - $aArgs['data'][] = [ - 'column' => 'filesize', - 'value' => $aArgs['fileSize'], - 'type' => 'int' - ]; - - $formatedData = []; - foreach ($aArgs['data'] as $value) { - $formatedData[$value['column']] = $value['value']; - } - - return $formatedData; - } - - public static function prepareExtStorage(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['data', 'resId']); - ValidatorModel::arrayType($aArgs, ['data']); - ValidatorModel::intVal($aArgs, ['resId']); - - $processLimitDateFound = false; - $admissionDate = null; - - foreach ($aArgs['data'] as $key => $value) { - $aArgs['data'][$key]['column'] = strtolower($value['column']); - } - - foreach ($aArgs['data'] as $value) { - if ($value['column'] == 'process_limit_date') { - $processLimitDateFound = true; - } - if ($value['column'] == 'category_id') { - $categoryId = $value['value']; - } - if ($value['column'] == 'admission_date') { - $admissionDate = $value['value']; - } - } - - if (!$processLimitDateFound) { - $processLimitDate = ResModel::getStoredProcessLimitDate(['resId' => $aArgs['resId'], 'admissionDate' => $admissionDate]); - - $aArgs['data'][] = [ - 'column' => 'process_limit_date', - 'value' => $processLimitDate, - 'type' => 'date' - ]; - } - - foreach ($aArgs['data'] as $key => $value) { - if (strtolower($value['type']) == 'integer' || strtolower($value['type']) == 'float') { - if ($value['value'] == '') { - $aArgs['data'][$key]['value'] = '0'; - } - $aArgs['data'][$key]['value'] = str_replace(',', '.', $value['value']); - } - if ($value['column'] == 'alt_identifier' && empty($value['value']) && !empty($categoryId)) { - $document = ResModel::getById(['resId' => $aArgs['resId'], 'select' => ['destination, type_id']]); - $aArgs['data'][$key]['value'] = ChronoModel::getChrono(['id' => $categoryId, 'entityId' => $document['destination'], 'typeId' => $document['type_id']]); - } elseif ($value['column'] == 'exp_contact_id' && !empty($value['value']) && !is_numeric($value['value'])) { - $mail = explode('<', str_replace('>', '', $value['value'])); - $contact = ContactModel::getByEmail(['email' => $mail[count($mail) - 1], 'select' => ['contacts_v2.contact_id']]); - if (!empty($contact['contact_id'])) { - $aArgs['data'][$key]['value'] = $contact['contact_id']; - } else { - $aArgs['data'][$key]['value'] = 0; - } - } elseif ($value['column'] == 'address_id' && !empty($value['value']) && !is_numeric($value['value'])) { - $mail = explode('<', str_replace('>', '', $value['value'])); - $contact = ContactModel::getByEmail(['email' => $mail[count($mail) - 1], 'select' => ['contact_addresses.id']]); - if (!empty($contact['id'])) { - $aArgs['data'][$key]['value'] = $contact['ca_id']; - } else { - $aArgs['data'][$key]['value'] = 0; - } - } - } - - $formatedData = []; - foreach ($aArgs['data'] as $value) { - $formatedData[$value['column']] = $value['value']; - } - $formatedData['res_id'] = $aArgs['resId']; - - return $formatedData; - } -} diff --git a/src/app/resource/models/ResModel.php b/src/app/resource/models/ResModel.php deleted file mode 100644 index 2ef8801c92..0000000000 --- a/src/app/resource/models/ResModel.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php - -/** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ - -/** -* @brief Res Model -* @author dev@maarch.org -*/ - -namespace Resource\models; - -class ResModel extends ResModelAbstract -{ -} diff --git a/src/app/resource/models/ResModelAbstract.php b/src/app/resource/models/ResModelAbstract.php deleted file mode 100644 index e43b661ef8..0000000000 --- a/src/app/resource/models/ResModelAbstract.php +++ /dev/null @@ -1,450 +0,0 @@ -<?php - -/** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ - -/** -* @brief Res Model -* @author dev@maarch.org -*/ - -namespace Resource\models; - -use SrcCore\models\CoreConfigModel; -use SrcCore\models\ValidatorModel; -use SrcCore\models\DatabaseModel; - -abstract class ResModelAbstract -{ - public static function getOnView(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['select']); - ValidatorModel::arrayType($aArgs, ['select', 'where', 'data', 'orderBy']); - ValidatorModel::intType($aArgs, ['limit', 'offset']); - - $aResources = DatabaseModel::select([ - 'select' => $aArgs['select'], - 'table' => ['res_view_letterbox'], - 'where' => empty($aArgs['where']) ? [] : $aArgs['where'], - 'data' => empty($aArgs['data']) ? [] : $aArgs['data'], - 'order_by' => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'], - 'offset' => empty($aArgs['offset']) ? 0 : $aArgs['offset'], - 'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit'] - ]); - - return $aResources; - } - - public static function getForList(array $aArgs) - { - ValidatorModel::arrayType($aArgs, ['orderBy']); - ValidatorModel::stringType($aArgs, ['clause']); - ValidatorModel::intType($aArgs, ['limit', 'offset']); - - $where = ['res_view_letterbox.priority = priorities.id', 'res_view_letterbox.status = status.id', 'res_view_letterbox.dest_user = users.user_id']; - $where[] = $aArgs['clause']; - - $aResources = DatabaseModel::select([ - 'select' => [ - 'alt_identifier', - 'category_id', - 'case_label', - 'closing_date', - 'category_id', - 'contact_lastname', - 'contact_society', - 'creation_date', - 'entity_label as entity_destination', - 'folder_name', - 'priorities.color as priority_color', - 'priorities.label as priority_label', - 'process_limit_date', - 'res_id', - 'status.img_filename as status_icon', - 'status.label_status as status_label', - 'status.id as status_id', - 'subject', - 'type_label as doctype_label', - 'user_lastname', - 'user_firstname', - 'users.lastname as user_dest_lastname', - 'users.firstname as user_dest_firstname', - ], - 'table' => ['res_view_letterbox, priorities, status, users'], - 'where' => $where, - 'data' => [], - 'order_by' => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'], - 'offset' => empty($aArgs['offset']) ? 0 : $aArgs['offset'], - 'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit'] - ]); - - return $aResources; - } - - public static function get(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['select']); - ValidatorModel::arrayType($aArgs, ['select', 'where', 'data']); - - $aResources = DatabaseModel::select([ - 'select' => $aArgs['select'], - 'table' => ['res_letterbox'], - 'where' => $aArgs['where'], - 'data' => $aArgs['data'] - ]); - - return $aResources; - } - - public static function getById(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId']); - ValidatorModel::intVal($aArgs, ['resId']); - - $aResources = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['res_letterbox'], - 'where' => ['res_id = ?'], - 'data' => [$aArgs['resId']] - ]); - - if (empty($aResources[0])) { - return []; - } - - return $aResources[0]; - } - - public static function getExtById(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId']); - ValidatorModel::intVal($aArgs, ['resId']); - - $aResources = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['mlb_coll_ext'], - 'where' => ['res_id = ?'], - 'data' => [$aArgs['resId']] - ]); - - if (empty($aResources[0])) { - return []; - } - - return $aResources[0]; - } - - public static function create(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['format', 'typist', 'creation_date', 'docserver_id', 'path', 'filename', 'fingerprint', 'filesize', 'status']); - ValidatorModel::stringType($aArgs, ['format', 'typist', 'creation_date', 'docserver_id', 'path', 'filename', 'fingerprint', 'status']); - ValidatorModel::intVal($aArgs, ['filesize']); - - $nextSequenceId = DatabaseModel::getNextSequenceValue(['sequenceId' => 'res_id_mlb_seq']); - $aArgs['res_id'] = $nextSequenceId; - - DatabaseModel::insert([ - 'table' => 'res_letterbox', - 'columnsValues' => $aArgs - ]); - - return $nextSequenceId; - } - - public static function createExt(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['res_id', 'category_id']); - ValidatorModel::stringType($aArgs, ['category_id']); - ValidatorModel::intVal($aArgs, ['res_id']); - - DatabaseModel::insert([ - 'table' => 'mlb_coll_ext', - 'columnsValues' => $aArgs - ]); - - return true; - } - - public static function update(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['set', 'where', 'data']); - ValidatorModel::arrayType($aArgs, ['set', 'where', 'data']); - - DatabaseModel::update([ - 'table' => 'res_letterbox', - 'set' => $aArgs['set'], - 'where' => $aArgs['where'], - 'data' => $aArgs['data'] - ]); - - return true; - } - - public static function updateExt(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['set', 'where', 'data']); - ValidatorModel::arrayType($aArgs, ['set', 'where', 'data']); - - DatabaseModel::update([ - 'table' => 'mlb_coll_ext', - 'set' => $aArgs['set'], - 'where' => $aArgs['where'], - 'data' => $aArgs['data'] - ]); - - return true; - } - - public static function delete(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId']); - ValidatorModel::intVal($aArgs, ['resId']); - - DatabaseModel::update([ - 'table' => 'res_letterbox', - 'set' => [ - 'status' => 'DEL' - ], - 'where' => ['res_id = ?'], - 'data' => [$aArgs['resId']] - ]); - - return true; - } - - public static function getLastResources(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['limit', 'userId', 'select']); - ValidatorModel::intType($aArgs, ['limit']); - ValidatorModel::stringType($aArgs, ['userId']); - ValidatorModel::arrayType($aArgs, ['select']); - - $resources = DatabaseModel::select([ - 'select' => $aArgs['select'], - 'table' => ['history, res_letterbox r, mlb_coll_ext mlb, status, priorities'], - 'where' => [ - 'history.user_id = ?', 'history.table_name IN (?)', - 'history.record_id IS NOT NULL', 'history.record_id != ?', - 'history.event_id != ?', 'history.event_id NOT LIKE ?', - 'CAST(history.record_id AS INT) = r.res_id', - 'r.res_id = r.res_id', 'r.status != ?', - 'r.status = status.id', - 'r.priority = priorities.id', - 'r.res_id = mlb.res_id', - ], - 'data' => [$aArgs['userId'], ['res_letterbox', 'res_view_letterbox'], 'none', 'linkup', 'attach%', 'DEL'], - 'group_by' => ['r.subject', 'r.creation_date', 'r.res_id', 'mlb.alt_identifier', 'mlb.closing_date', 'mlb.process_limit_date', 'status.id', 'status.label_status', 'status.img_filename', 'priorities.color', 'priorities.label'], - 'order_by' => ['MAX(history.event_date) DESC'], - 'limit' => $aArgs['limit'] - ]); - - return $resources; - } - - public static function isLock(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId', 'userId']); - ValidatorModel::intVal($aArgs, ['resId']); - ValidatorModel::stringType($aArgs, ['userId']); - - $aReturn = DatabaseModel::select([ - 'select' => ['locker_user_id', 'locker_time'], - 'table' => ['res_letterbox'], - 'where' => ['res_id = ?'], - 'data' => [$aArgs['resId']] - ]); - - $lock = true; - $lockBy = empty($aReturn[0]['locker_user_id']) ? '' : $aReturn[0]['locker_user_id']; - - if (empty($aReturn[0]['locker_user_id'] || empty($aReturn[0]['locker_time']))) { - $lock = false; - } elseif ($aReturn[0]['locker_user_id'] == $aArgs['userId']) { - $lock = false; - } elseif (strtotime($aReturn[0]['locker_time']) < time()) { - $lock = false; - } - - return ['lock' => $lock, 'lockBy' => $lockBy]; - } - - public static function getDocsByClause(array $aArgs = []) - { - ValidatorModel::notEmpty($aArgs, ['clause']); - - if (!empty($aArgs['table'])) { - $table = $aArgs['table']; - } else { - $table = 'res_view_letterbox'; - } - - $aReturn = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => [$table], - 'where' => [$aArgs['clause']], - 'order_by' => ['res_id'] - ]); - - return $aReturn; - } - - public static function getResIdByAltIdentifier(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['altIdentifier']); - ValidatorModel::stringType($aArgs, ['altIdentifier']); - - $aResources = DatabaseModel::select([ - 'select' => ['res_id'], - 'table' => ['mlb_coll_ext'], - 'where' => ['alt_identifier = ?'], - 'data' => [$aArgs['altIdentifier']] - ]); - - if (empty($aResources[0])) { - return []; - } - - return $aResources[0]; - } - - public static function getStoredProcessLimitDate(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId']); - ValidatorModel::intVal($aArgs, ['resId']); - ValidatorModel::stringType($aArgs, ['admissionDate']); - - $document = ResModel::getById(['resId' => $aArgs['resId'], 'select' => ['creation_date', 'type_id']]); - - $processDelay = 30; - if (!empty($document['type_id'])) { - $doctypeExt = DatabaseModel::select([ - 'select' => ['process_delay'], - 'table' => ['mlb_doctype_ext'], - 'where' => ['type_id = ?'], - 'data' => [$document['type_id']] - ]); - $processDelay = $doctypeExt[0]['process_delay']; - } - - if (!empty($aArgs['admissionDate'])) { - if (strtotime($aArgs['admissionDate']) === false) { - $defaultDate = date('c'); - } else { - $defaultDate = $aArgs['admissionDate']; - } - } elseif (!empty($document['creation_date'])) { - $defaultDate = $document['creation_date']; - } else { - $defaultDate = date('c'); - } - - $date = new \DateTime($defaultDate); - - $calendarType = 'calendar'; - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/features.xml']); - - if ($loadedXml && !empty((string)$loadedXml->FEATURES->type_calendar)) { - $calendarType = (string)$loadedXml->FEATURES->type_calendar; - } - - if ($calendarType == 'workingDay') { - $hollidays = [ - '01-01', - '01-05', - '08-05', - '14-07', - '15-08', - '01-11', - '11-11', - '25-12' - ]; - if (function_exists('easter_date')) { - $hollidays[] = date('d-m', easter_date() + 86400); - } - - $processDelayUpdated = 1; - for ($i = 1; $i <= $processDelay; $i++) { - $tmpDate = new \DateTime($defaultDate); - $tmpDate->add(new \DateInterval("P{$i}D")); - if (in_array($tmpDate->format('N'), [6, 7]) || in_array($tmpDate->format('d-m'), $hollidays)) { - ++$processDelay; - } - ++$processDelayUpdated; - } - - $date->add(new \DateInterval("P{$processDelayUpdated}D")); - } else { - $date->add(new \DateInterval("P{$processDelay}D")); - } - - return $date->format('Y-m-d H:i:s'); - } - - public static function getCategories() - { - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/config.xml']); - - $categories = []; - - if ($loadedXml) { - foreach ($loadedXml->COLLECTION as $collection) { - $collection = (array)$collection; - - if ($collection['id'] == 'letterbox_coll') { - foreach ($collection['categories']->category as $category) { - $category = (array)$category; - - $categories[] = [ - 'id' => $category['id'], - 'label' => defined($category['label']) ? constant($category['label']) : $category['label'], - 'defaultCategory' => $category['id'] == $collection['categories']->default_category - ]; - } - } - } - } - - return $categories; - } - - public static function getNatures() - { - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/entreprise.xml']); - - $natures = []; - - if ($loadedXml) { - foreach ($loadedXml->mail_natures->nature as $nature) { - $withReference = (string)$nature['with_reference'] == 'true' ? true : false; - $nature = (array)$nature; - - $natures[] = [ - 'id' => $nature['id'], - 'label' => defined($nature['label']) ? constant($nature['label']) : $nature['label'], - 'withReference' => $withReference, - 'defaultNature' => $nature['id'] == $loadedXml->mail_natures->default_nature - ]; - } - } - - return $natures; - } - - public static function getNbContactsByResId(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['resId']); - ValidatorModel::intVal($aArgs, ['resId']); - - $aResources = DatabaseModel::select([ - 'select' => ['count(1) as nb_contacts'], - 'table' => ['contacts_res'], - 'where' => ['res_id = ?', 'mode = ?'], - 'data' => [$aArgs['resId'], 'multi'] - ]); - return $aResources[0]['nb_contacts']; - } -} diff --git a/src/app/user/controllers/UserController.php b/src/app/user/controllers/UserController.php index 88c14050ab..5e80b8ed30 100644 --- a/src/app/user/controllers/UserController.php +++ b/src/app/user/controllers/UserController.php @@ -14,1124 +14,80 @@ namespace User\controllers; -use Basket\models\BasketModel; -use Basket\models\GroupBasketModel; use Docserver\controllers\DocserverController; use Docserver\models\DocserverModel; -use Entity\models\ListInstanceModel; -use Group\models\ServiceModel; -use Entity\models\EntityModel; -use Entity\models\ListTemplateModel; -use Group\models\GroupModel; -use History\controllers\HistoryController; -use History\models\HistoryModel; -use Notification\controllers\NotificationsEventsController; -use Parameter\models\ParameterModel; -use Resource\models\ResModel; use Respect\Validation\Validator; use Slim\Http\Request; use Slim\Http\Response; -use SrcCore\controllers\PasswordController; -use SrcCore\models\AuthenticationModel; -use SrcCore\models\CoreConfigModel; -use SrcCore\models\PasswordModel; -use User\models\UserBasketPreferenceModel; -use User\models\UserEntityModel; use User\models\UserModel; -use User\models\UserSignatureModel; class UserController { - const ALTERNATIVES_CONNECTIONS_METHODS = ['sso', 'cas', 'ldap', 'ozwillo']; - - public function get(Request $request, Response $response) - { - if (!ServiceModel::hasService(['id' => 'admin_users', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - if ($GLOBALS['userId'] == 'superadmin') { - $users = UserModel::get([ - 'select' => ['id', 'user_id', 'firstname', 'lastname', 'status', 'enabled', 'mail'], - 'where' => ['user_id != ?', 'status != ?'], - 'data' => ['superadmin', 'DEL'] - ]); - } else { - $entities = EntityModel::getAllEntitiesByUserId(['userId' => $GLOBALS['userId']]); - $users = UserEntityModel::getUsersByEntities([ - 'select' => ['DISTINCT users.id', 'users.user_id', 'firstname', 'lastname', 'status', 'enabled', 'mail'], - 'entities' => $entities - ]); - $usersNoEntities = UserEntityModel::getUsersWithoutEntities(['select' => ['id', 'users.user_id', 'firstname', 'lastname', 'status', 'enabled', 'mail']]); - $users = array_merge($users, $usersNoEntities); - } - - $usersIds = []; - foreach ($users as $value) { - $usersIds[] = $value['user_id']; - } - - $listModels = ListTemplateModel::get(['select' => ['item_id'], 'where' => ['item_id in (?)', 'object_type = ?', 'item_mode = ?'], 'data' => [$usersIds, 'entity_id', 'dest']]); - - $usersListModels = []; - foreach ($listModels as $value) { - $usersListModels[] = $value['item_id']; - } - - foreach ($users as $key => $value) { - if (in_array($value['user_id'], $usersListModels)) { - $users[$key]['inDiffListDest'] = 'Y'; - } else { - $users[$key]['inDiffListDest'] = 'N'; - } - } - - $quota = []; - $userQuota = ParameterModel::getById(['id' => 'user_quota', 'select' => ['param_value_int']]); - if (!empty($userQuota['param_value_int'])) { - $activeUser = UserModel::get(['select' => ['count(1)'], 'where' => ['enabled = ?', 'status = ?', 'user_id <> ?'], 'data' => ['Y', 'OK','superadmin']]); - $inactiveUser = UserModel::get(['select' => ['count(1)'], 'where' => ['enabled = ?', 'status = ?', 'user_id <> ?'], 'data' => ['N', 'OK','superadmin']]); - $quota = ['actives' => $activeUser[0]['count'], 'inactives' => $inactiveUser[0]['count'], 'userQuota' => $userQuota['param_value_int']]; - } - - return $response->withJson(['users' => $users, 'quota' => $quota]); - } - - public function getDetailledById(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['id', 'user_id', 'firstname', 'lastname', 'status', 'enabled', 'phone', 'mail', 'initials', 'thumbprint', 'loginmode']]); - $user['signatures'] = UserSignatureModel::getByUserSerialId(['userSerialid' => $aArgs['id']]); - $user['emailSignatures'] = UserModel::getEmailSignaturesById(['userId' => $user['user_id']]); - $user['groups'] = UserModel::getGroupsByUserId(['userId' => $user['user_id']]); - $user['allGroups'] = GroupModel::getAvailableGroupsByUserId(['userId' => $user['user_id']]); - $user['entities'] = UserModel::getEntitiesById(['userId' => $user['user_id']]); - $user['allEntities'] = EntityModel::getAvailableEntitiesForAdministratorByUserId(['userId' => $user['user_id'], 'administratorUserId' => $GLOBALS['userId']]); - $user['baskets'] = BasketModel::getBasketsByUserId(['userId' => $user['user_id'], 'unneededBasketId' => ['IndexingBasket']]); - $user['history'] = HistoryModel::getByUserId(['userId' => $user['user_id'], 'select' => ['event_type', 'event_date', 'info', 'remote_ip']]); - $user['canModifyPassword'] = true; - - $loggingMethod = CoreConfigModel::getLoggingMethod(); - if (in_array($loggingMethod['id'], self::ALTERNATIVES_CONNECTIONS_METHODS)) { - $user['canModifyPassword'] = false; - } - - return $response->withJson($user); - } - - public function create(Request $request, Response $response) + public function createSignature(Request $request, Response $response, array $args) { - if (!ServiceModel::hasService(['id' => 'admin_users', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); + $user = UserModel::getByLogin(['login' => $GLOBALS['login'], 'select' => ['id']]); + if ($user['id'] != $args['id']) { + return $response->withStatus(403)->withJson(['errors' => 'User out of perimeter']); } $data = $request->getParams(); - $check = Validator::stringType()->notEmpty()->validate($data['userId']) && preg_match("/^[\w.@-]*$/", $data['userId']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['firstname']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['lastname']); - $check = $check && (empty($data['mail']) || filter_var($data['mail'], FILTER_VALIDATE_EMAIL)); - $check = $check && (empty($data['phone']) || preg_match("/\+?((|\ |\.|\(|\)|\-)?(\d)*)*\d$/", $data['phone'])); + $check = Validator::notEmpty()->validate($data['encodedSignature']); + $check = $check && Validator::stringType()->notEmpty()->validate($data['format']); if (!$check) { return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); } - $existingUser = UserModel::getByUserId(['userId' => $data['userId'], 'select' => ['id', 'status']]); - if (!empty($existingUser) && $existingUser['status'] == 'DEL') { - UserModel::updateStatus(['id' => $existingUser['id'], 'status' => 'OK']); - $data['enabled'] = 'Y'; - UserModel::update(['id' => $existingUser['id'], 'user' => $data]); - - return $response->withJson(['user' => $existingUser]); - } elseif (!empty($existingUser)) { - return $response->withStatus(400)->withJson(['errors' => _USER_ID_ALREADY_EXISTS]); - } - - $logingModes = ['standard', 'restMode']; - if (!in_array($data['loginmode'], $logingModes)) { - $data['loginmode'] = 'standard'; - } - - UserModel::create(['user' => $data]); - - $newUser = UserModel::getByUserId(['userId' => $data['userId']]); - if (!Validator::intType()->notEmpty()->validate($newUser['id'])) { - return $response->withStatus(500)->withJson(['errors' => 'User Creation Error']); - } - - $userQuota = ParameterModel::getById(['id' => 'user_quota', 'select' => ['param_value_int']]); - if (!empty($userQuota['param_value_int'])) { - $activeUser = UserModel::get(['select' => ['count(1)'], 'where' => ['enabled = ?', 'status = ?', 'user_id <> ?'], 'data' => ['Y', 'OK','superadmin']]); - if ($activeUser[0]['count'] > $userQuota['param_value_int']) { - NotificationsEventsController::fillEventStack(['eventId' => 'user_quota', 'tableName' => 'users', 'recordId' => 'quota_exceed', 'userId' => 'superadmin', 'info' => _QUOTA_EXCEEDED]); - } - } - - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $GLOBALS['userId'], - 'eventType' => 'ADD', - 'eventId' => 'userCreation', - 'info' => _USER_CREATED . " {$data['userId']}" - ]); - - return $response->withJson(['user' => $newUser]); - } - - public function update(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['user_id']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['firstname']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['lastname']); - $check = $check && (empty($data['mail']) || filter_var($data['mail'], FILTER_VALIDATE_EMAIL)); - $check = $check && (empty($data['phone']) || preg_match("/\+?((|\ |\.|\(|\)|\-)?(\d)*)*\d$/", $data['phone'])); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['enabled']]); - - UserModel::update(['id' => $aArgs['id'], 'user' => $data]); - - $userQuota = ParameterModel::getById(['id' => 'user_quota', 'select' => ['param_value_int']]); - if (!empty($userQuota['param_value_int']) && $user['enabled'] == 'N' && $data['enabled'] == 'Y') { - $activeUser = UserModel::get(['select' => ['count(1)'], 'where' => ['enabled = ?', 'status = ?', 'user_id <> ?'], 'data' => ['Y', 'OK','superadmin']]); - if ($activeUser[0]['count'] > $userQuota['param_value_int']) { - NotificationsEventsController::fillEventStack(['eventId' => 'user_quota', 'tableName' => 'users', 'recordId' => 'quota_exceed', 'userId' => 'superadmin', 'info' => _QUOTA_EXCEEDED]); - } - } - - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $GLOBALS['userId'], - 'eventType' => 'ADD', - 'eventId' => 'userCreation', - 'info' => _USER_UPDATED . " {$data['user_id']}" - ]); - - return $response->withJson(['success' => 'success']); - } - - public function delete(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'delete' => true, 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - UserModel::delete(['id' => $aArgs['id']]); - - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $GLOBALS['userId'], - 'eventType' => 'ADD', - 'eventId' => 'userCreation', - 'info' => _USER_DELETED . " {$aArgs['id']}" - ]); - - return $response->withJson(['success' => 'success']); - } - - public function getProfile(Request $request, Response $response) - { - $user = UserModel::getByUserId(['userId' => $GLOBALS['userId'], 'select' => ['id', 'user_id', 'firstname', 'lastname', 'phone', 'mail', 'initials', 'thumbprint']]); -// $user['signatures'] = UserSignatureModel::getByUserSerialId(['userSerialid' => $user['id']]); -// $user['emailSignatures'] = UserModel::getEmailSignaturesById(['userId' => $user['user_id']]); -// $user['groups'] = UserModel::getGroupsByUserId(['userId' => $user['user_id']]); -// $user['entities'] = UserModel::getEntitiesById(['userId' => $user['user_id']]); -// $user['baskets'] = BasketModel::getBasketsByUserId(['userId' => $user['user_id'], 'unneededBasketId' => ['IndexingBasket']]); -// $user['redirectedBaskets'] = BasketModel::getRedirectedBasketsByUserId(['userId' => $user['user_id']]); -// $user['regroupedBaskets'] = BasketModel::getRegroupedBasketsByUserId(['userId' => $user['user_id']]); -// $user['passwordRules'] = PasswordModel::getEnabledRules(); -// $user['canModifyPassword'] = true; -// -// $loggingMethod = CoreConfigModel::getLoggingMethod(); -// if (in_array($loggingMethod['id'], self::ALTERNATIVES_CONNECTIONS_METHODS)) { -// $user['canModifyPassword'] = false; -// } - - return $response->withJson($user); - } - - public function updateProfile(Request $request, Response $response) - { - $user = UserModel::getByUserId(['userId' => $GLOBALS['userId'], 'select' => ['id', 'enabled']]); - - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['firstname']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['lastname']); - $check = $check && (empty($data['mail']) || filter_var($data['mail'], FILTER_VALIDATE_EMAIL)); - $check = $check && (empty($data['phone']) || preg_match("/\+?((|\ |\.|\(|\)|\-)?(\d)*)*\d/", $data['phone'])); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - $data['enabled'] = $user['enabled']; - - UserModel::update(['id' => $user['id'], 'user' => $data]); - - return $response->withJson(['success' => 'success']); - } - - public function resetPassword(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - UserModel::resetPassword(['id' => $aArgs['id']]); - - return $response->withJson(['success' => 'success']); - } - - public function updateCurrentUserPassword(Request $request, Response $response) - { - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['currentPassword']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['newPassword']); - $check = $check && Validator::stringType()->notEmpty()->validate($data['reNewPassword']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $user = UserModel::getByUserId(['userId' => $GLOBALS['userId'], 'select' => ['id']]); - - if ($data['newPassword'] != $data['reNewPassword']) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } elseif (!AuthenticationModel::authentication(['userId' => $GLOBALS['userId'], 'password' => $data['currentPassword']])) { - return $response->withStatus(401)->withJson(['errors' => _WRONG_PSW]); - } elseif (!PasswordController::isPasswordValid(['password' => $data['newPassword']])) { - return $response->withStatus(400)->withJson(['errors' => 'Password does not match security criteria']); - } elseif (!PasswordModel::isPasswordHistoryValid(['password' => $data['newPassword'], 'userSerialId' => $user['id']])) { - return $response->withStatus(400)->withJson(['errors' => _ALREADY_USED_PSW]); - } - - UserModel::updatePassword(['id' => $user['id'], 'password' => $data['newPassword']]); - PasswordModel::setHistoryPassword(['userSerialId' => $user['id'], 'password' => $data['newPassword']]); - - return $response->withJson(['success' => 'success']); - } - - public function setRedirectedBaskets(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - - $data = $request->getParams(); - - foreach ($data as $key => $value) { - if (empty($value['newUser']) || empty($value['basketId']) || empty($value['basketOwner']) || empty($value['virtual'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - $check = UserModel::getByUserId(['userId' => $value['newUser'], 'select' => ['1']]); - if (empty($check)) { - return $response->withStatus(400)->withJson(['errors' => 'User not found']); - } - - if ($value['basketOwner'] != $user['user_id']) { - BasketModel::updateRedirectedBaskets([ - 'userId' => $user['user_id'], - 'basketOwner' => $value['basketOwner'], - 'basketId' => $value['basketId'], - 'userAbs' => $value['basketOwner'], - 'newUser' => $value['newUser'] - ]); - HistoryController::add([ - 'tableName' => 'user_abs', - 'recordId' => $GLOBALS['userId'], - 'eventType' => 'UP', - 'eventId' => 'basketRedirection', - 'info' => _BASKET_REDIRECTION . " {$value['basketId']} {$user['user_id']} => {$value['newUser']}" - ]); - unset($data[$key]); - } - } - - if (!empty($data)) { - foreach ($data as $value) { - BasketModel::setRedirectedBaskets([ - 'userAbs' => $user['user_id'], - 'newUser' => $value['newUser'], - 'basketId' => $value['basketId'], - 'basketOwner' => $value['basketOwner'], - 'isVirtual' => $value['virtual'] - ]); - - HistoryController::add([ - 'tableName' => 'user_abs', - 'recordId' => $GLOBALS['userId'], - 'eventType' => 'UP', - 'eventId' => 'basketRedirection', - 'info' => _BASKET_REDIRECTION . " {$value['basketId']} {$user['user_id']} => {$value['newUser']}" - ]); - } - } - - return $response->withJson([ - 'baskets' => BasketModel::getBasketsByUserId(['userId' => $user['user_id'], 'unneededBasketId' => ['IndexingBasket']]) - ]); - } - - public function deleteRedirectedBaskets(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['basketOwner']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - - if ($data['basketOwner'] != $user['user_id']) { - BasketModel::deleteBasketRedirection(['userId' => $data['basketOwner'], 'basketId' => $aArgs['basketId']]); - } else { - BasketModel::deleteBasketRedirection(['userId' => $user['user_id'], 'basketId' => $aArgs['basketId']]); - } - - HistoryController::add([ - 'tableName' => 'user_abs', - 'recordId' => $GLOBALS['userId'], - 'eventType' => 'UP', - 'eventId' => 'basketRedirection', - 'info' => _BASKET_REDIRECTION_SUPPRESSION . " {$aArgs['basketId']} {$user['user_id']}" - ]); - - return $response->withJson([ - 'baskets' => BasketModel::getBasketsByUserId(['userId' => $user['user_id'], 'unneededBasketId' => ['IndexingBasket']]) - ]); - } - - public function getStatusByUserId(Request $request, Response $response, array $aArgs) - { - if (!ServiceModel::hasService(['id' => 'admin_users', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); - } - - $user = UserModel::getByUserId(['userId' => $aArgs['userId'], 'select' => ['status']]); - - return $response->withJson(['status' => $user['status']]); - } - - public function updateStatus(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - - $check = Validator::stringType()->notEmpty()->validate($data['status']); - $check = $check && ($data['status'] == 'OK' || $data['status'] == 'ABS'); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - UserModel::updateStatus(['id' => $aArgs['id'], 'status' => $data['status']]); - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id', 'firstname', 'lastname']]); - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $user['user_id'], - 'eventType' => 'RET', - 'eventId' => 'userabs', - 'info' => "{$user['firstname']} {$user['lastname']} " ._BACK_FROM_VACATION - ]); - - return $response->withJson(['user' => UserModel::getById(['id' => $aArgs['id'], 'select' => ['status']])]); - } - - public function getImageContent(Request $request, Response $response, array $aArgs) - { - if (!Validator::intVal()->validate($aArgs['id']) || !Validator::intVal()->validate($aArgs['signatureId'])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $signatures = UserSignatureModel::get([ - 'select' => ['signature_path', 'signature_file_name'], - 'where' => ['user_serial_id = ?', 'id = ?'], - 'data' => [$aArgs['id'], $aArgs['signatureId']] - ]); - if (empty($signatures[0])) { - return $response->withStatus(400)->withJson(['errors' => 'Signature does not exist']); - } - - $docserver = DocserverModel::getCurrentDocserver(['typeId' => 'TEMPLATES', 'collId' => 'templates', 'select' => ['path_template']]); - if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) { - return []; - } - - $pathToSignature = $docserver['path_template'] . str_replace('#', '/', $signatures[0]['signature_path']) . $signatures[0]['signature_file_name']; - $image = file_get_contents($pathToSignature); - if ($image === false) { - return $response->withStatus(404)->withJson(['errors' => 'Signature not found on docserver']); - } - - $finfo = new \finfo(FILEINFO_MIME_TYPE); - $mimeType = $finfo->buffer($image); - - $response->write($image); - - return $response->withHeader('Content-Type', $mimeType); - } - - public function addSignature(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - - if (!$this->checkNeededParameters(['data' => $data, 'needed' => ['base64', 'name', 'label']])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - $file = base64_decode($data['base64']); - $tmpName = "tmp_file_{$aArgs['id']}_" .rand(). "_{$data['name']}"; - - $finfo = new \finfo(FILEINFO_MIME_TYPE); - $mimeType = $finfo->buffer($file); - $size = strlen($file); - $type = explode('/', $mimeType); - $ext = strtoupper(substr($data['name'], strrpos($data['name'], '.') + 1)); - - $fileAccepted = false; - - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/extensions.xml']); - if ($loadedXml && count($loadedXml->FORMAT) > 0) { - foreach ($loadedXml->FORMAT as $value) { - if (strtoupper($value->name) == $ext && strtoupper($value->mime) == strtoupper($mimeType)) { - $fileAccepted = true; - break; - } - } - } - - if (!$fileAccepted || $type[0] != 'image') { - return $response->withStatus(400)->withJson(['errors' => _WRONG_FILE_TYPE]); - } elseif ($size > 2000000) { - return $response->withStatus(400)->withJson(['errors' => _MAX_SIZE_UPLOAD_REACHED . ' (2 MB)']); - } - - file_put_contents(CoreConfigModel::getTmpPath() . $tmpName, $file); - $storeInfos = DocserverController::storeResourceOnDocServer([ - 'collId' => 'templates', - 'docserverTypeId' => 'TEMPLATES', - 'fileInfos' => [ - 'tmpDir' => CoreConfigModel::getTmpPath(), - 'tmpFileName' => $tmpName, - ] - ]); - - if (!file_exists($storeInfos['path_template']. str_replace('#', '/', $storeInfos['destination_dir']) .$storeInfos['file_destination_name'])) { - return $response->withStatus(500)->withJson(['errors' => $storeInfos['error'] .' '. _PATH_OF_DOCSERVER_UNAPPROACHABLE]); - } - - UserSignatureModel::create([ - 'userSerialId' => $aArgs['id'], - 'signatureLabel' => $data['label'], - 'signaturePath' => $storeInfos['destination_dir'], - 'signatureFileName' => $storeInfos['file_destination_name'], - ]); - - return $response->withJson([ - 'signatures' => UserSignatureModel::getByUserSerialId(['userSerialid' => $aArgs['id']]) - ]); - } - - public function updateSignature(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - - if (!$this->checkNeededParameters(['data' => $data, 'needed' => ['label']])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - UserSignatureModel::update([ - 'signatureId' => $aArgs['signatureId'], - 'userSerialId' => $aArgs['id'], - 'label' => $data['label'] - ]); - - return $response->withJson([ - 'signature' => UserSignatureModel::getById(['id' => $aArgs['signatureId']]) - ]); - } - - public function deleteSignature(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id'], 'himself' => true]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - UserSignatureModel::delete(['signatureId' => $aArgs['signatureId'], 'userSerialId' => $aArgs['id']]); - - return $response->withJson([ - 'signatures' => UserSignatureModel::getByUserSerialId(['userSerialid' => $aArgs['id']]) + 'encodedFile' => $data['encodedSignature'], + 'format' => $data['format'], + 'docserverType' => 'SIGNATURE' ]); - } - public function createCurrentUserEmailSignature(Request $request, Response $response) - { - $data = $request->getParams(); - - if (!$this->checkNeededParameters(['data' => $data, 'needed' => ['title', 'htmlBody']])) { - return $response->withJson(['errors' => 'Bad Request']); + if (!empty($storeInfos['errors'])) { + return $response->withStatus(500)->withJson(['errors' => $storeInfos['errors']]); } - UserModel::createEmailSignature([ - 'userId' => $GLOBALS['userId'], - 'title' => $data['title'], - 'htmlBody' => $data['htmlBody'] - ]); - - return $response->withJson([ - 'emailSignatures' => UserModel::getEmailSignaturesById(['userId' => $GLOBALS['userId']]) - ]); - } - - public function updateCurrentUserEmailSignature(Request $request, Response $response, array $aArgs) - { - $data = $request->getParams(); - - if (!$this->checkNeededParameters(['data' => $data, 'needed' => ['title', 'htmlBody']])) { - return $response->withJson(['errors' => 'Bad Request']); - } - - UserModel::updateEmailSignature([ - 'id' => $aArgs['id'], - 'userId' => $GLOBALS['userId'], - 'title' => $data['title'], - 'htmlBody' => $data['htmlBody'] - ]); - - return $response->withJson([ - 'emailSignature' => UserModel::getEmailSignatureWithSignatureIdById(['userId' => $GLOBALS['userId'], 'signatureId' => $aArgs['id']]) - ]); - } - - public function deleteCurrentUserEmailSignature(Request $request, Response $response, array $aArgs) - { - UserModel::deleteEmailSignature([ - 'id' => $aArgs['id'], - 'userId' => $GLOBALS['userId'] - ]); - - return $response->withJson(['emailSignatures' => UserModel::getEmailSignaturesById(['userId' => $GLOBALS['userId']])]); - } - - public function addGroup(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - if (!$this->checkNeededParameters(['data' => $data, 'needed' => ['groupId']])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - $group = GroupModel::getByGroupId(['select' => ['id'], 'groupId' => $data['groupId']]); - if (empty($group)) { - return $response->withStatus(400)->withJson(['errors' => 'Group not found']); - } elseif (UserModel::hasGroup(['id' => $aArgs['id'], 'groupId' => $data['groupId']])) { - return $response->withStatus(400)->withJson(['errors' => _USER_ALREADY_LINK_GROUP]); - } - if (empty($data['role'])) { - $data['role'] = ''; - } - - UserModel::addGroup(['id' => $aArgs['id'], 'groupId' => $data['groupId'], 'role' => $data['role']]); - - $baskets = GroupBasketModel::get(['select' => ['basket_id'], 'where' => ['group_id = ?'], 'data' => [$data['groupId']]]); - foreach ($baskets as $basket) { - UserBasketPreferenceModel::create([ - 'userSerialId' => $aArgs['id'], - 'groupSerialId' => $group['id'], - 'basketId' => $basket['basket_id'], - 'display' => 'true' - ]); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $user['user_id'], - 'eventType' => 'UP', - 'info' => _USER_GROUP_CREATION . " : {$user['user_id']} {$data['groupId']}", - 'moduleId' => 'user', - 'eventId' => 'userModification', - ]); - - return $response->withJson([ - 'groups' => UserModel::getGroupsByUserId(['userId' => $user['user_id']]), - 'baskets' => BasketModel::getBasketsByUserId(['userId' => $user['user_id'], 'unneededBasketId' => ['IndexingBasket']]) - ]); - } - - public function updateGroup(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - if (empty(GroupModel::getByGroupId(['groupId' => $aArgs['groupId']]))) { - return $response->withStatus(400)->withJson(['errors' => 'Group not found']); - } - - $data = $request->getParams(); - if (empty($data['role'])) { - $data['role'] = ''; - } - - UserModel::updateGroup(['id' => $aArgs['id'], 'groupId' => $aArgs['groupId'], 'role' => $data['role']]); - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $user['user_id'], - 'eventType' => 'UP', - 'info' => _USER_GROUP_MODIFICATION . " : {$user['user_id']} {$aArgs['groupId']}", - 'moduleId' => 'user', - 'eventId' => 'userModification', + UserModel::createSignature([ + 'userId' => $args['id'], + 'path' => $storeInfos['path'], + 'filename' => $storeInfos['filename'], + 'fingerprint' => $storeInfos['fingerprint'], ]); return $response->withJson(['success' => 'success']); } - public function deleteGroup(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - $group = GroupModel::getByGroupId(['select' => ['id'], 'groupId' => $aArgs['groupId']]); - if (empty($group)) { - return $response->withStatus(400)->withJson(['errors' => 'Group not found']); - } - - UserModel::deleteGroup(['id' => $aArgs['id'], 'groupId' => $aArgs['groupId']]); - - UserBasketPreferenceModel::delete([ - 'where' => ['user_serial_id = ?', 'group_serial_id = ?'], - 'data' => [$aArgs['id'], $group['id']] - ]); - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $user['user_id'], - 'eventType' => 'UP', - 'info' => _USER_GROUP_SUPPRESSION . " : {$user['user_id']} {$aArgs['groupId']}", - 'moduleId' => 'user', - 'eventId' => 'userModification', - ]); - - return $response->withJson([ - 'groups' => UserModel::getGroupsByUserId(['userId' => $user['user_id']]), - 'baskets' => BasketModel::getBasketsByUserId(['userId' => $user['user_id'], 'unneededBasketId' => ['IndexingBasket']]) - ]); - } - - public function addEntity(Request $request, Response $response, array $aArgs) + public function getSignatures(Request $request, Response $response, array $args) { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); + $user = UserModel::getByLogin(['login' => $GLOBALS['login'], 'select' => ['id']]); + if ($user['id'] != $args['id']) { + return $response->withStatus(403)->withJson(['errors' => 'User out of perimeter']); } - $data = $request->getParams(); - if (!$this->checkNeededParameters(['data' => $data, 'needed' => ['entityId']])) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - if (empty(EntityModel::getById(['entityId' => $data['entityId']]))) { - return $response->withStatus(400)->withJson(['errors' => 'Entity not found']); - } elseif (UserModel::hasEntity(['id' => $aArgs['id'], 'entityId' => $data['entityId']])) { - return $response->withStatus(400)->withJson(['errors' => _USER_ALREADY_LINK_ENTITY]); - } - if (empty($data['role'])) { - $data['role'] = ''; - } - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - $primaryEntity = UserModel::getPrimaryEntityByUserId(['userId' => $user['user_id']]); - $pEntity = 'N'; - if (empty($primaryEntity)) { - $pEntity = 'Y'; + $rawSignatures = UserModel::getSignatures(['select' => ['path', 'filename', 'fingerprint']]); + $docserver = DocserverModel::getByType(['type' => 'SIGNATURE', 'select' => ['path']]); + if (empty($docserver['path']) || !file_exists($docserver['path'])) { + return $response->withStatus(400)->withJson(['errors' => 'Docserver does not exist']); } - UserEntityModel::addUserEntity(['id' => $aArgs['id'], 'entityId' => $data['entityId'], 'role' => $data['role'], 'primaryEntity' => $pEntity]); - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $user['user_id'], - 'eventType' => 'UP', - 'info' => _USER_ENTITY_CREATION . " : {$user['user_id']} {$data['entityId']}", - 'moduleId' => 'user', - 'eventId' => 'userModification', - ]); - - return $response->withJson([ - 'entities' => UserModel::getEntitiesById(['userId' => $user['user_id']]), - 'allEntities' => EntityModel::getAvailableEntitiesForAdministratorByUserId(['userId' => $user['user_id'], 'administratorUserId' => $GLOBALS['userId']]) - ]); - } - - public function updateEntity(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - if (empty(EntityModel::getById(['entityId' => $aArgs['entityId']]))) { - return $response->withStatus(400)->withJson(['errors' => 'Entity not found']); - } - - $data = $request->getParams(); - if (empty($data['user_role'])) { - $data['user_role'] = ''; - } - - UserEntityModel::updateUserEntity(['id' => $aArgs['id'], 'entityId' => $aArgs['entityId'], 'role' => $data['user_role']]); - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $aArgs['id'], - 'eventType' => 'UP', - 'info' => _USER_ENTITY_MODIFICATION . " : {$aArgs['id']} {$aArgs['entityId']}", - 'moduleId' => 'user', - 'eventId' => 'userModification', - ]); - - return $response->withJson(['success' => 'success']); - } - - public function updatePrimaryEntity(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - if (empty(EntityModel::getById(['entityId' => $aArgs['entityId']]))) { - return $response->withStatus(400)->withJson(['errors' => 'Entity not found']); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - UserEntityModel::updateUserPrimaryEntity(['id' => $aArgs['id'], 'entityId' => $aArgs['entityId']]); - - return $response->withJson(['entities' => UserModel::getEntitiesById(['userId' => $user['user_id']])]); - } - - public function deleteEntity(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - if (empty(EntityModel::getById(['entityId' => $aArgs['entityId']]))) { - return $response->withStatus(400)->withJson(['errors' => 'Entity not found']); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - - $data = $request->getParams(); - if (!empty($data['mode'])) { - if ($data['mode'] == 'reaffect') { - ListTemplateModel::update([ - 'set' => ['item_id' => $data['newUser']], - 'where' => ['object_id = ?', 'item_id = ?'], - 'data' => [$aArgs['entityId'], $user['user_id']] - ]); - $listInstances = ListInstanceModel::getWithConfidentiality(['select' => ['listinstance.res_id'], 'entityId' => $aArgs['entityId'], 'userId' => $user['user_id']]); - $resIdsToReplace = []; - foreach ($listInstances as $listInstance) { - $resIdsToReplace[] = $listInstance['res_id']; - } - if (!empty($resIdsToReplace)) { - ListInstanceModel::update([ - 'set' => ['item_id' => $data['newUser']], - 'where' => ['res_id in (?)', 'item_id = ?', 'process_date is null'], - 'data' => [$resIdsToReplace, $user['user_id']] - ]); - } - } else { - ListTemplateModel::delete([ - 'where' => ['object_id = ?', 'item_id = ?', 'item_mode != ?'], - 'data' => [$aArgs['entityId'], $user['user_id'], 'dest'] - ]); - - $ressources = ResModel::getOnView([ - 'select' => ['res_id'], - 'where' => ['confidentiality = ?', 'destination = ?', 'closing_date is null'], - 'data' => ['Y', $aArgs['entityId']] - ]); - foreach ($ressources as $ressource) { - $listInstanceId = ListInstanceModel::get([ - 'select' => ['listinstance_id'], - 'where' => ['res_id = ?', 'item_id = ?', 'item_type = ?', 'difflist_type = ?', 'item_mode = ?', 'process_date is null'], - 'data' => [$ressource['res_id'], $user['user_id'], 'user_id', 'VISA_CIRCUIT', 'sign'] - ]); - - if (!empty($listInstanceId)) { - ListInstanceModel::update([ - 'set' => ['process_date' => null], - 'where' => ['res_id = ?', 'difflist_type = ?', 'listinstance_id = ?'], - 'data' => [$ressource['res_id'], 'VISA_CIRCUIT', $listInstanceId[0]['listinstance_id'] - 1] - ]); - $listInstanceMinus = ListInstanceModel::get([ - 'select' => ['requested_signature'], - 'where' => ['listinstance_id = ?'], - 'data' => [$listInstanceId[0]['listinstance_id'] - 1] - ]); - if ($listInstanceMinus[0]['requested_signature']) { - ResModel::update(['set' => ['status' => 'ESIG'], 'where' => ['res_id = ?'], 'data' => [$ressource['res_id']]]); - } else { - ResModel::update(['set' => ['status' => 'EVIS'], 'where' => ['res_id = ?'], 'data' => [$ressource['res_id']]]); - } - } - } - - $listInstances = ListInstanceModel::getWithConfidentiality(['select' => ['listinstance.res_id', 'listinstance.difflist_type'], 'entityId' => $aArgs['entityId'], 'userId' => $user['user_id']]); - $resIdsToReplace = []; - foreach ($listInstances as $listInstance) { - $resIdsToReplace[] = $listInstance['res_id']; - } - if (!empty($resIdsToReplace)) { - ListInstanceModel::update([ - 'set' => ['process_comment' => '[DEL] supprimé - changement d\'entité', 'process_date' => 'CURRENT_TIMESTAMP'], - 'where' => ['res_id in (?)', 'item_id = ?'], - 'data' => [$resIdsToReplace, $user['user_id']] - ]); - } - } - } - - $primaryEntity = UserModel::getPrimaryEntityByUserId(['userId' => $user['user_id']]); - UserEntityModel::deleteUserEntity(['id' => $aArgs['id'], 'entityId' => $aArgs['entityId']]); - - if (!empty($primaryEntity['entity_id']) && $primaryEntity['entity_id'] == $aArgs['entityId']) { - UserEntityModel::reassignUserPrimaryEntity(['userId' => $user['user_id']]); - } - - HistoryController::add([ - 'tableName' => 'users', - 'recordId' => $user['user_id'], - 'eventType' => 'UP', - 'info' => _USER_ENTITY_SUPPRESSION . " : {$user['user_id']} {$aArgs['entityId']}", - 'moduleId' => 'user', - 'eventId' => 'userModification', - ]); - - return $response->withJson([ - 'entities' => UserModel::getEntitiesById(['userId' => $user['user_id']]), - 'allEntities' => EntityModel::getAvailableEntitiesForAdministratorByUserId(['userId' => $user['user_id'], 'administratorUserId' => $GLOBALS['userId']]) - ]); - } - - public function isEntityDeletable(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - if (empty(EntityModel::getById(['entityId' => $aArgs['entityId']]))) { - return $response->withStatus(400)->withJson(['errors' => 'Entity not found']); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - - $listInstances = ListInstanceModel::getWithConfidentiality(['select' => [1], 'entityId' => $aArgs['entityId'], 'userId' => $user['user_id']]); - - $listTemplates = ListTemplateModel::get(['select' => [1], 'where' => ['object_id = ?', 'item_type = ?', 'item_id = ?'], 'data' => [$aArgs['entityId'], 'user_id', $user['user_id']]]); - - return $response->withJson(['hasConfidentialityInstances' => !empty($listInstances), 'hasListTemplates' => !empty($listTemplates)]); - } - - public function updateBasketsDisplay(Request $request, Response $response, array $aArgs) - { - $error = $this->hasUsersRights(['id' => $aArgs['id']]); - if (!empty($error['error'])) { - return $response->withStatus($error['status'])->withJson(['errors' => $error['error']]); - } - - $data = $request->getParams(); - $check = Validator::arrayType()->notEmpty()->validate($data['baskets']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Bad Request']); - } - - foreach ($data['baskets'] as $basketContainer) { - $check = Validator::stringType()->notEmpty()->validate($basketContainer['basketId']); - $check = $check && Validator::intVal()->notEmpty()->validate($basketContainer['groupSerialId']); - $check = $check && Validator::boolType()->validate($basketContainer['allowed']); - if (!$check) { - return $response->withStatus(400)->withJson(['errors' => 'Element is missing']); - } - } - - foreach ($data['baskets'] as $basketContainer) { - $group = GroupModel::getById(['id' => $basketContainer['groupSerialId'], 'select' => ['group_id']]); - $basket = BasketModel::getById(['id' => $basketContainer['basketId'], 'select' => [1]]); - if (empty($group) || empty($basket)) { - return $response->withStatus(400)->withJson(['errors' => 'Group or basket does not exist']); - } - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - $groups = UserModel::getGroupsByUserId(['userId' => $user['user_id']]); - $groupFound = false; - foreach ($groups as $value) { - if ($value['id'] == $basketContainer['groupSerialId']) { - $groupFound = true; - } - } - if (!$groupFound) { - return $response->withStatus(400)->withJson(['errors' => 'Group is not linked to this user']); - } - $groups = GroupBasketModel::get(['where' => ['basket_id = ?'], 'data' => [$basketContainer['basketId']]]); - $groupFound = false; - foreach ($groups as $value) { - if ($value['group_id'] == $group['group_id']) { - $groupFound = true; - } - } - if (!$groupFound) { - return $response->withStatus(400)->withJson(['errors' => 'Group is not linked to this basket']); - } - - if ($basketContainer['allowed']) { - $preference = UserBasketPreferenceModel::get([ - 'select' => [1], - 'where' => ['user_serial_id = ?', 'group_serial_id = ?', 'basket_id = ?'], - 'data' => [$aArgs['id'], $basketContainer['groupSerialId'], $basketContainer['basketId']] - ]); - if (!empty($preference)) { - return $response->withStatus(400)->withJson(['errors' => 'Preference already exists']); + $signatures = []; + foreach ($rawSignatures as $signature) { + $pathToSignature = $docserver['path'] . $signature['path'] . $signature['filename']; + if (file_exists($pathToSignature)) { + $fingerprint = DocserverController::getFingerPrint(['path' => $pathToSignature]); + if ($signature['fingerprint'] == $fingerprint) { + $signatures[] = [ + 'encodedSignature' => base64_encode(file_get_contents($pathToSignature)) + ]; + } else { + //TODO LOG } - $basketContainer['userSerialId'] = $aArgs['id']; - $basketContainer['display'] = 'true'; - UserBasketPreferenceModel::create($basketContainer); } else { - UserBasketPreferenceModel::delete([ - 'where' => ['user_serial_id = ?', 'group_serial_id = ?', 'basket_id = ?'], - 'data' => [$aArgs['id'], $basketContainer['groupSerialId'], $basketContainer['basketId']] - ]); - } - } - - return $response->withJson(['success' => 'success']); - } - - public function updateCurrentUserBasketPreferences(Request $request, Response $response, array $aArgs) - { - $data = $request->getParams(); - - $user = UserModel::getByUserId(['userId' => $GLOBALS['userId'], 'select' => ['id']]); - - if (isset($data['color']) && $data['color'] == '') { - UserBasketPreferenceModel::update([ - 'set' => ['color' => null], - 'where' => ['user_serial_id = ?', 'group_serial_id = ?', 'basket_id = ?'], - 'data' => [$user['id'], $aArgs['groupId'], $aArgs['basketId']] - ]); - } elseif (!empty($data['color'])) { - UserBasketPreferenceModel::update([ - 'set' => ['color' => $data['color']], - 'where' => ['user_serial_id = ?', 'group_serial_id = ?', 'basket_id = ?'], - 'data' => [$user['id'], $aArgs['groupId'], $aArgs['basketId']] - ]); - } - - return $response->withJson([ - 'userBaskets' => BasketModel::getRegroupedBasketsByUserId(['userId' => $GLOBALS['userId']]) - ]); - } - - private function hasUsersRights(array $aArgs) - { - $error = [ - 'status' => 200, - 'error' => '' - ]; - - $user = UserModel::getById(['id' => $aArgs['id'], 'select' => ['user_id']]); - if (empty($user['user_id'])) { - $error['status'] = 400; - $error['error'] = 'User not found'; - } else { - if (empty($aArgs['himself']) || $GLOBALS['userId'] != $user['user_id']) { - if (!ServiceModel::hasService(['id' => 'admin_users', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) { - $error['status'] = 403; - $error['error'] = 'Service forbidden'; - } - if ($GLOBALS['userId'] != 'superadmin') { - $entities = EntityModel::getAllEntitiesByUserId(['userId' => $GLOBALS['userId']]); - $users = UserEntityModel::getUsersByEntities([ - 'select' => ['users.id'], - 'entities' => $entities - ]); - $usersNoEntities = UserEntityModel::getUsersWithoutEntities(['select' => ['id']]); - $users = array_merge($users, $usersNoEntities); - $allowed = false; - foreach ($users as $value) { - if ($value['id'] == $aArgs['id']) { - $allowed = true; - } - } - if (!$allowed) { - $error['status'] = 403; - $error['error'] = 'UserId out of perimeter'; - } - } - } elseif ($aArgs['delete'] && $GLOBALS['userId'] == $user['user_id']) { - $error['status'] = 403; - $error['error'] = 'Can not delete yourself'; - } - } - - return $error; - } - - private function checkNeededParameters(array $aArgs) - { - foreach ($aArgs['needed'] as $value) { - if (empty($aArgs['data'][$value])) { - return false; + //TODO LOG } } - return true; + return $response->withJson(['signatures' => $signatures]); } } diff --git a/src/app/user/models/UserModel.php b/src/app/user/models/UserModel.php index f464cfe764..9aec62b787 100644 --- a/src/app/user/models/UserModel.php +++ b/src/app/user/models/UserModel.php @@ -14,6 +14,118 @@ namespace User\models; -class UserModel extends UserModelAbstract +use SrcCore\models\DatabaseModel; +use SrcCore\models\ValidatorModel; + +class UserModel { + public static function get(array $aArgs) + { + ValidatorModel::arrayType($aArgs, ['select', 'where', 'data', 'orderBy']); + ValidatorModel::intType($aArgs, ['limit']); + + $aUsers = DatabaseModel::select([ + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['users'], + 'where' => empty($aArgs['where']) ? [] : $aArgs['where'], + 'data' => empty($aArgs['data']) ? [] : $aArgs['data'], + 'order_by' => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'], + 'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit'] + ]); + + return $aUsers; + } + + public static function getById(array $aArgs) + { + ValidatorModel::notEmpty($aArgs, ['id']); + ValidatorModel::intVal($aArgs, ['id']); + + $aUser = DatabaseModel::select([ + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['users'], + 'where' => ['id = ?'], + 'data' => [$aArgs['id']] + ]); + + if (empty($aUser)) { + return []; + } + + return $aUser[0]; + } + + public static function getByLogin(array $aArgs) + { + ValidatorModel::notEmpty($aArgs, ['login']); + ValidatorModel::stringType($aArgs, ['login']); + + $aUser = DatabaseModel::select([ + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['users'], + 'where' => ['login = ?'], + 'data' => [$aArgs['login']] + ]); + + if (empty($aUser)) { + return []; + } + + return $aUser[0]; + } + + public static function getLabelledUserById(array $aArgs) + { + ValidatorModel::intVal($aArgs, ['id']); + ValidatorModel::stringType($aArgs, ['login']); + + if (!empty($aArgs['id'])) { + $rawUser = UserModel::getById(['id' => $aArgs['id'], 'select' => ['firstname', 'lastname']]); + } elseif (!empty($aArgs['login'])) { + $rawUser = UserModel::getByLogin(['login' => $aArgs['login'], 'select' => ['firstname', 'lastname']]); + } + + $labelledUser = ''; + if (!empty($rawUser)) { + $labelledUser = $rawUser['firstname']. ' ' .$rawUser['lastname']; + } + + return $labelledUser; + } + + public static function getSignatures(array $aArgs) + { + ValidatorModel::arrayType($aArgs, ['select', 'where', 'data', 'orderBy']); + ValidatorModel::intType($aArgs, ['limit']); + + $signatures = DatabaseModel::select([ + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['signatures'], + 'where' => empty($aArgs['where']) ? [] : $aArgs['where'], + 'data' => empty($aArgs['data']) ? [] : $aArgs['data'], + 'order_by' => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'], + 'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit'] + ]); + + return $signatures; + } + + public static function createSignature(array $aArgs) + { + ValidatorModel::notEmpty($aArgs, ['userId', 'path', 'filename', 'fingerprint']); + ValidatorModel::stringType($aArgs, ['path', 'filename', 'fingerprint']); + ValidatorModel::intVal($aArgs, ['userId']); + + DatabaseModel::insert([ + 'table' => 'signatures', + 'columnsValues' => [ + 'user_id' => $aArgs['userId'], + 'path' => $aArgs['path'], + 'filename' => $aArgs['filename'], + 'fingerprint' => $aArgs['fingerprint'] + ] + ]); + + return true; + } } diff --git a/src/app/user/models/UserModelAbstract.php b/src/app/user/models/UserModelAbstract.php deleted file mode 100644 index 8d04d19a56..0000000000 --- a/src/app/user/models/UserModelAbstract.php +++ /dev/null @@ -1,96 +0,0 @@ -<?php - -/** - * Copyright Maarch since 2008 under licence GPLv3. - * See LICENCE.txt file at the root folder for more details. - * This file is part of Maarch software. - * - */ - -/** - * @brief User Model - * @author dev@maarch.org - */ - -namespace User\models; - -use SrcCore\models\DatabaseModel; -use SrcCore\models\ValidatorModel; - - -abstract class UserModelAbstract -{ - public static function get(array $aArgs) - { - ValidatorModel::arrayType($aArgs, ['select', 'where', 'data', 'orderBy']); - ValidatorModel::intType($aArgs, ['limit']); - - $aUsers = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['users'], - 'where' => empty($aArgs['where']) ? [] : $aArgs['where'], - 'data' => empty($aArgs['data']) ? [] : $aArgs['data'], - 'order_by' => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'], - 'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit'] - ]); - - return $aUsers; - } - - public static function getById(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['id']); - ValidatorModel::intVal($aArgs, ['id']); - - $aUser = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['users'], - 'where' => ['id = ?'], - 'data' => [$aArgs['id']] - ]); - - if (empty($aUser)) { - return []; - } - - return $aUser[0]; - } - - public static function getByLogin(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['login']); - ValidatorModel::stringType($aArgs, ['login']); - - $aUser = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['users'], - 'where' => ['login = ?'], - 'data' => [$aArgs['login']] - ]); - - if (empty($aUser)) { - return []; - } - - return $aUser[0]; - } - - public static function getLabelledUserById(array $aArgs) - { - ValidatorModel::intVal($aArgs, ['id']); - ValidatorModel::stringType($aArgs, ['login']); - - if (!empty($aArgs['id'])) { - $rawUser = UserModel::getById(['id' => $aArgs['id'], 'select' => ['firstname', 'lastname']]); - } elseif (!empty($aArgs['login'])) { - $rawUser = UserModel::getByLogin(['login' => $aArgs['login'], 'select' => ['firstname', 'lastname']]); - } - - $labelledUser = ''; - if (!empty($rawUser)) { - $labelledUser = $rawUser['firstname']. ' ' .$rawUser['lastname']; - } - - return $labelledUser; - } -} diff --git a/src/app/user/models/UserSignatureModel.php b/src/app/user/models/UserSignatureModel.php deleted file mode 100644 index 9a0dd36ddf..0000000000 --- a/src/app/user/models/UserSignatureModel.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php - -/** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ - -/** -* @brief User Signature Model -* @author dev@maarch.org -*/ - -namespace User\models; - -class UserSignatureModel extends UserSignatureModelAbstract -{ -} diff --git a/src/app/user/models/UserSignatureModelAbstract.php b/src/app/user/models/UserSignatureModelAbstract.php deleted file mode 100644 index 5057039eed..0000000000 --- a/src/app/user/models/UserSignatureModelAbstract.php +++ /dev/null @@ -1,118 +0,0 @@ -<?php - -/** - * Copyright Maarch since 2008 under licence GPLv3. - * See LICENCE.txt file at the root folder for more details. - * This file is part of Maarch software. - * - */ - -/** - * @brief User Signature Model Abstract - * @author dev@maarch.org - */ - -namespace User\models; - -use SrcCore\models\DatabaseModel; -use SrcCore\models\ValidatorModel; - -abstract class UserSignatureModelAbstract -{ - public static function get(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['select', 'where', 'data']); - ValidatorModel::arrayType($aArgs, ['select', 'where', 'data']); - - $signatures = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['user_signatures'], - 'where' => $aArgs['where'], - 'data' => $aArgs['data'] - ]); - - return $signatures; - } - - public static function getById(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['id']); - ValidatorModel::intVal($aArgs, ['id']); - - $signature = DatabaseModel::select([ - 'select' => ['id', 'user_serial_id', 'signature_label'], - 'table' => ['user_signatures'], - 'where' => ['id = ?'], - 'data' => [$aArgs['id']], - ]); - - return $signature[0]; - } - - public static function getByUserSerialId(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['userSerialid']); - ValidatorModel::intVal($aArgs, ['userSerialid']); - - $signatures = DatabaseModel::select([ - 'select' => ['id', 'user_serial_id', 'signature_label'], - 'table' => ['user_signatures'], - 'where' => ['user_serial_id = ?'], - 'data' => [$aArgs['userSerialid']], - 'order_by' => ['id'] - ]); - - return $signatures; - } - - public static function create(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['userSerialId', 'signatureLabel', 'signaturePath', 'signatureFileName']); - ValidatorModel::stringType($aArgs, ['signatureLabel', 'signaturePath', 'signatureFileName']); - ValidatorModel::intVal($aArgs, ['userSerialId']); - - DatabaseModel::insert([ - 'table' => 'user_signatures', - 'columnsValues' => [ - 'user_serial_id' => $aArgs['userSerialId'], - 'signature_label' => $aArgs['signatureLabel'], - 'signature_path' => $aArgs['signaturePath'], - 'signature_file_name' => $aArgs['signatureFileName'] - ] - ]); - - return true; - } - - public static function update(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['signatureId', 'userSerialId', 'label']); - ValidatorModel::stringType($aArgs, ['label']); - ValidatorModel::intVal($aArgs, ['signatureId', 'userSerialId']); - - DatabaseModel::update([ - 'table' => 'user_signatures', - 'set' => [ - 'signature_label' => $aArgs['label'] - ], - 'where' => ['user_serial_id = ?', 'id = ?'], - 'data' => [$aArgs['userSerialId'], $aArgs['signatureId']] - ]); - - return true; - } - - public static function delete(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['signatureId', 'userSerialId']); - ValidatorModel::intVal($aArgs, ['signatureId', 'userSerialId']); - - DatabaseModel::delete([ - 'table' => 'user_signatures', - 'where' => ['user_serial_id = ?', 'id = ?'], - 'data' => [$aArgs['userSerialId'], $aArgs['signatureId']], - ]); - - return true; - } -} diff --git a/src/core/controllers/PreparedClauseController.php b/src/core/controllers/PreparedClauseController.php deleted file mode 100644 index 004a3c38e4..0000000000 --- a/src/core/controllers/PreparedClauseController.php +++ /dev/null @@ -1,240 +0,0 @@ -<?php - -/** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ - -/** -* @brief Prepared Clause Controller -* @author dev@maarch.org -*/ - -namespace SrcCore\controllers; - -use SrcCore\models\ValidatorModel; -use Entity\models\EntityModel; -use Resource\models\ResModel; -use User\models\UserModel; - -class PreparedClauseController -{ - public static function getPreparedClause(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['clause', 'userId']); - ValidatorModel::stringType($aArgs, ['clause', 'userId']); - - $clause = $aArgs['clause']; - - if (preg_match('/@user/', $clause)) { - $clause = str_replace('@user', "'{$aArgs['userId']}'", $clause); - } - if (preg_match('/@email/', $clause)) { - $user = UserModel::getByUserId(['userId' => $aArgs['userId'], 'select' => ['mail']]); - $clause = str_replace('@email', "'{$user['mail']}'", $clause); - } - if (preg_match('/@my_entities/', $clause)) { - $entities = EntityModel::getByUserId(['userId' => $aArgs['userId'], 'select' => ['entity_id']]); - - $myEntitiesClause = ''; - foreach ($entities as $key => $entity) { - if ($key > 0) { - $myEntitiesClause .= ", "; - } - $myEntitiesClause .= "'{$entity['entity_id']}'"; - } - if (empty($myEntitiesClause)) { - $myEntitiesClause = "''"; - } - - $clause = str_replace('@my_entities', $myEntitiesClause, $clause); - } - if (preg_match('/@my_primary_entity/', $clause)) { - $entity = UserModel::getPrimaryEntityByUserId(['userId' => $aArgs['userId']]); - - if (empty($entity)) { - $primaryEntity = "''"; - } else { - $primaryEntity = "'" . $entity['entity_id'] . "'"; - } - - $clause = str_replace('@my_primary_entity', $primaryEntity, $clause); - } - if (preg_match('/@all_entities/', $clause)) { - $allEntities = EntityModel::get(['select' => ['entity_id'], 'where' => ['enabled = ?'], 'data' => ['Y']]); - - $allEntitiesClause = ''; - foreach ($allEntities as $key => $allEntity) { - if ($key > 0) { - $allEntitiesClause .= ", "; - } - $allEntitiesClause .= "'{$allEntity['entity_id']}'"; - } - if (empty($allEntitiesClause)) { - $allEntitiesClause = "''"; - } - - $clause = str_replace("@all_entities", $allEntitiesClause, $clause); - } - - $total = preg_match_all("|@subentities\[('[^\]]*')\]|", $clause, $subEntities, PREG_PATTERN_ORDER); - if ($total > 0) { - for ($i = 0; $i < $total; $i++) { - $aEntities = []; - $tmpSubEntities = str_replace("'", '', $subEntities[1][$i]); - if (preg_match('/,/', $tmpSubEntities)) { - $aEntities = preg_split('/,/', $tmpSubEntities); - } else { - $aEntities[] = $tmpSubEntities; - } - - $allSubEntities = []; - foreach ($aEntities as $entity) { - if (!empty($entity)) { - $subEntitiesForEntity = EntityModel::getEntityChildren(['entityId' => trim($entity)]); - unset($subEntitiesForEntity[0]); - $allSubEntities = array_merge($allSubEntities, $subEntitiesForEntity); - } - } - - $allSubEntitiesClause = ''; - foreach ($allSubEntities as $key => $allSubEntity) { - if ($key > 0) { - $allSubEntitiesClause .= ", "; - } - $allSubEntitiesClause .= "'{$allSubEntity}'"; - } - if (empty($allSubEntitiesClause)) { - $allSubEntitiesClause = "''"; - } - - $clause = preg_replace("|@subentities\['[^\]]*'\]|", $allSubEntitiesClause, $clause, 1); - } - } - - $total = preg_match_all("|@immediate_children\[('[^\]]*')\]|", $clause, $immediateChildrens, PREG_PATTERN_ORDER); - if ($total > 0) { - for ($i = 0; $i < $total; $i++) { - $aEntities = []; - $tmpImmediateChildrens = str_replace("'", '', $immediateChildrens[1][$i]); - if (preg_match('/,/' , $tmpImmediateChildrens)) { - $aEntities = preg_split('/,/', $tmpImmediateChildrens); - } else { - $aEntities[] = $tmpImmediateChildrens; - } - - $allImmediateChildrens = []; - foreach ($aEntities as $entity) { - $immediateChildrensForEntity = EntityModel::get(['select' => ['entity_id'], 'where' => ['parent_entity_id = ?'], 'data' => [trim($entity)]]); - foreach ($immediateChildrensForEntity as $value) { - $allImmediateChildrens[] = $value['entity_id']; - } - } - - $allImmediateChildrensClause = ''; - foreach ($allImmediateChildrens as $key => $allImmediateChild) { - if ($key > 0) { - $allImmediateChildrensClause .= ", "; - } - $allImmediateChildrensClause .= "'{$allImmediateChild}'"; - } - if (empty($allImmediateChildrensClause)) { - $allImmediateChildrensClause = "''"; - } - - $clause = preg_replace("|@immediate_children\['[^\]]*'\]|", $allImmediateChildrensClause, $clause, 1); - } - } - - $total = preg_match_all("|@parent_entity\[('[^\]]*')\]|", $clause, $parentEntity, PREG_PATTERN_ORDER); - if ($total > 0) { - for ($i = 0; $i < $total; $i++) { - $tmpParentEntity = trim(str_replace("'", '', $parentEntity[1][$i])); - if (!empty($tmpParentEntity)) { - $entity = EntityModel::getById(['entityId' => $tmpParentEntity, 'select' => ['entity_id', 'parent_entity_id']]); - } - if (empty($entity['parent_entity_id'])) { - $parentEntityClause = "''"; - } else { - $parentEntityClause = "'{$entity['parent_entity_id']}'"; - } - - $clause = preg_replace("|@parent_entity\['[^\]]*'\]|", $parentEntityClause, $clause, 1); - } - } - - $total = preg_match_all("|@sisters_entities\[('[^\]]*')\]|", $clause, $sistersEntities, PREG_PATTERN_ORDER); - if ($total > 0) { - for ($i = 0; $i < $total; $i++) { - $tmpSisterEntity = trim(str_replace("'", '', $sistersEntities[1][$i])); - $sisterEntity = EntityModel::getById(['entityId' => $tmpSisterEntity, 'select' => ['parent_entity_id']]); - $allSisterEntities = EntityModel::get(['select' => ['entity_id'], 'where' => ['parent_entity_id = ?'], 'data' => [$sisterEntity['parent_entity_id']]]); - - $allSisterEntitiesClause = ''; - foreach ($allSisterEntities as $key => $allSisterEntity) { - if ($key > 0) { - $allSisterEntitiesClause .= ", "; - } - $allSisterEntitiesClause .= "'{$allSisterEntity['entity_id']}'"; - } - if (empty($allSisterEntitiesClause)) { - $allSisterEntitiesClause = "''"; - } - - $clause = preg_replace("|@sisters_entities\['[^\]]*'\]|", $allSisterEntitiesClause, $clause, 1); - } - } - - $total = preg_match_all("|@entity_type\[('[^\]]*')\]|", $clause, $entityType, PREG_PATTERN_ORDER); - if ($total > 0) { - for ($i = 0; $i < $total; $i++) { - $tmpEntityType = trim(str_replace("'", '', $entityType[1][$i])); - $allEntitiesType = EntityModel::get(['select' => ['entity_id'], 'where' => ['entity_type = ?'], 'data' => [$tmpEntityType]]); - - $allEntitiesTypeClause = ''; - foreach ($allEntitiesType as $key => $allEntityType) { - if ($key > 0) { - $allEntitiesTypeClause .= ", "; - } - $allEntitiesTypeClause .= "'{$allEntityType['entity_id']}'"; - } - if (empty($allEntitiesTypeClause)) { - $allEntitiesTypeClause = "''"; - } - - $clause = preg_replace("|@entity_type\['[^\]]*'\]|", $allEntitiesTypeClause, $clause, 1); - } - } - - return $clause; - } - - public static function isRequestValid(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['clause', 'userId']); - ValidatorModel::stringType($aArgs, ['clause', 'userId']); - ValidatorModel::arrayType($aArgs, ['select', 'orderBy']); - ValidatorModel::intType($aArgs, ['limit']); - - $clause = PreparedClauseController::getPreparedClause(['clause' => $aArgs['clause'], 'userId' => $aArgs['userId']]); - - $preg = preg_match('#\b(?:abort|alter|copy|create|delete|disgard|drop|execute|grant|insert|load|lock|move|reset|truncate|update)\b#i', $clause); - if ($preg === 1) { - return false; - } - - if (empty($aArgs['select'])) { - $aArgs['select'] = [1]; - } - - try { - ResModel::getOnView(['select' => $aArgs['select'], 'where' => [$clause, '1=1'], 'orderBy' => $aArgs['orderBy'], 'limit' => $aArgs['limit']]); - } catch (\Exception $e) { - return false; - } - - return true; - } -} diff --git a/src/core/models/CurlModel.php b/src/core/models/CurlModel.php deleted file mode 100644 index ca87ad7cd0..0000000000 --- a/src/core/models/CurlModel.php +++ /dev/null @@ -1,184 +0,0 @@ -<?php - -/** - * Copyright Maarch since 2008 under licence GPLv3. - * See LICENCE.txt file at the root folder for more details. - * This file is part of Maarch software. - * - */ - -/** - * @brief Curl Model - * @author dev@maarch.org - */ - -namespace SrcCore\models; - -class CurlModel -{ - public static function exec(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['curlCallId']); - ValidatorModel::stringType($aArgs, ['curlCallId']); - ValidatorModel::arrayType($aArgs, ['bodyData']); - ValidatorModel::boolType($aArgs, ['noAuth', 'multipleObject']); - - $curlConfig = CurlModel::getConfigByCallId(['curlCallId' => $aArgs['curlCallId']]); - if (empty($curlConfig)) { - return []; - } - - $opts = [ - CURLOPT_URL => $curlConfig['url'], - CURLOPT_RETURNTRANSFER => true, - ]; - - if (empty($aArgs['multipleObject'])) { - $opts[CURLOPT_HTTPHEADER][] = 'accept:application/json'; - $opts[CURLOPT_HTTPHEADER][] = 'content-type:application/json'; - } - - if (empty($aArgs['noAuth']) && !empty($curlConfig['user']) && !empty($curlConfig['password'])) { - $opts[CURLOPT_HTTPHEADER][] = 'Authorization: Basic ' . base64_encode($curlConfig['user']. ':' .$curlConfig['password']); - } else { - $opts[CURLOPT_HTTPHEADER][] = 'Api-Key: ' . $curlConfig['apiKey']; - $opts[CURLOPT_HTTPHEADER][] = 'appName: ' . $curlConfig['appName']; - } - - if ($curlConfig['method'] == 'POST' || $curlConfig['method'] == 'PUT') { - if (is_array($aArgs['bodyData']) && !empty($aArgs['bodyData']) && $aArgs['multipleObject']) { - $bodyData = []; - foreach ($aArgs['bodyData'] as $key => $value) { - $bodyData[$key] = json_encode($value); - } - } else { - $bodyData = json_encode($aArgs['bodyData']); - } - $opts[CURLOPT_POSTFIELDS] = $bodyData; - } - if ($curlConfig['method'] == 'POST' && empty($aArgs['multipleObject'])) { - $opts[CURLOPT_POST] = true; - } elseif ($curlConfig['method'] == 'PUT' || $curlConfig['method'] == 'DELETE') { - $opts[CURLOPT_CUSTOMREQUEST] = $curlConfig['method']; - } - - $curl = curl_init(); - curl_setopt_array($curl, $opts); - $rawResponse = curl_exec($curl); - curl_close($curl); - - return json_decode($rawResponse, true); - } - - public static function execSOAP(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['xmlPostString', 'url']); - ValidatorModel::stringType($aArgs, ['xmlPostString', 'url', 'soapAction']); - ValidatorModel::arrayType($aArgs, ['options']); - - $opts = [ - CURLOPT_URL => $aArgs['url'], - CURLOPT_RETURNTRANSFER => true, - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => $aArgs['xmlPostString'], - CURLOPT_HTTPHEADER => [ - 'content-type:text/xml;charset="utf-8"', - 'accept:text/xml', - 'Cache-Control: no-cache', - 'Pragma: no-cache', - 'Content-length: ' . strlen($aArgs['xmlPostString']), - ] - ]; - - if (!empty($aArgs['soapAction'])) { - $opts[CURLOPT_HTTPHEADER][] = "SOAPAction: \"{$aArgs['soapAction']}\""; - } - if (!empty($aArgs['options'])) { - foreach ($aArgs['options'] as $key => $option) { - $opts[$key] = $option; - } - } - - $curl = curl_init(); - curl_setopt_array($curl, $opts); - $rawResponse = curl_exec($curl); - - $infos = curl_getinfo($curl); - - $cookies = array(); - if (!empty($aArgs['options'][CURLOPT_HEADER])) { - preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $rawResponse, $matches); - foreach ($matches[1] as $item) { - $cookie = explode("=", $item); - $cookies = array_merge($cookies, [$cookie[0] => $cookie[1]]); - } - $rawResponse = substr($rawResponse, $infos['header_size']); - } - - return ['response' => simplexml_load_string($rawResponse), 'infos' => $infos, 'cookies' => $cookies]; - } - - public static function getConfigByCallId(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['curlCallId']); - ValidatorModel::stringType($aArgs, ['curlCallId']); - - $curlConfig = []; - - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/curlCall.xml']); - if ($loadedXml) { - $curlConfig['user'] = (string)$loadedXml->user; - $curlConfig['password'] = (string)$loadedXml->password; - $curlConfig['apiKey'] = (string)$loadedXml->apiKey; - $curlConfig['appName'] = (string)$loadedXml->appName; - foreach ($loadedXml->call as $call) { - if ((string)$call->id == $aArgs['curlCallId']) { - $curlConfig['url'] = (string)$call->url; - $curlConfig['method'] = strtoupper((string)$call->method); - if (!empty($call->sendInObject)) { - $curlConfig['objectName'] = (string)$call->sendInObject; - } - if (!empty($call->file)) { - $curlConfig['file'] = (string)$call->file->key; - } - if (!empty($call->data)) { - $curlConfig['data'] = []; - foreach ($call->data as $data) { - $curlConfig['data'][(string)$data->key] = (string)$data->value; - } - } - if (!empty($call->rawData)) { - $curlConfig['rawData'] = []; - foreach ($call->rawData as $data) { - $curlConfig['rawData'][(string)$data->key] = (string)$data->value; - } - } - if (!empty($call->return)) { - $curlConfig['return'] = (string)$call->return; - } - } - } - } - - return $curlConfig; - } - - public static function isEnabled(array $aArgs) - { - ValidatorModel::notEmpty($aArgs, ['curlCallId']); - ValidatorModel::stringType($aArgs, ['curlCallId']); - - $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'apps/maarch_entreprise/xml/curlCall.xml']); - if ($loadedXml) { - foreach ($loadedXml->call as $call) { - if ((string)$call->id == $aArgs['curlCallId']) { - if (!empty((string)$call->enabled) && (string)$call->enabled == 'true') { - return true; - } - } - } - } - - return false; - } -} -- GitLab