Merged in feature/PMCORE-1388 (pull request #7374)

PMCORE-1388

Approved-by: Julio Cesar Laura Avendaño <contact@julio-laura.com>
This commit is contained in:
Paula Quispe
2020-06-13 01:35:29 +00:00
committed by Julio Cesar Laura Avendaño
36 changed files with 1689 additions and 277 deletions

View File

@@ -14,6 +14,7 @@ use AppHistoryPeer;
use Application;
use ApplicationPeer;
use Applications;
use AppNotes;
use AppNotesPeer;
use AppSolr;
use BasePeer;
@@ -40,12 +41,16 @@ use ProcessMaker\BusinessModel\Task as BmTask;
use ProcessMaker\BusinessModel\User as BmUser;
use ProcessMaker\Core\System;
use ProcessMaker\Exception\UploadException;
use ProcessMaker\Exception\CaseNoteUploadFile;
use ProcessMaker\Model\Application as ModelApplication;
use ProcessMaker\Model\AppNotes as Notes;
use ProcessMaker\Model\Delegation;
use ProcessMaker\Model\Documents;
use ProcessMaker\Plugins\PluginRegistry;
use ProcessMaker\Services\OAuth2\Server;
use ProcessMaker\Util\DateTime as UtilDateTime;
use ProcessMaker\Validation\ExceptionRestApi;
use ProcessMaker\Validation\ValidationUploadedFiles;
use ProcessMaker\Validation\Validator as FileValidator;
use ProcessPeer;
use ProcessUser;
@@ -3843,6 +3848,186 @@ class Cases
return $response;
}
/**
* Add a case note
*
* @param string $appUid
* @param string $userUid
* @param string $note
* @param bool $sendMail
* @param array $files
*
* @return array
*/
public function addNote($appUid, $userUid, $note, $sendMail = false, $files = [])
{
// Register the note
$attributes = [
"APP_UID" => $appUid,
"USR_UID" => $userUid,
"NOTE_DATE" => date("Y-m-d H:i:s"),
"NOTE_CONTENT" => $note,
"NOTE_TYPE" => "USER",
"NOTE_AVAILABILITY" => "PUBLIC",
"NOTE_RECIPIENTS" => ""
];
$newNote = Notes::create($attributes);
// Get the FK
$noteId = $newNote->NOTE_ID;
$attachments = [];
// Register the files related to the note
if (!empty($files) || !empty($_FILES["filesToUpload"])) {
$filesResponse = $this->uploadFilesInCaseNotes($userUid, $appUid, $files, $noteId);
foreach ($filesResponse['attachments'] as $key => $value) {
$attachments[$key] = [];
$attachments[$key]['APP_DOC_FILENAME'] = $value['APP_DOC_FILENAME'];
$attachments[$key]['LINK'] = "../cases/casesShowCaseNotes?a=" . $value["APP_DOC_UID"] . "&v=" . $value["DOC_VERSION"];
}
}
// Send the email
if ($sendMail) {
// Get the recipients
$case = new ClassesCases();
$p = $case->getUsersParticipatedInCase($appUid, 'ACTIVE');
$noteRecipientsList = [];
foreach ($p["array"] as $key => $userParticipated) {
if ($key != '') {
$noteRecipientsList[] = $key;
}
}
$noteRecipients = implode(",", $noteRecipientsList);
$note = stripslashes($note);
// Send the notification
$appNote = new AppNotes();
$appNote->sendNoteNotification($appUid, $userUid, $note, $noteRecipients, '', 0, $noteId);
}
// Prepare the response
$result = [];
$result['success'] = 'success';
$result['message'] = '';
$result['attachments'] = $attachments;
$result['attachment_errors'] = [];
return $result;
}
/**
* Upload file related to the case notes
*
* @param string $userUid
* @param string $appUid
* @param array $filesReferences
* @param int $noteId
*
* @return array
* @throws Exception
*/
public function uploadFilesInCaseNotes($userUid, $appUid, $filesReferences = [], $noteId = 0)
{
$files = [];
if (!empty($_FILES["filesToUpload"])) {
$upload = true;
// This format is from ext-js multipart
$filesName = !empty($_FILES["filesToUpload"]["name"]) ? $_FILES["filesToUpload"]["name"] : [];
$filesTmpName = !empty($_FILES["filesToUpload"]["tmp_name"]) ? $_FILES["filesToUpload"]["tmp_name"] : [];
$filesError = !empty($_FILES["filesToUpload"]["error"]) ? $_FILES["filesToUpload"]["error"] : [];
foreach ($filesName as $index => $value) {
if (!empty($value)) {
$files[] = [
'name' => $filesName[$index],
'tmp_name' => $filesTmpName[$index],
'error' => $filesError[$index]
];
}
}
} elseif (!empty($filesReferences)) {
$upload = false;
// Array with path references
foreach ($filesReferences as $fileIndex => $fileName) {
$nameFile = !is_numeric($fileIndex) ? basename($fileIndex) : basename($fileName);
$files[] = [
'name' => $nameFile,
'tmp_name' => $fileName,
'error' => UPLOAD_ERR_OK
];
}
}
//rules validation
foreach ($files as $key => $value) {
$entry = [
"filename" => $value['name'],
"path" => $value['tmp_name']
];
$validator = ValidationUploadedFiles::getValidationUploadedFiles()
->runRulesForPostFilesOfNote($entry);
if ($validator->fails()) {
Notes::where('NOTE_ID', '=', $noteId)->delete();
$messageError = G::LoadTranslation('ID_THE_FILE_COULDNT_BE_UPLOADED');
throw new CaseNoteUploadFile($messageError . ' ' . $validator->getMessage());
}
}
// Get the delIndex related to the case
$cases = new ClassesCases();
$delIndex = $cases->getCurrentDelegation($appUid);
// We will to register the files in the database
$response = [];
$response['attachments'] = [];
$response['attachment_errors'] = [];
if (!empty($files)) {
$i = 0;
$j = 0;
foreach ($files as $fileIndex => $fileName) {
// There is no error, the file uploaded with success
if ($fileName["error"] === UPLOAD_ERR_OK) {
$appDocUid = G::generateUniqueID();
// Upload or move the file
$isUploaded = saveAppDocument($fileName, $appUid, $appDocUid, 1, $upload);
// If the file was uploaded correctly we will to register in the DB
if ($isUploaded) {
$attributes = [
"DOC_ID" => $noteId,
"APP_DOC_UID" => $appDocUid,
"DOC_VERSION" => 1,
"APP_UID" => $appUid,
"DEL_INDEX" => $delIndex,
"USR_UID" => $userUid,
"DOC_UID" => -1,
"APP_DOC_TYPE" => 'CASE_NOTE',
"APP_DOC_CREATE_DATE" => date("Y-m-d H:i:s"),
"APP_DOC_FILENAME" => $fileName["name"]
];
Documents::create($attributes);
// List of files uploaded or copy
$response['attachments'][$i++] = $attributes;
} else {
$response['attachment_errors'][$j++] = [
'error' => 'error',
'file' => $fileName["name"]
];
}
} else {
throw new UploadException($fileName['error']);
}
}
}
return $response;
}
/**
* Run the validations related to an Input Document
*

View File

@@ -0,0 +1,21 @@
<?php
namespace ProcessMaker\Exception;
use Exception;
use Throwable;
class CaseNoteUploadFile extends Exception
{
/**
* Constructor method.
* @param string $message
* @param int $code
* @param Throwable $previous
*/
public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@@ -6,6 +6,101 @@ use Illuminate\Database\Eloquent\Model;
class AppNotes extends Model
{
// Set our table name
protected $table = 'APP_NOTES';
// No timestamps
public $timestamps = false;
// Primary key
protected $primaryKey = 'NOTE_ID';
// The IDs are auto-incrementing
public $incrementing = true;
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'NOTE_TYPE' => 'USER',
'NOTE_ORIGIN_OBJ' => '',
'NOTE_AFFECTED_OBJ1' => '',
'NOTE_AFFECTED_OBJ2' => ''
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'APP_UID',
'USR_UID',
'NOTE_DATE',
'NOTE_CONTENT',
'NOTE_TYPE',
'NOTE_AVAILABILITY',
'NOTE_ORIGIN_OBJ',
'NOTE_AFFECTED_OBJ1',
'NOTE_AFFECTED_OBJ2',
'NOTE_RECIPIENTS'
];
/**
* Scope a query to filter an specific case
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $appUid
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeAppUid($query, string $appUid)
{
return $query->where('APP_UID', $appUid);
}
/**
* Return the documents related to the case
*
* @param string $appUid
* @param int $start
* @param int $limit
* @param string $dir
*
* @return array
*/
public static function getNotes(string $appUid, $start = 0, $limit = 25, $dir = 'DESC')
{
$query = AppNotes::query()->select([
'NOTE_ID',
'APP_UID',
'NOTE_DATE',
'NOTE_CONTENT',
'NOTE_TYPE',
'NOTE_AVAILABILITY',
'USERS.USR_UID',
'USERS.USR_USERNAME',
'USERS.USR_FIRSTNAME',
'USERS.USR_LASTNAME'
]);
$query->leftJoin('USERS', function ($join) {
$join->on('USERS.USR_UID', '=', 'APP_NOTES.USR_UID');
});
$query->appUid($appUid);
$query->orderBy('NOTE_DATE', $dir);
// Add pagination to the query
$query->offset($start)->limit($limit);
$results = $query->get();
$notes = [];
$notes['notes'] = [];
$results->each(function ($item, $key) use (&$notes) {
$row = $item->toArray();
$row['NOTE_CONTENT'] = stripslashes($row['NOTE_CONTENT']);
$notes['notes'][] = $row;
});
// Add the total of rows to return
$notes['totalCount'] = $limit;
return $notes;
}
}

