Merge remote-tracking branch 'upstream/3.0.1.7-Gmail' into BY-237

Conflicts:
	workflow/engine/methods/cases/cases_Derivate.php
This commit is contained in:
Dante
2016-06-09 14:00:37 -04:00
100 changed files with 10748 additions and 5449 deletions

View File

@@ -41,7 +41,7 @@ class FilesManager
*
* @access public
*/
public function getProcessFilesManagerPath($sProcessUID, $path)
public function getProcessFilesManagerPath($sProcessUID, $path, $getContent = true)
{
try {
$checkPath = substr($path, -1);
@@ -85,7 +85,10 @@ class FilesManager
}
foreach ($aFiles as $aFile) {
$arrayFileUid = $this->getFileManagerUid($sDirectory.$aFile['FILE']);
$fcontent = file_get_contents($sDirectory.$aFile['FILE']);
$fcontent = "";
if ($getContent === true) {
$fcontent = file_get_contents($sDirectory . $aFile['FILE']);
}
$fileUid = $arrayFileUid["PRF_UID"];
if ($fileUid != null) {
$oProcessFiles = \ProcessFilesPeer::retrieveByPK($fileUid);
@@ -243,6 +246,11 @@ class FilesManager
}
}
/**
* @param $aData
* @throws Exception
* @throws \Exception
*/
public function addProcessFilesManagerInDb($aData)
{
try {
@@ -250,13 +258,32 @@ class FilesManager
$aData = array_change_key_case($aData, CASE_UPPER);
$oProcessFiles->fromArray($aData, \BasePeer::TYPE_FIELDNAME);
$path = $aData['PRF_PATH'];
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$path = str_replace("/", DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, $path);
}
$path = explode(DIRECTORY_SEPARATOR,$path);
$fileDirectory = $path[count($path)-3];
switch ($fileDirectory) {
case 'mailTemplates':
$sDirectory = PATH_DATA_MAILTEMPLATES . $aData['PRO_UID'] . PATH_SEP . basename($aData['PRF_PATH']);
break;
case 'public':
$sDirectory = PATH_DATA_PUBLIC . $aData['PRO_UID'] . PATH_SEP . basename($aData['PRF_PATH']);
break;
default:
throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_FOR", array($aData['PRF_PATH'])));
break;
}
$oProcessFiles->setPrfPath($sDirectory);
if($this->existsProcessFile($aData['PRF_UID'])) {
$sPkProcessFiles = \G::generateUniqueID();
$oProcessFiles->setPrfUid($sPkProcessFiles);
$sDirectory = PATH_DATA_MAILTEMPLATES . $aData['PRO_UID'] . PATH_SEP . basename($aData['PRF_PATH']);
$oProcessFiles->setPrfPath($sDirectory);
$emailEvent = new \ProcessMaker\BusinessModel\EmailEvent();
$emailEvent->updatePrfUid($aData['PRF_UID'], $sPkProcessFiles, $aData['PRO_UID']);
}
@@ -267,6 +294,30 @@ class FilesManager
}
}
/**
* @param $aData
* @throws Exception
*/
public function updateProcessFilesManagerInDb($aData)
{
try {
//update database
if ($this->existsProcessFile($aData['prf_uid'])) {
$aData = array_change_key_case($aData, CASE_UPPER);
$oProcessFiles = \ProcessFilesPeer::retrieveByPK($aData['PRF_UID']);
$sDate = date('Y-m-d H:i:s');
$oProcessFiles->setPrfUpdateDate($sDate);
$oProcessFiles->setProUid($aData['PRO_UID']);
$oProcessFiles->setPrfPath($aData['PRF_PATH']);
$oProcessFiles->save();
} else {
$this->addProcessFilesManagerInDb($aData);
}
} catch (Exception $e) {
throw $e;
}
}
public function existsProcessFile($prfUid)
{
try {
@@ -506,7 +557,7 @@ class FilesManager
if ($path == '') {
throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_FOR", array('prf_uid')));
}
$sFile = end(explode("/",$path));
$sFile = end(explode("/",str_replace('\\', '/',$path)));
$sPath = str_replace($sFile,'',$path);
$sSubDirectory = substr(str_replace($sProcessUID,'',substr($sPath,(strpos($sPath, $sProcessUID)))),0,-1);
$sMainDirectory = str_replace(substr($sPath, strpos($sPath, $sProcessUID)),'', $sPath);

View File

@@ -193,6 +193,19 @@ class InputDocument
$flagAssigned = true;
$arrayData[] = \G::LoadTranslation("ID_PROCESS_PERMISSIONS");
}
//Variables
$criteria = new \Criteria("workflow");
$criteria->addSelectColumn(\ProcessVariablesPeer::VAR_UID);
$criteria->add(\ProcessVariablesPeer::INP_DOC_UID, $inputDocumentUid);
$rsCriteria = \ProcessVariablesPeer::doSelectRS($criteria);
if ($rsCriteria->next()) {
$flagAssigned = true;
$arrayData[] = \G::LoadTranslation("ID_VARIABLES");
}
//Return
return array($flagAssigned, $arrayData);

View File

@@ -2,10 +2,23 @@
namespace ProcessMaker\BusinessModel\Light;
use \ProcessMaker\Services\Api;
use G;
class NotificationDevice
{
public function checkMobileNotifications()
{
$conf = \System::getSystemConfiguration('', '', SYS_SYS);
$activeNotifications = true;
if (isset($conf['mobileNotifications'])) {
$activeNotifications = $conf['mobileNotifications'] == 1 ? true : false;
}
return $activeNotifications;
}
/**
* Post Create register device with userUid
*
@@ -135,7 +148,7 @@ class NotificationDevice
}
} catch (\Exception $e) {
throw new \Exception(\Api::STAT_APP_EXCEPTION, $e->getMessage());
throw new \Exception($e->getMessage(), Api::STAT_APP_EXCEPTION);
}
return $response;
}
@@ -229,8 +242,9 @@ class NotificationDevice
}
}
} catch (\Exception $e) {
throw new \Exception(\Api::STAT_APP_EXCEPTION, $e->getMessage());
throw new \Exception($e->getMessage(), Api::STAT_APP_EXCEPTION);
}
return $response;
}

View File

@@ -0,0 +1,101 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
/**
* The assignment rules migrator class.
* The container class that stores the import and export rules for assignment rules.
*
* Class AssignmentRulesMigrator
* @package ProcessMaker\BusinessModel\Migrator
*/
class AssignmentRulesMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* AssignmentRulesMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Assignment Rules';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createTaskRows($data['tasks']);
$this->processes->addNewGroupRow($data['groupwfs']);
$this->processes->removeTaskUserRows($data['tasks']);
$this->processes->createTaskUserRows($data['taskusers']);
} else {
$this->processes->addNewTaskRows($data['tasks']);
$this->processes->addNewGroupRow($data['groupwfs']);
$this->processes->addNewTaskUserRows($data['taskusers']);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oAssignRules = new \StdClass();
$oAssignRules->tasks = $this->processes->getTaskRows($prj_uid);
$oAssignRules->taskusers = $this->processes->getTaskUserRows($oAssignRules->tasks);
//groups - task
$oDataTaskUsers = $this->processes->getTaskUserRows($oAssignRules->tasks);
$oAssignRules->groupwfs = $this->processes->getGroupwfRows($oDataTaskUsers);
$result = array(
'workflow-definition' => (array)$oAssignRules
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class DBConnectionMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* DBConnectionMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'DB Connection';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createDBConnectionsRows($data);
} else {
$this->processes->addNewDBConnectionsRows($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->dbconnections = $this->processes->getDBConnectionsRows($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class DynaformsMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* DynaformsMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Dynaforms';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createDynaformRows($data);
} else {
$this->processes->addNewDynaformRows($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->steps = $this->processes->getStepRowsByElement($prj_uid,'DYNAFORM');
$oData->dynaforms = $this->processes->getDynaformRows($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class ExportException extends \Exception
{
protected $nameException;
/**
* @return mixed
*/
public function getNameException()
{
return $this->nameException;
}
/**
* @param mixed $nameException
*/
public function setNameException($nameException)
{
$this->nameException = $nameException;
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class ExportObjects
{
/**
* @var array
*/
protected $objectsList = array(
'Process Definition',
'Assignment Rules',
'Variables',
'Dynaforms',
'Input Documents',
'Output Documents',
'Triggers',
'Report Tables',
'Templates',
'Files',
'DB Connection',
'Permissions',
'Supervisors',
'Supervisors Objects'
);
/**
* @return array
*/
public function getObjectsList()
{
return $this->objectsList;
}
/**
* @param array $objectsList
*/
public function setObjectsList($objectsList)
{
$this->objectsList = $objectsList;
}
/**
* @param string $objectsEnable
* @return mixed|string
* @throws \Exception
*/
public function objectList($objectsEnable = '')
{
$grid = [];
try {
$aObjectsEnable = explode('|', $objectsEnable);
foreach ($this->objectsList as $key => $val) {
$grid[] = array(
'OBJECT_ID' => $key+1,
'OBJECT_NAME' => $val,
'OBJECT_ACTION' => 1,
'OBJECT_ENABLE' => in_array(strtoupper(str_replace(' ', '',$val)), $aObjectsEnable)
);
}
$r = new \stdclass();
$r->data = $grid;
return \G::json_encode($r);
} catch (\Exception $e) {
throw $e;
}
}
/**
* @param $idObject
* @return mixed
* @throws \Exception
*/
public function getObjectName($idObject)
{
try {
return (str_replace(' ', '', $this->objectsList[$idObject - 1]));
} catch (\Exception $e) {
throw $e;
}
}
/**
* @param $objects
* @return array
* @throws \Exception
*/
public function mapObjectList($objects)
{
try {
$mapObjectList = array();
foreach ($objects as $objectId) {
array_push($mapObjectList, strtoupper(str_replace(' ', '', $this->objectsList[$objectId - 1])));
}
return $mapObjectList;
} catch (\Exception $e) {
throw $e;
}
}
/**
* @param $objects
* @return array
* @throws \Exception
*/
public function getIdObjectList($objects)
{
try {
$idObjectList = array();
foreach ($this->objectsList as $key => $val) {
$key++;
foreach ($objects as $row) {
if(strtoupper(str_replace(' ', '', $this->objectsList[$key - 1])) === $row){
array_push($idObjectList, $key);
}
}
}
return $idObjectList;
} catch (\Exception $e) {
throw $e;
}
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
// Declare the interface 'Exportable'
interface Exportable
{
public function beforeExport();
public function export($prj_uid);
public function afterExport();
}

View File

@@ -0,0 +1,73 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Util;
class FileHandler
{
/**
* @param $prj_uid
* @return array
*/
public function getFilesToExclude($prj_uid)
{
try {
$arrayPublicFileToExclude = array("wsClient.php");
$criteria = new \Criteria("workflow");
$criteria->addSelectColumn(\WebEntryPeer::WE_DATA);
$criteria->add(\WebEntryPeer::PRO_UID, $prj_uid, \Criteria::EQUAL);
$criteria->add(\WebEntryPeer::WE_METHOD, "WS", \Criteria::EQUAL);
$rsCriteria = \WebEntryPeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
while ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$arrayPublicFileToExclude[] = $row["WE_DATA"];
$arrayPublicFileToExclude[] = preg_replace("/^(.+)\.php$/", "$1Post.php", $row["WE_DATA"]);
}
return $arrayPublicFileToExclude;
} catch (\Exception $e) {
\Logger::log($e);
}
}
/**
* @param $prj_uid
* @param $arrayPublicFileToExclude
* @param $target
* @return array
*/
public function getTemplatesOrPublicFiles($prj_uid, $arrayPublicFileToExclude = array(), $target)
{
$workflowFile = array();
$workspaceTargetDir = ($target === 'PUBLIC') ? 'public' : 'mailTemplates';
$workspaceDir = PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP;
$templatesDir = $workspaceDir . $workspaceTargetDir . PATH_SEP . $prj_uid;
$templatesFiles = Util\Common::rglob("$templatesDir/*", 0, true);
foreach ($templatesFiles as $templatesFile) {
if (is_dir($templatesFile)) {
continue;
}
$filename = basename($templatesFile);
if ($target == "PUBLIC" && in_array($filename, $arrayPublicFileToExclude)) {
continue;
}
$workflowFile[$target][] = array(
"filename" => $filename,
"filepath" => $prj_uid . PATH_SEP . $filename,
"file_content" => file_get_contents($templatesFile)
);
}
return $workflowFile;
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Util;
use \ProcessMaker\BusinessModel\Migrator\FileHandler;
class FilesMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* FilesMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Public Files';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
$aTable = $data['TABLE'];
foreach ($aTable as $value) {
if ($value['PRF_EDITABLE'] === '0') {
if ($replace) {
$this->processes->createFilesManager($value['PRO_UID'], array($value));
} else {
$this->processes->addNewFilesManager($value['PRO_UID'], array($value));
}
}
}
$aPath = $data['PATH'];
foreach ($aPath as $target => $files) {
$basePath = PATH_DATA . 'sites' . PATH_SEP . SYS_SYS . PATH_SEP . 'public' . PATH_SEP;
if (strtoupper($target) === 'PUBLIC') {
foreach ($files as $file) {
$filename = $basePath . ((isset($file["file_path"])) ? $file["file_path"] : $file["filepath"]);
$path = dirname($filename);
if (!is_dir($path)) {
Util\Common::mk_dir($path, 0775);
}
if (file_exists($filename)) {
if ($replace) {
file_put_contents($filename, $file["file_content"]);
}
} else {
file_put_contents($filename, $file["file_content"]);
}
@chmod($filename, 0775);
}
}
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->filesManager = $this->processes->getFilesManager($prj_uid, 'public');
$fileHandler = new FileHandler();
$arrayPublicFileToExclude = $fileHandler->getFilesToExclude($prj_uid);
$workflowFile = $fileHandler->getTemplatesOrPublicFiles($prj_uid, $arrayPublicFileToExclude, 'PUBLIC');
$result = array(
'workflow-definition' => (array)$oData,
'workflow-files' => $workflowFile
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Project;
class GranularExporter
{
protected $factory;
protected $publisher;
protected $generator;
protected $data;
protected $prjuid;
/**
* GranularExporter constructor.
*/
public function __construct($prj_uid)
{
$this->prjuid = $prj_uid;
$this->factory = new MigratorFactory();
$this->generator = new PMXGenerator();
$this->publisher = new PMXPublisher();
}
/**
* @param $objectList
* @return array|string
* @throws \Exception
*/
public function export($objectList)
{
try {
$exportObject = new ExportObjects();
$objectList = $exportObject->mapObjectList($objectList);
$this->beforeExport($objectList);
foreach ($objectList as $data) {
$migrator = $this->factory->create($data);
$migratorData = $migrator->export($this->prjuid);
$this->mergeData($migratorData);
}
return $this->publish();
} catch (ExportException $e) {
return array(
'success' => false,
'message' => $e->getMessage()
);
}
}
protected function beforeExport()
{
$objectList = func_get_args()[0];
$bpmnProject = Project\Bpmn::load($this->prjuid);
$projectData = $bpmnProject->getProject();
$getProjectName = $this->publisher->truncateName($projectData['PRJ_NAME'], false);
$outputDir = PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP . "files" . PATH_SEP . "output" . PATH_SEP;
$version = \ProcessMaker\Util\Common::getLastVersion($outputDir . $getProjectName . "-*.pmx2") + 1;
$outputFilename = $outputDir . sprintf("%s-%s.%s", str_replace(" ", "_", $getProjectName), $version, "pmx2");
$bpnmDefinition = array(
'ACTIVITY' => [],
'ARTIFACT' => [],
'BOUND' => [],
'DATA' => [],
'DIAGRAM' => [],
'DOCUMENTATION' => [],
'EXTENSION' => [],
'FLOW' => [],
'GATEWAY' => [],
'LANE' => [],
'LANESET' => [],
'PARTICIPANT' => [],
'PROCESS' => [],
'PROJECT' => array(\BpmnProjectPeer::retrieveByPK($this->prjuid)->toArray())
);
$workflowDefinition = array(
'process' => array(\Processes::getProcessRow($this->prjuid, false)),
'tasks' => [],
'routes' => [],
'lanes' => [],
'gateways' => [],
'inputs' => [],
'outputs' => [],
'dynaforms' => [],
'steps' => [],
'triggers' => [],
'taskusers' => [],
'groupwfs' => [],
'steptriggers' => [],
'dbconnections' => [],
'reportTables' => [],
'reportTablesVars' => [],
'stepSupervisor' => [],
'objectPermissions' => [],
'subProcess' => [],
'caseTracker' => [],
'caseTrackerObject' => [],
'stage' => [],
'fieldCondition' => [],
'event' => [],
'caseScheduler' => [],
'processCategory' => [],
'taskExtraProperties' => [],
'processUser' => [],
'processVariables' => [],
'webEntry' => [],
'webEntryEvent' => [],
'messageType' => [],
'messageTypeVariable' => [],
'messageEventDefinition' => [],
'scriptTask' => [],
'timerEvent' => [],
'emailEvent' => []
);
$data = array(
'bpmn-definition' => $bpnmDefinition,
'workflow-definition' => $workflowDefinition,
'workflow-files' => []
);
$data["filename"] = $outputFilename;
$data["version"] = "3.1";
$data["container"] = "ProcessMaker-Project";
$data["metadata"] = array(
"vendor_version" => \System::getVersion(),
"vendor_version_code" => "Michelangelo",
"export_timestamp" => date("U"),
"export_datetime" => date("Y-m-d\TH:i:sP"),
"export_server_addr" => isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"].":".$_SERVER["SERVER_PORT"] : "Unknown",
"export_server_os" => PHP_OS ,
"export_server_php_version" => PHP_VERSION_ID,
);
$data["metadata"]["workspace"] = defined("SYS_SYS") ? SYS_SYS : "Unknown";
$data["metadata"]["name"] = $projectData['PRJ_NAME'];
$data["metadata"]["uid"] = $projectData['PRJ_UID'];
$data["metadata"]["export_version"] = $version;
$data["metadata"]["export_objects"] = implode('|', $objectList);
$this->data = $data;
}
/**
* @param $migratorData
*/
protected function mergeData($migratorData)
{
$migratorData = $this->verifyConsistenceData($migratorData);
$this->data = array_merge_recursive($this->data, $migratorData);
}
/**
* @param $migratorData
* @return mixed
*/
protected function verifyConsistenceData($migratorData)
{
//verifying data consistency group
if (isset($migratorData['workflow-definition']['groupwfs'])) {
foreach ($this->data['workflow-definition']['groupwfs'] as $rowGroup) {
foreach ($migratorData['workflow-definition']['groupwfs'] as $key => $row) {
if ($rowGroup['GRP_UID'] == $row['GRP_UID']) {
array_splice($migratorData['workflow-definition']['groupwfs'], $key);
}
}
}
}
return $migratorData;
}
public function publish()
{
return $this->publisher->publish(
$this->data['filename'],
$this->generator->generate(
$this->data
)
);
}
}

View File

@@ -0,0 +1,272 @@
<?php
/**
* Description of Granular Importer
*
*/
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Importer\XmlImporter;
use ProcessMaker\Project\Adapter;
class GranularImporter
{
protected $factory;
protected $data;
/**
* GranularImporter constructor.
*/
public function __construct()
{
$this->factory = new MigratorFactory();
$this->bpmn = new Adapter\BpmnWorkflow();
$this->exportObjects = new ExportObjects();
}
/**
* @param $data
* @param $aGranular
* @return array
* @throws \Exception
*/
public function loadObjectsListSelected($data, $aGranular)
{
$listObjectGranular = array();
$this->exportObjects = new ExportObjects();
//create structure
foreach ($aGranular as $key => $rowObject) {
array_push($listObjectGranular, array("name" => strtoupper($this->exportObjects->getObjectName
($rowObject->id)), "data" => "", "value" => $rowObject->action));
}
//add data
foreach ($listObjectGranular as $key => $rowObject) {
$listObjectGranular[$key]['data'] = $this->addObjectData($listObjectGranular[$key]['name'], $data);
}
return $listObjectGranular;
}
/**
* @param $nameObject
* @param $data
* @return array
*/
public function addObjectData($nameObject, $data)
{
$objectList = array();
switch ($nameObject) {
case 'PROCESSDEFINITION':
$objectList['PROCESSDEFINITION']['bpmn'] = isset($data['tables']['bpmn']) ? $this->structureBpmnData
($data['tables']['bpmn']) : '';
$objectList['PROCESSDEFINITION']['workflow'] = isset($data['tables']['workflow']) ?
$data['tables']['workflow'] : '';
break;
case 'ASSIGNMENTRULES':
$objectList['ASSIGNMENTRULES']['tasks'] = isset($data['tables']['workflow']['tasks']) ?
$data['tables']['workflow']['tasks'] : [];
$objectList['ASSIGNMENTRULES']['taskusers'] = isset($data['tables']['workflow']['taskusers']) ?
$data['tables']['workflow']['taskusers'] : [];
$objectList['ASSIGNMENTRULES']['groupwfs'] = isset($data['tables']['workflow']['groupwfs']) ?
$data['tables']['workflow']['groupwfs'] : [];
break;
case 'VARIABLES':
$objectList['VARIABLES'] = isset($data['tables']['workflow']['processVariables']) ?
$data['tables']['workflow']['processVariables'] : '';
break;
case 'DYNAFORMS':
$objectList['DYNAFORMS'] = isset($data['tables']['workflow']['dynaforms']) ?
$data['tables']['workflow']['dynaforms'] : '';
break;
case 'INPUTDOCUMENTS':
$objectList['INPUTDOCUMENTS'] = isset($data['tables']['workflow']['inputs']) ?
$data['tables']['workflow']['inputs'] : '';
break;
case 'OUTPUTDOCUMENTS':
$objectList['OUTPUTDOCUMENTS'] = isset($data['tables']['workflow']['outputs']) ?
$data['tables']['workflow']['outputs'] : '';
break;
case 'TRIGGERS':
$objectList['TRIGGERS'] = isset($data['tables']['workflow']['triggers']) ?
$data['tables']['workflow']['triggers'] : '';
break;
case 'TEMPLATES':
$objectList['TEMPLATES']['TABLE'] = isset($data['tables']['workflow']['filesManager']) ?
$data['tables']['workflow']['filesManager'] : '';
$objectList['TEMPLATES']['PATH'] = isset($data['files']['workflow']) ? $data['files']['workflow'] : '';
break;
case 'FILES':
$objectList['FILES']['TABLE'] = isset($data['tables']['workflow']['filesManager']) ?
$data['tables']['workflow']['filesManager'] : '';
$objectList['FILES']['PATH'] = isset($data['files']['workflow']) ? $data['files']['workflow'] : '';
break;
case 'DBCONNECTION':
case 'DBCONNECTIONS':
$objectList['DBCONNECTION'] = isset($data['tables']['workflow']['dbconnections']) ?
$data['tables']['workflow']['dbconnections'] : '';
break;
case 'PERMISSIONS':
$objectList['PERMISSIONS']['objectPermissions'] = isset($data['tables']['workflow']['objectPermissions']) ?
$data['tables']['workflow']['objectPermissions'] : '';
$objectList['PERMISSIONS']['groupwfs'] = isset($data['tables']['workflow']['groupwfs']) ?
$data['tables']['workflow']['groupwfs'] : '';
break;
case 'SUPERVISORS':
$objectList['SUPERVISORS']['processUser'] = isset($data['tables']['workflow']['processUser']) ?
$data['tables']['workflow']['processUser'] : '';
$objectList['SUPERVISORS']['groupwfs'] = isset($data['tables']['workflow']['groupwfs']) ?
$data['tables']['workflow']['groupwfs'] : '';
break;
case 'SUPERVISORSOBJECTS':
$objectList['SUPERVISORSOBJECTS'] = isset($data['tables']['workflow']['stepSupervisor']) ?
$data['tables']['workflow']['stepSupervisor'] : '';
break;
case 'REPORTTABLES':
$objectList['REPORTTABLES']['reportTablesDefinition'] = isset($data['tables']['workflow']['reportTablesDefinition']) ?
$data['tables']['workflow']['reportTablesDefinition'] : [];
$objectList['REPORTTABLES']['reportTablesFields'] = isset($data['tables']['workflow']['reportTablesFields']) ?
$data['tables']['workflow']['reportTablesFields'] : [];
break;
default:
break;
}
return $objectList;
}
/**
* Update the structure from File
*/
public function structureBpmnData(array $tables)
{
$project = $tables["project"][0];
$diagram = $tables["diagram"][0];
$diagram["activities"] = (isset($tables["activity"])) ? $tables["activity"] : array();
$diagram["artifacts"] = (isset($tables["artifact"])) ? $tables["artifact"] : array();
$diagram["events"] = (isset($tables["event"])) ? $tables["event"] : array();
$diagram["flows"] = (isset($tables["flow"])) ? $tables["flow"] : array();
$diagram["gateways"] = (isset($tables["gateway"])) ? $tables["gateway"] : array();
$diagram["data"] = (isset($tables["data"])) ? $tables["data"] : array();
$diagram["participants"] = (isset($tables["participant"])) ? $tables["participant"] : array();
$diagram["laneset"] = (isset($tables["laneset"])) ? $tables["laneset"] : array();
$diagram["lanes"] = (isset($tables["lane"])) ? $tables["lane"] : array();
$project["diagrams"] = array($diagram);
$project["prj_author"] = isset($this->data["usr_uid"]) ? $this->data["usr_uid"] : "00000000000000000000000000000001";
$project["process"] = $tables["process"][0];
return $project;
}
/**
* @param $objectList
* @throws \Exception
*/
public function import($objectList)
{
try {
$objectList = $this->reorderImportOrder($objectList);
foreach ($objectList as $data) {
$objClass = $this->factory->create($data['name']);
if (is_object($objClass)) {
$dataImport = $data['data'][$data['name']];
$replace = ($data['value'] == 'replace') ? true : false;
$migratorData = $objClass->import($dataImport, $replace);
}
}
} catch (\Exception $e) {
$exception = new ImportException('Please review your current process definition
for missing elements, it\'s recommended that a new process should be exported
with all the elements.');
throw $exception;
}
}
/**
* @param $objectList
* @param bool $generateUid
* @return bool
* @throws \Exception
*/
public function validateImportData($objectList, $option)
{
try {
if (XmlImporter::IMPORT_OPTION_OVERWRITE !== $option) {
if (count($objectList) !== count($this->exportObjects->getObjectsList())) {
$exception = new ImportException();
$exception->setNameException(\G::LoadTranslation('ID_PROCESS_DEFINITION_INCOMPLETE'));
throw($exception);
}
}
return true;
} catch (\Exception $e) {
throw $e;
}
}
/**
* It's very important to import the elements in the right order, if not
* chaos will be unleashed, God forgive us all.
* @param $objectList
*/
public function reorderImportOrder($objectList)
{
$arrangeList = array(
0 => 12,
1 => 13,
2 => 0,
3 => 1,
4 => 2,
5 => 3,
6 => 4,
7 => 5,
8 => 6,
9 => 7,
10 => 8,
11 => 9,
12 => 10,
13 => 11
);
$orderedList = array();
foreach ($arrangeList as $objectOrder => $executionOrder) {
if (!empty($objectList[$objectOrder])) {
$orderedList[$executionOrder] = $objectList[$objectOrder];
}
}
ksort($orderedList);
return $orderedList;
}
/**
* @param $objectList
* @param array $data
* @return data
* @throws \Exception
*/
public function regenerateAllUids($data, $generateUid = true)
{
try {
$newData = array();
$arrayBpmnTables = $data["tables"]["bpmn"];
$arrayWorkflowTables = $data["tables"]["workflow"];
$arrayWorkflowFiles = $data["files"]["workflow"];
$result = $this->bpmn->createFromStruct($this->structureBpmnData($arrayBpmnTables), $generateUid);
$projectUidOld = $arrayBpmnTables["project"][0]["prj_uid"];
$projectUid = ($generateUid)? $result[0]["new_uid"] : $result;
if ($generateUid) {
$result[0]["object"] = "project";
$result[0]["old_uid"] = $projectUidOld;
$result[0]["new_uid"] = $projectUid;
$workflow = new \ProcessMaker\Project\Workflow();
list($arrayWorkflowTables, $arrayWorkflowFiles) = $workflow->updateDataUidByArrayUid($arrayWorkflowTables, $arrayWorkflowFiles, $result);
}
$newData['tables']['workflow'] = $arrayWorkflowTables;
$newData['files']['workflow'] = $arrayWorkflowFiles;
return array(
'data' => $newData,
'new_uid' => $projectUid);
} catch (\Exception $e) {
throw $e;
}
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class ImportException extends \Exception
{
protected $nameException;
/**
* @return mixed
*/
public function getNameException()
{
return $this->nameException;
}
/**
* @param mixed $nameException
*/
public function setNameException($nameException)
{
$this->nameException = $nameException;
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
// Declare the interface 'Importable'
interface Importable
{
public function beforeImport($data);
public function import($data, $replace);
public function afterImport($data);
}

View File

@@ -0,0 +1,84 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class InputDocumentsMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* InputDocumentsMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'InputDocument';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createInputRows($data);
} else {
$this->processes->addNewInputRows($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->steps = $this->processes->getStepRowsByElement($prj_uid,'INPUT_DOCUMENT');
$oData->inputs = $this->processes->getInputRows($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class MigratorFactory
{
public function create($classname)
{
$class = new NullMigrator();
switch (strtoupper($classname)) {
case 'ASSIGNMENTRULES':
$class = new AssignmentRulesMigrator();
break;
case 'FILES':
$class = new FilesMigrator();
break;
case 'DBCONNECTION':
case 'DBCONNECTIONS':
$class = new DBConnectionMigrator();
break;
case 'DYNAFORMS':
$class = new DynaformsMigrator();
break;
case 'INPUTDOCUMENTS':
$class = new InputDocumentsMigrator();
break;
case 'OUTPUTDOCUMENTS':
$class = new OutputDocumentsMigrator();
break;
case 'PROCESSDEFINITION':
$class = new ProcessDefinitionMigrator();
break;
case 'REPORTTABLES':
$class = new ReportTablesMigrator();
break;
case 'SUPERVISORS':
$class = new SupervisorsMigrator();
break;
case 'SUPERVISORSOBJECTS':
$class = new SupervisorsObjectsMigrator();
break;
case 'TEMPLATES':
$class = new TemplatesMigrator();
break;
case 'TRIGGERS':
$class = new TriggersMigrator();
break;
case 'VARIABLES':
$class = new VariablesMigrator();
break;
case 'PERMISSIONS':
$class = new PermissionsMigrator();
break;
}
return $class;
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class NullMigrator implements Importable, Exportable
{
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
public function export($prj_uid)
{
// TODO: Implement export() method.
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
public function import($data, $replace)
{
// TODO: Implement import() method.
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class OutputDocumentsMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* OutputDocumentsMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'OutputDocument';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createOutputRows($data);
} else {
$this->processes->addNewOutputRows($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->steps = $this->processes->getStepRowsByElement($prj_uid,'OUTPUT_DOCUMENT');
$oData->outputs = $this->processes->getOutputRows($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
/**
* Class PMXGenerator
* This class generates the a PMX class based on the data passed on the generate method.
*
* @package ProcessMaker\BusinessModel\Migrator
*/
class PMXGenerator
{
/**
* @var \DOMElement
*/
protected $rootNode;
/**
* @var \DOMDocument
*/
protected $domDocument;
/**
* PMXPublisher constructor.
* @param $domDocument
*/
public function __construct()
{
$this->domDocument = new \DOMDocument("1.0", "utf-8");
$this->domDocument->formatOutput = true;
}
/**
* Generates a PMX xml string based on the $data passed along.
*
* @param $data
* @return string
*/
public function generate($data)
{
$rootNode = $this->domDocument->createElement($data['container']);
$rootNode->setAttribute("version", $data['version']);
$this->domDocument->appendChild($rootNode);
$metadata = $data["metadata"];
$metadataNode = $this->domDocument->createElement("metadata");
foreach ($metadata as $key => $value) {
$metaNode = $this->domDocument->createElement("meta");
$metaNode->setAttribute("key", $key);
$metaNode->appendChild($this->getTextNode($value));
$metadataNode->appendChild($metaNode);
}
$rootNode->appendChild($metadataNode);
$dbData = array("BPMN" => $data["bpmn-definition"], "workflow" => $data["workflow-definition"]);
foreach ($dbData as $sectionName => $sectionData) {
$dataNode = $this->domDocument->createElement("definition");
$dataNode->setAttribute("class", $sectionName);
foreach ($sectionData as $elementName => $elementData) {
$elementNode = $this->domDocument->createElement("table");
$elementNode->setAttribute("name", $elementName);
foreach ($elementData as $recordData) {
$recordNode = $this->domDocument->createElement("record");
if(is_array($recordData)){
$recordData = array_change_key_case($recordData, CASE_LOWER);
foreach ($recordData as $key => $value) {
if (is_object($value) || is_array($value)) {
$value = serialize($value);
}
$columnNode = $this->domDocument->createElement($key);
$columnNode->appendChild($this->getTextNode($value));
$recordNode->appendChild($columnNode);
}
$elementNode->appendChild($recordNode);
}
}
$dataNode->appendChild($elementNode);
}
$rootNode->appendChild($dataNode);
}
$workflowFilesNode = $this->domDocument->createElement("workflow-files");
foreach ($data["workflow-files"] as $elementName => $elementData) {
foreach ($elementData as $fileData) {
$fileNode = $this->domDocument->createElement("file");
$fileNode->setAttribute("target", strtolower($elementName));
$filenameNode = $this->domDocument->createElement("file_name");
$filenameNode->appendChild($this->getTextNode($fileData["filename"]));
$fileNode->appendChild($filenameNode);
$filepathNode = $this->domDocument->createElement("file_path");
$filepathNode->appendChild($this->domDocument->createCDATASection($fileData["filepath"]));
$fileNode->appendChild($filepathNode);
$fileContentNode = $this->domDocument->createElement("file_content");
$fileContentNode->appendChild($this->domDocument->createCDATASection(base64_encode($fileData["file_content"])));
$fileNode->appendChild($fileContentNode);
$workflowFilesNode->appendChild($fileNode);
}
}
$rootNode->appendChild($workflowFilesNode);
return $this->domDocument->saveXML($rootNode);
}
/**
* @param $value
* @return mixed
*/
private function getTextNode($value)
{
if (empty($value) || preg_match('/^[\w\s\.\-]+$/', $value, $match)) {
return $this->domDocument->createTextNode($value);
} else {
return $this->domDocument->createCDATASection($value);
}
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Util;
class PMXPublisher
{
public function publish($filename, $data)
{
$parentDir = dirname($filename);
if (! is_dir($parentDir)) {
Util\Common::mk_dir($parentDir, 0775);
}
$outputFile = $this->truncateName($filename);
file_put_contents($outputFile, $data);
@chmod($outputFile, 0755);
return basename($outputFile);
}
public function truncateName($outputFile, $dirName = true)
{
$limit = 200;
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$limit = 150;
}
if ($dirName) {
if (strlen(basename($outputFile)) >= $limit) {
$lastPos = strrpos(basename($outputFile), '.');
$fileName = substr(basename($outputFile), 0, $lastPos);
$newFileName = str_replace(".", "_", $fileName);
$newFileName = str_replace(" ", "_", $fileName);
$excess = strlen($newFileName) - $limit;
$newFileName = substr($newFileName, 0, strlen($newFileName) - $excess);
$newOutputFile = str_replace($fileName, $newFileName, $outputFile);
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$newOutputFile = str_replace("/", DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, $newOutputFile);
}
$outputFile = $newOutputFile;
}
} else {
$outputFile = str_replace(".", "_", $outputFile);
$outputFile = str_replace(" ", "_", $outputFile);
if (strlen($outputFile) >= $limit) {
$excess = strlen($outputFile) - $limit;
$newFileName = substr($outputFile, 0, strlen($outputFile) - $excess);
$outputFile = $newFileName;
}
}
return $outputFile;
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class PermissionsMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* PermissionsMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Permissions';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createObjectPermissionsRows($data['objectPermissions']);
$this->processes->addNewGroupRow($data['groupwfs']);
} else {
$this->processes->addNewObjectPermissionRows($data['objectPermissions']);
$this->processes->addNewGroupRow($data['groupwfs']);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$processData = new \StdClass();
$processData->process = $this->processes->getProcessRow($prj_uid, false);
$processData->tasks = $this->processes->getTaskRows($prj_uid);
$processData->routes = $this->processes->getRouteRows($prj_uid);
$processData->lanes = $this->processes->getLaneRows($prj_uid);
$processData->gateways = $this->processes->getGatewayRows($prj_uid);
$processData->steps = $this->processes->getStepRows($prj_uid);
$processData->taskusers = $this->processes->getTaskUserRows($processData->tasks);
$processData->groupwfs = $this->processes->getGroupwfRows($processData->taskusers);
$processData->steptriggers = $this->processes->getStepTriggerRows($processData->tasks);
$processData->reportTablesVars = $this->processes->getReportTablesVarsRows($prj_uid);
$oData = new \StdClass();
$oData->objectPermissions = $this->processes->getObjectPermissionRows($prj_uid, $processData);
//groups - permissions
$oData->groupwfs = $this->processes->getGroupwfRows($oData->objectPermissions);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,167 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Project\Adapter;
use Symfony\Component\Config\Definition\Exception\Exception;
class ProcessDefinitionMigrator implements Importable, Exportable
{
protected $bpmn;
protected $processes;
protected $className;
/**
* ProcessDefinitionMigrator constructor.
*/
public function __construct()
{
$this->bpmn = new Adapter\BpmnWorkflow();
$this->processes = new \Processes();
$this->className = 'ProcessDefinition';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
//Bpmn elements
$pjrUid = $this->bpmn->createFromStruct($data['bpmn'], false);
//Import workflow elements
$this->afterImport($data);
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
/**
* @param $data
* @throws ImportException
*/
public function afterImport($data)
{
try {
//Workflow elements
$this->processes->updateProcessRow($data['workflow']['process']);
$this->processes->createTaskRows($data['workflow']['tasks']);
$this->processes->createTaskUserRows($data['workflow']['taskusers']);
$this->processes->createRouteRows($data['workflow']['routes']);
$this->processes->createLaneRows($data['workflow']['lanes']);
$this->processes->createGatewayRows($data['workflow']['gateways']);
$this->processes->createStepRows($data['workflow']['steps']);
$this->processes->createStepTriggerRows($data['workflow']['steptriggers']);
$this->processes->createSubProcessRows($data['workflow']['subProcess']);
$this->processes->createCaseTrackerRows($data['workflow']['caseTracker']);
$this->processes->createCaseTrackerObjectRows($data['workflow']['caseTrackerObject']);
$this->processes->createStageRows($data['workflow']['stage']);
$this->processes->createFieldCondition($data['workflow']['fieldCondition'], $data['workflow']['dynaforms']);
$this->processes->createEventRows($data['workflow']['event']);
$this->processes->createCaseSchedulerRows($data['workflow']['caseScheduler']);
$this->processes->createProcessCategoryRow($data['workflow']['processCategory']);
$this->processes->createTaskExtraPropertiesRows($data['workflow']['taskExtraProperties']);
$this->processes->createWebEntry($data['workflow']['process']['PRO_UID'], $data['workflow']['process']['PRO_CREATE_USER'], $data['workflow']['webEntry']);
$this->processes->createWebEntryEvent($data['workflow']['process']['PRO_UID'], $data['workflow']['process']['PRO_CREATE_USER'], $data['workflow']['webEntryEvent']);
$this->processes->createMessageType($data['workflow']['messageType']);
$this->processes->createMessageTypeVariable($data['workflow']['messageTypeVariable']);
$this->processes->createMessageEventDefinition($data['workflow']['process']['PRO_UID'], $data['workflow']['messageEventDefinition']);
$this->processes->createScriptTask($data['workflow']['process']['PRO_UID'], $data['workflow']['scriptTask']);
$this->processes->createTimerEvent($data['workflow']['process']['PRO_UID'], $data['workflow']['timerEvent']);
$this->processes->createEmailEvent($data['workflow']['process']['PRO_UID'], $data['workflow']['emailEvent']);
$this->processes->createActionsByEmail($data['workflow']['process']['PRO_UID'], $data['workflow']['abeConfiguration']);
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$bpmnStruct["ACTIVITY"] = \BpmnActivity::getAll($prj_uid);
$bpmnStruct["ARTIFACT"] = \BpmnArtifact::getAll($prj_uid);
$bpmnStruct["BOUND"] = \BpmnBound::getAll($prj_uid);
$bpmnStruct["DATA"] = \BpmnData::getAll($prj_uid);
$bpmnStruct["DIAGRAM"] = \BpmnDiagram::getAll($prj_uid);
$bpmnStruct["DOCUMENTATION"] = array();
$bpmnStruct["EVENT"] = \BpmnEvent::getAll($prj_uid);
$bpmnStruct["EXTENSION"] = array();
$bpmnStruct["FLOW"] = \BpmnFlow::getAll($prj_uid, null, null, "", CASE_UPPER, false);
$bpmnStruct["GATEWAY"] = \BpmnGateway::getAll($prj_uid);
$bpmnStruct["LANE"] = \BpmnLane::getAll($prj_uid);
$bpmnStruct["LANESET"] = \BpmnLaneset::getAll($prj_uid);
$bpmnStruct["PARTICIPANT"] = \BpmnParticipant::getAll($prj_uid);
$bpmnStruct["PROCESS"] = \BpmnProcess::getAll($prj_uid);
$oData = new \StdClass();
$oData->tasks = $this->processes->getTaskRows($prj_uid);
$oData->taskusers = $this->processes->getTaskUserRows($oData->tasks);
$oData->routes = $this->processes->getRouteRows($prj_uid);
$oData->lanes = $this->processes->getLaneRows($prj_uid);
$oData->gateways = $this->processes->getGatewayRows($prj_uid);
$oData->subProcess = $this->processes->getSubProcessRow($prj_uid);
$oData->caseTracker = $this->processes->getCaseTrackerRow($prj_uid);
$oData->caseTrackerObject = $this->processes->getCaseTrackerObjectRow($prj_uid);
$oData->stage = $this->processes->getStageRow($prj_uid);
$oData->fieldCondition = $this->processes->getFieldCondition($prj_uid);
$oData->event = $this->processes->getEventRow($prj_uid);
$oData->caseScheduler = $this->processes->getCaseSchedulerRow($prj_uid);
$oData->processCategory = $this->processes->getProcessCategoryRow($prj_uid);
$oData->taskExtraProperties = $this->processes->getTaskExtraPropertiesRows($prj_uid);
$oData->webEntry = $this->processes->getWebEntries($prj_uid);
$oData->webEntryEvent = $this->processes->getWebEntryEvents($prj_uid);
$oData->messageType = $this->processes->getMessageTypes($prj_uid);
$oData->messageTypeVariable = $this->processes->getMessageTypeVariables($prj_uid);
$oData->messageEventDefinition = $this->processes->getMessageEventDefinitions($prj_uid);
$oData->steps = $this->processes->getStepRows($prj_uid);
$oData->steptriggers = $this->processes->getStepTriggerRows($oData->tasks);
$oData->scriptTask = $this->processes->getScriptTasks($prj_uid);
$oData->timerEvent = $this->processes->getTimerEvents($prj_uid);
$oData->emailEvent = $this->processes->getEmailEvent($prj_uid);
$oData->abeConfiguration = $this->processes->getActionsByEmail($prj_uid);
$oData->processUser = $this->processes->getProcessUser($prj_uid);
$oData->process["PRO_TYPE_PROCESS"] = "PUBLIC";
$result = array(
'bpmn-definition' => (array)$bpmnStruct,
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class ReportTablesMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* ReportTablesMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'ReportTables';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
$reportTable = new \ProcessMaker\BusinessModel\ReportTable();
$arrayTableSchema = [];
$arrayTablesToExclude = [];
$processUid = '';
foreach ($data['reportTablesDefinition'] as $value) {
$arrayTable = $value;
$processUid = $arrayTable['PRO_UID'];
$arrayField = [];
foreach ($data['reportTablesFields'] as $value2) {
if ($value2['ADD_TAB_UID'] == $arrayTable['ADD_TAB_UID']) {
unset($value2['ADD_TAB_UID']);
$arrayField[] = $value2;
}
}
if (!empty($arrayField)) {
$arrayTable['FIELDS'] = $arrayField;
$arrayTableSchema[] = $arrayTable;
//$replace: true //Delete all tables and create it again
//$replace: false //Only create the tables that do not exist
if (!$replace) {
$additionalTable = new \AdditionalTables();
if ($additionalTable->loadByName($arrayTable['ADD_TAB_NAME']) !== false) {
$arrayTablesToExclude[] = $arrayTable['ADD_TAB_NAME'];
}
}
}
}
if (!empty($arrayTableSchema)) {
$errors = $reportTable->createStructureOfTables(
$arrayTableSchema, [], $processUid, false, true, $arrayTablesToExclude
);
if ($errors != '') {
throw new \Exception($errors);
}
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->reportTablesDefinition = $this->processes->getReportTables($prj_uid);
$oData->reportTablesFields = $this->processes->getReportTablesVar($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class SupervisorsMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* SupervisorsMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Supervisor';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createProcessUser($data['processUser']);
$this->processes->addNewGroupRow($data['groupwfs']);
} else {
$this->processes->addNewProcessUser($data['processUser']);
$this->processes->addNewGroupRow($data['groupwfs']);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->processUser = $this->processes->getProcessUser($prj_uid);
//groups - supervisor
$oData->groupwfs = $this->processes->getGroupwfRows($oData->processUser);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
class SupervisorsObjectsMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* SupervisorsObjectsMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Supervisor Object';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createStepSupervisorRows($data);
} else {
$this->processes->updateStepSupervisorRows($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->stepSupervisor = $this->processes->getStepSupervisorRows($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\Util;
class TemplatesMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* TemplatesMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Templates';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
$aTable = $data['TABLE'];
foreach ($aTable as $value) {
if ($value['PRF_EDITABLE'] === '1') {
if ($replace) {
$this->processes->createFilesManager($value['PRO_UID'], array($value));
} else {
$this->processes->addNewFilesManager($value['PRO_UID'], array($value));
}
}
}
$aPath = $data['PATH'];
foreach ($aPath as $target => $files) {
$basePath = PATH_DATA . 'sites' . PATH_SEP . SYS_SYS . PATH_SEP . 'mailTemplates' . PATH_SEP;
if (strtoupper($target) === 'TEMPLATE') {
foreach ($files as $file) {
$filename = $basePath . ((isset($file["file_path"])) ? $file["file_path"] : $file["filepath"]);
$path = dirname($filename);
if (!is_dir($path)) {
Util\Common::mk_dir($path, 0775);
}
if (file_exists($filename)) {
if ($replace) {
file_put_contents($filename, $file["file_content"]);
}
} else {
file_put_contents($filename, $file["file_content"]);
}
@chmod($filename, 0775);
}
}
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$arrayExcludeFile = array();
$oData->filesManager = $this->processes->getFilesManager($prj_uid, 'template');
$fileHandler = new FileHandler();
$workflowFile = $fileHandler->getTemplatesOrPublicFiles($prj_uid, $arrayExcludeFile, 'template');
$result = array(
'workflow-definition' => (array)$oData,
'workflow-files' => $workflowFile
);
return $result;
} catch (\Exception $e) {
throw new ExportException($e->getMessage());
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
use Symfony\Component\Config\Definition\Exception\Exception;
class TriggersMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* TriggersMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Triggers';
}
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createTriggerRows($data);
} else {
$this->processes->addNewTriggerRows($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$tasks = $this->processes->getTaskRows($prj_uid);
$oData->steptriggers = $this->processes->getStepTriggerRows($tasks);
$oData->triggers = $this->processes->getTriggerRows($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace ProcessMaker\BusinessModel\Migrator;
/**
* Class VariablesMigrator
* @package ProcessMaker\BusinessModel\Migrator
*/
class VariablesMigrator implements Importable, Exportable
{
protected $processes;
protected $className;
/**
* VariablesMigrator constructor.
*/
public function __construct()
{
$this->processes = new \Processes();
$this->className = 'Variables';
}
/**
* beforeImport hook
* @param $data
*/
public function beforeImport($data)
{
// TODO: Implement beforeImport() method.
}
/**
* @param $data
* @param $replace
* @throws ImportException
*/
public function import($data, $replace)
{
try {
if ($replace) {
$this->processes->createProcessVariables($data);
} else {
$this->processes->updateProcessVariables($data);
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
/**
* Hook to launch after the import process has just finished
* @param $data
*/
public function afterImport($data)
{
// TODO: Implement afterImport() method.
}
public function beforeExport()
{
// TODO: Implement beforeExport() method.
}
/**
* @param $prj_uid
* @return array
* @throws ExportException
*/
public function export($prj_uid)
{
try {
$oData = new \StdClass();
$oData->processVariables = $this->processes->getProcessVariables($prj_uid);
$result = array(
'workflow-definition' => (array)$oData
);
return $result;
} catch (\Exception $e) {
$exception = new ExportException($e->getMessage());
$exception->setNameException($this->className);
throw($exception);
}
}
public function afterExport()
{
// TODO: Implement afterExport() method.
}
}

View File

@@ -538,20 +538,42 @@ class Process
$trigger = new \ProcessMaker\BusinessModel\Trigger();
/**
* Try catch block is added to escape the exception and continue editing
* the properties of the process, otherwise there is no way to edit
* the properties that the exception is thrown: trigger nonexistent.
* The same goes for the similar blocks.
*/
if (isset($arrayData["PRO_TRI_DELETED"]) && $arrayData["PRO_TRI_DELETED"] . "" != "") {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_DELETED"], $processUid, $this->arrayFieldNameForException["processTriDeleted"]);
try {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_DELETED"], $processUid, $this->arrayFieldNameForException["processTriDeleted"]);
} catch (\Exception $e) {
}
}
if (isset($arrayData["PRO_TRI_CANCELED"]) && $arrayData["PRO_TRI_CANCELED"] . "" != "") {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_CANCELED"], $processUid, $this->arrayFieldNameForException["processTriCanceled"]);
try {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_CANCELED"], $processUid, $this->arrayFieldNameForException["processTriCanceled"]);
} catch (\Exception $e) {
}
}
if (isset($arrayData["PRO_TRI_PAUSED"]) && $arrayData["PRO_TRI_PAUSED"] . "" != "") {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_PAUSED"], $processUid, $this->arrayFieldNameForException["processTriPaused"]);
try {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_PAUSED"], $processUid, $this->arrayFieldNameForException["processTriPaused"]);
} catch (\Exception $e) {
}
}
if (isset($arrayData["PRO_TRI_REASSIGNED"]) && $arrayData["PRO_TRI_REASSIGNED"] . "" != "") {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_REASSIGNED"], $processUid, $this->arrayFieldNameForException["processTriReassigned"]);
try {
$trigger->throwExceptionIfNotExistsTrigger($arrayData["PRO_TRI_REASSIGNED"], $processUid, $this->arrayFieldNameForException["processTriReassigned"]);
} catch (\Exception $e) {
}
}
if (isset($arrayData["PRO_PARENT"])) {

View File

@@ -0,0 +1,706 @@
<?php
namespace ProcessMaker\BusinessModel;
class ReportTable
{
/**
* Get report table default columns
*
* @param string $type
*
* @return object
*/
private function __getDefaultColumns($type = 'NORMAL')
{
$defaultColumns = [];
$application = new \stdClass(); //APPLICATION KEY
$application->uid = '';
$application->field_dyn = '';
$application->field_uid = '';
$application->field_name = 'APP_UID';
$application->field_label = 'APP_UID';
$application->field_type = 'VARCHAR';
$application->field_size = 32;
$application->field_dyn = '';
$application->field_key = 1;
$application->field_index = 1;
$application->field_null = 0;
$application->field_filter = false;
$application->field_autoincrement = false;
array_push($defaultColumns, $application);
$application = new \stdClass(); //APP_NUMBER
$application->uid = '';
$application->field_dyn = '';
$application->field_uid = '';
$application->field_name = 'APP_NUMBER';
$application->field_label = 'APP_NUMBER';
$application->field_type = 'INTEGER';
$application->field_size = 11;
$application->field_dyn = '';
$application->field_key = 0;
$application->field_null = 0;
$application->field_filter = false;
$application->field_autoincrement = false;
array_push($defaultColumns, $application);
$application = new \stdClass(); //APP_STATUS
$application->uid = '';
$application->field_dyn = '';
$application->field_uid = '';
$application->field_name = 'APP_STATUS';
$application->field_label = 'APP_STATUS';
$application->field_type = 'VARCHAR';
$application->field_size = 10;
$application->field_dyn = '';
$application->field_key = 0;
$application->field_null = 0;
$application->field_filter = false;
$application->field_autoincrement = false;
array_push($defaultColumns, $application);
//If it is a grid report table
if ($type == 'GRID') {
//GRID INDEX
$gridIndex = new \stdClass();
$gridIndex->uid = '';
$gridIndex->field_dyn = '';
$gridIndex->field_uid = '';
$gridIndex->field_name = 'ROW';
$gridIndex->field_label = 'ROW';
$gridIndex->field_type = 'INTEGER';
$gridIndex->field_size = '11';
$gridIndex->field_dyn = '';
$gridIndex->field_key = 1;
$gridIndex->field_null = 0;
$gridIndex->field_filter = false;
$gridIndex->field_autoincrement = false;
array_push($defaultColumns, $gridIndex);
}
return $defaultColumns;
}
/**
* Populate the data
*
* @param array $arrayTableData
* @param array $tableNameMap
*
* @return string
*/
private function __populateData(array $arrayTableData, array $tableNameMap)
{
try {
$errors = '';
foreach ($arrayTableData as $key => $value) {
$tableName = $key;
$contentData = $value;
if (isset($tableNameMap[$tableName])) {
$tableName = $tableNameMap[$tableName];
$additionalTable = new \AdditionalTables();
$arrayAdditionalTableData = $additionalTable->loadByName($tableName);
if ($arrayAdditionalTableData !== false) {
$flagIsPmTable = $arrayAdditionalTableData['PRO_UID'] == '';
if ($flagIsPmTable && !empty($contentData)) {
$additionalTable->load($arrayAdditionalTableData['ADD_TAB_UID'], true);
$primaryKeys = $additionalTable->getPrimaryKeys();
//Obtain a list of columns
$primaryKeyColumn = [];
foreach ($contentData as $key => $row) {
$primaryKeyColumn[$key] = $row[$primaryKeys[0]['FLD_NAME']];
}
array_multisort($primaryKeyColumn, SORT_ASC, $contentData);
foreach ($contentData as $row) {
$arrayResult = $this->createRecord(
[
'id' => $arrayAdditionalTableData['ADD_TAB_UID'],
'rows' => base64_encode(serialize($row)),
],
'base64'
);
if (!$arrayResult['success']) {
$errors .= $arrayResult['message'];
}
}
}
}
}
}
//Return
return $errors;
} catch (\Exception $e) {
throw $e;
}
}
/**
* Create record
*
* @param array $arrayData
* @param string $codification
*
* @return array
*/
public function createRecord(array $arrayData, $codification = 'json')
{
try {
$additionalTable = new \AdditionalTables();
$arrayAdditionalTableData = $additionalTable->load($arrayData['id'], true);
$additionalTableClassName = $arrayAdditionalTableData['ADD_TAB_CLASS_NAME'];
$additionalTableClassPeerName = $additionalTableClassName . 'Peer';
$row = ($codification == 'base64')?
unserialize(base64_decode($arrayData['rows'])) : \G::json_decode($arrayData['rows']);
$row = (array)($row);
$row = array_merge(array_change_key_case($row, CASE_LOWER), array_change_key_case($row, CASE_UPPER));
$flagSave = false;
if (!file_exists(PATH_WORKSPACE . 'classes' . PATH_SEP . $additionalTableClassName . '.php')) {
throw new Exception(\G::LoadTranslation('ID_PMTABLE_CLASS_DOESNT_EXIST', [$additionalTableClassName]));
}
require_once(PATH_WORKSPACE . 'classes' . PATH_SEP . $additionalTableClassName . '.php');
if (!empty($row)) {
eval('$con = \\Propel::getConnection(' . $additionalTableClassPeerName . '::DATABASE_NAME);');
eval('$obj = new \\' . $additionalTableClassName . '();');
$obj->fromArray($row, \BasePeer::TYPE_FIELDNAME);
if ($obj->validate()) {
$obj->save();
$primaryKeysValues = [];
foreach ($additionalTable->getPrimaryKeys() as $primaryKey) {
$method = 'get' . \AdditionalTables::getPHPName($primaryKey['FLD_NAME']);
$primaryKeysValues[] = $obj->$method();
}
$index = \G::encrypt(implode(',', $primaryKeysValues), 'pmtable');
\G::auditLog(
'AddDataPmtable',
'Table Name: ' . $arrayAdditionalTableData['ADD_TAB_NAME'] .
' Table ID: (' . $arrayAdditionalTableData['ADD_TAB_UID'] . ')'
);
$flagSave = true;
} else {
$msg = '';
foreach ($obj->getValidationFailures() as $objValidationFailure) {
$msg .= $objValidationFailure->getMessage() . "\n";
}
throw new Exception(
\G::LoadTranslation('ID_ERROR_TRYING_INSERT') .
'"' . $arrayAdditionalTableData['ADD_TAB_NAME'] . "\"\n" . $msg
);
}
} else {
$flagSave = false;
}
//Return
return [
'success' => $flagSave,
'message' => ($flagSave)? \G::LoadTranslation('ID_RECORD_SAVED_SUCCESFULLY') : '',
'rows' => ($flagSave)? $obj->toArray(\BasePeer::TYPE_FIELDNAME) : [],
'index' => ($flagSave)? $index : '',
];
} catch (\Exception $e) {
throw $e;
}
}
/**
* Review the table schema and throw all errors
*
* @param array $arrayTableSchema
* @param string $processUid
* @param bool $flagFromAdmin
* @param bool $flagOverwrite
* @param string $postProUid
*
* @return array
*/
public function checkPmtFileThrowErrors(
array $arrayTableSchema,
$processUid,
$flagFromAdmin,
$flagOverwrite,
$postProUid
) {
try {
$arrayError = [];
//Ask for all Process
$processMap = new \processMap();
$arrayProcessUid = [];
foreach (\G::json_decode($processMap->getAllProcesses()) as $value) {
if ($value->value != '') {
$arrayProcessUid[] = $value->value;
}
}
$i = 0;
foreach ($arrayTableSchema as $value) {
$contentSchema = $value;
//The table exists?
$additionalTable = new \AdditionalTables();
$arrayAdditionalTableData = $additionalTable->loadByName($contentSchema['ADD_TAB_NAME']);
$tableProUid = (isset($contentSchema['PRO_UID']))? $contentSchema['PRO_UID'] : $postProUid;
$flagIsPmTable = ($contentSchema['PRO_UID'] == '')? true : false;
if ($flagFromAdmin) {
if ($flagIsPmTable) {
if ($arrayAdditionalTableData !== false && !$flagOverwrite) {
$arrayError[$i]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME'];
$arrayError[$i]['ERROR_TYPE'] = 1; //ERROR_PM_TABLES_OVERWRITE
$arrayError[$i]['ERROR_MESS'] = \G::LoadTranslation('ID_OVERWRITE_PMTABLE', [$contentSchema['ADD_TAB_NAME']]);
$arrayError[$i]['IS_PMTABLE'] = $flagIsPmTable;
$arrayError[$i]['PRO_UID'] = $tableProUid;
}
} else {
if (!in_array($tableProUid, $arrayProcessUid)) {
$arrayError[$i]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME'];
$arrayError[$i]['ERROR_TYPE'] = 2; //ERROR_PROCESS_NOT_EXIST
$arrayError[$i]['ERROR_MESS'] = \G::LoadTranslation('ID_PROCESS_NOT_EXIST', [$contentSchema['ADD_TAB_NAME']]);
$arrayError[$i]['IS_PMTABLE'] = $flagIsPmTable;
$arrayError[$i]['PRO_UID'] = $tableProUid;
} else {
if ($arrayAdditionalTableData !== false && !$flagOverwrite) {
$arrayError[$i]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME'];
$arrayError[$i]['ERROR_TYPE'] = 3; //ERROR_RP_TABLES_OVERWRITE
$arrayError[$i]['ERROR_MESS'] = \G::LoadTranslation('ID_OVERWRITE_RPTABLE', [$contentSchema['ADD_TAB_NAME']]);
$arrayError[$i]['IS_PMTABLE'] = $flagIsPmTable;
$arrayError[$i]['PRO_UID'] = $tableProUid;
}
}
}
} else {
if ($flagIsPmTable) {
$arrayError[$i]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME'];
$arrayError[$i]['ERROR_TYPE'] = 4; //ERROR_NO_REPORT_TABLE
$arrayError[$i]['ERROR_MESS'] = \G::LoadTranslation('ID_NO_REPORT_TABLE', [$contentSchema['ADD_TAB_NAME']]);
$arrayError[$i]['IS_PMTABLE'] = $flagIsPmTable;
$arrayError[$i]['PRO_UID'] = $tableProUid;
} else {
if ($tableProUid != $processUid) {
$arrayError[$i]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME'];
$arrayError[$i]['ERROR_TYPE'] = 5; //ERROR_OVERWRITE_RELATED_PROCESS
$arrayError[$i]['ERROR_MESS'] = \G::LoadTranslation('ID_OVERWRITE_RELATED_PROCESS', [$contentSchema['ADD_TAB_NAME']]);
$arrayError[$i]['IS_PMTABLE'] = $flagIsPmTable;
$arrayError[$i]['PRO_UID'] = $tableProUid;
} else {
if ($arrayAdditionalTableData !== false && !$flagOverwrite) {
$arrayError[$i]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME'];
$arrayError[$i]['ERROR_TYPE'] = 3; //ERROR_RP_TABLES_OVERWRITE
$arrayError[$i]['ERROR_MESS'] = \G::LoadTranslation('ID_OVERWRITE_RPTABLE', [$contentSchema['ADD_TAB_NAME']]);
$arrayError[$i]['IS_PMTABLE'] = $flagIsPmTable;
$arrayError[$i]['PRO_UID'] = $tableProUid;
}
}
}
}
$i++;
}
//Return
return $arrayError;
} catch (\Exception $e) {
throw $e;
}
}
/**
* Save structure of table
*
* @param array $arrayData
* @param bool $flagAlterTable
*
* @return object
*/
public function saveStructureOfTable($arrayData, $flagAlterTable = true)
{
$result = new \stdClass();
try {
ob_start();
$arrayData['PRO_UID'] = trim($arrayData['PRO_UID']);
$arrayData['columns'] = \G::json_decode(stripslashes($arrayData['columns'])); //Decofing data columns
$additionalTable = new \AdditionalTables();
$repTabClassName = $additionalTable->getPHPName($arrayData['REP_TAB_NAME']);
$flagIsReportTable = ($arrayData['PRO_UID'] != '')? true : false;
$columns = $arrayData['columns'];
//Reserved Words Table
$reservedWords = [
'ALTER', 'CLOSE', 'COMMIT', 'CREATE','DECLARE','DELETE','DROP','FETCH','FUNCTION','GRANT','INDEX',
'INSERT','OPEN','REVOKE','ROLLBACK','SELECT','SYNONYM','TABLE','UPDATE','VIEW','APP_UID','ROW','PMTABLE'
];
//Reserved Words Field
$reservedWordsPhp = [
'case','catch','cfunction','class','clone','const','continue','declare','default','do','else','elseif',
'enddeclare','endfor','endforeach','endif','endswitch','endwhile','extends','final','for','foreach',
'function','global','goto','if','implements','interface','instanceof','private','namespace','new',
'old_function','or','throw','protected','public','static','switch','xor','try','use','var','while'
];
$reservedWordsSql = \G::reservedWordsSql();
//Verify if exists
if ($arrayData['REP_TAB_UID'] == '' || (isset($arrayData['forceUid']) && $arrayData['forceUid'])) {
//New report table
if ($flagIsReportTable && $flagAlterTable) {
//Setting default columns
$defaultColumns = $this->__getDefaultColumns($arrayData['REP_TAB_TYPE']);
$columns = array_merge($defaultColumns, $columns);
}
//Validations
if (is_array($additionalTable->loadByName($arrayData['REP_TAB_NAME']))) {
throw new \Exception(\G::LoadTranslation('ID_PMTABLE_ALREADY_EXISTS', [$arrayData['REP_TAB_NAME']]));
}
if (in_array(strtoupper($arrayData['REP_TAB_NAME']), $reservedWords) ||
in_array(strtoupper($arrayData['REP_TAB_NAME']), $reservedWordsSql)
) {
throw new \Exception(\G::LoadTranslation('ID_PMTABLE_INVALID_NAME', [$arrayData['REP_TAB_NAME']]));
}
}
//Backward compatility
foreach ($columns as $i => $column) {
if (in_array(strtoupper($columns[$i]->field_name), $reservedWordsSql) ||
in_array(strtolower($columns[$i]->field_name), $reservedWordsPhp)
) {
throw new \Exception(\G::LoadTranslation('ID_PMTABLE_INVALID_FIELD_NAME', [$columns[$i]->field_name]));
}
switch ($column->field_type) {
case 'INT':
$columns[$i]->field_type = 'INTEGER';
break;
case 'TEXT':
$columns[$i]->field_type = 'LONGVARCHAR';
break;
case 'DATETIME':
//Propel: DATETIME equivalent is TIMESTAMP
$columns[$i]->field_type = 'TIMESTAMP';
break;
}
//Validations
if ($columns[$i]->field_autoincrement) {
$typeCol = $columns[$i]->field_type;
if (!($typeCol === 'INTEGER' || $typeCol === 'TINYINT' || $typeCol === 'SMALLINT' || $typeCol === 'BIGINT')) {
$columns[$i]->field_autoincrement = false;
}
}
}
$pmTable = new \PmTable($arrayData['REP_TAB_NAME']);
$pmTable->setDataSource($arrayData['REP_TAB_CONNECTION']);
$pmTable->setColumns($columns);
$pmTable->setAlterTable($flagAlterTable);
if (isset($arrayData['keepData']) && $arrayData['keepData'] == 1) {
//PM Table
$pmTable->setKeepData(true);
}
$pmTable->build();
$buildResult = ob_get_contents();
ob_end_clean();
//Updating additional table struture information
$addTabData = [
'ADD_TAB_UID' => $arrayData['REP_TAB_UID'],
'ADD_TAB_NAME' => $arrayData['REP_TAB_NAME'],
'ADD_TAB_CLASS_NAME' => $repTabClassName,
'ADD_TAB_DESCRIPTION' => $arrayData['REP_TAB_DSC'],
'ADD_TAB_PLG_UID' => '',
'DBS_UID' => ($arrayData['REP_TAB_CONNECTION'])? $arrayData['REP_TAB_CONNECTION'] : 'workflow',
'PRO_UID' => $arrayData['PRO_UID'],
'ADD_TAB_TYPE' => $arrayData['REP_TAB_TYPE'],
'ADD_TAB_GRID' => $arrayData['REP_TAB_GRID']
];
if ($arrayData['REP_TAB_UID'] == '' || (isset($arrayData['forceUid']) && $arrayData['forceUid'])) {
//New report table
//create record
$addTabUid = $additionalTable->create($addTabData);
} else {
//Editing report table
//updating record
$addTabUid = $arrayData['REP_TAB_UID'];
$additionalTable->update($addTabData);
//Removing old data fields references
$oCriteria = new \Criteria('workflow');
$oCriteria->add(\FieldsPeer::ADD_TAB_UID, $arrayData['REP_TAB_UID']);
\FieldsPeer::doDelete($oCriteria);
}
//Updating pmtable fields
$field = new \Fields();
foreach ($columns as $i => $column) {
$field->create([
'FLD_UID' => $column->uid,
'FLD_INDEX' => $i,
'ADD_TAB_UID' => $addTabUid,
'FLD_NAME' => $column->field_name,
'FLD_DESCRIPTION' => $column->field_label,
'FLD_TYPE' => $column->field_type,
'FLD_SIZE' => ($column->field_size == '')? null : $column->field_size,
'FLD_NULL' => ($column->field_null)? 1 : 0,
'FLD_AUTO_INCREMENT' => ($column->field_autoincrement)? 1 : 0,
'FLD_KEY' => ($column->field_key)? 1 : 0,
'FLD_TABLE_INDEX' => (isset($column->field_index) && $column->field_index)? 1 : 0,
'FLD_FOREIGN_KEY' => 0,
'FLD_FOREIGN_KEY_TABLE' => '',
'FLD_DYN_NAME' => $column->field_dyn,
'FLD_DYN_UID' => $column->field_uid,
'FLD_FILTER' => (isset($column->field_filter) && $column->field_filter)? 1 : 0
]);
}
if ($flagIsReportTable && $flagAlterTable) {
//The table was create successfully but we're catching problems while populating table
try {
$additionalTable->populateReportTable(
$arrayData['REP_TAB_NAME'],
$pmTable->getDataSource(),
$arrayData['REP_TAB_TYPE'],
$arrayData['PRO_UID'],
$arrayData['REP_TAB_GRID'],
$addTabUid
);
} catch (\Exception $e) {
$result->message = $result->msg = $e->getMessage();
}
}
//Audit Log
$nFields = count($columns) - 1;
$fieldsName = '';
foreach ($columns as $i => $column) {
if ($i != $nFields) {
$fieldsName = $fieldsName . $columns[$i]->field_name . ' [' . implode(', ', get_object_vars($column)) . '], ';
} else {
$fieldsName = $fieldsName . $columns[$i]->field_name . ' [' . implode(', ', get_object_vars($column)) . '].';
}
}
\G::auditLog(
(isset($arrayData['REP_TAB_UID']) && $arrayData['REP_TAB_UID'] == '')?
'CreatePmtable' : 'UpdatePmtable', 'Fields: ' . $fieldsName
);
$result->success = true;
$result->message = $result->msg = $buildResult;
} catch (\Exception $e) {
$buildResult = ob_get_contents();
ob_end_clean();
$result->success = false;
//If it is a propel exception message
if (preg_match('/(.*)\s\[(.*):\s(.*)\]\s\[(.*):\s(.*)\]/', $e->getMessage(), $match)) {
$result->message = $result->msg = $match[3];
$result->type = ucfirst($pmTable->getDbConfig()->adapter);
} else {
$result->message = $result->msg = $e->getMessage();
$result->type = \G::LoadTranslation('ID_EXCEPTION');
}
$result->trace = $e->getTraceAsString();
}
//Return
return $result;
}
/**
* Create the structure of tables
*
* @param array $arrayTableSchema,
* @param array $arrayTableData,
* @param string $processUid
* @param bool $flagFromAdmin
* @param bool $flagOverwrite
* @param array $arrayTablesToExclude
* @param array $arrayTablesToCreate
*
* @return string
*/
public function createStructureOfTables(
array $arrayTableSchema,
array $arrayTableData,
$processUid,
$flagFromAdmin,
$flagOverwrite = true,
array $arrayTablesToExclude = [],
array $arrayTablesToCreate = []
) {
try {
$errors = '';
$tableNameMap = [];
$processQueue = [];
$processQueueTables = [];
foreach ($arrayTableSchema as $value) {
$contentSchema = $value;
if (!in_array($contentSchema['ADD_TAB_NAME'], $arrayTablesToExclude)) {
$additionalTable = new \AdditionalTables();
$arrayAdditionalTableData = $additionalTable->loadByName($contentSchema['ADD_TAB_NAME']);
$tableNameMap[$contentSchema['ADD_TAB_NAME']] = $contentSchema['ADD_TAB_NAME'];
$tableData = new \stdClass();
if (isset( $contentSchema['PRO_UID'] )) {
$tableData->PRO_UID = $contentSchema['PRO_UID'];
} else {
$tableData->PRO_UID = $_POST['form']['PRO_UID'];
}
$flagIsPmTable = $contentSchema['PRO_UID'] === '';
if (!$flagFromAdmin && !$flagIsPmTable) {
$tableData->PRO_UID = $processUid;
}
$flagOverwrite2 = $flagOverwrite;
if (in_array($contentSchema['ADD_TAB_NAME'], $arrayTablesToCreate)) {
$flagOverwrite2 = false;
}
//Overwrite
if ($flagOverwrite2) {
if ($arrayAdditionalTableData !== false) {
$additionalTable->deleteAll($arrayAdditionalTableData['ADD_TAB_UID']);
}
} else {
if ($arrayAdditionalTableData !== false) {
//Some table exists with the same name
//renaming...
$tNameOld = $contentSchema['ADD_TAB_NAME'];
$newTableName = $contentSchema['ADD_TAB_NAME'] . '_' . date('YmdHis');
$contentSchema['ADD_TAB_UID'] = \G::generateUniqueID();
$contentSchema['ADD_TAB_NAME'] = $newTableName;
$contentSchema['ADD_TAB_CLASS_NAME'] = \AdditionalTables::getPHPName($newTableName);
//Mapping the table name for posterior uses
$tableNameMap[$tNameOld] = $contentSchema['ADD_TAB_NAME'];
}
}
//Validating invalid bds_uid in old tables definition -> mapped to workflow
if (!$contentSchema['DBS_UID'] || $contentSchema['DBS_UID'] == '0' || !$contentSchema['DBS_UID']) {
$contentSchema['DBS_UID'] = 'workflow';
}
$columns = [];
foreach ($contentSchema['FIELDS'] as $field) {
$columns[] = [
'uid' => '',
'field_uid' => '',
'field_name' => $field['FLD_NAME'],
'field_dyn' => (isset($field['FLD_DYN_NAME']))? $field['FLD_DYN_NAME'] : '',
'field_label' => (isset($field['FLD_DESCRIPTION']))? $field['FLD_DESCRIPTION'] : '',
'field_type' => $field['FLD_TYPE'],
'field_size' => $field['FLD_SIZE'],
'field_key' => (isset($field['FLD_KEY']))? $field['FLD_KEY'] : 0,
'field_null' => (isset($field['FLD_NULL']))? $field['FLD_NULL'] : 1,
'field_autoincrement' => (isset($field['FLD_AUTO_INCREMENT']))?
$field['FLD_AUTO_INCREMENT'] : 0
];
}
$tableData->REP_TAB_UID = $contentSchema['ADD_TAB_UID'];
$tableData->REP_TAB_NAME = $contentSchema['ADD_TAB_NAME'];
$tableData->REP_TAB_DSC = $contentSchema['ADD_TAB_DESCRIPTION'];
$tableData->REP_TAB_CONNECTION = $contentSchema['DBS_UID'];
$tableData->REP_TAB_TYPE = (isset($contentSchema['ADD_TAB_TYPE']))? $contentSchema['ADD_TAB_TYPE'] : '';
$tableData->REP_TAB_GRID = (isset($contentSchema['ADD_TAB_GRID']))? $contentSchema['ADD_TAB_GRID'] : '';
$tableData->columns = \G::json_encode($columns);
$tableData->forceUid = true;
//Save the table
$alterTable = false;
$result = $this->saveStructureOfTable((array)($tableData), $alterTable);
if ($result->success) {
\G::auditLog(
'ImportTable', $contentSchema['ADD_TAB_NAME'] . ' (' . $contentSchema['ADD_TAB_UID'] . ')'
);
$processQueueTables[$contentSchema['DBS_UID']][] = $contentSchema['ADD_TAB_NAME'];
} else {
$errors .= \G::LoadTranslation('ID_ERROR_CREATE_TABLE') . $tableData->REP_TAB_NAME . '-> ' . $result->message . '\n\n';
}
}
}
foreach ($processQueueTables as $dbsUid => $tables) {
$pmTable = new \PmTable();
ob_start();
$pmTable->buildModelFor($dbsUid, $tables);
$buildResult = ob_get_contents();
ob_end_clean();
$errors .= $pmTable->upgradeDatabaseFor($pmTable->getDataSource(), $tables);
}
if (!empty($tableNameMap)) {
$errors = $this->__populateData($arrayTableData, $tableNameMap);
}
//Return
return $errors;
} catch (\Exception $e) {
throw $e;
}
}
}

View File

@@ -1182,7 +1182,7 @@ class TimerEvent
//Start Timer-Event (start new case) ///////////////////////////////////////////////////////////////////////
$common->frontEndShow("START");
$this->log("START-NEW-CASES", "Date \"$datetime\": Start new cases");
$this->log("START-NEW-CASES", "Date \"$datetime (UTC +00:00)\": Start new cases");
//Query
$criteria = $this->getTimerEventCriteria();
@@ -1349,17 +1349,17 @@ class TimerEvent
}
if (!$flagRecord) {
$common->frontEndShow("TEXT", "Not exists any record to start a new case, on date \"$datetime\"");
$common->frontEndShow("TEXT", "Not exists any record to start a new case, on date \"$datetime (UTC +00:00)\"");
$this->log("NO-RECORDS", "Not exists any record to start a new case");
}
$common->frontEndShow("END");
$this->log("END-NEW-CASES", "Date \"$datetime\": End new cases");
$this->log("END-NEW-CASES", "Date \"$datetime (UTC +00:00)\": End new cases");
//Intermediate Catch Timer-Event (continue the case) ///////////////////////////////////////////////////////
$this->log("START-CONTINUE-CASES", "Date \"$datetime\": Start continue the cases");
$this->log("START-CONTINUE-CASES", "Date \"$datetime (UTC +00:00)\": Start continue the cases");
//Query
$criteriaMain = $this->getTimerEventCriteria();
@@ -1555,14 +1555,14 @@ class TimerEvent
} while ($flagNextRecord);
if (!$flagRecord) {
$common->frontEndShow("TEXT", "Not exists any record to continue a case, on date \"$datetime\"");
$common->frontEndShow("TEXT", "Not exists any record to continue a case, on date \"$datetime (UTC +00:00)\"");
$this->log("NO-RECORDS", "Not exists any record to continue a case");
}
$common->frontEndShow("END");
$this->log("END-CONTINUE-CASES", "Date \"$datetime\": End continue the cases");
$this->log("END-CONTINUE-CASES", "Date \"$datetime (UTC +00:00)\": End continue the cases");
} catch (\Exception $e) {
throw $e;
}

View File

@@ -4,6 +4,8 @@ namespace ProcessMaker\Importer;
use ProcessMaker\Util;
use ProcessMaker\Project;
use ProcessMaker\Project\Adapter;
use ProcessMaker\BusinessModel\Migrator;
use ProcessMaker\BusinessModel\Migrator\ImportException;
abstract class Importer
{
@@ -76,7 +78,7 @@ abstract class Importer
}
}
public function import($option = self::IMPORT_OPTION_CREATE_NEW, $optionGroup = self::GROUP_IMPORT_OPTION_CREATE_NEW, $generateUidFromJs = null)
public function import($option = self::IMPORT_OPTION_CREATE_NEW, $optionGroup = self::GROUP_IMPORT_OPTION_CREATE_NEW, $generateUidFromJs = null, $objectsToImport = '')
{
$this->prepare();
@@ -169,7 +171,28 @@ abstract class Importer
break;
case self::IMPORT_OPTION_OVERWRITE:
//Shouldn't generate new UID for all objects
$this->removeProject();
/*----------------------------------********---------------------------------*/
if($objectsToImport === ''){
/*----------------------------------********---------------------------------*/
$this->removeProject();
/*----------------------------------********---------------------------------*/
} else {
$granularObj = new \ProcessMaker\BusinessModel\Migrator\GranularImporter();
$objectList = $granularObj->loadObjectsListSelected($this->importData, $objectsToImport);
try {
foreach ($objectList as $rowObject) {
if ($rowObject['name'] === 'PROCESSDEFINITION') {
$onlyDiagram = true;
$this->removeProject($onlyDiagram);
}
}
} catch (\Exception $e) {
$exception = new ImportException($e->getMessage());
$exception->setNameException(\G::LoadTranslation('ID_PROCESS_DEFINITION_INCOMPLETE'));
throw $exception;
}
}
/*----------------------------------********---------------------------------*/
$name = $this->currentProcessTitle;
$generateUid = false;
break;
@@ -204,6 +227,44 @@ abstract class Importer
if(!empty($generateUidFromJs)) {
$generateUid = $generateUidFromJs;
}
/*----------------------------------********---------------------------------*/
//Granular Import
try {
if ($objectsToImport !== '') {
$granularObj = new \ProcessMaker\BusinessModel\Migrator\GranularImporter();
$newObjectArray = $objectsToImport;
$projectUid = $this->importData['tables']['bpmn']["project"][0]["prj_uid"];
$processGranulate = $granularObj->validateImportData($objectsToImport, $option);
if($generateUid){
$result = $granularObj->regenerateAllUids($this->importData, $generateUid);
$this->importData = $result['data'];
$projectUid = $result['new_uid'];
$newObjectArray = array();
$count = 0;
foreach ($objectsToImport as $key => $rowObject) {
if($rowObject->id != '1'){
$newObjectArray[++$count] = $rowObject;
}
}
}
if(sizeof($newObjectArray)){
$objectList = $granularObj->loadObjectsListSelected($this->importData, $newObjectArray);
if (sizeof($objectList) > 0 && $processGranulate) {
$granularObj->import($objectList);
}
}
if($option === self::IMPORT_OPTION_CREATE_NEW || $option === self::IMPORT_OPTION_KEEP_WITHOUT_CHANGING_AND_CREATE_NEW){
$oProcessDef = new \ProcessMaker\BusinessModel\Migrator\ProcessDefinitionMigrator();
$oProcessDef->afterImport($this->importData['tables']);
}
return $projectUid;
}
} catch (\Exception $e) {
throw $e;
}
/*----------------------------------********---------------------------------*/
$result = $this->doImport($generateUid);
//Return
@@ -226,7 +287,6 @@ abstract class Importer
$this->importData = $this->load();
$this->validateImportData();
}
public function setData($key, $value)
@@ -281,14 +341,14 @@ abstract class Importer
$project->setDisabled();
}
public function removeProject()
public function removeProject($onlyDiagram = false)
{
/* @var $process \Process */
$process = new \Process();
$process->load($this->metadata["uid"]);
$this->currentProcessTitle = $process->getProTitle();
$project = \ProcessMaker\Project\Adapter\BpmnWorkflow::load($this->metadata["uid"]);
$project->remove(true, false);
$project->remove(true, false, $onlyDiagram);
}
/**
@@ -356,11 +416,11 @@ abstract class Importer
// Build BPMN project struct
$project = $tables["project"][0];
$diagram = $tables["diagram"][0];
$diagram["activities"] = $tables["activity"];
$diagram["activities"] = (isset($tables["activity"]))? $tables["activity"] : array();
$diagram["artifacts"] = (isset($tables["artifact"]))? $tables["artifact"] : array();
$diagram["events"] = $tables["event"];
$diagram["flows"] = $tables["flow"];
$diagram["gateways"] = $tables["gateway"];
$diagram["events"] = (isset($tables["event"]))? $tables["event"] : array();
$diagram["flows"] = (isset($tables["flow"]))? $tables["flow"] : array();
$diagram["gateways"] = (isset($tables["gateway"]))? $tables["gateway"]: array();
$diagram["data"] = (isset($tables["data"]))? $tables["data"] : array();
$diagram["participants"] = (isset($tables["participant"]))? $tables["participant"] : array();
$diagram["laneset"] = (isset($tables["laneset"]))? $tables["laneset"] : array();
@@ -388,58 +448,62 @@ abstract class Importer
public function doImport($generateUid = true)
{
$arrayBpmnTables = $this->importData["tables"]["bpmn"];
$arrayWorkflowTables = $this->importData["tables"]["workflow"];
$arrayWorkflowFiles = $this->importData["files"]["workflow"];
try {
$arrayBpmnTables = $this->importData["tables"]["bpmn"];
$arrayWorkflowTables = $this->importData["tables"]["workflow"];
$arrayWorkflowFiles = $this->importData["files"]["workflow"];
//Import BPMN tables
$result = $this->importBpmnTables($arrayBpmnTables, $generateUid);
//Import BPMN tables
$result = $this->importBpmnTables($arrayBpmnTables, $generateUid);
$projectUidOld = $arrayBpmnTables["project"][0]["prj_uid"];
$projectUid = ($generateUid)? $result[0]["new_uid"] : $result;
$projectUidOld = $arrayBpmnTables["project"][0]["prj_uid"];
$projectUid = ($generateUid) ? $result[0]["new_uid"] : $result;
//Import workflow tables
if ($generateUid) {
$result[0]["object"] = "project";
$result[0]["old_uid"] = $projectUidOld;
$result[0]["new_uid"] = $projectUid;
//Import workflow tables
if ($generateUid) {
$result[0]["object"] = "project";
$result[0]["old_uid"] = $projectUidOld;
$result[0]["new_uid"] = $projectUid;
$workflow = new \ProcessMaker\Project\Workflow();
$workflow = new \ProcessMaker\Project\Workflow();
list($arrayWorkflowTables, $arrayWorkflowFiles) = $workflow->updateDataUidByArrayUid($arrayWorkflowTables, $arrayWorkflowFiles, $result);
}
$this->importWfTables($arrayWorkflowTables);
//Import workflow files
$this->importWfFiles($arrayWorkflowFiles);
//Update
$workflow = \ProcessMaker\Project\Workflow::load($projectUid);
foreach ($arrayWorkflowTables["tasks"] as $key => $value) {
$arrayTaskData = $value;
if (!in_array($arrayTaskData["TAS_TYPE"], array("GATEWAYTOGATEWAY", "WEBENTRYEVENT", "END-MESSAGE-EVENT", "START-MESSAGE-EVENT", "INTERMEDIATE-THROW-MESSAGE-EVENT", "INTERMEDIATE-CATCH-MESSAGE-EVENT", "START-TIMER-EVENT", "INTERMEDIATE-CATCH-TIMER-EVENT", "END-EMAIL-EVENT", "INTERMEDIATE-EMAIL-EVENT"))) {
$result = $workflow->updateTask($arrayTaskData["TAS_UID"], $arrayTaskData);
list($arrayWorkflowTables, $arrayWorkflowFiles) = $workflow->updateDataUidByArrayUid($arrayWorkflowTables, $arrayWorkflowFiles, $result);
}
$this->importWfTables($arrayWorkflowTables);
//Import workflow files
$this->importWfFiles($arrayWorkflowFiles);
//Update
$workflow = \ProcessMaker\Project\Workflow::load($projectUid);
foreach ($arrayWorkflowTables["tasks"] as $key => $value) {
$arrayTaskData = $value;
if (!in_array($arrayTaskData["TAS_TYPE"], array("GATEWAYTOGATEWAY", "WEBENTRYEVENT", "END-MESSAGE-EVENT", "START-MESSAGE-EVENT", "INTERMEDIATE-THROW-MESSAGE-EVENT", "INTERMEDIATE-CATCH-MESSAGE-EVENT", "START-TIMER-EVENT", "INTERMEDIATE-CATCH-TIMER-EVENT", "END-EMAIL-EVENT", "INTERMEDIATE-EMAIL-EVENT"))) {
$result = $workflow->updateTask($arrayTaskData["TAS_UID"], $arrayTaskData);
}
}
unset($arrayWorkflowTables["process"]["PRO_CREATE_USER"]);
unset($arrayWorkflowTables["process"]["PRO_CREATE_DATE"]);
unset($arrayWorkflowTables["process"]["PRO_UPDATE_DATE"]);
unset($arrayWorkflowTables["process"]["PRO_CATEGORY"]);
unset($arrayWorkflowTables["process"]["PRO_CATEGORY_LABEL"]);
$workflow->update($arrayWorkflowTables["process"]);
//Process-Files upgrade
$filesManager = new \ProcessMaker\BusinessModel\FilesManager();
$filesManager->processFilesUpgrade($projectUid);
//Return
return $projectUid;
} catch (\Exception $e) {
throw $e;
}
unset($arrayWorkflowTables["process"]["PRO_CREATE_USER"]);
unset($arrayWorkflowTables["process"]["PRO_CREATE_DATE"]);
unset($arrayWorkflowTables["process"]["PRO_UPDATE_DATE"]);
unset($arrayWorkflowTables["process"]["PRO_CATEGORY"]);
unset($arrayWorkflowTables["process"]["PRO_CATEGORY_LABEL"]);
$workflow->update($arrayWorkflowTables["process"]);
//Process-Files upgrade
$filesManager = new \ProcessMaker\BusinessModel\FilesManager();
$filesManager->processFilesUpgrade($projectUid);
//Return
return $projectUid;
}
/**

View File

@@ -8,7 +8,8 @@ class XmlImporter extends Importer
*/
protected $dom;
protected $root;
protected $version = "";
protected $version = '';
protected $objects = '';
public function __construct()
{
@@ -129,10 +130,14 @@ class XmlImporter extends Importer
);
}
}
//Get the ProcessObject
$this->objects = (isset($this->metadata['export_objects'])) ? $this->metadata['export_objects'] : '';
return array(
"tables" => $tables,
"files" => array("workflow" => $wfFiles, "bpmn" => array())
"tables" => $tables,
"files" => array("workflow" => $wfFiles, "bpmn" => array()),
"version" => $this->getVersion(),
"objects" => $this->getObjects()
);
}
@@ -144,5 +149,22 @@ class XmlImporter extends Importer
return (string) simplexml_import_dom($node->parentNode);
}
}
/**
* Gets the $version value
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* Gets the $objects value
* @return string
*/
public function getObjects()
{
return $this->objects;
}
}

View File

@@ -1217,10 +1217,10 @@ class BpmnWorkflow extends Project\Bpmn
}
}
public function remove($flagForceRemoveProject = false, $flagRemoveCases = true)
public function remove($flagForceRemoveProject = false, $flagRemoveCases = true, $onlyDiagram = false)
{
parent::remove($flagForceRemoveProject);
$this->wp->remove($flagRemoveCases);
$this->wp->remove($flagRemoveCases, $onlyDiagram);
}
public static function createFromStruct(array $projectData, $generateUid = true)

View File

@@ -115,11 +115,11 @@ class Workflow extends Handler
$process->update($data);
}
public function remove($flagRemoveCases = true)
public function remove($flagRemoveCases = true, $onlyDiagram = false)
{
try {
self::log("Remove Process with uid: {$this->proUid}");
$this->deleteProcess($this->proUid, $flagRemoveCases);
$this->deleteProcess($this->proUid, $flagRemoveCases, $onlyDiagram);
self::log("Remove Process Success!");
} catch (\Exception $e) {
self::log("Exception: ", $e->getMessage(), "Trace: ", $e->getTraceAsString());
@@ -577,7 +577,7 @@ class Workflow extends Handler
}
}
public function deleteProcess($sProcessUID, $flagRemoveCases = true)
public function deleteProcess($sProcessUID, $flagRemoveCases = true, $onlyDiagram = false)
{
try {
//G::LoadClass('case');
@@ -651,46 +651,49 @@ class Workflow extends Handler
$oDataset->next();
}
//Delete the dynaforms of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\DynaformPeer::PRO_UID, $sProcessUID);
$oDataset = \DynaformPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oDynaform->remove($aRow['DYN_UID']);
$oDataset->next();
}
//Delete the input documents of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\InputDocumentPeer::PRO_UID, $sProcessUID);
$oDataset = \InputDocumentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oInputDocument->remove($aRow['INP_DOC_UID']);
$oDataset->next();
}
//Delete the output documents of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\OutputDocumentPeer::PRO_UID, $sProcessUID);
$oDataset = \OutputDocumentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oOutputDocument->remove($aRow['OUT_DOC_UID']);
$oDataset->next();
}
//Delete the triggers of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\TriggersPeer::PRO_UID, $sProcessUID);
$oDataset = \TriggersPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oTrigger->remove($aRow['TRI_UID']);
//Delete the dynaforms of process
if (!$onlyDiagram) {
$oCriteria = new Criteria('workflow');
$oCriteria->add(\DynaformPeer::PRO_UID, $sProcessUID);
$oDataset = \DynaformPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oDynaform->remove($aRow['DYN_UID']);
$oDataset->next();
}
//Delete the input documents of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\InputDocumentPeer::PRO_UID, $sProcessUID);
$oDataset = \InputDocumentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oInputDocument->remove($aRow['INP_DOC_UID']);
$oDataset->next();
}
//Delete the output documents of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\OutputDocumentPeer::PRO_UID, $sProcessUID);
$oDataset = \OutputDocumentPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oOutputDocument->remove($aRow['OUT_DOC_UID']);
$oDataset->next();
}
//Delete the triggers of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\TriggersPeer::PRO_UID, $sProcessUID);
$oDataset = \TriggersPeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oTrigger->remove($aRow['TRI_UID']);
$oDataset->next();
}
}
//Delete the routes of process
@@ -746,39 +749,17 @@ class Workflow extends Handler
$oConfiguration->remove($aRow['CFG_UID'], $aRow['OBJ_UID'], $aRow['PRO_UID'], $aRow['USR_UID'], $aRow['APP_UID']);
$oDataset->next();
}
//Delete the DB sources of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\DbSourcePeer::PRO_UID, $sProcessUID);
$oDataset = \DbSourcePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
/**
* note added by gustavo cruz gustavo-at-colosa-dot-com 27-01-2010
* in order to solve the bug 0004389, we use the validation function Exists
* inside the remove function in order to verify if the DbSource record
* exists in the Database, however there is a strange behavior within the
* propel engine, when the first record is erased somehow the "_deleted"
* attribute of the next row is set to true, so when propel tries to erase
* it, obviously it can't and trows an error. With the "Exist" function
* we ensure that if there is the record in the database, the _delete attribute must be false.
*
* note added by gustavo cruz gustavo-at-colosa-dot-com 28-01-2010
* I have just identified the source of the issue, when is created a $oDbSource DbSource object
* it's used whenever a record is erased or removed in the db, however the problem
* it's that the same object is used every time, and the delete method invoked
* sets the _deleted attribute to true when its called, of course as we use
* the same object, the first time works fine but trowns an error with the
* next record, cos it's the same object and the delete method checks if the _deleted
* attribute it's true or false, the attrib _deleted is setted to true the
* first time and later is never changed, the issue seems to be part of
* every remove function in the model classes, not only DbSource
* i recommend that a more general solution must be achieved to resolve
* this issue in every model class, to prevent future problems.
*/
$oDbSource->remove($aRow['DBS_UID'], $sProcessUID);
if (!$onlyDiagram) {
//Delete the DB sources of process
$oCriteria = new Criteria('workflow');
$oCriteria->add(\DbSourcePeer::PRO_UID, $sProcessUID);
$oDataset = \DbSourcePeer::doSelectRS($oCriteria);
$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$oDataset->next();
while ($aRow = $oDataset->getRow()) {
$oDbSource->remove($aRow['DBS_UID'], $sProcessUID);
$oDataset->next();
}
}
//Delete the supervisors
$oCriteria = new Criteria('workflow');
@@ -917,19 +898,20 @@ class Workflow extends Handler
$emailEvent->delete($sProcessUID,$row["EMAIL_EVENT_UID"],false);
}
//Delete files Manager
$filesManager = new \ProcessMaker\BusinessModel\FilesManager();
$criteria = new \Criteria("workflow");
$criteria->addSelectColumn(\ProcessFilesPeer::PRF_UID);
$criteria->add(\ProcessFilesPeer::PRO_UID, $sProcessUID, \Criteria::EQUAL);
$rsCriteria = \ProcessFilesPeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
if (!$onlyDiagram) {
//Delete files Manager
$filesManager = new \ProcessMaker\BusinessModel\FilesManager();
$criteria = new \Criteria("workflow");
$criteria->addSelectColumn(\ProcessFilesPeer::PRF_UID);
$criteria->add(\ProcessFilesPeer::PRO_UID, $sProcessUID, \Criteria::EQUAL);
$rsCriteria = \ProcessFilesPeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC);
while ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$filesManager->deleteProcessFilesManager($sProcessUID, $row["PRF_UID"]);
while ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$filesManager->deleteProcessFilesManager($sProcessUID, $row["PRF_UID"]);
}
}
//Delete the actions by email
$oCriteria = new Criteria('workflow');
$oCriteria->add(\AbeConfigurationPeer::PRO_UID, $sProcessUID);
@@ -1335,6 +1317,18 @@ class Workflow extends Handler
}
}
foreach ($arrayWorkflowData["inputs"] as $keyin => $value) {
$newUid = $value["INP_DOC_UID"];
if(isset($value["INP_DOC_UID_OLD"])){
foreach ($arrayWorkflowData["processVariables"] as $keypv => $vars) {
if($vars['INP_DOC_UID'] === $value["INP_DOC_UID_OLD"]){
$arrayWorkflowData["processVariables"][$keypv]["INP_DOC_UID"] = $newUid;
}
}
unset($arrayWorkflowData["inputs"][$keyin]["INP_DOC_UID_OLD"]);
}
}
//Workflow files
foreach ($arrayWorkflowFile as $key => $value) {
$arrayFile = $value;

View File

@@ -170,9 +170,6 @@ class Light extends Api
}
/*----------------------------------********---------------------------------*/
if ($newerThan != '') {
$response['data'] = array_reverse($response['data']);
}
$result = $this->parserDataTodo($response['data']);
return DateTime::convertUtcToIso8601($result, $this->arrayFieldIso8601);
} catch (\Exception $e) {
@@ -264,9 +261,6 @@ class Light extends Api
}
/*----------------------------------********---------------------------------*/
if ($newerThan != '') {
$response['data'] = array_reverse($response['data']);
}
$result = $this->parserDataDraft($response['data']);
return DateTime::convertUtcToIso8601($result, $this->arrayFieldIso8601);
} catch (\Exception $e) {
@@ -367,9 +361,6 @@ class Light extends Api
}
/*----------------------------------********---------------------------------*/
if ($newerThan != '') {
$response['data'] = array_reverse($response['data']);
}
$result = $this->parserDataParticipated($response['data']);
return DateTime::convertUtcToIso8601($result, $this->arrayFieldIso8601);
} catch (\Exception $e) {
@@ -724,6 +715,28 @@ class Light extends Api
return $response;
}
/**
* Get Already Route
*
* @param string $app_uid {@min 1}{@max 32}
* @param int $cas_index
*
* @status 204
* @url GET /case/:app_uid/:cas_index
*/
public function doIfAlreadyRoute($app_uid, $cas_index)
{
try {
$oAppDelegate = new \AppDelegation();
$alreadyRouted = $oAppDelegate->alreadyRouted($app_uid, $cas_index);
if ($alreadyRouted) {
throw (new RestException(Api::STAT_APP_EXCEPTION, G::LoadTranslation('ID_CASE_DELEGATION_ALREADY_CLOSED')));
}
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
/**
*
* @url GET /project/:prj_uid/dynaforms
@@ -835,6 +848,13 @@ class Light extends Api
{
try {
$oCase = new \Cases();
$oAppDelegate = new \AppDelegation();
$alreadyRouted = $oAppDelegate->alreadyRouted($app_uid, $cas_index);
if ($alreadyRouted) {
throw (new RestException(Api::STAT_APP_EXCEPTION, G::LoadTranslation('ID_CASE_DELEGATION_ALREADY_CLOSED')));
}
$userUid = $this->getUserId();
$_SESSION["APPLICATION"] = $app_uid;
$_SESSION["PROCESS"] = $pro_uid;

View File

@@ -7,6 +7,9 @@ use \ProcessMaker\Project\Adapter;
use \ProcessMaker\Util;
use \ProcessMaker\Util\DateTime;
use \ProcessMaker\BusinessModel\Validator;
use \ProcessMaker\BusinessModel\Migrator\GranularExporter;
use \ProcessMaker\BusinessModel\Migrator\ExportObjects;
use \ProcessMaker\Util\IO\HttpStream;
/**
* Class Project
@@ -114,6 +117,44 @@ class Project extends Api
}
}
/**
* @url GET /:prj_uid/export/listObjects
*
* @param string $prj_uid {@min 32}{@max 32}
* @return mixed|string
* @throws RestException
*/
public function objectList($prj_uid)
{
try {
$exportProcess= new ExportObjects();
$result = $exportProcess->objectList($prj_uid);
return $result;
} catch (\Exception $e) {
throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage());
}
}
/**
* @url GET /:prj_uid/export-granular
*
* @param string $prj_uid {@min 32}{@max 32}
* @param string $objects
*/
public function exportGranular($prj_uid, $objects)
{
$objects = \G::json_decode($objects);
$granularExporter = new GranularExporter($prj_uid);
$outputFilename = $granularExporter->export($objects);
$outputFilename = PATH_DATA . 'sites' . PATH_SEP . SYS_SYS . PATH_SEP . 'files' . PATH_SEP . 'output' .
PATH_SEP . $outputFilename;
$httpStream = new HttpStream();
$fileExtension = pathinfo($outputFilename, PATHINFO_EXTENSION);
$httpStream->loadFromFile($outputFilename);
$httpStream->setHeader("Content-Type", "application/xml; charset=UTF-8");
$httpStream->send();
}
/**
* @url GET /:prj_uid/export
*

View File

@@ -14,15 +14,16 @@ class FilesManager extends Api
/**
* @param string $prj_uid {@min 32} {@max 32}
* @param string $path
* @param string $get_content
*
* @url GET /:prj_uid/file-manager
*/
public function doGetProcessFilesManager($prj_uid, $path = '')
public function doGetProcessFilesManager($prj_uid, $path = '', $get_content = true)
{
try {
$filesManager = new \ProcessMaker\BusinessModel\FilesManager();
if ($path != '') {
$arrayData = $filesManager->getProcessFilesManagerPath($prj_uid, $path);
$arrayData = $filesManager->getProcessFilesManagerPath($prj_uid, $path, $get_content);
} else {
$arrayData = $filesManager->getProcessFilesManager($prj_uid);
}