Solving conflicts merginf with last merge in develop branch

This commit is contained in:
Julio Cesar Laura Avendaño
2020-11-25 13:18:20 +00:00
34 changed files with 2288 additions and 680 deletions

View File

@@ -59,7 +59,7 @@ class ResponseReader
try {
if (!extension_loaded('imap')) {
G::outRes(G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", ['php_imap']) . "\n");
exit;
return;
}
if (PMLicensedFeatures
::getSingleton()
@@ -145,6 +145,7 @@ class ResponseReader
$emailSetup['MESS_ACCOUNT'],
$this->decryptPassword($emailSetup)
);
Log::channel(':' . $this->channel)->debug("Open mailbox", Bootstrap::context($emailSetup));
// Read all messages into an array
$mailsIds = $mailbox->searchMailbox('UNSEEN');
@@ -153,6 +154,7 @@ class ResponseReader
foreach ($mailsIds as $key => $mailId) {
/** @var IncomingMail $mail */
$mail = $mailbox->getMail($mailId, false);
Log::channel(':' . $this->channel)->debug("Get mail", Bootstrap::context(['mailId' => $mailId]));
if (!empty($mail->textPlain)) {
preg_match("/{(.*)}/", $mail->textPlain, $matches);
if ($matches) {

View File

@@ -17,6 +17,7 @@ use Applications;
use AppNotes;
use AppNotesPeer;
use AppSolr;
use AppTimeoutActionExecuted;
use BasePeer;
use Bootstrap;
use BpmnEngineServicesSearchIndex;
@@ -25,6 +26,7 @@ use CasesPeer;
use Configurations;
use CreoleTypes;
use Criteria;
use DateTime;
use DBAdapter;
use EntitySolrRequestData;
use Exception;
@@ -44,8 +46,11 @@ use ProcessMaker\Exception\UploadException;
use ProcessMaker\Exception\CaseNoteUploadFile;
use ProcessMaker\Model\Application as ModelApplication;
use ProcessMaker\Model\AppNotes as Notes;
use ProcessMaker\Model\AppTimeoutAction;
use ProcessMaker\Model\Delegation;
use ProcessMaker\Model\Documents;
use ProcessMaker\Model\ListUnassigned;
use ProcessMaker\Model\Triggers;
use ProcessMaker\Plugins\PluginRegistry;
use ProcessMaker\Services\OAuth2\Server;
use ProcessMaker\Util\DateTime as UtilDateTime;
@@ -4107,4 +4112,127 @@ class Cases
return true;
}
/**
* Get the cases related to the self services timeout that needs to execute the trigger related
*
* @return array
* @throws Exception
*/
public static function executeSelfServiceTimeout()
{
try {
$casesSelfService = ListUnassigned::selfServiceTimeout();
$casesExecuted = [];
foreach ($casesSelfService as $row) {
$appUid = $row["APP_UID"];
$appNumber = $row["APP_NUMBER"];
$delIndex = $row["DEL_INDEX"];
$delegateDate = $row["DEL_DELEGATE_DATE"];
$proUid = $row["PRO_UID"];
$taskUid = $row["TAS_UID"];
$taskSelfServiceTime = intval($row["TAS_SELFSERVICE_TIME"]);
$taskSelfServiceTimeUnit = $row["TAS_SELFSERVICE_TIME_UNIT"];
$triggerUid = $row["TAS_SELFSERVICE_TRIGGER_UID"];
/*----------------------------------********---------------------------------*/
$typeOfExecution = $row["TAS_SELFSERVICE_EXECUTION"];
$flagExecuteOnce = true;
// This option will be executed just once, can check if was executed before
if ($typeOfExecution == 'ONCE') {
$appTimeout = new AppTimeoutAction();
$appTimeout->setCaseUid($appUid);
$appTimeout->setIndex($delIndex);
$caseExecuted = $appTimeout->cases();
$flagExecuteOnce = !empty($caseExecuted) ? false : true;
}
/*----------------------------------********---------------------------------*/
// Add the time in the corresponding unit to the delegation date
$delegateDate = calculateDate($delegateDate, $taskSelfServiceTimeUnit, $taskSelfServiceTime);
// Define the current time
$datetime = new DateTime('now');
$currentDate = $datetime->format('Y-m-d H:i:s');
// Check if the triggers to be executed
if ($currentDate >= $delegateDate && $flagExecuteOnce) {
// Review if the session process is defined
$sessProcess = null;
$sessProcessSw = false;
if (isset($_SESSION["PROCESS"])) {
$sessProcess = $_SESSION["PROCESS"];
$sessProcessSw = true;
}
// Load case data
$case = new ClassesCases();
$appFields = $case->loadCase($appUid);
$appFields["APP_DATA"]["APPLICATION"] = $appUid;
// Set the process defined in the case related
$_SESSION["PROCESS"] = $appFields["PRO_UID"];
// Get the trigger related and execute
$triggersList = [];
if (!empty($triggerUid)) {
$trigger = new Triggers();
$trigger->setTrigger($triggerUid);
$triggersList = $trigger->triggers();
}
// If the trigger exist, let's to execute
if (!empty($triggersList)) {
// Execute the trigger defined in the self service timeout
$fieldsCase['APP_DATA'] = $case->executeTriggerFromList(
$triggersList,
$appFields['APP_DATA'],
'SELF_SERVICE_TIMEOUT',
'',
'',
'',
false
);
// Update the case
$case->updateCase($appUid, $fieldsCase);
/*----------------------------------********---------------------------------*/
if ($typeOfExecution == 'ONCE') {
// Saving the case`s data if the 'Execution' is set in ONCE.
$appTimeoutActionExecuted = new AppTimeoutActionExecuted();
$dataSelf = [];
$dataSelf["APP_UID"] = $appUid;
$dataSelf["DEL_INDEX"] = $delIndex;
$dataSelf["EXECUTION_DATE"] = time();
$appTimeoutActionExecuted->create($dataSelf);
}
/*----------------------------------********---------------------------------*/
array_push($casesExecuted, $appNumber); // Register the cases executed
// Logging this action
$context = [
'appUid' => $appUid,
'appNumber' => $appNumber,
'triUid' => $triggerUid,
'proUid' => $proUid,
'tasUid' => $taskUid,
'selfServiceTime' => $taskSelfServiceTime,
'selfServiceTimeUnit' => $taskSelfServiceTimeUnit,
];
Log::channel(':TriggerExecution')->info('Timeout trigger execution', Bootstrap::context($context));
}
unset($_SESSION["PROCESS"]);
if ($sessProcessSw) {
$_SESSION["PROCESS"] = $sessProcess;
}
}
}
return $casesExecuted;
} catch (Exception $e) {
throw $e;
}
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace ProcessMaker\AuditLog;
namespace ProcessMaker\Log;
use Bootstrap;
use Configurations;

View File

@@ -0,0 +1,103 @@
<?php
namespace ProcessMaker\Model;
use Illuminate\Database\Eloquent\Model;
class AppTimeoutAction extends Model
{
protected $table = 'APP_TIMEOUT_ACTION_EXECUTED';
// We do not have create/update timestamps for this table
public $timestamps = false;
// Filter by a specific case using case number
private $caseUid = '';
// Filter by a specific index
private $index = 0;
/**
* Set Case Uid
*
* @param string $caseUid
*/
public function setCaseUid($caseUid)
{
$this->caseUid = $caseUid;
}
/**
* Get Case Uid
*
* @return string
*/
public function getCaseUid()
{
return $this->caseUid;
}
/**
* Set index
*
* @param int $index
*/
public function setIndex($index)
{
$this->index = $index;
}
/**
* Get index
*
* @return int
*/
public function getIndex()
{
return $this->index;
}
/**
* Scope a query to get specific case uid
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $appUid
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCase($query, $appUid)
{
return $query->where('APP_UID', $appUid);
}
/**
* Scope a query to get index
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $index
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeIndex($query, $index)
{
return $query->where('DEL_INDEX', $index);
}
/**
* Get the records related to the case and index if it was defined
*
* @return array
*/
public function cases()
{
$query = AppTimeoutAction::query()->select();
// Specific case uid
if (!empty($this->getCaseUid())) {
$query->case($this->getCaseUid());
}
// Specific index
if (!empty($this->getIndex())) {
$query->index($this->getIndex());
}
$results = $query->get()->toArray();
return $results;
}
}

View File

@@ -46,8 +46,9 @@ class ListUnassigned extends Model
/**
* Scope a query to only include specific tasks
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $tasks
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $tasks
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeTasksIn($query, array $tasks)
@@ -58,8 +59,8 @@ class ListUnassigned extends Model
/**
* Scope a query to only include a specific case
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $appNumber
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $appNumber
*
* @return \Illuminate\Database\Eloquent\Builder
*/
@@ -71,8 +72,8 @@ class ListUnassigned extends Model
/**
* Scope a query to only include a specific index
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $index
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $index
*
* @return \Illuminate\Database\Eloquent\Builder
*/
@@ -84,8 +85,8 @@ class ListUnassigned extends Model
/**
* Scope a query to only include a specific task
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $task
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $task
*
* @return \Illuminate\Database\Eloquent\Builder
*/
@@ -100,7 +101,7 @@ class ListUnassigned extends Model
* @param string $userUid
* @param array $filters
*
* @return array
* @return int
*/
public static function doCount($userUid, $filters = [])
{
@@ -125,4 +126,21 @@ class ListUnassigned extends Model
return $result;
}
/**
* Get the unassigned cases related to the self service timeout
*
* @return array
*/
public static function selfServiceTimeout()
{
$query = ListUnassigned::query()->select();
$query->join('TASK', function ($join) {
$join->on('LIST_UNASSIGNED.TAS_ID', '=', 'TASK.TAS_ID')
->where('TASK.TAS_SELFSERVICE_TIMEOUT', '=', 1);
});
$results = $query->get()->toArray();
return $results;
}
}

View File

@@ -10,11 +10,34 @@ class Triggers extends Model
protected $table = 'TRIGGERS';
// No timestamps
public $timestamps = false;
//primary key
// Primary key
protected $primaryKey = 'TRI_UID';
//No incrementing
// No incrementing
public $incrementing = false;
// Filter by a specific uid
private $triUid = '';
/**
* Set trigger uid
*
* @param string $triUid
*/
public function setTrigger($triUid)
{
$this->triUid = $triUid;
}
/**
* Get trigger uid
*
* @return int
*/
public function getTrigger()
{
return $this->triUid;
}
/**
* Scope a query to filter an specific process
*
@@ -22,8 +45,37 @@ class Triggers extends Model
* @param string $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeProcess($query, string $proUID)
public function scopeProcess($query, string $proUid)
{
return $query->where('PRO_UID', $proUID);
return $query->where('PRO_UID', $proUid);
}
/**
* Scope a query to filter an specific trigger
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $triUid
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeTrigger($query, string $triUid)
{
return $query->where('TRI_UID', $triUid);
}
/**
* Get the records
*
* @return array
*/
public function triggers()
{
$query = Triggers::query()->select();
// Specific trigger
if (!empty($this->getTrigger())) {
$query->trigger($this->getTrigger());
}
$results = $query->get()->toArray();
return $results;
}
}

View File

@@ -0,0 +1,687 @@
<?php
namespace ProcessMaker\TaskScheduler;
use Application;
use AppAssignSelfServiceValueGroupPeer;
use AppAssignSelfServiceValuePeer;
use AppCacheView;
use AppDelegation;
use App\Jobs\TaskScheduler;
use Bootstrap;
use Cases;
use ConfigurationPeer;
use Criteria;
use Exception;
use G;
use Illuminate\Support\Facades\Log;
use ldapadvancedClassCron;
use NotificationQueue;
use ProcessMaker\BusinessModel\ActionsByEmail\ResponseReader;
use ProcessMaker\BusinessModel\Cases as BmCases;
use ProcessMaker\BusinessModel\Light\PushMessageAndroid;
use ProcessMaker\BusinessModel\Light\PushMessageIOS;
use ProcessMaker\BusinessModel\MessageApplication;
use ProcessMaker\BusinessModel\TimerEvent;
use ProcessMaker\Core\JobsManager;
use ProcessMaker\Plugins\PluginRegistry;
use Propel;
use ResultSet;
use SpoolRun;
class Task
{
/**
* Property asynchronous,
* @var bool
*/
private $asynchronous;
/**
* Property object
* @var mix
*/
private $object;
/**
* Constructor class.
* @param bool $async
* @param mix $object
*/
public function __construct(bool $asynchronous, $object)
{
$this->asynchronous = $asynchronous;
$this->object = $object;
}
/**
* Run job, the property async indicate if is synchronous or asynchronous.
* @param callable $job
*/
private function runTask(callable $job)
{
if ($this->asynchronous === false) {
$job();
}
if ($this->asynchronous === true) {
JobsManager::getSingleton()->dispatch(TaskScheduler::class, $job);
}
}
/**
* Print start message in console.
* @param string $message
*/
public function setExecutionMessage(string $message)
{
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
if ($this->asynchronous === false) {
$len = strlen($message);
$linesize = 60;
$rOffset = $linesize - $len;
eprint("* $message");
for ($i = 0; $i < $rOffset; $i++) {
eprint('.');
}
}
}
/**
* Print result message in console.
* @param string $message
* @param string $type
*/
public function setExecutionResultMessage(string $message, string $type = '')
{
$color = 'green';
if ($type == 'error') {
$color = 'red';
Log::channel('taskScheduler:taskScheduler')->error($message, Bootstrap::context());
}
if ($type == 'info') {
$color = 'yellow';
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
}
if ($type == 'warning') {
$color = 'yellow';
Log::channel('taskScheduler:taskScheduler')->warning($message, Bootstrap::context());
}
if ($this->asynchronous === false) {
eprintln("[$message]", $color);
}
}
/**
* Save logs.
* @param string $source
* @param string $type
* @param string $description
*/
public function saveLog(string $source, string $type, string $description)
{
if ($this->asynchronous === true) {
$context = [
'type' => $type,
'description' => $description
];
Log::channel('taskScheduler:taskScheduler')->info($source, Bootstrap::context($context));
}
if ($this->asynchronous === false) {
try {
G::verifyPath(PATH_DATA . "log" . PATH_SEP, true);
G::log("| $this->object | " . $source . " | $type | " . $description, PATH_DATA);
} catch (Exception $e) {
Log::channel('taskScheduler:taskScheduler')->error($e->getMessage(), Bootstrap::context());
}
}
}
/**
* This resend the emails.
* @param string $now
* @param string $dateSystem
*/
public function resendEmails($now, $dateSystem)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($now, $dateSystem, $scheduledTaskIdentifier) {
$this->setExecutionMessage("Resending emails");
try {
$dateResend = $now;
if ($now == $dateSystem) {
$arrayDateSystem = getdate(strtotime($dateSystem));
$mktDateSystem = mktime(
$arrayDateSystem["hours"],
$arrayDateSystem["minutes"],
$arrayDateSystem["seconds"],
$arrayDateSystem["mon"],
$arrayDateSystem["mday"],
$arrayDateSystem["year"]
);
$dateResend = date("Y-m-d H:i:s", $mktDateSystem - (7 * 24 * 60 * 60));
}
$spoolRun = new SpoolRun();
$spoolRun->resendEmails($dateResend, 1);
$this->saveLog("resendEmails", "action", "Resending Emails", "c");
$spoolWarnings = $spoolRun->getWarnings();
if ($spoolWarnings !== false) {
foreach ($spoolWarnings as $warning) {
print("MAIL SPOOL WARNING: " . $warning . "\n");
$this->saveLog("resendEmails", "warning", "MAIL SPOOL WARNING: " . $warning);
}
}
$this->setExecutionResultMessage("DONE");
} catch (Exception $e) {
$context = [
"trace" => $e->getTraceAsString()
];
Log::channel('taskScheduler:taskScheduler')->error($e->getMessage(), Bootstrap::context($context));
$criteria = new Criteria("workflow");
$criteria->clearSelectColumns();
$criteria->addSelectColumn(ConfigurationPeer::CFG_UID);
$criteria->add(ConfigurationPeer::CFG_UID, "Emails");
$result = ConfigurationPeer::doSelectRS($criteria);
$result->setFetchmode(ResultSet::FETCHMODE_ASSOC);
if ($result->next()) {
$this->setExecutionResultMessage("WARNING", "warning");
$message = "Emails won't be sent, but the cron will continue its execution";
if ($this->asynchronous === false) {
eprintln(" '-" . $message, "yellow");
}
} else {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
}
$this->saveLog("resendEmails", "error", "Error Resending Emails: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This unpause applications.
* @param string $now
*/
public function unpauseApplications($now)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($now, $scheduledTaskIdentifier) {
$this->setExecutionMessage("Unpausing applications");
try {
$cases = new Cases();
$cases->ThrowUnpauseDaemon($now, 1);
$this->setExecutionResultMessage('DONE');
$this->saveLog('unpauseApplications', 'action', 'Unpausing Applications');
} catch (Exception $e) {
$this->setExecutionResultMessage('WITH ERRORS', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('unpauseApplications', 'error', 'Error Unpausing Applications: ' . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* Check if some task unassigned has enable the setting timeout and execute the trigger related
*
* @link https://wiki.processmaker.com/3.2/Tasks#Self-Service
*/
function executeCaseSelfService()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
try {
$this->setExecutionMessage("Unassigned case");
$this->saveLog("unassignedCase", "action", "Unassigned case", "c");
$casesExecuted = BmCases::executeSelfServiceTimeout();
foreach ($casesExecuted as $caseNumber) {
$this->saveLog("unassignedCase", "action", "OK Executed trigger to the case $caseNumber");
}
$this->setExecutionResultMessage(count($casesExecuted) . " Cases");
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
$this->saveLog("unassignedCase", "action", "Unassigned case", "c");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("unassignedCase", "error", "Error in unassigned case: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This calculate duration.
*/
public function calculateDuration()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$this->setExecutionMessage("Calculating Duration");
try {
$appDelegation = new AppDelegation();
$appDelegation->calculateDuration(1);
$this->setExecutionResultMessage('DONE');
$this->saveLog('calculateDuration', 'action', 'Calculating Duration');
} catch (Exception $e) {
$this->setExecutionResultMessage('WITH ERRORS', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('calculateDuration', 'error', 'Error Calculating Duration: ' . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This calculate application duration.
*/
public function calculateAppDuration()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$this->setExecutionMessage("Calculating Duration by Application");
try {
$application = new Application();
$application->calculateAppDuration(1);
$this->setExecutionResultMessage('DONE');
$this->saveLog('calculateDurationByApp', 'action', 'Calculating Duration by Application');
} catch (Exception $e) {
$this->setExecutionResultMessage('WITH ERRORS', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('calculateDurationByApp', 'error', 'Error Calculating Duration: ' . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* Clean unused records in tables related to the Self-Service Value Based feature.
*/
public function cleanSelfServiceTables()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
try {
// Start message
$this->setExecutionMessage("Clean unused records for Self-Service Value Based feature");
// Get Propel connection
$cnn = Propel::getConnection(AppAssignSelfServiceValueGroupPeer::DATABASE_NAME);
// Delete related rows and missing relations, criteria don't execute delete with joins
$cnn->begin();
$stmt = $cnn->createStatement();
$stmt->executeQuery("DELETE " . AppAssignSelfServiceValueGroupPeer::TABLE_NAME . "
FROM " . AppAssignSelfServiceValueGroupPeer::TABLE_NAME . "
LEFT JOIN " . AppAssignSelfServiceValuePeer::TABLE_NAME . "
ON (" . AppAssignSelfServiceValueGroupPeer::ID . " = " . AppAssignSelfServiceValuePeer::ID . ")
WHERE " . AppAssignSelfServiceValuePeer::ID . " IS NULL");
$cnn->commit();
// Success message
$this->setExecutionResultMessage("DONE");
} catch (Exception $e) {
$cnn->rollback();
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("ExecuteCleanSelfServiceTables", "error", "Error when try to clean self-service tables " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute plugins cron.
* @return boolean
*/
public function executePlugins()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$pathCronPlugins = PATH_CORE . 'bin' . PATH_SEP . 'plugins' . PATH_SEP;
// Executing cron files in bin/plugins directory
if (!is_dir($pathCronPlugins)) {
return false;
}
if ($handle = opendir($pathCronPlugins)) {
$this->setExecutionMessage('Executing cron files in bin/plugins directory in Workspace: ' . config("system.workspace"));
while (false !== ($file = readdir($handle))) {
if (strpos($file, '.php', 1) && is_file($pathCronPlugins . $file)) {
$filename = str_replace('.php', '', $file);
$className = $filename . 'ClassCron';
// Execute custom cron function
$this->executeCustomCronFunction($pathCronPlugins . $file, $className);
}
}
}
// Executing registered cron files
// -> Get registered cron files
$pluginRegistry = PluginRegistry::loadSingleton();
$cronFiles = $pluginRegistry->getCronFiles();
// -> Execute functions
if (!empty($cronFiles)) {
$this->setExecutionMessage('Executing registered cron files for Workspace: ' . config('system.workspace'));
/**
* @var \ProcessMaker\Plugins\Interfaces\CronFile $cronFile
*/
foreach ($cronFiles as $cronFile) {
$path = PATH_PLUGINS . $cronFile->getNamespace() . PATH_SEP . 'bin' . PATH_SEP . $cronFile->getCronFile() . '.php';
if (file_exists($path)) {
$this->executeCustomCronFunction($path, $cronFile->getCronFile());
} else {
$this->setExecutionMessage('File ' . $cronFile->getCronFile() . '.php ' . 'does not exist.');
}
}
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute custom cron function.
* @param string $pathFile
* @param string $className
*/
public function executeCustomCronFunction($pathFile, $className)
{
include_once $pathFile;
$plugin = new $className();
if (method_exists($plugin, 'executeCron')) {
$arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
$arrayCron["processcTimeProcess"] = 60; //Minutes
$arrayCron["processcTimeStart"] = time();
@file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
//Try to execute Plugin Cron. If there is an error then continue with the next file
$this->setExecutionMessage("\n--- Executing cron file: $pathFile");
try {
$plugin->executeCron();
$this->setExecutionResultMessage('DONE');
} catch (Exception $e) {
$this->setExecutionResultMessage('FAILED', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('executePlugins', 'error', 'Error executing cron file: ' . $pathFile . ' - ' . $e->getMessage());
}
}
}
/**
* This fills the report by user.
* @param string $dateInit
* @param string $dateFinish
* @return boolean
*/
public function fillReportByUser($dateInit, $dateFinish)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
if ($dateInit == null) {
if ($this->asynchronous === false) {
eprintln("You must enter the starting date.", "red");
eprintln('Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"', "red");
}
if ($this->asynchronous === true) {
$message = 'You must enter the starting date. Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"';
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
}
return false;
}
$job = function() use($dateInit, $dateFinish, $scheduledTaskIdentifier) {
try {
$dateFinish = ($dateFinish != null) ? $dateFinish : date("Y-m-d H:i:s");
$appCacheView = new AppCacheView();
$appCacheView->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP);
$this->setExecutionMessage("Calculating data to fill the 'User Reporting'...");
$appCacheView->fillReportByUser($dateInit, $dateFinish);
setExecutionResultMessage("DONE");
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("fillReportByUser", "error", "Error in fill report by user: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This fills the report by process.
* @param string $dateInit
* @param string $dateFinish
* @return boolean
*/
public function fillReportByProcess($dateInit, $dateFinish)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
if ($dateInit == null) {
if ($this->asynchronous === false) {
eprintln("You must enter the starting date.", "red");
eprintln('Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"', "red");
}
if ($this->asynchronous === true) {
$message = 'You must enter the starting date. Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"';
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
}
return false;
}
$job = function() use($dateInit, $dateFinish, $scheduledTaskIdentifier) {
try {
$dateFinish = ($dateFinish != null) ? $dateFinish : date("Y-m-d H:i:s");
$appcv = new AppCacheView();
$appcv->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP);
$this->setExecutionMessage("Calculating data to fill the 'Process Reporting'...");
$appcv->fillReportByProcess($dateInit, $dateFinish);
$this->setExecutionResultMessage("DONE");
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("fillReportByProcess", "error", "Error in fill report by process: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute ldap cron.
* @param boolean $debug
*/
public function ldapcron($debug)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($debug, $scheduledTaskIdentifier) {
require_once(PATH_HOME . 'engine' . PATH_SEP . 'methods' . PATH_SEP . 'services' . PATH_SEP . 'ldapadvanced.php');
$ldapadvancedClassCron = new ldapadvancedClassCron();
$ldapadvancedClassCron->executeCron($debug);
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute the sending of notifications.
*/
function sendNotifications()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
try {
$this->setExecutionMessage("Resending Notifications");
$this->setExecutionResultMessage("PROCESSING");
$notQueue = new NotificationQueue();
$notQueue->checkIfCasesOpenForResendingNotification();
$notificationsAndroid = $notQueue->loadStatusDeviceType('pending', 'android');
if ($notificationsAndroid) {
$this->setExecutionMessage("|-- Send Android's Notifications");
$n = 0;
foreach ($notificationsAndroid as $key => $item) {
$notification = new PushMessageAndroid();
$notification->setSettingNotification();
$notification->setDevices(unserialize($item['DEV_UID']));
$response['android'] = $notification->send($item['NOT_MSG'], unserialize($item['NOT_DATA']));
$notQueue = new NotificationQueue();
$notQueue->changeStatusSent($item['NOT_UID']);
$n += $notification->getNumberDevices();
}
$this->setExecutionResultMessage("Processed $n");
}
$notificationsApple = $notQueue->loadStatusDeviceType('pending', 'apple');
if ($notificationsApple) {
$this->setExecutionMessage("|-- Send Apple Notifications");
$n = 0;
foreach ($notificationsApple as $key => $item) {
$notification = new PushMessageIOS();
$notification->setSettingNotification();
$notification->setDevices(unserialize($item['DEV_UID']));
$response['apple'] = $notification->send($item['NOT_MSG'], unserialize($item['NOT_DATA']));
$notQueue = new NotificationQueue();
$notQueue->changeStatusSent($item['NOT_UID']);
$n += $notification->getNumberDevices();
}
$this->setExecutionResultMessage("Processed $n");
}
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("ExecuteSendNotifications", "error", "Error when sending notifications " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This executes an actions by email responses.
*/
public function actionsByEmailResponse()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$responseReader = new ResponseReader();
$responseReader->actionsByEmailEmailResponse();
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute message event cron.
*/
public function messageeventcron()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$messageApplication = new MessageApplication();
$messageApplication->catchMessageEvent(true);
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* Start/Continue cases by Timer-Event
*
* @param string $datetime
* @param bool $frontEnd
*/
public function timerEventCron($datetime, $frontEnd)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use ($datetime, $frontEnd, $scheduledTaskIdentifier) {
$timerEvent = new TimerEvent();
$timerEvent->startContinueCaseByTimerEvent($datetime, $frontEnd);
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
}

View File

@@ -640,3 +640,33 @@ function saveAppDocument($file, $appUid, $appDocUid, $version = 1, $upload = tru
throw $e;
}
}
/**
* Add a specific date minutes, hours or days
*
* @param string $iniDate
* @param string $timeUnit
* @param int $time
*
* @return string
*
* @link https://www.php.net/manual/en/datetime.modify.php
*/
function calculateDate($iniDate, $timeUnit, $time)
{
$datetime = new DateTime($iniDate);
switch ($timeUnit) {
case 'DAYS':
$datetime->modify('+' . $time . ' day');
break;
case 'HOURS':
$datetime->modify('+' . $time . ' hour');
break;
case 'MINUTES':
$datetime->modify('+' . $time . ' minutes');
break;
}
return $datetime->format('Y-m-d H:i:s');
}