View File

@@ -0,0 +1,148 @@
<?php
namespace ProcessMaker\Model;
use Illuminate\Database\Eloquent\Model;
class Documents extends Model
{
// Set our table name
protected $table = 'APP_DOCUMENT';
// No timestamps
public $timestamps = false;
// Primary key
protected $primaryKey = 'NOTE_ID';
// The IDs are auto-incrementing
public $incrementing = false;
// Valid AppDocType's
const DOC_TYPE_ATTACHED = 'ATTACHED';
const DOC_TYPE_CASE_NOTE = 'CASE_NOTE';
const DOC_TYPE_INPUT = 'INPUT';
const DOC_TYPE_OUTPUT = 'OUTPUT';
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'APP_DOC_TITLE' => '',
'APP_DOC_COMMENT' => '',
'DOC_UID' => '-1',
'FOLDER_UID' => '',
'APP_DOC_PLUGIN' => '',
'APP_DOC_TAGS' => '',
'APP_DOC_FIELDNAME' => '',
'APP_DOC_DRIVE_DOWNLOAD' => 'a:0:{}',
'SYNC_WITH_DRIVE' => 'UNSYNCHRONIZED',
'SYNC_PERMISSIONS' => '',
'APP_DOC_STATUS_DATE' => '',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'DOC_ID',
'APP_DOC_UID',
'DOC_VERSION',
'APP_DOC_FILENAME',
'APP_UID',
'DEL_INDEX',
'DOC_UID',
'USR_UID',
'APP_DOC_TYPE',
'APP_DOC_CREATE_DATE',
'APP_DOC_INDEX',
'FOLDER_UID',
'APP_DOC_STATUS',
];
/**
* Scope a query to filter an specific case
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $appUid
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeAppUid($query, string $appUid)
{
return $query->where('APP_UID', $appUid);
}
/**
* Scope a query to filter an specific reference file
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $docId
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeDocId($query, int $docId)
{
return $query->where('DOC_ID', $docId);
}
/**
* Return the documents related to the case
*
* @param string $appUid
* @param string $type
*
* @return array
*/
public static function getAppFiles(string $appUid, $type = 'CASE_NOTES')
{
$query = Documents::query()->select();
$query->appUid($appUid);
$query->where('APP_DOC_TYPE', $type);
$results = $query->get();
$documentList = [];
$results->each(function ($item, $key) use (&$documentList) {
$documentList[] = $item->toArray();
});
return $documentList;
}
/**
* Get attached files from the case note.
*
* @param string $appUid
*
* @return object
*/
public static function getAttachedFilesFromTheCaseNote(string $appUid)
{
$result = Documents::select('APP_DOCUMENT.APP_DOC_UID', 'APP_DOCUMENT.DOC_VERSION', 'APP_DOCUMENT.APP_DOC_FILENAME')
->join('APP_NOTES', function($join) use($appUid) {
$join->on('APP_NOTES.NOTE_ID', '=', 'APP_DOCUMENT.DOC_ID')
->where('APP_DOCUMENT.APP_UID', '=', $appUid);
})
->get();
return $result;
}
/**
* Return the documents related to the specific DOC_ID
*
* @param int $docId
*
* @return array
*/
public static function getFiles(int $docId)
{
$query = Documents::query()->select(['APP_DOC_UID', 'APP_DOC_FILENAME', 'DOC_VERSION']);
$query->docId($docId);
$results = $query->get();
$documentList = [];
$results->each(function ($item, $key) use (&$documentList) {
$row = $item->toArray();
$row['LINK'] = "../cases/casesShowCaseNotes?a=" . $row["APP_DOC_UID"] . "&v=" . $row["DOC_VERSION"];
$documentList[] = $row;
});
return $documentList;
}
}

View File

@@ -601,3 +601,42 @@ function getMysqlVersion()
return $mysqlVersion;
}
/**
* Move the uploaded file to the documents folder
*
* @param array $file
* @param string $appUid
* @param string $appDocUid
* @param int $version
* @param bool $upload
*
* @return string
*/
function saveAppDocument($file, $appUid, $appDocUid, $version = 1, $upload = true)
{
try {
$info = pathinfo($file["name"]);
$extension = ((isset($info["extension"])) ? $info["extension"] : "");
$fileName = $appDocUid . "_" . $version . "." . $extension;
$pathCase = PATH_DATA_SITE . 'files' . PATH_SEP . G::getPathFromUID($appUid) . PATH_SEP;
$response = false;
if ($upload) {
G::uploadFile(
$file["tmp_name"],
$pathCase,
$fileName
);
$response = true;
} else {
G::verifyPath($pathCase, true);
$response = copy($file["tmp_name"], $pathCase . $fileName);
}
return $response;
} catch (Exception $e) {
throw $e;
}
}

View File

@@ -27,6 +27,16 @@ class ValidationUploadedFiles
*/
private $fails = [];
/**
* Return this constant when rule is invalid.
*/
private const INVALID = true;
/**
* Return this constant when rule is valid.
*/
private const VALID = false;
/**
* Check if the loaded files comply with the validation rules, add here if you
* want more validation rules.
@@ -280,6 +290,110 @@ class ValidationUploadedFiles
return $validator->validate();
}
/**
* Check if the loaded files comply with the validation rules, add here if you
* want more validation rules.
* Accept per argument an array or object that contains a "filename" and "path" values.
* The rules are verified in the order in which they have been added.
*
* @param array|object $file
* @return Validator
*/
public function runRulesForPostFilesOfNote($file)
{
$validator = new Validator();
//rule: file exists
$rule = $validator->addRule();
$rule->validate($file, function($file) use($rule) {
$path = isset($file->path) ? $file->path : "";
$filesystem = new Filesystem();
if (!$filesystem->exists($path)) {
$rule->message(G::LoadTranslation('ID_NOT_EXISTS_FILE'));
return self::INVALID;
}
return self::VALID;
})
->status(400)
->log(function($rule) {
/**
* Levels supported by MonologProvider is:
* 100 "DEBUG"
* 200 "INFO"
* 250 "NOTICE"
* 300 "WARNING"
* 400 "ERROR"
* 500 "CRITICAL"
* 550 "ALERT"
* 600 "EMERGENCY"
*/
Bootstrap::registerMonologPhpUploadExecution('phpUpload', $rule->getStatus(), $rule->getMessage(), $rule->getData()->filename);
});
//rule: extensions
$rule = $validator->addRule();
$rule->validate($file, function($file) use($rule) {
$filesystem = new Filesystem();
$extension = strtolower($filesystem->extension($file->filename));
$extensions = [
'pdf', 'gif', 'jpg', 'png', 'doc', 'docx', 'xls', 'xlsx', 'txt', 'mp4', 'mpv', 'mpeg', 'mpg', 'mov'
];
if (!in_array($extension, $extensions)) {
$rule->message(G::LoadTranslation('ID_YOU_UPLOADED_AN_UNSUPPORTED_FILE_EXTENSION'));
return self::INVALID;
}
return self::VALID;
})
->status(400)
->log(function($rule) {
/**
* Levels supported by MonologProvider is:
* 100 "DEBUG"
* 200 "INFO"
* 250 "NOTICE"
* 300 "WARNING"
* 400 "ERROR"
* 500 "CRITICAL"
* 550 "ALERT"
* 600 "EMERGENCY"
*/
Bootstrap::registerMonologPhpUploadExecution('phpUpload', $rule->getStatus(), $rule->getMessage(), $rule->getData()->filename);
});
//rule: file size
$rule = $validator->addRule();
$rule->validate($file, function($file) use($rule) {
$path = isset($file->path) ? $file->path : "";
$filesystem = new Filesystem();
$limitSize = '10M';
$size = $filesystem->size($path);
$phpShorthandByte = new PhpShorthandByte();
$postMaxSizeBytes = $phpShorthandByte->valueToBytes($limitSize);
if ($size > $postMaxSizeBytes) {
$rule->message(G::LoadTranslation('ID_YOUR_FILE_HAS_EXCEEDED', [$limitSize]));
return self::INVALID;
}
return self::VALID;
})
->status(400)
->log(function($rule) {
/**
* Levels supported by MonologProvider is:
* 100 "DEBUG"
* 200 "INFO"
* 250 "NOTICE"
* 300 "WARNING"
* 400 "ERROR"
* 500 "CRITICAL"
* 550 "ALERT"
* 600 "EMERGENCY"
*/
Bootstrap::registerMonologPhpUploadExecution('phpUpload', $rule->getStatus(), $rule->getMessage(), $rule->getData()->filename);
});
return $validator->validate();
}
/**
* Get the first error and call the argument function.
*