From a50d3c5e5ed5feab8f452f745138a52dc23dc188 Mon Sep 17 00:00:00 2001 From: Marco Antonio Nina Mena Date: Thu, 1 Feb 2018 13:06:32 +0000 Subject: [PATCH] HOR-4532 --- gulliver/bin/tasks/templates/dbInfo.php.tpl | 10 +- gulliver/system/class.database_mysql.php | 775 ++++++++++-------- gulliver/system/class.dbMaintenance.php | 475 +++++------ workflow/engine/bin/tasks/cliUpgrade.php | 39 +- .../engine/classes/MultipleFilesBackup.php | 39 +- workflow/engine/classes/Net.php | 69 +- workflow/engine/classes/WorkspaceTools.php | 249 +++--- workflow/engine/classes/model/Content.php | 144 ++-- .../engine/controllers/InstallerModule.php | 557 +++++++------ .../methods/setup/upgrade_SystemAjax.php | 401 ++++----- .../src/ProcessMaker/Core/Installer.php | 434 ++++++---- .../engine/src/ProcessMaker/Core/System.php | 234 +++++- 12 files changed, 1856 insertions(+), 1570 deletions(-) diff --git a/gulliver/bin/tasks/templates/dbInfo.php.tpl b/gulliver/bin/tasks/templates/dbInfo.php.tpl index 3868ff189..12d52aec3 100644 --- a/gulliver/bin/tasks/templates/dbInfo.php.tpl +++ b/gulliver/bin/tasks/templates/dbInfo.php.tpl @@ -68,11 +68,11 @@ function lookup($target) try { switch ($driver) { case 'mysql': - if ($link = mysqli_connect(DB_HOST, DB_USER, DB_PASS)) { - $v = mysqli_get_server_info($link); - } else { - throw new Exception(mysqli_error($link)); - } + $results = \Illuminate\Support\Facades\DB::select(DB::raw("select version()")); + + preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $results[0]->{'version()'}, $version); + + $v = $version[0]; break; } return (isset($v))?$v:'none'; diff --git a/gulliver/system/class.database_mysql.php b/gulliver/system/class.database_mysql.php index 419d6ccb6..8191f51db 100644 --- a/gulliver/system/class.database_mysql.php +++ b/gulliver/system/class.database_mysql.php @@ -1,181 +1,222 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ -/** - * - * @package gulliver.system - * - */ +use Illuminate\Support\Facades\DB; + class database extends database_base { public $iFetchType = MYSQLI_ASSOC; + /** + * Name connection eloquent + * @var string + */ + private $nameConnection; + + /** + * Expression regex validate version mysql. + * @var string + */ + private $regexVersionMysql = '@[0-9]+\.[0-9]+\.[0-9]+@'; + /** * class database constructor. * - * @param string $sType adapter type - * @param string $sServer server - * @param string $sUser db user - * @param string $sPass db user password - * @param string $sDataBase Database name + * @param string $type adapter type + * @param string $server server + * @param string $user db user + * @param string $pass db user password + * @param string $database Database name */ - public function __construct($sType = DB_ADAPTER, $sServer = DB_HOST, $sUser = DB_USER, $sPass = DB_PASS, $sDataBase = DB_NAME) + public function __construct($type = null, $server = null, $user = null, $pass = null, $database = null) { - $this->sType = $sType; - $this->sServer = $sServer; - $this->sUser = $sUser; - $this->sPass = $sPass; - $this->sDataBase = $sDataBase; - $this->oConnection = mysqli_connect($sServer, $sUser, $sPass, $sDataBase) or die('Could not connect to database...'); + if ($type === null) { + $type = config('connections.driver'); + } + if ($server === null) { + $server = config('connections.workflow.host'); + } + if ($user === null) { + $user = config('connections.workflow.username'); + } + if ($pass === null) { + $pass = config('connections.workflow.password'); + } + if ($database === null) { + $database = config('connections.workflow.database'); + } + $this->sType = $type; + $this->sServer = $server; + $this->sUser = $user; + $this->sPass = $pass; + $this->sDataBase = $database; $this->sQuoteCharacter = '`'; $this->nullString = 'null'; + try { + $this->setNameConnection('workflow'); + if ($type !== config('connections.driver') || + $server !== config('connections.workflow.host') || + $user !== config('connections.workflow.username') || + $pass !== config('connections.workflow.password') || + $database !== config('connections.workflow.database')) { + $this->setNameConnection('DATABASE_' . $database); + InstallerModule::setNewConnection($this->getNameConnection(), $server, $user, $pass, $database, ''); + } + + $this->oConnection = true; + } catch (Exception $exception) { + $this->oConnection = false; + } + } + + /** + * @return string + */ + public function getNameConnection() + { + return $this->nameConnection; + } + + /** + * @param string $nameConnection + */ + public function setNameConnection($nameConnection) + { + $this->nameConnection = $nameConnection; + } + + /** + * @return string + */ + public function getRegexVersionMysql() + { + return $this->regexVersionMysql; + } + + /** + * @param string $regexVersionMysql + */ + public function setRegexVersionMysql($regexVersionMysql) + { + $this->regexVersionMysql = $regexVersionMysql; } /** * generate the sql sentence to create a table * - * @param $sTable table name - * @param $aColumns array of columns - * @return $sSql the sql sentence + * @param string $table table name + * @param array $columns array of columns + * @return string $sql the sql sentence */ - public function generateCreateTableSQL($sTable, $aColumns) + public function generateCreateTableSQL($table, $columns) { - $sKeys = ''; - $sSQL = 'CREATE TABLE IF NOT EXISTS ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . '('; + $keys = ''; + $sql = 'CREATE TABLE IF NOT EXISTS ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . '('; - foreach ($aColumns as $sColumnName => $aParameters) { - if ($sColumnName != 'INDEXES') { - if ($sColumnName != '' && isset($aParameters['Type']) && $aParameters['Type'] != '') { - $sSQL .= $this->sQuoteCharacter . $sColumnName . $this->sQuoteCharacter . ' ' . $aParameters['Type']; + foreach ($columns as $columnName => $parameters) { + if ($columnName !== 'INDEXES') { + if (!empty($columnName) && isset($parameters['Type']) && !empty($parameters['Type'])) { + $sql .= $this->sQuoteCharacter . $columnName . $this->sQuoteCharacter . ' ' . $parameters['Type']; - if (isset($aParameters['Null']) && $aParameters['Null'] == 'YES') { - $sSQL .= ' NULL'; + if (isset($parameters['Null']) && $parameters['Null'] === 'YES') { + $sql .= ' NULL'; } else { - $sSQL .= ' NOT NULL'; + $sql .= ' NOT NULL'; } - if (isset($aParameters['AutoIncrement']) && $aParameters['AutoIncrement']) { - $sSQL .= ' AUTO_INCREMENT PRIMARY KEY'; + if (isset($parameters['AutoIncrement']) && $parameters['AutoIncrement']) { + $sql .= ' AUTO_INCREMENT PRIMARY KEY'; } - if (isset($aParameters['Key']) && $aParameters['Key'] == 'PRI') { - $sKeys .= $this->sQuoteCharacter . $sColumnName . $this->sQuoteCharacter . ','; + if (isset($parameters['Key']) && $parameters['Key'] == 'PRI') { + $keys .= $this->sQuoteCharacter . $columnName . $this->sQuoteCharacter . ','; } - if (isset($aParameters['Default'])) { - $sSQL .= " DEFAULT '" . trim($aParameters['Default']) . "'"; + if (isset($parameters['Default'])) { + $sql .= " DEFAULT '" . trim($parameters['Default']) . "'"; } - $sSQL .= ','; + $sql .= ','; } } } - $sSQL = substr($sSQL, 0, -1); - if ($sKeys != '') { - $sSQL .= ',PRIMARY KEY(' . substr($sKeys, 0, -1) . ')'; + $sql = substr($sql, 0, -1); + if ($keys != '') { + $sql .= ',PRIMARY KEY(' . substr($keys, 0, -1) . ')'; } - $sSQL .= ')ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci' . $this->sEndLine; + $sql .= ')ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci'; - return $sSQL; + return $sql; } /** * generate a drop table sentence * - * @param $sTable table name - * @return sql sentence string + * @param string $table table name + * @return string sql sentence string */ - public function generateDropTableSQL($sTable) + public function generateDropTableSQL($table) { - return 'DROP TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . $this->sEndLine; + return 'DROP TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter; } /** * generate rename table sentence * - * @param $sTableOld old table name - * @return $sSql sql sentence + * @param string $sTableOld old table name + * @return string $sql sql sentence */ public function generateRenameTableSQL($sTableOld) { - $sSQL = 'ALTER TABLE ' . $sTableOld . ' RENAME TO RBAC_' . $sTableOld; - return $sSQL; + $sql = 'ALTER TABLE ' . $sTableOld . ' RENAME TO RBAC_' . $sTableOld; + return $sql; } /** * generate drop column sentence * - * @param $sTable table name - * @param $sColumn column name - * @return $sSql sql sentence + * @param string $table table name + * @param string $column column name + * @return string $sql sql sentence */ - public function generateDropColumnSQL($sTable, $sColumn) + public function generateDropColumnSQL($table, $column) { - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' DROP COLUMN ' . $this->sQuoteCharacter . $sColumn . $this->sQuoteCharacter . $this->sEndLine; - return $sSQL; + $sql = 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' DROP COLUMN ' . $this->sQuoteCharacter . $column . $this->sQuoteCharacter; + return $sql; } /** * This method has to refactor - * @param $sTable - * @param $sColumn - * @param $aParameters + * @param string $table + * @param string $column + * @param string $parameters * @return string */ - public function generateCheckAddColumnSQL($sTable, $sColumn, $aParameters) + public function generateCheckAddColumnSQL($table, $column, $parameters) { - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' DROP PRIMARY KEY '; - $sSQL .= $this->sEndLine; - return $sSQL; + return 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' DROP PRIMARY KEY '; } /** * This method has to refactor - * @param $sTable - * @param $sColumn - * @param $aParameters + * @param string $table + * @param string $column + * @param string $parameters * @return string */ - public function deleteAllIndexesIntable($sTable, $sColumn, $aParameters) + public function deleteAllIndexesIntable($table, $column = null, $parameters = null) { - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' DROP INDEX indexLoginLog '; - $sSQL .= $this->sEndLine; - return $sSQL; + return 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' DROP INDEX indexLoginLog '; } /** * This method is used exclusively to verify if it was made changes in the DB to solve the HOR-1787 issue, later * a generic method which covers all the possible similar problems found in the HOR-1787 issue will be generated. - * @param $sTable - * @param $sColumn - * @param $aParameters + * @param string $table + * @param string $column + * @param array $parameters * @return bool */ - public function checkPatchHor1787($sTable, $sColumn, $aParameters) + public function checkPatchHor1787($table, $column = null, $parameters = []) { - if (isset($aParameters['AutoIncrement']) && $aParameters['AutoIncrement'] && $sTable == 'LOGIN_LOG') { + if (isset($parameters['AutoIncrement']) && $parameters['AutoIncrement'] && $table == 'LOGIN_LOG') { return true; } return false; @@ -185,208 +226,199 @@ class database extends database_base /** * generate an add column sentence * - * @param $sTable table name - * @param $sColumn column name - * @param $aParameters parameters of field like typo or if it can be null - * @return $sSql sql sentence + * @param string $table table name + * @param string $column column name + * @param array $parameters parameters of field like typo or if it can be null + * @return string $sql sql sentence */ - public function generateAddColumnSQL($sTable, $sColumn, $aParameters) + public function generateAddColumnSQL($table, $column, $parameters) { - if (isset($aParameters['Type']) && isset($aParameters['Null'])) { - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' ADD COLUMN ' . $this->sQuoteCharacter . $sColumn . $this->sQuoteCharacter . ' ' . $aParameters['Type']; - if ($aParameters['Null'] == 'YES') { - $sSQL .= ' NULL'; + $sql = ''; + if (isset($parameters['Type']) && isset($parameters['Null'])) { + $sql = 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' ADD COLUMN ' . $this->sQuoteCharacter . $column . $this->sQuoteCharacter . ' ' . $parameters['Type']; + if ($parameters['Null'] == 'YES') { + $sql .= ' NULL'; } else { - $sSQL .= ' NOT NULL'; + $sql .= ' NOT NULL'; } } - if (isset($aParameters['AutoIncrement']) && $aParameters['AutoIncrement']) { - $sSQL .= ' AUTO_INCREMENT'; + if (isset($parameters['AutoIncrement']) && $parameters['AutoIncrement']) { + $sql .= ' AUTO_INCREMENT'; } - if (isset($aParameters['PrimaryKey']) && $aParameters['PrimaryKey']) { - $sSQL .= ' PRIMARY KEY'; + if (isset($parameters['PrimaryKey']) && $parameters['PrimaryKey']) { + $sql .= ' PRIMARY KEY'; } - if (isset($aParameters['Unique']) && $aParameters['Unique']) { - $sSQL .= ' UNIQUE'; + if (isset($parameters['Unique']) && $parameters['Unique']) { + $sql .= ' UNIQUE'; } //we need to check the property AI - if (isset($aParameters['AI'])) { - if ($aParameters['AI'] == 1) { - $sSQL .= ' AUTO_INCREMENT'; + if (isset($parameters['AI'])) { + if ($parameters['AI'] == 1) { + $sql .= ' AUTO_INCREMENT'; } else { - if ($aParameters['Default'] != '') { - $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; + if ($parameters['Default'] != '') { + $sql .= " DEFAULT '" . $parameters['Default'] . "'"; } } } else { - if (isset($aParameters['Default'])) { - $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; + if (isset($parameters['Default'])) { + $sql .= " DEFAULT '" . $parameters['Default'] . "'"; } } - $sSQL .= $this->sEndLine; - return $sSQL; + return $sql; } /** * generate a change column sentence * - * @param $sTable table name - * @param $sColumn column name - * @param $aParameters parameters of field like typo or if it can be null - * @param $sColumnNewName column new name - * @return $sSql sql sentence + * @param string $table table name + * @param string $column column name + * @param array $parameters parameters of field like typo or if it can be null + * @param string $columnNewName column new name + * + * @return string $sql sql sentence */ - public function generateChangeColumnSQL($sTable, $sColumn, $aParameters, $sColumnNewName = '') + public function generateChangeColumnSQL($table, $column, $parameters, $columnNewName = '') { - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' CHANGE COLUMN ' . $this->sQuoteCharacter . ($sColumnNewName != '' ? $sColumnNewName : $sColumn) . $this->sQuoteCharacter . ' ' . $this->sQuoteCharacter . $sColumn . $this->sQuoteCharacter; - if (isset($aParameters['Type'])) { - $sSQL .= ' ' . $aParameters['Type']; + $sql = 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' CHANGE COLUMN ' . $this->sQuoteCharacter . ($columnNewName != '' ? $columnNewName : $column) . $this->sQuoteCharacter . ' ' . $this->sQuoteCharacter . $column . $this->sQuoteCharacter; + if (isset($parameters['Type'])) { + $sql .= ' ' . $parameters['Type']; } - if (isset($aParameters['Null'])) { - if ($aParameters['Null'] == 'YES') { - $sSQL .= ' NULL'; + if (isset($parameters['Null'])) { + if ($parameters['Null'] === 'YES') { + $sql .= ' NULL'; } else { - $sSQL .= ' NOT NULL'; + $sql .= ' NOT NULL'; } } - //if (isset($aParameters['AI'])) { - // if ($aParameters['AI'] == 1) { - // $sSQL .= ' AUTO_INCREMENT'; - // } - // else { - // if (isset($aParameters['Default'])) { - // if ($aParameters['Default'] != '') { - // $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; - // } - // } - // } - //} - //else { - if (isset($aParameters['Default'])) { - if (trim($aParameters['Default']) == '' && $aParameters['Type'] == 'datetime') { + + if (isset($parameters['Default'])) { + if (empty(trim($parameters['Default'])) && $parameters['Type'] === 'datetime') { //do nothing } else { - $sSQL .= " DEFAULT '" . $aParameters['Default'] . "'"; + $sql .= " DEFAULT '" . $parameters['Default'] . "'"; } - //} } - if (!isset($aParameters['Default']) && isset($aParameters['Null']) && $aParameters['Null'] == 'YES') { - $sSQL .= " DEFAULT NULL "; + if (!isset($parameters['Default']) && isset($parameters['Null']) && $parameters['Null'] === 'YES') { + $sql .= ' DEFAULT NULL '; } - //} - $sSQL .= $this->sEndLine; - return $sSQL; + return $sql; } /** * Generate and get the primary key in a sentence * - * @param $sTable table name - * @return $sSql sql sentence + * @param string $table table name + * @return string $sql sql sentence + * @throws Exception */ - public function generateGetPrimaryKeysSQL($sTable) + public function generateGetPrimaryKeysSQL($table) { try { - if ($sTable == '') { + if (empty($table)) { throw new Exception('The table name cannot be empty!'); } - return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' WHERE Seq_in_index = 1' . $this->sEndLine; - } catch (Exception $oException) { - throw $oException; + return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' WHERE Seq_in_index = 1'; + } catch (Exception $exception) { + throw $exception; } } /** * generate a sentence to drop the primary key * - * @param $sTable table name - * @return sql sentence + * @param string $table table name + * @return string sql sentence + * @throws Exception */ - public function generateDropPrimaryKeysSQL($sTable) + public function generateDropPrimaryKeysSQL($table) { try { - if ($sTable == '') { + if (empty($table)) { throw new Exception('The table name cannot be empty!'); } - return 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' DROP PRIMARY KEY' . $this->sEndLine; - } catch (Exception $oException) { - throw $oException; + return 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' DROP PRIMARY KEY'; + } catch (Exception $exception) { + throw $exception; } } /** * generate a sentence to add multiple primary keys * - * @param $sTable table name - * @param $aPrimaryKeys array of primary keys - * @return sql sentence + * @param string $table table name + * @param array $primaryKeys array of primary keys + * @return string sql sentence + * @throws Exception */ - public function generateAddPrimaryKeysSQL($sTable, $aPrimaryKeys) + public function generateAddPrimaryKeysSQL($table, $primaryKeys) { try { - if ($sTable == '') { + if (empty($table)) { throw new Exception('The table name cannot be empty!'); } - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' ADD PRIMARY KEY ('; - foreach ($aPrimaryKeys as $sKey) { - $sSQL .= $this->sQuoteCharacter . $sKey . $this->sQuoteCharacter . ','; + $sql = 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' ADD PRIMARY KEY ('; + foreach ($primaryKeys as $key) { + $sql .= $this->sQuoteCharacter . $key . $this->sQuoteCharacter . ','; } - $sSQL = substr($sSQL, 0, -1) . ')' . $this->sEndLine; - return $sSQL; - } catch (Exception $oException) { - throw $oException; + $sql = substr($sql, 0, -1) . ')'; + return $sql; + } catch (Exception $exception) { + throw $exception; } } /** * generate a sentence to drop an index * - * @param $sTable table name - * @param $sIndexName index name - * @return sql sentence + * @param string $table table name + * @param string $indexName index name + * @return string sql sentence + * @throws Exception */ - public function generateDropKeySQL($sTable, $sIndexName) + public function generateDropKeySQL($table, $indexName) { try { - if ($sTable == '') { + if (empty($table)) { throw new Exception('The table name cannot be empty!'); } - if ($sIndexName == '') { + if (empty($indexName)) { throw new Exception('The column name cannot be empty!'); } - return 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' DROP INDEX ' . $this->sQuoteCharacter . $sIndexName . $this->sQuoteCharacter . $this->sEndLine; - } catch (Exception $oException) { - throw $oException; + return 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' DROP INDEX ' . $this->sQuoteCharacter . $indexName . $this->sQuoteCharacter; + } catch (Exception $exception) { + throw $exception; } } /** * generate a sentence to add indexes or primary keys * - * @param $sTable table name - * @param $indexName index name - * @param $aKeys array of keys - * @return sql sentence + * @param string $table table name + * @param string $indexName index name + * @param array $keys array of keys + * @return string sql sentence + * @throws Exception */ - public function generateAddKeysSQL($sTable, $indexName, $aKeys) + public function generateAddKeysSQL($table, $indexName, $keys) { try { $indexType = 'INDEX'; - if ($indexName == 'primaryKey' || $indexName == 'PRIMARY') { + if ($indexName === 'primaryKey' || $indexName === 'PRIMARY') { $indexType = 'PRIMARY'; $indexName = 'KEY'; } - $sSQL = 'ALTER TABLE ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . ' ADD ' . $indexType . ' ' . $indexName . ' ('; - foreach ($aKeys as $sKey) { - $sSQL .= $this->sQuoteCharacter . $sKey . $this->sQuoteCharacter . ', '; + $sql = 'ALTER TABLE ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' ADD ' . $indexType . ' ' . $indexName . ' ('; + foreach ($keys as $key) { + $sql .= $this->sQuoteCharacter . $key . $this->sQuoteCharacter . ', '; } - $sSQL = substr($sSQL, 0, -2); - $sSQL .= ')' . $this->sEndLine; - return $sSQL; - } catch (Exception $oException) { - throw $oException; + $sql = substr($sql, 0, -2); + $sql .= ')'; + return $sql; + } catch (Exception $exception) { + throw $exception; } } @@ -397,85 +429,76 @@ class database extends database_base */ public function generateShowTablesSQL() { - return 'SHOW TABLES' . $this->sEndLine; + return 'SHOW TABLES'; } /** * generate a sentence to show the tables with a like sentence * - * @return sql sentence + * @return string sql sentence */ - public function generateShowTablesLikeSQL($sTable) + public function generateShowTablesLikeSQL($table) { - return "SHOW TABLES LIKE '" . $sTable . "'" . $this->sEndLine; + return "SHOW TABLES LIKE '" . $table . "'"; } /** * generate a sentence to show the tables with a like sentence * - * @param $sTable table name - * @return sql sentence + * @param string $table table name + * @return string sql sentence + * @throws Exception */ - public function generateDescTableSQL($sTable) + public function generateDescTableSQL($table) { try { - if ($sTable == '') { + if (empty($table)) { throw new Exception('The table name cannot be empty!'); } - return 'DESC ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . $this->sEndLine; - } catch (Exception $oException) { - throw $oException; + return 'DESC ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter; + } catch (Exception $exception) { + throw $exception; } } /** * generate a sentence to show some table indexes * - * @param $sTable table name - * @return sql sentence + * @param string $table table name + * @return string sql sentence */ - public function generateTableIndexSQL($sTable) + public function generateTableIndexSQL($table) { - return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . " " . $this->sEndLine; - //return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $sTable . $this->sQuoteCharacter . " WHERE Key_name <> 'PRIMARY'" . $this->sEndLine; + return 'SHOW INDEX FROM ' . $this->sQuoteCharacter . $table . $this->sQuoteCharacter . ' '; } /** * execute a sentence to check if there is connection * - * @return void + * @return boolean */ public function isConnected() { - $connect = false; - if ($this->oConnection !== false) { - $this->executeQuery('USE ' . $this->sDataBase); - $connect = true; - } - return $connect; + return $this->oConnection; } /** * generate a sentence to show the tables with a like sentence * - * @param $sQuery sql query string - * @return void + * @param string $query sql query string */ - public function logQuery($sQuery) + public function logQuery($query) { try { $found = false; - if (substr($sQuery, 0, 6) == 'SELECT') { - $found = true; - } - if (substr($sQuery, 0, 4) == 'SHOW') { - $found = true; - } - if (substr($sQuery, 0, 4) == 'DESC') { - $found = true; - } - if (substr($sQuery, 0, 4) == 'USE ') { + if (substr($query, 0, 6) === 'SELECT') { $found = true; + } else { + $option = substr($query, 0, 4); + $options = ['SHOW', 'DESC', 'USE ']; + if (in_array($option, $options, true)) { + $found = true; + } } if (!$found) { $logDir = PATH_DATA . 'log'; @@ -487,65 +510,45 @@ class database extends database_base $logFile = "$logDir/query.log"; $fp = fopen($logFile, 'a+'); if ($fp !== false) { - fwrite($fp, date("Y-m-d H:i:s") . " " . $this->sDataBase . " " . $sQuery . "\n"); + fwrite($fp, date('Y-m-d H:i:s') . ' ' . $this->sDataBase . ' ' . $query . "\n"); fclose($fp); } } - } catch (Exception $oException) { + } catch (Exception $exception) { } } /** * execute a sql query * - * @param $sQuery table name - * @return void + * @param string $query + * @return array + * @throws Exception */ - public function executeQuery($sQuery) + public function executeQuery($query) { - $this->logQuery($sQuery); + $this->logQuery($query); try { - if ($this->oConnection) { - mysqli_select_db($this->oConnection, $this->sDataBase); - $result = mysqli_query($this->oConnection, $sQuery); - mysqli_use_result($this->oConnection); - return $result; - } else { + if (!$this->oConnection) { throw new Exception('invalid connection to database ' . $this->sDataBase); } - } catch (Exception $oException) { - $this->logQuery($oException->getMessage()); - throw $oException; + $result = DB::connection($this->getNameConnection()) + ->select($query); + $result = array_map(function ($value) { + $data = (array)$value; + if ($this->iFetchType === 2) { + $data = $data[key($data)]; + } + return $data; + }, $result); + return $result; + } catch (Exception $exception) { + $this->logQuery($exception->getMessage()); + return []; } } - /** - * count the rows of a dataset - * - * @param $oDataset - * @return the number of rows - */ - public function countResults($oDataset) - { - return mysqli_num_rows($oDataset); - } - - /** - * count an array of the registry from a dataset - * - * @param $dataSet - * @return the registry - */ - public function getRegistry($dataSet) - { - $response = null; - if ($dataSet !== false) { - $response = mysqli_fetch_array($dataSet, $this->iFetchType); - } - return $response; - } - /** * close the current connection * @@ -553,50 +556,66 @@ class database extends database_base */ public function close() { - mysqli_close($this->oConnection); + if ($this->getNameConnection() !== 'workflow') { + DB::disconnect($this->getNameConnection()); + } } + /** + * Generate sql insert + * + * @param string $table + * @param array $data + * @return string + */ public function generateInsertSQL($table, $data) { - $fields = array(); - $values = array(); + $fields = []; + $values = []; foreach ($data as $field) { $fields[] = $field['field']; if (!is_null($field['value'])) { switch ($field['type']) { case 'text': case 'date': - $values[] = "'" . mysqli_real_escape_string($this->oConnection, $field['value']) . "'"; + $values[] = "'" . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']) . "'"; break; case 'int': default: - $values[] = mysqli_real_escape_string($this->oConnection, $field['value']); + $values[] = DB::connection($this->getNameConnection())->getPdo()->quote($field['value']); break; } } else { $values[] = $this->nullString; } } - $fields = array_map(array($this, 'putQuotes' - ), $fields); + $fields = array_map([$this, 'putQuotes'], $fields); $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $this->putQuotes($table), implode(', ', $fields), implode(', ', $values)); return $sql; } + /** + * Generate update sql + * + * @param string $table + * @param array $keys + * @param array $data + * @return string + */ public function generateUpdateSQL($table, $keys, $data) { - $fields = array(); - $where = array(); + $fields = []; + $where = []; foreach ($data as $field) { if (!is_null($field['value'])) { switch ($field['type']) { case 'text': case 'date': - $fields[] = $this->putQuotes($field['field']) . " = '" . mysqli_real_escape_string($this->oConnection, $field['value']) . "'"; + $fields[] = $this->putQuotes($field['field']) . " = '" . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']) . "'"; break; case 'int': default: - $fields[] = $this->putQuotes($field['field']) . " = " . mysqli_real_escape_string($this->oConnection, $field['value']); + $fields[] = $this->putQuotes($field['field']) . " = " . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']); break; } } else { @@ -610,21 +629,29 @@ class database extends database_base return $sql; } + /** + * Generate delete table + * + * @param string $table + * @param array $keys + * @param array $data + * @return string + */ public function generateDeleteSQL($table, $keys, $data) { - $fields = array(); - $where = array(); + $fields = []; + $where = []; foreach ($data as $field) { if (in_array($field['field'], $keys)) { if (!is_null($field['value'])) { switch ($field['type']) { case 'text': case 'date': - $where[] = $this->putQuotes($field['field']) . " = '" . mysqli_real_escape_string($this->oConnection, $field['value']) . "'"; + $where[] = $this->putQuotes($field['field']) . " = '" . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']) . "'"; break; case 'int': default: - $where[] = $this->putQuotes($field['field']) . " = " . mysqli_real_escape_string($this->oConnection, $field['value']); + $where[] = $this->putQuotes($field['field']) . " = " . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']); break; } } else { @@ -636,21 +663,29 @@ class database extends database_base return $sql; } + /** + * Generate sql select + * + * @param string $table + * @param array $keys + * @param array $data + * @return string + */ public function generateSelectSQL($table, $keys, $data) { - $fields = array(); - $where = array(); + $fields = []; + $where = []; foreach ($data as $field) { if (in_array($field['field'], $keys)) { if (!is_null($field['value'])) { switch ($field['type']) { case 'text': case 'date': - $where[] = $this->putQuotes($field['field']) . " = '" . mysqli_real_escape_string($this->oConnection, $field['value']) . "'"; + $where[] = $this->putQuotes($field['field']) . " = '" . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']) . "'"; break; case 'int': default: - $where[] = $this->putQuotes($field['field']) . " = " . mysqli_real_escape_string($this->oConnection, $field['value']); + $where[] = $this->putQuotes($field['field']) . " = " . DB::connection($this->getNameConnection())->getPdo()->quote($field['value']); break; } } else { @@ -675,25 +710,25 @@ class database extends database_base * author Hector Cortez * date 2010-08-04 * - * @return string $sConcat + * @return string $concat */ public function concatString() { $nums = func_num_args(); $vars = func_get_args(); - $sConcat = " CONCAT("; + $concat = ' CONCAT('; for ($i = 0; $i < $nums; $i++) { if (isset($vars[$i])) { - $sConcat .= $vars[$i]; + $concat .= $vars[$i]; if (($i + 1) < $nums) { - $sConcat .= ", "; + $concat .= ', '; } } } - $sConcat .= ")"; + $concat .= ')'; - return $sConcat; + return $concat; } /* @@ -711,8 +746,7 @@ class database extends database_base */ public function getCaseWhen($compareValue, $trueResult, $falseResult) { - $sCompare = "IF(" . $compareValue . ", " . $trueResult . ", " . $falseResult . ") "; - return $sCompare; + return 'IF(' . $compareValue . ', ' . $trueResult . ', ' . $falseResult . ') '; } /** @@ -725,7 +759,7 @@ class database extends database_base */ public function createTableObjectPermission() { - $sql = "CREATE TABLE IF NOT EXISTS `OBJECT_PERMISSION` ( + return "CREATE TABLE IF NOT EXISTS `OBJECT_PERMISSION` ( `OP_UID` varchar(32) NOT NULL, `PRO_UID` varchar(32) NOT NULL, `TAS_UID` varchar(32) NOT NULL, @@ -737,8 +771,7 @@ class database extends database_base `OP_OBJ_UID` varchar(32) NOT NULL, `OP_ACTION` varchar(10) NOT NULL default 'VIEW', KEY `PRO_UID` (`PRO_UID`,`TAS_UID`,`USR_UID`,`OP_TASK_SOURCE`,`OP_OBJ_UID`) - )ENGINE=InnoDB DEFAULT CHARSET=latin1;"; - return $sql; + )ENGINE=InnoDB DEFAULT CHARSET=latin1"; } /* @@ -857,42 +890,80 @@ class database extends database_base * query functions for class class.net.php * */ - public function getServerVersion($driver, $dbIP, $dbPort, $dbUser, $dbPasswd, $dbSourcename) + /** + * Version mysql + * + * @param string $driver + * @param string $host + * @param string $port + * @param string $user + * @param string $pass + * @param string $database + * @return string version mysql + * @throws Exception + */ + public function getServerVersion($driver, $host, $port, $user, $pass, $database) { - if ($link = mysqli_connect($dbIP, $dbUser, $dbPasswd, $dbSourcename)) { - $v = mysqli_get_server_info($link); - } else { - throw new Exception(mysqli_error($link)); + try { + $connection = 'TEST_VERSION'; + InstallerModule::setNewConnection($connection, $host, $user, $pass, $database, $port); + + $results = DB::connection($connection) + ->select(DB::raw('select version()')); + + preg_match($this->getRegexVersionMysql(), $results[0]->{'version()'}, $version); + + DB::disconnect($connection); + + return $version[0]; + + } catch (Exception $exception) { + throw new Exception($exception->getMessage()); } - return (isset($v)) ? $v : 'none'; } /* * query functions for class class.net.php, class.reportTables.php * */ - public function getDropTable($sTableName) + + /** + * Generate drop table + * + * @param string $tableName + * @return string sql + */ + public function getDropTable($tableName) { - $sql = 'DROP TABLE IF EXISTS `' . $sTableName . '`'; - return $sql; + return 'DROP TABLE IF EXISTS `' . $tableName . '`'; } - public function getTableDescription($sTableName) + /** + * Generate Description table + * + * @param string $tableName + * @return string sql + */ + public function getTableDescription($tableName) { - $sql = "DESC " . $sTableName; - return $sql; + return 'DESC ' . $tableName; } + /** + * @return string + */ public function getFieldNull() { - $fieldName = "Null"; - return $fieldName; + return 'Null'; } + /** + * @param $validate + * @return mixed + */ public function getValidate($validate) { - $oValidate = $validate; - return $oValidate; + return $validate; } /** @@ -901,23 +972,24 @@ class database extends database_base */ public function reportTableExist() { - $filter = new InputFilter(); - $DB_NAME = $filter->validateInput(DB_NAME); - $bExists = true; - $oConnection = mysqli_connect(DB_HOST, DB_USER, DB_PASS); - mysqli_select_db($oConnection, $DB_NAME); - $oDataset = mysqli_query($oConnection, 'SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false); - - return $bExists; + $result = DB::select("show tables like 'REPORT_TABLE'"); + return count($result) > 0; } /** * It is part of class.pagedTable.php */ - public function getLimitRenderTable($nCurrentPage, $nRowsPerPage) + + /** + * Generate limit sql + * + * @param int $currentPage + * @param int $rowsPerPage + * @return string + */ + public function getLimitRenderTable($currentPage, $rowsPerPage) { - $sql = ' LIMIT ' . (($nCurrentPage - 1) * $nRowsPerPage) . ', ' . $nRowsPerPage; - return $sql; + return ' LIMIT ' . (($currentPage - 1) * $rowsPerPage) . ', ' . $rowsPerPage; } /** @@ -930,15 +1002,14 @@ class database extends database_base */ public function tableExists($tableName, $database) { - mysqli_select_db($this->oConnection, $database); - $tables = array(); - $tablesResult = mysqli_query($this->oConnection, "SHOW TABLES FROM $database;"); - while ($row = mysqli_fetch_row($tablesResult)) { - $tables[] = $row[0]; + try { + $result = DB::connect($this->getNameConnection()) + ->select("show tables like '$tableName'"); + $flag = count($result) > 0; + + } catch (\Illuminate\Database\QueryException $exception) { + $flag = false; } - if (in_array($tableName, $tables)) { - return true; - } - return false; + return $flag; } } diff --git a/gulliver/system/class.dbMaintenance.php b/gulliver/system/class.dbMaintenance.php index 7184ac386..cfa1ce711 100644 --- a/gulliver/system/class.dbMaintenance.php +++ b/gulliver/system/class.dbMaintenance.php @@ -1,83 +1,53 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ +use Illuminate\Database\QueryException; +use Illuminate\Support\Facades\DB; /** * * * Database Maintenance class * - * author Erik A. Ortiz - * date May 17th, 2010 * * @package gulliver.system */ class DataBaseMaintenance { - private $host; - private $user; - private $passwd; + private $host = null; + private $user = null; + private $passwd = null; - private $link; - private $dbName; + private $connect = null; + private $dbName = null; public $result; - protected $tmpDir; + protected $tmpDir = null; protected $outfile; protected $infile; protected $isWindows; /** - * __construct + * DataBaseMaintenance constructor. * - * @param string $host is null - * @param string $user is null - * @param string $passwd is null + * @param string $host + * @param string $user + * @param string $passwd * - * @return none */ public function __construct($host = null, $user = null, $passwd = null) { $this->tmpDir = './'; - $this->link = null; - $this->dbName = null; + $this->setConnection(null); + $this->setDbName(null); $this->isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; - if (isset($host) && isset($user) && isset($passwd)) { - $this->host = $host; - $this->user = $user; - $this->passwd = $passwd; - } + $this->setUser($user); + $this->setHost($host); + $this->setPasswd($passwd); } /** * setUser * * @param string $user - * - * @return none */ public function setUser($user) { @@ -85,11 +55,9 @@ class DataBaseMaintenance } /** - * setPasswd + * Set Password * * @param string $passwd - * - * @return none */ public function setPasswd($passwd) { @@ -97,11 +65,9 @@ class DataBaseMaintenance } /** - * setHost + * Set Host * * @param string $host - * - * @return none */ public function setHost($host) { @@ -109,11 +75,9 @@ class DataBaseMaintenance } /** - * setTempDir + * Set TempDir * * @param string $tmpDir - * - * @return none */ public function setTempDir($tmpDir) { @@ -124,7 +88,64 @@ class DataBaseMaintenance } /** - * getTempDir + * Set Db Name + * + * @param $dbName + */ + public function setDbName($dbName) + { + $this->dbName = $dbName; + } + + /** + * Set Connection + * + * @param $name + */ + public function setConnection($name) + { + $this->connect = 'DB_' . $name; + } + + /** + * Get User + * @return string + */ + public function getUser() + { + return $this->user; + } + + /** + * Get Password + * @return string + */ + public function getPasswd() + { + return $this->passwd; + } + + /** + * Get Host + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * Get Name Connection + * + * @return string + */ + public function getConnect() + { + return $this->connect; + } + + /** + * get TempDir * * @return $this->tmpDir */ @@ -134,116 +155,74 @@ class DataBaseMaintenance } /** - * status + * Get Name DB * - * @return $this->link + * @return string */ - public function status() + public function getDbName() { - return $$this->link; + return $this->dbName; } /** - * connect + * Connect to DB * - * @param string $dbname is null - * - * @return none - */ - public function connect($dbname = null) - { - if ($this->link != null) { - mysqli_close($this->link); - $this->link = null; - } - if (isset($dbname)) { - $this->dbName = $dbname; - } - - $this->link = mysqli_connect($this->host, $this->user, $this->passwd, $this->dbName); - if (!$this->link) { - throw new Exception("Couldn't connect to host {$this->host} with user {$this->user}"); - } - mysqli_query($this->link, "SET NAMES 'utf8';"); - mysqli_query($this->link, "SET FOREIGN_KEY_CHECKS=0;"); - - if ($this->dbName != null) { - $this->selectDataBase($this->dbName); - } - } - - /** - * setDbName - * - * @param string $dbname is null - * - * @return none - */ - public function setDbName($dbname) - { - $this->dbName = $dbname; - } - - /** - * selectDataBase - * - * @param string $dbname - * @param $dbname + * @param string $dbName * * @throws Exception */ - public function selectDataBase($dbname) + public function connect($dbName) { - $this->setDbName($dbname); - if (!mysqli_select_db($this->link, $this->dbName)) { - throw new Exception("Couldn't select database $dbname"); + try { + $this->setConnection($dbName); + $this->setDbName($dbName); + InstallerModule::setNewConnection( + $this->getConnect(), + $this->getHost(), + $this->getUser(), + $this->getPasswd(), + $this->getDbName(), + ''); + + DB::connection($this->getConnect()) + ->statement("SET NAMES 'utf8'"); + DB::connection($this->getConnect()) + ->statement('SET FOREIGN_KEY_CHECKS=0'); + + } catch (QueryException $exception) { + throw new Exception("Couldn't connect to host {$this->getHost()} with user {$this->getUser()}" . $exception->getMessage()); } } /** - * query + * Query * * @param string $sql * - * @return $aRows + * @return array + * @throws Exception */ public function query($sql) { - $this->result = mysqli_query($this->link, $sql); - if ($this->result) { - $aRows = []; - while ($aRow = mysqli_fetch_assoc($this->result)) { - $aRows[] = $aRow; - } - return $aRows; - } else { - return false; + try { + $result = DB::connection($this->getConnect()) + ->select($sql); + + return $result; + } catch (QueryException $exception) { + throw new Exception("Couldn't connect to host {$this->getHost()} with user {$this->getUser()}" . $exception->getMessage()); } } /** - * error - * - * @return mysqli_error() - */ - public function error() - { - return mysqli_error($this->link); - } - - /** - * getTablesList + * get Tables List * * @return array + * @throws Exception */ public function getTablesList() { - $this->result = mysqli_query($this->link, 'SHOW TABLES;'); - $rows = []; - while ($row = mysqli_fetch_row($this->result)) { - $rows[] = $row[0]; - } - return $rows; + return $this->query('SHOW TABLES'); } /** @@ -255,25 +234,26 @@ class DataBaseMaintenance */ public function dumpData($table) { - $this->outfile = $this->tmpDir . $table . '.dump'; + try { + $this->outfile = $this->tmpDir . $table . '.dump'; - //if the file exists delete it - if (is_file($this->outfile)) { - @unlink($this->outfile); - } + //if the file exists delete it + if (is_file($this->outfile)) { + @unlink($this->outfile); + } - $sql = "SELECT * INTO OUTFILE '{$this->outfile}' FIELDS TERMINATED BY '\t|\t' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\t\t\r\r\n' FROM $table"; - // The mysql_escape_string function has been DEPRECATED as of PHP 5.3.0. - // Commented that is not assigned to a variable. - // mysql_escape_string("';"); - if (!@mysqli_query($this->link, $sql)) { + $sql = "SELECT * INTO OUTFILE '{$this->outfile}' FIELDS TERMINATED BY '\t|\t' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\t\t\r\r\n' FROM $table"; + + DB::connection($this->getConnect())->raw($sql); + + return true; + } catch (QueryException $exception) { $ws = (!empty(config('system.workspace'))) ? config('system.workspace') : 'Undefined Workspace'; - Bootstrap::registerMonolog('MysqlCron', 400, mysqli_error($this->link), ['sql' => $sql], $ws, 'processmaker.log'); - $varRes = mysqli_error($this->link) . "\n"; + Bootstrap::registerMonolog('MysqlCron', 400, $exception->getMessage(), ['sql' => $sql], $ws, 'processmaker.log'); + $varRes = $exception->getMessage() . "\n"; G::outRes($varRes); return false; } - return true; } /** @@ -285,16 +265,20 @@ class DataBaseMaintenance */ public function restoreData($backupFile) { - $tableName = str_replace('.dump', '', basename($backupFile)); - $sql = "LOAD DATA INFILE '$backupFile' INTO TABLE $tableName FIELDS TERMINATED BY '\t|\t' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\t\t\r\r\n'"; - if (!@mysqli_query($this->link, $sql)) { + try { + $tableName = str_replace('.dump', '', basename($backupFile)); + $sql = "LOAD DATA INFILE '$backupFile' INTO TABLE $tableName FIELDS TERMINATED BY '\t|\t' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\t\t\r\r\n'"; + + DB::connection($this->getConnect())->raw($sql); + + return true; + } catch (QueryException $exception) { $ws = (!empty(config("system.workspace"))) ? config("system.workspace") : "Wokspace Undefined"; - Bootstrap::registerMonolog('MysqlCron', 400, mysqli_error($this->link), ['sql' => $sql], $ws, 'processmaker.log'); - $varRes = mysqli_error($this->link) . "\n"; + Bootstrap::registerMonolog('MysqlCron', 400, $exception->getMessage(), ['sql' => $sql], $ws, 'processmaker.log'); + $varRes = $exception->getMessage() . "\n"; G::outRes($varRes); return false; } - return true; } /** @@ -302,24 +286,22 @@ class DataBaseMaintenance * * @param string $type default value null * - * @return none + * @throws Exception */ public function restoreAllData($type = null) { - $aTables = $this->getTablesList(); - - foreach ($aTables as $table) { - if (isset($type) && $type == 'sql') { - $this->infile = $this->tmpDir . $table . ".sql"; + foreach ($this->getTablesList() as $table) { + if (isset($type) && $type === 'sql') { + $this->infile = $this->tmpDir . $table . '.sql'; if (is_file($this->infile)) { $queries = $this->restoreFromSql($this->infile, true); if (!isset($queries)) { - $queries = "unknown"; + $queries = 'unknown'; } printf("%-59s%20s", "Restored table $table", "$queries queries\n"); } } else { - $this->infile = $this->tmpDir . $table . ".dump"; + $this->infile = $this->tmpDir . $table . '.dump'; if (is_file($this->infile)) { $this->restoreData($this->infile); printf("%20s %s %s\n", 'Restoring data from ', $this->infile, " in table $table"); @@ -329,63 +311,27 @@ class DataBaseMaintenance } /** - * createDb + * Create DB * * @param string $dbname - * @param string $drop default value false + * @param boolean $drop * - * @return none + * @return bool + * @throws Exception */ public function createDb($dbname, $drop = false) { - if ($drop) { - $sql = "DROP DATABASE IF EXISTS $dbname;"; - if (!mysqli_query($this->link, $sql)) { - throw new Exception(mysqli_error($this->link)); + try { + if ($drop) { + DB::connection($this->getConnect())->statement("DROP DATABASE IF EXISTS $dbname"); } - } - $sql = "CREATE DATABASE IF NOT EXISTS $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"; - if (!mysqli_query($this->link, $sql)) { - throw new Exception(mysqli_error($this->link)); - } - } - /** - * restoreFromSql2 - * - * @param string $sqlfile - * - * @return none - */ - public function restoreFromSql2($sqlfile) - { - ini_set('memory_limit', '512M'); - if (!is_file($sqlfile)) { - throw new Exception("the $sqlfile doesn't exist!"); - } - $query = file_get_contents($sqlfile); - $mysqli = new mysqli($this->host, $this->user, $this->passwd, $this->dbName); + DB::connection($this->getConnect())->statement("CREATE DATABASE IF NOT EXISTS $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"); - /* check connection */ - if (mysqli_connect_errno()) { - printf("Connect failed: %s\n", mysqli_connect_error()); - exit(); + return true; + } catch (QueryException $exception) { + throw new Exception($exception->getMessage()); } - - /* execute multi query */ - if ($mysqli->multi_query($query)) { - do { - /* store first result set */ - if ($result = $mysqli->store_result()) { - while ($row = $result->fetch_row()) { - } - $result->free(); - } - } while ($mysqli->next_result()); - } - - /* close connection */ - $mysqli->close(); } /** @@ -397,36 +343,36 @@ class DataBaseMaintenance */ public function backupDataBase($outfile) { - $password = escapeshellarg($this->passwd); + $password = escapeshellarg($this->getPasswd()); //On Windows, escapeshellarg() instead replaces percent signs, exclamation //marks (delayed variable substitution) and double quotes with spaces and //adds double quotes around the string. //See: http://php.net/manual/en/function.escapeshellarg.php if ($this->isWindows) { - $password = $this->escapeshellargCustom($this->passwd); + $password = $this->escapeshellargCustom($this->getPasswd()); } - $aHost = explode(':', $this->host); + $aHost = explode(':', $this->getHost()); $dbHost = $aHost[0]; if (isset($aHost[1])) { $dbPort = $aHost[1]; $command = 'mysqldump' - . ' --user=' . $this->user + . ' --user=' . $this->getUser() . ' --password=' . $password . ' --host=' . $dbHost . ' --port=' . $dbPort . ' --opt' . ' --skip-comments' - . ' ' . $this->dbName + . ' ' . $this->getDbName() . ' > ' . $outfile; } else { $command = 'mysqldump' . ' --host=' . $dbHost - . ' --user=' . $this->user + . ' --user=' . $this->getUser() . ' --opt' . ' --skip-comments' . ' --password=' . $password - . ' ' . $this->dbName + . ' ' . $this->getDbName() . ' > ' . $outfile; } shell_exec($command); @@ -448,21 +394,21 @@ class DataBaseMaintenance */ private function escapeshellargCustom($string, $quotes = "") { - if ($quotes === "") { + if ($quotes === '') { $quotes = $this->isWindows ? "\"" : "'"; } $n = strlen($string); $special = ["!", "%", "\""]; - $substring = ""; + $substring = ''; $result1 = []; $result2 = []; for ($i = 0; $i < $n; $i++) { if (in_array($string[$i], $special, true)) { $result2[] = $string[$i]; $result1[] = $substring; - $substring = ""; + $substring = ''; } else { - $substring = $substring . $string[$i]; + $substring .= $string[$i]; } } $result1[] = $substring; @@ -471,43 +417,47 @@ class DataBaseMaintenance for ($i = 0; $i < $n; $i++) { $result1[$i] = trim(escapeshellarg($result1[$i]), $quotes); if (isset($result2[$i])) { - $result1[$i] = $result1[$i] . $result2[$i]; + $result1[$i] .= $result2[$i]; } } //add simple quotes, see escapeshellarg function - $newString = $quotes . implode("", $result1) . $quotes; + $newString = $quotes . implode('', $result1) . $quotes; return $newString; } /** - * restoreFromSql + * Restore from sql * - * @param string $sqlfile + * @param string $sqlFile + * @param string $type * * @return boolean false or true + * @throws Exception */ - public function restoreFromSql($sqlfile, $type = 'file') + public function restoreFromSql($sqlFile, $type = 'file') { ini_set('memory_limit', '64M'); - if ($type == 'file' && !is_file($sqlfile)) { - throw new Exception("the $sqlfile doesn't exist!"); + if ($type == 'file' && !is_file($sqlFile)) { + throw new Exception("the $sqlFile doesn't exist!"); } - $metaFile = str_replace('.sql', '.meta', $sqlfile); + $metaFile = str_replace('.sql', '.meta', $sqlFile); $queries = 0; if (is_file($metaFile)) { echo "Using $metaFile as metadata.\n"; - $fp = fopen($sqlfile, 'rb'); + $fp = fopen($sqlFile, 'rb'); $fpmd = fopen($metaFile, 'r'); while ($offset = fgets($fpmd, 1024)) { $buffer = intval($offset); //reading the size of $oData $query = fread($fp, $buffer); //reading string $oData - $queries += 1; + $queries++; - if (!mysqli_query($this->link, $query)) { - $varRes = mysqli_error($this->link) . "\n"; + try { + DB::connection($this->getConnect())->raw($query); + } catch (QueryException $exception) { + $varRes = $exception->getMessage() . "\n"; G::outRes($varRes); $varRes = "==>" . $query . "<==\n"; G::outRes($varRes); @@ -516,45 +466,25 @@ class DataBaseMaintenance } else { $queries = null; try { - $mysqli = new mysqli($this->host, $this->user, $this->passwd, $this->dbName); - /* check connection */ - if (mysqli_connect_errno()) { - printf("Connect failed: %s\n", mysqli_connect_error()); - exit(); - } + if ($type === 'file') { - $query = file_get_contents($sqlfile); + $query = file_get_contents($sqlFile); } elseif ($type === 'string') { - $query = $sqlfile; + $query = $sqlFile; } else { return false; } - if (trim($query) == "") { + if (empty(trim($query))) { return false; } - /* execute multi query */ - if ($mysqli->multi_query($query)) { - do { - /* store first result set */ - if ($result = $mysqli->store_result()) { - while ($row = $result->fetch_row()) { - //printf("%s\n", $row[0]); - } - $result->free(); - } - /* print divider */ - if ($mysqli->more_results()) { - //printf("-----------------\n"); - } - } while ($mysqli->next_result()); - } else { - throw new Exception(mysqli_error($mysqli)); + try { + DB::connection($this->getConnect())->raw($query); + } catch (QueryException $exception) { + throw new Exception($exception->getMessage()); } - /* close connection */ - $mysqli->close(); } catch (Exception $e) { echo $query; $token = strtotime("now"); @@ -574,19 +504,18 @@ class DataBaseMaintenance */ public function getSchemaFromTable($tablename) { - //$tableSchema = "/* Structure for table `$tablename` */\n"; - //$tableSchema .= "DROP TABLE IF EXISTS `$tablename`;\n\n"; - $tableSchema = ""; - $sql = "show create table `$tablename`; "; - $result = mysqli_query($this->link, $sql); - if ($result) { - if ($row = mysqli_fetch_assoc($result)) { - $tableSchema .= $row['Create Table'] . ";\n\n"; + try { + $tableSchema = ''; + $result = DB::connection($this->getConnect())->select("show create table `$tablename`"); + + if ($result) { + $tableSchema = $result['Create Table'] . ";\n\n"; } - mysqli_free_result($result); - } else { - G::outRes(mysqli_error($this->link)); + + } catch (QueryException $exception) { + G::outRes($exception->getMessage()); } + return $tableSchema; } diff --git a/workflow/engine/bin/tasks/cliUpgrade.php b/workflow/engine/bin/tasks/cliUpgrade.php index 6f3a455f4..3c80ad393 100644 --- a/workflow/engine/bin/tasks/cliUpgrade.php +++ b/workflow/engine/bin/tasks/cliUpgrade.php @@ -1,30 +1,6 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - * @author Alexandre Rosenfeld - * @package workflow-engine-bin-tasks - */ +use Illuminate\Support\Facades\DB; use ProcessMaker\Core\System; CLI::taskName('upgrade'); @@ -296,25 +272,24 @@ function run_unify_database($args) $metadata["version"] = 1; list($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); - $link = mysqli_connect($dbHost, $dbUser, $dbPass); + $connectionName = 'UPGRADE'; + InstallerModule::setNewConnection($connectionName, $dbHost, $dbUser, $dbPass,'', ''); foreach ($metadata['databases'] as $db) { $dbName = $metadata['DB_NAME']; CLI::logging("+> Restoring {$db['name']} to $dbName database\n"); - $aParameters = array('dbHost'=>$dbHost,'dbUser'=>$dbUser,'dbPass'=>$dbPass); + $aParameters = ['dbHost'=>$dbHost,'dbUser'=>$dbUser,'dbPass'=>$dbPass]; - $restore = $workspace->executeScript($dbName, "$tempDirectory/{$db['name']}.sql", $aParameters, $link); + $restore = $workspace->executeScript($dbName, "$tempDirectory/{$db['name']}.sql", $aParameters, $connectionName); if ($restore) { CLI::logging("+> Remove {$db['name']} database\n"); - $sql = "DROP DATABASE IF EXISTS {$db['name']};"; - if (!mysqli_query($link, $sql)) { - throw new Exception(mysqli_error($link)); - } + DB::connection($connectionName)->statement("DROP DATABASE IF EXISTS {$db['name']}"); } } + DB::disconnect($connectionName); CLI::logging("Removing temporary files\n"); G::rm_dir($tempDirectory); diff --git a/workflow/engine/classes/MultipleFilesBackup.php b/workflow/engine/classes/MultipleFilesBackup.php index c09a9dc48..8e06e5852 100644 --- a/workflow/engine/classes/MultipleFilesBackup.php +++ b/workflow/engine/classes/MultipleFilesBackup.php @@ -1,5 +1,7 @@ filename = $filename; } - if (!empty($size) && (int) $size > 0) { + if (!empty($size) && (int)$size > 0) { $this->fileSize = $size; } } @@ -91,6 +93,7 @@ class MultipleFilesBackup G::rm_dir($tempDirectory); } } + /* Restore from file(s) commpressed by letsBackup function, into a temporary directory * @ filename got the name and path of the compressed file(s), if there are many files with file extention as a numerical series, the extention should be discriminated. * @ srcWorkspace contains the workspace to be restored. @@ -162,14 +165,14 @@ class MultipleFilesBackup CLI::logging(CLI::warning("> Workspace $backupWorkspace found, but not restoring.") . "\n"); continue; } else { - CLI::logging("> Restoring " . CLI::info($backupWorkspace) . " to " . CLI::info($workspaceName) . "\n"); + CLI::logging('> Restoring ' . CLI::info($backupWorkspace) . ' to ' . CLI::info($workspaceName) . "\n"); } $workspace = new WorkspaceTools($workspaceName); if ($workspace->workspaceExists()) { if ($overwrite) { CLI::logging(CLI::warning("> Workspace $workspaceName already exist, overwriting!") . "\n"); } else { - throw new Exception("Destination workspace already exist (use -o to overwrite)"); + throw new Exception('Destination workspace already exist (use -o to overwrite)'); } } if (file_exists($workspace->path)) { @@ -196,31 +199,35 @@ class MultipleFilesBackup list($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); CLI::logging("> Connecting to system database in '$dbHost'\n"); - $link = mysqli_connect($dbHost, $dbUser, $dbPass); - mysqli_query($link, "SET NAMES 'utf8';"); - mysqli_query($link, "SET FOREIGN_KEY_CHECKS=0;"); - if (!$link) { - throw new Exception('Could not connect to system database: ' . mysqli_error($link)); + + try { + $connectionLestRestore = 'RESTORE'; + InstallerModule::setNewConnection($connectionLestRestore, $dbHost, $dbUser, $dbPass, '', ''); + DB::connection($connectionLestRestore) + ->statement("SET NAMES 'utf8'"); + DB::connection($connectionLestRestore) + ->statement('SET FOREIGN_KEY_CHECKS=0'); + } catch (Exception $exception) { + throw new Exception('Could not connect to system database: ' . $exception->getMessage()); } + + $onedb = false; if (strpos($metadata->DB_RBAC_NAME, 'rb_') === false) { $onedb = true; - } else { - $onedb = false; } $newDBNames = $workspace->resetDBInfo($dbHost, $createWorkspace, $onedb); - $aParameters = array('dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass); + $aParameters = ['dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass]; foreach ($metadata->databases as $db) { $dbName = $newDBNames[$db->name]; CLI::logging("+> Restoring database {$db->name} to $dbName\n"); - $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql", $aParameters, 1, $link); - $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName, $link); - $workspace->createDBUser($dbName, $db->pass, "%", $dbName, $link); + $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql", $aParameters, 1, $connectionLestRestore); + $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName, $connectionLestRestore); + $workspace->createDBUser($dbName, $db->pass, "%", $dbName, $connectionLestRestore); } $workspace->upgradeCacheView(false); - mysqli_close($link); } CLI::logging("Removing temporary files\n"); G::rm_dir($tempDirectory); diff --git a/workflow/engine/classes/Net.php b/workflow/engine/classes/Net.php index d2d50c67c..dd8e2232d 100644 --- a/workflow/engine/classes/Net.php +++ b/workflow/engine/classes/Net.php @@ -1,5 +1,7 @@ db_user) && (isset($this->db_passwd) || $this->db_passwd == "") && (isset($this->db_sourcename) || $flagTns == 1)) { switch ($pDbDriver) { case 'mysql': - // Note, we suppress warnings on the connection calls because we want to avoid displaying warning - // When utilizing this code in an API call. Otherwise it will return invalid JSON overall. - if ($this->db_passwd == '') { - $link = @mysqli_connect($this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_sourcename); - } else { - $link = @mysqli_connect($this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd, $this->db_sourcename); - } - if ($link) { - if (mysqli_ping($link)) { - $stat->status = 'SUCCESS'; - $this->errstr = ""; - $this->errno = 0; - } else { - $this->error = "Lost MySql Connection"; - $this->errstr = "NET::MYSQL->Lost Connection"; - $this->errno = 10010; - } - } else { - $this->error = "MySql connection refused!"; - $this->errstr = "NET::MYSQL->The connection was refused"; + + try { + InstallerModule::setNewConnection('NET', $this->ip, $this->db_user, $this->db_passwd, $this->db_sourcename, $this->db_port); + $stat->status = 'SUCCESS'; + $this->errstr = ''; + $this->errno = 0; + } catch (Exception $exception) { + $this->error = 'MySql connection refused!'; + $this->errstr = 'NET::MYSQL->The connection was refused'; $this->errno = 10001; } break; case 'pgsql': + //todo $this->db_port = ($this->db_port == "") ? "5432" : $this->db_port; $link = @pg_connect("host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'"); if ($link) { @@ -260,6 +252,7 @@ class Net } break; case 'mssql': + //todo if ($this->db_instance != "") { $str_port = ""; $link = @mssql_connect($this->ip . "\\" . $this->db_instance, $this->db_user, $this->db_passwd); @@ -279,6 +272,7 @@ class Net } break; case 'oracle': + //todo try { if ($flagTns == 0) { $this->db_port = ($this->db_port == "" || $this->db_port == 0) ? "1521" : $this->db_port; @@ -349,28 +343,23 @@ class Net if (isset($this->db_user) && (isset($this->db_passwd) || $this->db_passwd == "") && (isset($this->db_sourcename) || $flagTns == 1)) { switch ($pDbDriver) { case 'mysql': - $link = mysqli_connect($this->ip . (($this->db_port !== '') && ($this->db_port !== 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd, $this->db_sourcename); - $db = mysqli_select_db($link, $this->db_sourcename); - $this->error = 'MySql connection refused!'; - $this->errstr = 'NET::MYSQL->The connection was refused'; - $this->errno = 10001; + try { + $this->errstr = 'NET::MYSQL->The connection was refused'; + $this->errno = 10001; + $connection = 'NET_' . $this->db_sourcename; + InstallerModule::setNewConnection($connection, $this->ip, $this->db_user, $this->db_passwd, $this->db_sourcename, $this->db_port); - if ($link) { - $this->error = 'The $this->db_sourcename data base does\'n exist!'; - $this->errstr = 'NET::MYSQL->Select data base failed'; - $this->errno = 10011; - if ($db) { - $result = mysqli_query($link, 'show tables;'); - $this->error = 'the user $this->db_user doesn\'t have privileges to run queries!'; - $this->errstr = 'NET::MYSQL->Test query failed'; - $this->errno = 10100; - if ($result) { - $stat->status = 'SUCCESS'; - $this->errstr = ''; - $this->errno = 0; - mysqli_free_result($result); - } + $this->errstr = 'NET::MYSQL->Test query failed'; + $this->errno = 10100; + + $result = DB::connection($connection)->statement('show tables'); + if ($result) { + $stat->status = 'SUCCESS'; + $this->errstr = ''; + $this->errno = 0; } + } catch (Exception $exception) { + $this->error = $exception->getMessage(); } break; case 'pgsql': diff --git a/workflow/engine/classes/WorkspaceTools.php b/workflow/engine/classes/WorkspaceTools.php index 6ae26cd1e..6af1ad085 100644 --- a/workflow/engine/classes/WorkspaceTools.php +++ b/workflow/engine/classes/WorkspaceTools.php @@ -1,5 +1,7 @@ getDatabase($rbac); + $database = $this->getDatabase($rbac); - $aOldSchema = []; + $oldSchema = []; try { - $oDataBase->iFetchType = MYSQLI_NUM; - $oDataset1 = $oDataBase->executeQuery($oDataBase->generateShowTablesSQL()); + $database->iFetchType = MYSQLI_NUM; + $result = $database->executeQuery($database->generateShowTablesSQL()); } catch (Exception $e) { - $oDataBase->logQuery($e->getmessage()); + $database->logQuery($e->getmessage()); return null; } //going thru all tables in current WF_ database - while ($aRow1 = $oDataBase->getRegistry($oDataset1)) { - $aPrimaryKeys = []; - $sTable = strtoupper($aRow1[0]); + foreach ($result as $table) { + $table = strtoupper($table); //get description of each table, ( column and primary keys ) - //$oDataset2 = $oDataBase->executeQuery( $oDataBase->generateDescTableSQL($aRow1[0]) ); - $oDataset2 = $oDataBase->executeQuery($oDataBase->generateDescTableSQL($sTable)); - $aOldSchema[$sTable] = []; - $oDataBase->iFetchType = MYSQLI_ASSOC; - while ($aRow2 = $oDataBase->getRegistry($oDataset2)) { - $aOldSchema[$sTable][$aRow2['Field']]['Field'] = $aRow2['Field']; - $aOldSchema[$sTable][$aRow2['Field']]['Type'] = $aRow2['Type']; - $aOldSchema[$sTable][$aRow2['Field']]['Null'] = $aRow2['Null']; - $aOldSchema[$sTable][$aRow2['Field']]['Default'] = $aRow2['Default']; + $database->iFetchType = MYSQLI_ASSOC; + $description = $database->executeQuery($database->generateDescTableSQL($table)); + $oldSchema[$table] = []; + foreach ($description as $field) { + $oldSchema[$table][$field['Field']]['Field'] = $field['Field']; + $oldSchema[$table][$field['Field']]['Type'] = $field['Type']; + $oldSchema[$table][$field['Field']]['Null'] = $field['Null']; + $oldSchema[$table][$field['Field']]['Default'] = $field['Default']; } //get indexes of each table SHOW INDEX FROM `ADDITIONAL_TABLES`; -- WHERE Key_name <> 'PRIMARY' - $oDataset2 = $oDataBase->executeQuery($oDataBase->generateTableIndexSQL($aRow1[0])); - $oDataBase->iFetchType = MYSQLI_ASSOC; - while ($aRow2 = $oDataBase->getRegistry($oDataset2)) { - if (!isset($aOldSchema[$sTable]['INDEXES'])) { - $aOldSchema[$sTable]['INDEXES'] = []; + $description = $database->executeQuery($database->generateTableIndexSQL($table)); + foreach ($description as $field) { + if (!isset($oldSchema[$table]['INDEXES'])) { + $oldSchema[$table]['INDEXES'] = []; } - if (!isset($aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']])) { - $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']] = []; + if (!isset($oldSchema[$table]['INDEXES'][$field['Key_name']])) { + $oldSchema[$table]['INDEXES'][$field['Key_name']] = []; } - $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']][] = $aRow2['Column_name']; + $oldSchema[$table]['INDEXES'][$field['Key_name']][] = $field['Column_name']; } - $oDataBase->iFetchType = MYSQLI_NUM; //this line is neccesary because the next fetch needs to be with MYSQLI_NUM } //finally return the array with old schema obtained from the Database - if (count($aOldSchema) === 0) { - $aOldSchema = null; + if (count($oldSchema) === 0) { + $oldSchema = null; } - return $aOldSchema; + return $oldSchema; } /** @@ -1154,14 +1152,14 @@ class WorkspaceTools $this->setFormatRows(); $workspaceSchema = $this->getSchema($rbac); - $oDataBase = $this->getDatabase($rbac); + $database = $this->getDatabase($rbac); if (!$onedb) { if ($rbac) { $rename = System::verifyRbacSchema($workspaceSchema); if (count($rename) > 0) { foreach ($rename as $tableName) { - $oDataBase->executeQuery($oDataBase->generateRenameTableSQL($tableName)); + $database->executeQuery($database->generateRenameTableSQL($tableName)); } } } @@ -1184,19 +1182,19 @@ class WorkspaceTools } } - $oDataBase->iFetchType = $this->num; + $database->iFetchType = $this->num; - $oDataBase->logQuery(count($changes)); + $database->logQuery(count($changes)); if (!empty($changes['tablesToAdd'])) { CLI::logging("-> " . count($changes['tablesToAdd']) . " tables to add\n"); } foreach ($changes['tablesToAdd'] as $sTable => $aColumns) { - $oDataBase->executeQuery($oDataBase->generateCreateTableSQL($sTable, $aColumns)); + $database->executeQuery($database->generateCreateTableSQL($sTable, $aColumns)); if (isset($changes['tablesToAdd'][$sTable]['INDEXES'])) { foreach ($changes['tablesToAdd'][$sTable]['INDEXES'] as $indexName => $aIndex) { - $oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $indexName, $aIndex)); + $database->executeQuery($database->generateAddKeysSQL($sTable, $indexName, $aIndex)); } } } @@ -1210,17 +1208,17 @@ class WorkspaceTools foreach ($aAction as $sColumn => $vData) { switch ($sAction) { case 'DROP': - $oDataBase->executeQuery($oDataBase->generateDropColumnSQL($sTable, $vData)); + $database->executeQuery($database->generateDropColumnSQL($sTable, $vData)); break; case 'ADD': - if ($oDataBase->checkPatchHor1787($sTable, $sColumn, $vData)) { - $oDataBase->executeQuery($oDataBase->generateCheckAddColumnSQL($sTable, $sColumn, $vData)); - $oDataBase->executeQuery($oDataBase->deleteAllIndexesIntable($sTable, $sColumn, $vData)); + if ($database->checkPatchHor1787($sTable, $sColumn, $vData)) { + $database->executeQuery($database->generateCheckAddColumnSQL($sTable, $sColumn, $vData)); + $database->executeQuery($database->deleteAllIndexesIntable($sTable, $sColumn, $vData)); } - $oDataBase->executeQuery($oDataBase->generateAddColumnSQL($sTable, $sColumn, $vData)); + $database->executeQuery($database->generateAddColumnSQL($sTable, $sColumn, $vData)); break; case 'CHANGE': - $oDataBase->executeQuery($oDataBase->generateChangeColumnSQL($sTable, $sColumn, $vData)); + $database->executeQuery($database->generateChangeColumnSQL($sTable, $sColumn, $vData)); break; } } @@ -1232,7 +1230,7 @@ class WorkspaceTools } foreach ($changes['tablesWithNewIndex'] as $sTable => $aIndexes) { foreach ($aIndexes as $sIndexName => $aIndexFields) { - $oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields)); + $database->executeQuery($database->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields)); } } @@ -1241,8 +1239,8 @@ class WorkspaceTools } foreach ($changes['tablesToAlterIndex'] as $sTable => $aIndexes) { foreach ($aIndexes as $sIndexName => $aIndexFields) { - $oDataBase->executeQuery($oDataBase->generateDropKeySQL($sTable, $sIndexName)); - $oDataBase->executeQuery($oDataBase->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields)); + $database->executeQuery($database->generateDropKeySQL($sTable, $sIndexName)); + $database->executeQuery($database->generateAddKeysSQL($sTable, $sIndexName, $aIndexFields)); } } $this->closeDatabase(); @@ -1288,7 +1286,7 @@ class WorkspaceTools case 4: $sql = $dataBase->generateSelectSQL($data['table'], $data['keys'], $data['data']); $dataset = $dataBase->executeQuery($sql); - if ($dataBase->getRegistry($dataset)) { + if ($dataset) { $sql = $dataBase->generateDeleteSQL($data['table'], $data['keys'], $data['data']); $dataBase->executeQuery($sql); } @@ -1414,31 +1412,31 @@ class WorkspaceTools /** * exports this workspace database to the specified path * - * This function is used mainly for backup purposes. - * * @param string $path the directory where to create the sql files + * @param boolean $onedb + * + * @return array + * @throws Exception */ public function exportDatabase($path, $onedb = false) { $dbInfo = $this->getDBInfo(); + $databases = ['wf', 'rp', 'rb']; if ($onedb) { - $databases = array("rb", "rp"); - } elseif ($dbInfo['DB_NAME'] == $dbInfo['DB_RBAC_NAME']) { - $databases = array("wf"); - } else { - $databases = array("wf", "rp", "rb"); + $databases = ['rb', 'rp']; + } else if ($dbInfo['DB_NAME'] === $dbInfo['DB_RBAC_NAME']) { + $databases = ['wf']; } $dbNames = []; - foreach ($databases as $db) { $dbInfo = $this->getDBCredentials($db); - $oDbMaintainer = new DataBaseMaintenance($dbInfo["host"], $dbInfo["user"], $dbInfo["pass"]); - CLI::logging("Saving database {$dbInfo["name"]}\n"); - $oDbMaintainer->connect($dbInfo["name"]); - $oDbMaintainer->setTempDir($path . "/"); - $oDbMaintainer->backupDataBase($oDbMaintainer->getTempDir() . $dbInfo["name"] . ".sql"); + $oDbMaintainer = new DataBaseMaintenance($dbInfo['host'], $dbInfo['user'], $dbInfo['pass']); + CLI::logging("Saving database {$dbInfo['name']}\n"); + $oDbMaintainer->connect($dbInfo['name']); + $oDbMaintainer->setTempDir($path . '/'); + $oDbMaintainer->backupDataBase($oDbMaintainer->getTempDir() . $dbInfo['name'] . '.sql'); $dbNames[] = $dbInfo; } return $dbNames; @@ -1548,29 +1546,29 @@ class WorkspaceTools * @param string $password password * @param string $hostname the hostname the user will be connecting from * @param string $database the database to grant permissions + * @param string $connection name + * + * @throws Exception */ - public function createDBUser($username, $password, $hostname, $database, $connection = null) + public function createDBUser($username, $password, $hostname, $database, $connection) { - mysqli_select_db($connection, 'mysql'); - $hosts = explode(':', $hostname); - $hostname = array_shift($hosts); + try { + $message = 'Unable to retrieve users: '; + $hosts = explode(':', $hostname); + $hostname = array_shift($hosts); - $sqlstmt = "SELECT * FROM user WHERE user = '$username' AND host = '$hostname'"; - $result = mysqli_query($connection, $sqlstmt); - if ($result === false) { - throw new Exception('Unable to retrieve users: ' . mysqli_error($connection)); - } - $users = mysqli_num_rows($result); - if ($users === 0) { - CLI::logging("Creating user $username for $hostname\n"); - $result = mysqli_query($connection, "CREATE USER '$username'@'$hostname' IDENTIFIED BY '$password'"); - if ($result === false) { - throw new Exception("Unable to create user $username: " . mysqli_error($connection)); + $result = DB::connection($connection)->select(DB::raw("SELECT * FROM mysql.user WHERE user = '$username' AND host = '$hostname'")); + + if (count($result) === 0) { + $message = "Unable to create user $username: "; + CLI::logging("Creating user $username for $hostname\n"); + + DB::connection($connection)->statement("CREATE USER '$username'@'$hostname' IDENTIFIED BY '$password'"); } - } - $result = mysqli_query($connection, "GRANT ALL ON $database.* TO '$username'@'$hostname'"); - if ($result === false) { - throw new Exception("Unable to grant priviledges to user $username: " . mysqli_error($connection)); + $message = "Unable to grant priviledges to user $username: "; + DB::connection($connection)->statement("GRANT ALL ON $database.* TO '$username'@'$hostname'"); + } catch (QueryException $exception) { + throw new Exception($message . $exception->getMessage()); } } @@ -1596,19 +1594,20 @@ class WorkspaceTools * @param string $database the database to execute this script into * @param $parameters * @param int $versionBackupEngine - * @param object $connection + * @param string $connection */ - public function executeSQLScript($database, $filename, $parameters, $versionBackupEngine = 1, $connection = null) + public function executeSQLScript($database, $filename, $parameters, $versionBackupEngine = 1, $connection) { - mysqli_query($connection, 'CREATE DATABASE IF NOT EXISTS ' . mysqli_real_escape_string($connection, $database)); + DB::connection($connection) + ->statement('CREATE DATABASE IF NOT EXISTS ' . $database); //check function shell_exec $disabled_functions = ini_get('disable_functions'); $flag = false; - if ($disabled_functions != '') { + if (!empty($disabled_functions)) { $arr = explode(',', $disabled_functions); sort($arr); - if (in_array("shell_exec", $arr)) { + if (in_array('shell_exec', $arr)) { $flag = true; } } @@ -1619,8 +1618,8 @@ class WorkspaceTools $flagFunction = shell_exec('mysql --version'); } - $arrayRegExpEngineSearch = array("/\)\s*TYPE\s*=\s*(InnoDB)/i", "/\)\s*TYPE\s*=\s*(MyISAM)/i", "/SET\s*FOREIGN_KEY_CHECKS\s*=\s*0\s*;/"); - $arrayRegExpEngineReplace = array(") ENGINE=\\1 DEFAULT CHARSET=utf8", ") ENGINE=\\1", "SET FOREIGN_KEY_CHECKS=0;\nSET unique_checks=0;\nSET AUTOCOMMIT=0;"); + $arrayRegExpEngineSearch = ["/\)\s*TYPE\s*=\s*(InnoDB)/i", "/\)\s*TYPE\s*=\s*(MyISAM)/i", "/SET\s*FOREIGN_KEY_CHECKS\s*=\s*0\s*;/"]; + $arrayRegExpEngineReplace = [") ENGINE=\\1 DEFAULT CHARSET=utf8", ") ENGINE=\\1", "SET FOREIGN_KEY_CHECKS=0;\nSET unique_checks=0;\nSET AUTOCOMMIT=0;"]; //replace DEFINER $script = preg_replace('/DEFINER=[^*]*/', '', file_get_contents($filename)); @@ -1632,8 +1631,8 @@ class WorkspaceTools $script = preg_replace($arrayRegExpEngineSearch, $arrayRegExpEngineReplace, file_get_contents($filename)); file_put_contents($filename, $script . "\nCOMMIT;"); } else { - $arrayRegExpEngineSearch = array("/\)\s*TYPE\s*=\s*(InnoDB)/i", "/\)\s*TYPE\s*=\s*(MyISAM)/i"); - $arrayRegExpEngineReplace = array(") ENGINE=\\1 DEFAULT CHARSET=utf8", ") ENGINE=\\1"); + $arrayRegExpEngineSearch = ["/\)\s*TYPE\s*=\s*(InnoDB)/i", "/\)\s*TYPE\s*=\s*(MyISAM)/i"]; + $arrayRegExpEngineReplace = [") ENGINE=\\1 DEFAULT CHARSET=utf8", ") ENGINE=\\1"]; $script = preg_replace($arrayRegExpEngineSearch, $arrayRegExpEngineReplace, file_get_contents($filename)); file_put_contents($filename, $script); } @@ -1647,7 +1646,7 @@ class WorkspaceTools . ' --port=' . $dbPort . ' --user=' . $parameters['dbUser'] . ' --password=' . escapeshellarg($parameters['dbPass']) - . ' --database=' . mysqli_real_escape_string($connection, $database) + . ' --database=' . $database . ' --default_character_set utf8' . ' --execute="SOURCE ' . $filename . '"'; } else { @@ -1655,7 +1654,7 @@ class WorkspaceTools . ' --host=' . $dbHost . ' --user=' . $parameters['dbUser'] . ' --password=' . escapeshellarg($parameters['dbPass']) - . ' --database=' . mysqli_real_escape_string($connection, $database) + . ' --database=' . $database . ' --default_character_set utf8' . ' --execute="SOURCE ' . $filename . '"'; } @@ -1663,7 +1662,8 @@ class WorkspaceTools } else { //If the safe mode of the server is actived try { - mysqli_select_db($connection, $database); + $connection = 'RESTORE_' . $database; + InstallerModule::setNewConnection($connection, $parameters['dbHost'], $parameters['dbUser'], $parameters['dbPass'], $database, ''); //Replace TYPE by ENGINE $script = preg_replace($arrayRegExpEngineSearch, $arrayRegExpEngineReplace, file_get_contents($filename)); @@ -1677,51 +1677,55 @@ class WorkspaceTools foreach ($lines as $j => $line) { // Remove comments from the script $line = trim($line); - if (strpos($line, "--") === 0) { - $line = substr($line, 0, strpos($line, "--")); + if (strpos($line, '--') === 0) { + $line = substr($line, 0, strpos($line, '--')); } if (empty($line)) { continue; } // Concatenate the previous line, if any, with the current if ($previous) { - $line = $previous . " " . $line; + $line = $previous . ' ' . $line; } $previous = null; // If the current line doesnt end with ; then put this line together // with the next one, thus supporting multi-line statements. - if (strrpos($line, ";") != strlen($line) - 1) { + if (strrpos($line, ';') !== strlen($line) - 1) { $previous = $line; continue; } - $line = substr($line, 0, strrpos($line, ";")); + $line = substr($line, 0, strrpos($line, ';')); - if (strrpos($line, "INSERT INTO") !== false) { + if (strrpos($line, 'INSERT INTO') !== false) { $insert = true; if ($insert) { - $result = mysqli_query($connection, "START TRANSACTION"); + DB::connection($connection)->beginTransaction(); $insert = false; } - $result = mysqli_query($connection, $line); + $result = DB::connection($connection)->statement($line); continue; } else { if (!$insert) { - $result = mysqli_query($connection, "COMMIT"); + DB::connection($connection)->commitTransaction(); $insert = true; } } - $result = mysqli_query($connection, $line); + $result = DB::connection($connection)->statement($line); if ($result === false) { - throw new Exception("Error when running script '$filename', line $j, query '$line': " . mysqli_error($connection)); + DB::connection($connection)->rollbackTransaction(); + throw new Exception("Error when running script '$filename', line $j, query '$line' "); } } if (!$insert) { - $result = mysqli_query($connection, "COMMIT"); + DB::connection($connection)->commitTransaction(); } } catch (Exception $e) { CLI::logging(CLI::error("Error:" . "There are problems running script '$filename': " . $e)); + } catch (QueryException $exception) { + DB::connection($connection)->rollbackTransaction(); + throw new Exception("Error when running script '$filename', line $j, query '$line': " . $exception->getMessage()); } } } @@ -1919,28 +1923,31 @@ class WorkspaceTools if ($port != '') { $dbHost = $dbHost . $port; //127.0.0.1:3306 } - $aParameters = array('dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass); + $aParameters = ['dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass]; //Restore - if (empty(config("system.workspace"))) { - define("SYS_SYS", $workspaceName); - config(["system.workspace" => $workspaceName]); + if (empty(config('system.workspace'))) { + define('SYS_SYS', $workspaceName); + config(['system.workspace' => $workspaceName]); } - if (!defined("PATH_DATA_SITE")) { - define("PATH_DATA_SITE", PATH_DATA . "sites" . PATH_SEP . config("system.workspace") . PATH_SEP); + if (!defined('PATH_DATA_SITE')) { + define('PATH_DATA_SITE', PATH_DATA . 'sites' . PATH_SEP . config('system.workspace') . PATH_SEP); } - $pmVersionWorkspaceToRestore = (preg_match("/^([\d\.]+).*$/", $metadata->PM_VERSION, $arrayMatch)) ? $arrayMatch[1] : ""; + $pmVersionWorkspaceToRestore = preg_match("/^([\d\.]+).*$/", $metadata->PM_VERSION, $arrayMatch) ? $arrayMatch[1] : ''; CLI::logging("> Connecting to system database in '$dbHost'\n"); - $link = mysqli_connect($dbHost, $dbUser, $dbPass); - mysqli_query($link, "SET NAMES 'utf8';"); - mysqli_query($link, "SET FOREIGN_KEY_CHECKS=0;"); - mysqli_query($link, "SET GLOBAL log_bin_trust_routine_creators = 1;"); - if (!$link) { - throw new Exception('Could not connect to system database: ' . mysqli_error($link)); + try { + $connection = 'RESTORE'; + InstallerModule::setNewConnection('RESTORE', $dbHost, $dbUser, $dbPass, '', ''); + DB::connection($connection) + ->statement("SET NAMES 'utf8'"); + DB::connection($connection) + ->statement('SET FOREIGN_KEY_CHECKS=0'); + } catch (Exception $exception) { + throw new Exception('Could not connect to system database: ' . $exception->getMessage()); } $dbName = ''; @@ -1952,17 +1959,16 @@ class WorkspaceTools if (isset($newDBNames['DB_USER'])) { $dbUser = $newDBNames['DB_USER']; } - if (mysqli_select_db($link, $dbName)) { - if (!$overwrite) { - throw new Exception("Destination Database already exist (use -o to overwrite)"); - } + $result = DB::connection($connection)->select("show databases like '$dbName'"); + if (count($result) > 0 && !$overwrite) { + throw new Exception("Destination Database already exist (use -o to overwrite)"); } CLI::logging("+> Restoring database {$db->name} to $dbName\n"); $versionBackupEngine = (isset($metadata->backupEngineVersion)) ? $metadata->backupEngineVersion : 1; - $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql", $aParameters, $versionBackupEngine, $link); - $workspace->createDBUser($dbUser, ($workspace->dbGrantUserPassword != '' ? $workspace->dbGrantUserPassword : $db->pass), "localhost", $dbName, $link); - $workspace->createDBUser($dbUser, ($workspace->dbGrantUserPassword != '' ? $workspace->dbGrantUserPassword : $db->pass), "%", $dbName, $link); + $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql", $aParameters, $versionBackupEngine, $connection); + $workspace->createDBUser($dbUser, ($workspace->dbGrantUserPassword != '' ? $workspace->dbGrantUserPassword : $db->pass), "localhost", $dbName, $connection); + $workspace->createDBUser($dbUser, ($workspace->dbGrantUserPassword != '' ? $workspace->dbGrantUserPassword : $db->pass), "%", $dbName, $connection); } } @@ -2048,7 +2054,6 @@ class WorkspaceTools //Updating generated class files for PM Tables passthru(PHP_BINARY . ' processmaker regenerate-pmtable-classes ' . $workspace->name); - mysqli_close($link); } CLI::logging("Removing temporary files\n"); diff --git a/workflow/engine/classes/model/Content.php b/workflow/engine/classes/model/Content.php index 5df9b2977..9404162eb 100644 --- a/workflow/engine/classes/model/Content.php +++ b/workflow/engine/classes/model/Content.php @@ -1,43 +1,7 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ -//require_once 'classes/model/om/BaseContent.php'; +use Illuminate\Support\Facades\DB; -/** - * Skeleton subclass for representing a row from the 'CONTENT' table. - * - * - * - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package workflow.engine.classes.model - */ class Content extends BaseContent { public $langs; @@ -335,51 +299,56 @@ class Content extends BaseContent $this->rowsUnchanged = 0; $this->rowsClustered = 0; - //Creating table CONTENT_BACKUP - $connection = Propel::getConnection('workflow'); - $oStatement = $connection->prepareStatement("CREATE TABLE IF NOT EXISTS `CONTENT_BACKUP` ( + $workSpace = new WorkspaceTools($workSpace); + $workSpace->getDBInfo(); + + $connection = 'regenerate'; + InstallerModule::setNewConnection( + $connection, + $workSpace->dbHost, + $workSpace->dbUser, + $workSpace->dbPass, + $workSpace->dbName, + '', + ['PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET SESSION SQL_BIG_SELECTS=1']); + + $query = "CREATE TABLE IF NOT EXISTS `CONTENT_BACKUP` ( `CON_CATEGORY` VARCHAR(30) default '' NOT NULL, `CON_PARENT` VARCHAR(32) default '' NOT NULL, `CON_ID` VARCHAR(100) default '' NOT NULL, `CON_LANG` VARCHAR(10) default '' NOT NULL, `CON_VALUE` MEDIUMTEXT NOT NULL, CONSTRAINT CONTENT_BACKUP_PK PRIMARY KEY (CON_CATEGORY,CON_PARENT,CON_ID,CON_LANG) - )Engine=InnoDB DEFAULT CHARSET='utf8' COMMENT='Table for add content';"); - $oStatement->executeQuery(); + )Engine=InnoDB DEFAULT CHARSET='utf8' COMMENT='Table for add content'"; - $sql = ' SELECT DISTINCT CON_LANG FROM CONTENT '; - $stmt = $connection->createStatement(); - $rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); - while ($rs->next()) { - $row = $rs->getRow(); - $language = $row['CON_LANG']; - if (array_search($row['CON_LANG'], $langs) === false) { - Content::removeLanguageContent($row['CON_LANG']); + DB::connection($connection)->statement($query); + + $languages = DB::table('CONTENT')->select('CON_LANG')->distinct()->get(); + + foreach ($languages as $value) { + if (array_search($value->CON_LANG, $langs) === false) { + Content::removeLanguageContent($value->CON_LANG); } } - $sql = " SELECT CON_ID, CON_CATEGORY, CON_LANG, CON_PARENT, CON_VALUE - FROM CONTENT - ORDER BY CON_ID, CON_CATEGORY, CON_PARENT, CON_LANG"; + DB::connection($connection)->statement('SET NAMES "utf8"'); + DB::connection($connection)->statement('SET FOREIGN_KEY_CHECKS=0'); + DB::connection($connection)->statement('SET SQL_BIG_SELECTS=1'); - $workSpace = new WorkspaceTools($workSpace); - $workSpace->getDBInfo(); - - $mysqli = new mysqli($workSpace->dbHost, $workSpace->dbUser, $workSpace->dbPass, $workSpace->dbName) or die("Could not connect"); - - $mysqli->query( 'SET NAMES "utf8";'); - $mysqli->query( 'SET FOREIGN_KEY_CHECKS=0;'); - $mysqli->query( 'SET OPTION SQL_BIG_SELECTS=1'); - $result = $mysqli->query( $sql, MYSQLI_USE_RESULT); + $result = DB::table('CONTENT') + ->select('CON_ID', 'CON_CATEGORY', 'CON_LANG', 'CON_PARENT', 'CON_VALUE') + ->orderBy('CON_ID', 'CON_CATEGORY', 'CON_LANG', 'CON_PARENT', 'CON_VALUE') + ->get(); $list = []; $default = []; - $sw = array('CON_ID' => '','CON_CATEGORY' => '','CON_PARENT' => '' - ); - while ($row = $result->fetch_assoc()) { + $sw = ['CON_ID' => '', 'CON_CATEGORY' => '', 'CON_PARENT' => '']; + + foreach ($result as $value) { + $row = (array)$value; if ($sw['CON_ID'] === $row['CON_ID'] && $sw['CON_CATEGORY'] === $row['CON_CATEGORY'] && $sw['CON_PARENT'] === $row['CON_PARENT']) { $list[] = $row; } else { - $this->rowsClustered ++; + $this->rowsClustered++; if (count($langs) !== count($list)) { $this->checkLanguage($list, $default); } else { @@ -399,37 +368,30 @@ class Content extends BaseContent if ($sw['CON_LANG'] === $langs[$key]) { $default = $row; } - $this->rowsProcessed ++; + $this->rowsProcessed++; } + if (count($langs) !== count($list)) { $this->checkLanguage($list, $default); } else { $this->rowsUnchanged += count($langs); } - mysqli_free_result($result); $total = $this->rowsProcessed + $this->rowsInserted; - $result->close(); - - $statement = $connection->prepareStatement("REPLACE INTO CONTENT + DB::connection($connection)->statement('REPLACE INTO CONTENT SELECT CON_CATEGORY, CON_PARENT, CON_ID , CON_LANG, CON_VALUE - FROM CONTENT_BACKUP"); - $statement->executeQuery(); + FROM CONTENT_BACKUP'); - $statement = $connection->prepareStatement("DROP TABLE CONTENT_BACKUP"); - $statement->executeQuery(); + DB::connection($connection)->statement('DROP TABLE CONTENT_BACKUP'); - //close connection - $sql = "SELECT * FROM information_schema.processlist WHERE command = 'Sleep' and user = SUBSTRING_INDEX(USER(),'@',1) and db = DATABASE() ORDER BY id;"; - $stmt = $connection->createStatement(); - $rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); - while ($rs->next()) { - $row = $rs->getRow(); - $oStatement = $connection->prepareStatement("kill ". $row['ID']); - $oStatement->executeQuery(); + $result = DB::connection($connection) + ->select("SELECT * FROM information_schema.processlist WHERE command = 'Sleep' and user = SUBSTRING_INDEX(USER(),'@',1) and db = DATABASE() ORDER BY id"); + + foreach ($result as $value) { + DB::connection($connection)->statement('kill ' . $value->ID); } - if (! isset($_SERVER['SERVER_NAME'])) { + if (!isset($_SERVER['SERVER_NAME'])) { CLI::logging("Rows Processed ---> $this->rowsProcessed ..... \n"); CLI::logging("Rows Clustered ---> $this->rowsClustered ..... \n"); CLI::logging("Rows Unchanged ---> $this->rowsUnchanged ..... \n"); @@ -457,12 +419,14 @@ class Content extends BaseContent public function fastInsertContent($ConCategory, $ConParent, $ConId, $ConLang, $ConValue) { - $connection = Propel::getConnection('workflow'); - $ConValue = mysqli_real_escape_string($connection, $ConValue); - $statement = $connection->prepareStatement("INSERT INTO CONTENT_BACKUP ( - CON_CATEGORY, CON_PARENT, CON_ID , CON_LANG, CON_VALUE) - VALUES ('$ConCategory', '$ConParent', '$ConId', '$ConLang', '$ConValue');"); - $statement->executeQuery(); + DB::table('CONTENT_BACKUP') + ->insert([ + 'CON_CATEGORY' => $ConCategory, + 'CON_PARENT' => $ConParent, + 'CON_ID' => $ConId, + 'CON_LANG' => $ConLang, + 'CON_VALUE' => $ConValue + ]); } public function removeLanguageContent($lanId) diff --git a/workflow/engine/controllers/InstallerModule.php b/workflow/engine/controllers/InstallerModule.php index 223704a66..fb569e0a9 100644 --- a/workflow/engine/controllers/InstallerModule.php +++ b/workflow/engine/controllers/InstallerModule.php @@ -1,7 +1,12 @@ path_config = PATH_CORE . 'config/'; @@ -116,6 +132,56 @@ class InstallerModule extends Controller } } + /** + * Set config connection + * + * @param string $nameConnection name Connection + * @param string $host + * @param string $user + * @param string $pass + * @param string $database + * @param int $port + * @param array $options + * + * @throws Exception + */ + public static function setNewConnection($nameConnection, $host, $user, $pass, $database, $port, $options = []) + { + try { + if (empty($port)) { + $dbHost = explode(':', $host); + $port = 3306; + if (count($dbHost) > 1) { + $port = $dbHost[1]; + } + $host = $dbHost[0]; + } + config(['database.connections.' . $nameConnection => [ + 'driver' => 'mysql', + 'host' => $host, + 'port' => $port, + 'database' => $database, + 'username' => $user, + 'password' => $pass, + 'unix_socket' => '', + 'charset' => 'utf8', + 'collation' => 'utf8_unicode_ci', + 'prefix' => '', + 'strict' => false, + 'engine' => 'InnoDB', + 'options' => $options + ]]); + DB::connection($nameConnection)->getPdo(); + } catch (Exception $e) { + throw new Exception(G::LoadTranslation('ID_MYSQL_CREDENTIALS_WRONG')); + } + } + + /** + * Get system information for review the requirements to install ProcessMaker + * + * @return object + */ public function getSystemInfo() { $this->setResponseType('json'); @@ -241,7 +307,7 @@ class InstallerModule extends Controller $this->setResponseType('json'); $info = new StdClass(); $info->success = true; - $noWritableFiles = array(); + $noWritableFiles = []; $noWritable = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); $writable = G::LoadTranslation('ID_WRITEABLE'); @@ -387,16 +453,15 @@ class InstallerModule extends Controller * the install.log files should be placed in shared/logs * for that reason we are using the $_REQUEST of pathShared */ - public function installLog($text) + private function installLog($text) { - $serverAddr = $_SERVER['SERVER_ADDR']; //if this function is called outside the createWorkspace, just returns and do nothing if (!isset($_REQUEST['pathShared'])) { return; } //log file is in shared/logs $pathShared = trim($_REQUEST['pathShared']); - if (substr($pathShared, -1) != '/') { + if (substr($pathShared, -1) !== '/') { $pathShared .= '/'; } $pathSharedLog = $pathShared . 'log/'; @@ -410,12 +475,11 @@ class InstallerModule extends Controller fwrite($fpt, sprintf("%s %s\n", date('Y:m:d H:i:s'), '----- ' . G::LoadTranslation('ID_STARTING_LOG_FILE') . ' ------')); fclose($fpt); } else { - throw (new Exception(G::LoadTranslation('ID_FILE_NOT_WRITEABLE', SYS_LANG, array($logFile)))); + throw new Exception(G::LoadTranslation('ID_FILE_NOT_WRITEABLE', SYS_LANG, [$logFile])); return $false; } } - $filter = new InputFilter(); $logFile = $filter->validateInput($logFile, 'path'); @@ -497,26 +561,12 @@ class InstallerModule extends Controller } /** - * send a query to MySQL and log the query - */ - public function mysqlQuery($sql) - { - $this->installLog($sql); - $query = mysqli_query($this->link, $sql); - if (!$query) { - $errorMessage = mysqli_error($this->link); - $this->installLog(G::LoadTranslation('ID_MYSQL_ERROR', SYS_LANG, array($errorMessage))); - throw new \Exception($errorMessage); - return false; - } - if (is_object($query)) { - mysqli_free_result($query); - } - return true; - } - - /** - * send a query to MSSQL and log the query + * Send a query to MSSQL and log the query + * + * @param string $sql + * + * @return boolean + * @throws Exception */ public function mssqlQuery($sql) { @@ -544,32 +594,30 @@ class InstallerModule extends Controller public function mysqlFileQuery($file) { if (!is_file($file)) { - throw (new Exception(G::LoadTranslation('ID_SQL_FILE_INVALID', SYS_LANG, array($file)))); + throw new Exception(G::LoadTranslation('ID_SQL_FILE_INVALID', SYS_LANG, [$file])); return $false; } - $this->installLog(G::LoadTranslation('ID_PROCESING', SYS_LANG, array($file))); + $this->installLog(G::LoadTranslation('ID_PROCESING', SYS_LANG, [$file])); $startTime = microtime(true); //New Update, to support more complex queries - $lines = file($file); $previous = null; - $errors = ''; - mysqli_query($this->link, "SET NAMES 'utf8';"); + DB::connection(self::CONNECTION_INSTALL) + ->statement("SET NAMES 'utf8'"); foreach ($lines as $j => $line) { $line = trim($line); // Remove comments from the script - - if (strpos($line, "--") === 0) { - $line = substr($line, 0, strpos($line, "--")); + if (strpos($line, '--') === 0) { + $line = substr($line, 0, strpos($line, '--')); } if (empty($line)) { continue; } - if (strpos($line, "#") === 0) { - $line = substr($line, 0, strpos($line, "#")); + if (strpos($line, '#') === 0) { + $line = substr($line, 0, strpos($line, '#')); } if (empty($line)) { @@ -578,23 +626,24 @@ class InstallerModule extends Controller // Concatenate the previous line, if any, with the current if ($previous) { - $line = $previous . " " . $line; + $line = $previous . ' ' . $line; } $previous = null; // If the current line doesnt end with ; then put this line together // with the next one, thus supporting multi-line statements. - if (strrpos($line, ";") != strlen($line) - 1) { + if (strrpos($line, ';') !== strlen($line) - 1) { $previous = $line; continue; } - $line = substr($line, 0, strrpos($line, ";")); - mysqli_query($this->link, $line); + $line = substr($line, 0, strrpos($line, ';')); + DB::connection(self::CONNECTION_INSTALL) + ->statement($line); } $endTime = microtime(true); - $this->installLog(G::LoadTranslation('ID_FILE_PROCESSED', SYS_LANG, array(basename($file), $endTime - $startTime))); + $this->installLog(G::LoadTranslation('ID_FILE_PROCESSED', SYS_LANG, [basename($file), $endTime - $startTime])); return true; } @@ -636,31 +685,25 @@ class InstallerModule extends Controller * @param string $psUser * @param string $psPassword * @param string $psDatabase - * @return void + * @param string $host + * + * @throws Exception */ - public function setGrantPrivilegesMySQL($psUser, $psPassword, $psDatabase, $host) + private function setGrantPrivilegesMySQL($psUser, $psPassword, $psDatabase, $host) { - $filter = new InputFilter(); - $host = ($host == 'localhost' || $host == '127.0.0.1' ? 'localhost' : '%'); + try { + $host = $host === 'localhost' || $host === '127.0.0.1' ? 'localhost' : '%'; - $query = "GRANT ALL PRIVILEGES ON `%s`.* TO %s@'%s' IDENTIFIED BY '%s' WITH GRANT OPTION"; - $sql = sprintf($query, $psDatabase, $psUser, $host, $psPassword); - $sql = $filter->preventSqlInjection($query, array($psDatabase, $psUser, $host, $psPassword), $this->link); - $query = mysqli_query($this->link, $sql); + $query = "GRANT ALL PRIVILEGES ON `$psDatabase`.* TO $psUser@'$host' IDENTIFIED BY '$psPassword' WITH GRANT OPTION"; + DB::connection(self::CONNECTION_INSTALL) + ->statement($query); - if (!$query) { - $errorMessage = mysqli_error($this->link); - $this->installLog(G::LoadTranslation('ID_MYSQL_ERROR', SYS_LANG, array($errorMessage))); - if (mysqli_errno($this->link) === 1410 || mysqli_errno($this->link) === 1132) { - $errorMessage .= '. ' . G::LoadTranslation('ID_INSTALL_USE_CURRENT_USER'); - } - throw new Exception($errorMessage); - return false; + $this->installLog($query); + + } catch (QueryException $e) { + $this->installLog(G::LoadTranslation('ID_MYSQL_ERROR', SYS_LANG, [$e->getMessage()])); + throw new Exception($e->getMessage()); } - if (is_object($query)) { - mysqli_free_result($query); - } - $this->installLog($sql); } /** @@ -703,12 +746,11 @@ class InstallerModule extends Controller return true; } - private function file_get_contents_utf8($fn) { - $content = file_get_contents($fn); - return mb_convert_encoding($content, 'UTF-8', - mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)); - } - + /** + * Create a workspace in a MySQL database + * + * @return StdClass object + */ public function createMySQLWorkspace() { $filter = new InputFilter(); @@ -726,76 +768,61 @@ class InstallerModule extends Controller $db_password = urlencode(trim($_REQUEST['db_password'])); $db_password = urldecode($filter->validateInput($db_password)); $wf = trim($_REQUEST['wfDatabase']); - $rb = trim($_REQUEST['wfDatabase']); - $rp = trim($_REQUEST['wfDatabase']); $workspace = trim($_REQUEST['workspace']); - $pathConfig = trim($_REQUEST['pathConfig']); - $pathLanguages = trim($_REQUEST['pathLanguages']); - $pathPlugins = trim($_REQUEST['pathPlugins']); $pathShared = trim($_REQUEST['pathShared']); - $pathXmlforms = trim($_REQUEST['pathXmlforms']); $adminPassword = trim($_REQUEST['adminPassword']); $adminPassword = $filter->validateInput($adminPassword); $adminUsername = trim($_REQUEST['adminUsername']); $adminUsername = $filter->validateInput($adminUsername); - $deleteDB = ($_REQUEST['deleteDB'] == 'true'); - $userLogged = (isset($_REQUEST['userLogged']) ? ($_REQUEST['userLogged'] == 'true') : false); + $deleteDB = $_REQUEST['deleteDB'] === 'true'; + $userLogged = isset($_REQUEST['userLogged']) ? $_REQUEST['userLogged'] === 'true' : false; $userLogged = $filter->validateInput($userLogged); - if (substr($pathShared, -1) != '/') { + if (substr($pathShared, -1) !== '/') { $pathShared .= '/'; } $this->installLog('-------------------------------------------'); - $this->installLog(G::LoadTranslation('ID_CREATING_WORKSPACE', SYS_LANG, array($workspace))); + $this->installLog(G::LoadTranslation('ID_CREATING_WORKSPACE', SYS_LANG, [$workspace])); try { + self::setNewConnection(self::CONNECTION_TEST_INSTALL, $db_hostname, $db_username, $db_password, '', $db_port); $db_host = ($db_port != '' && $db_port != 3306) ? $db_hostname . ':' . $db_port : $db_hostname; - $this->link = mysqli_connect($db_host, $db_username, $db_password); - mysqli_set_charset($this->link, 'utf8'); - $this->installLog(G::LoadTranslation('ID_CONNECT_TO_SERVER', SYS_LANG, array($db_hostname, $db_port, $db_username))); + $this->installLog(G::LoadTranslation('ID_CONNECT_TO_SERVER', SYS_LANG, [$db_hostname, $db_port, $db_username])); if ($deleteDB) { - $q = sprintf('DROP DATABASE IF EXISTS %s;', $wf, $wf); - $this->mysqlQuery($q); + $query = sprintf('DROP DATABASE IF EXISTS %s', $wf); + DB::connection(self::CONNECTION_TEST_INSTALL)->statement($query); } - // CREATE databases wf_workflow, rb_workflow and rp_workflow - $q = sprintf('CREATE DATABASE IF NOT EXISTS %s;', $wf, $wf); - $this->mysqlQuery($q); + // CREATE databases wf_workflow + DB::connection(self::CONNECTION_TEST_INSTALL) + ->statement("CREATE DATABASE IF NOT EXISTS $wf"); + + self::setNewConnection(self::CONNECTION_INSTALL, $db_hostname, $db_username, $db_password, $wf, $db_port); // CREATE users and GRANT Privileges $wf_workspace = $wf; $wfGrantUser = uniqid('wf_'); - $rb_workspace = $wf; - $rp_workspace = $wf; if (!$userLogged) { $wfPass = G::generate_password(15); $this->setGrantPrivilegesMySQL($wfGrantUser, $wfPass, $wf, $db_hostname); - $this->setGrantPrivilegesMySQL($wfGrantUser, $wfPass, $wf, $db_hostname); - $this->setGrantPrivilegesMySQL($wfGrantUser, $wfPass, $wf, $db_hostname); } else { $wfPass = $db_password; - $rbPass = $db_password; - $rpPass = $db_password; $wf = $db_username; $wfGrantUser = $db_username; - $rb = $db_username; - $rp = $db_username; } - // Generate the db.php file and folders - $pathSharedSites = $pathShared; - $path_site = $pathShared . "/sites/" . $workspace . "/"; + $path_site = $pathShared . '/sites/' . $workspace . '/'; @mkdir($path_site, 0777, true); - @mkdir($path_site . "files/", 0777, true); - @mkdir($path_site . "mailTemplates/", 0777, true); - @mkdir($path_site . "public/", 0777, true); - @mkdir($path_site . "reports/", 0777, true); - @mkdir($path_site . "xmlForms", 0777, true); + @mkdir($path_site . 'files/', 0777, true); + @mkdir($path_site . 'mailTemplates/', 0777, true); + @mkdir($path_site . 'public/', 0777, true); + @mkdir($path_site . 'reports/', 0777, true); + @mkdir($path_site . 'xmlForms', 0777, true); $db_file = $path_site . 'db.php'; $dbText = "systemName != '') { + $dbText .= " define ('PARTNER_FLAG', " . (defined('PARTNER_FLAG') ? PARTNER_FLAG : isset($_REQUEST['PARTNER_FLAG']) ? $_REQUEST['PARTNER_FLAG'] : 'false') . ");\n"; + if (!empty($this->systemName)) { $dbText .= " define ('SYSTEM_NAME', '" . $this->systemName . "');\n"; } } - $this->installLog(G::LoadTranslation('ID_CREATING', SYS_LANG, array($db_file))); + $this->installLog(G::LoadTranslation('ID_CREATING', SYS_LANG, [$db_file])); file_put_contents($db_file, $dbText); /*----------------------------------********---------------------------------*/ @@ -854,15 +881,8 @@ class InstallerModule extends Controller $this->installLog(G::LoadTranslation('ID_CREATING', SYS_LANG, array($databases_file))); file_put_contents($databases_file, $databasesText); - // Execute scripts to create and populates databases - $query = sprintf("USE %s;", $wf_workspace); - $this->mysqlQuery($query); - $this->mysqlFileQuery(PATH_RBAC_HOME . 'engine/data/mysql/schema.sql'); $this->mysqlFileQuery(PATH_RBAC_HOME . 'engine/data/mysql/insert.sql'); - - $query = sprintf("USE %s;", $wf_workspace); - $this->mysqlQuery($query); $this->mysqlFileQuery(PATH_HOME . 'engine/data/mysql/schema.sql'); $this->mysqlFileQuery(PATH_HOME . 'engine/data/mysql/insert.sql'); @@ -877,61 +897,86 @@ class InstallerModule extends Controller file_exists(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql') && file_exists(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationDelete.sql') && file_exists(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerContentUpdate.sql')) { - $this->mysqlQuery($this->file_get_contents_utf8(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql')); - $this->mysqlQuery($this->file_get_contents_utf8(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql')); - $this->mysqlQuery($this->file_get_contents_utf8(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql')); - $this->mysqlQuery($this->file_get_contents_utf8(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationDelete.sql')); - $this->mysqlQuery($this->file_get_contents_utf8(PATH_HOME . "engine/methods/setup/setupSchemas/triggerSubApplicationInsert.sql")); - $this->mysqlQuery($this->file_get_contents_utf8(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerContentUpdate.sql')); + DB::connection(self::CONNECTION_INSTALL)->raw(file_get_contents(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql')); + DB::connection(self::CONNECTION_INSTALL)->raw(file_get_contents(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql')); + DB::connection(self::CONNECTION_INSTALL)->raw(file_get_contents(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql')); + DB::connection(self::CONNECTION_INSTALL)->raw(file_get_contents(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationDelete.sql')); + DB::connection(self::CONNECTION_INSTALL)->raw(file_get_contents(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerSubApplicationInsert.sql')); + DB::connection(self::CONNECTION_INSTALL)->raw(file_get_contents(PATH_HOME . 'engine/methods/setup/setupSchemas/triggerContentUpdate.sql')); - $this->mysqlQuery("INSERT INTO `CONFIGURATION` ( - `CFG_UID`, - `CFG_VALUE` - ) - VALUES ( - 'APP_CACHE_VIEW_ENGINE', - '" . mysqli_real_escape_string(serialize(array('LANG' => 'en', 'STATUS' => 'active' - ))) . "' - )"); + DB::connection(self::CONNECTION_INSTALL) + ->table('CONFIGURATION') + ->insert([ + 'CFG_UID' => 'APP_CACHE_VIEW_ENGINE', + 'CFG_VALUE' => serialize(['LANG' => 'en', 'STATUS' => 'active']) + ]); - $this->mysqlQuery("INSERT INTO EMAIL_SERVER(MESS_UID, MESS_ENGINE) VALUES('" . \ProcessMaker\Util\Common::generateUID() . "', 'MAIL')"); + DB::connection(self::CONNECTION_INSTALL) + ->table('EMAIL_SERVER') + ->insert([ + 'MESS_UID' => Common::generateUID(), + 'MESS_ENGINE' => 'MAIL' + ]); } // Change admin user - $query = sprintf("USE %s;", $wf_workspace); - $this->mysqlQuery($query); - - $query = sprintf("UPDATE USERS SET USR_USERNAME = '%s', USR_LASTNAME = '%s', USR_PASSWORD = '%s' WHERE USR_UID = '00000000000000000000000000000001' ", $adminUsername, $adminUsername, G::encryptHash($adminPassword)); - $this->mysqlQuery($query); - - $query = sprintf("UPDATE RBAC_USERS SET USR_USERNAME = '%s', USR_LASTNAME = '%s', USR_PASSWORD = '%s' WHERE USR_UID = '00000000000000000000000000000001' ", $adminUsername, $adminUsername, G::encryptHash($adminPassword)); - $this->mysqlQuery($query); + DB::connection(self::CONNECTION_INSTALL) + ->table('USERS') + ->where('USR_UID', '00000000000000000000000000000001') + ->update([ + 'USR_USERNAME' => $adminUsername, + 'USR_LASTNAME' => $adminUsername, + 'USR_PASSWORD' => Bootstrap::hashPassword($adminPassword, Bootstrap::hashBcrypt) + ]); + DB::connection(self::CONNECTION_INSTALL) + ->table('RBAC_USERS') + ->where('USR_UID', '00000000000000000000000000000001') + ->update([ + 'USR_USERNAME' => $adminUsername, + 'USR_LASTNAME' => $adminUsername, + 'USR_PASSWORD' => Bootstrap::hashPassword($adminPassword, Bootstrap::hashBcrypt) + ]); // Write the paths_installed.php file (contains all the information configured so far) if (!file_exists(FILE_PATHS_INSTALLED)) { $sh = G::encryptOld(filemtime(PATH_GULLIVER . '/class.g.php')); - $h = G::encrypt($db_hostname . $sh . $db_username . $sh . $db_password, $sh); + $h = G::encrypt($db_host . $sh . $db_username . $sh . $db_password, $sh); $dbText = "installLog(G::LoadTranslation('ID_CREATING', SYS_LANG, array(FILE_PATHS_INSTALLED))); + $this->installLog(G::LoadTranslation('ID_CREATING', SYS_LANG, [FILE_PATHS_INSTALLED])); file_put_contents(FILE_PATHS_INSTALLED, $dbText); } /** * AppCacheView Build */ - define( 'HASH_INSTALLATION', $h ); - define( 'SYSTEM_HASH', $sh ); - define( 'PATH_DB', $pathShared . 'sites' . PATH_SEP ); - define( 'SYS_SYS', $workspace ); - config(["system.workspace" => $workspace]); + define('HASH_INSTALLATION', $h); + define('SYSTEM_HASH', $sh); + define('PATH_DB', $pathShared . 'sites' . PATH_SEP); + define('SYS_SYS', $workspace); + config(['system.workspace' => $workspace]); - require_once("propel/Propel.php"); + System::setConnectionConfig( + 'mysql', + $db_host, + $wf_workspace, + $wfGrantUser, + $wfPass, + $db_host, + $wf_workspace, + $wfGrantUser, + $wfPass, + $db_host, + $wf_workspace, + $wfGrantUser, + $wfPass); - Propel::init(PATH_CORE . "config/databases.php"); + require_once('propel/Propel.php'); + + Propel::init(PATH_CORE . 'config/databases.php'); $con = Propel::getConnection('workflow'); require_once('classes/model/AppCacheView.php'); @@ -990,8 +1035,8 @@ class InstallerModule extends Controller $info->uri = PATH_SEP . 'sys' . $_REQUEST['workspace'] . PATH_SEP . $langUri . PATH_SEP . $skinUri . PATH_SEP . 'login' . PATH_SEP . 'login'; //register PMDesigner Client - $http = (G::is_https() == true) ? 'https' : 'http'; - $host = $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] != '80' ? ':' . $_SERVER['SERVER_PORT'] : ''); + $http = G::is_https() ? 'https' : 'http'; + $host = $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] !== '80' ? ':' . $_SERVER['SERVER_PORT'] : ''); $endpoint = sprintf( '%s://%s/sys%s/%s/%s/oauth2/grant', @@ -1003,15 +1048,17 @@ class InstallerModule extends Controller ); // inserting the outh_client - if (!$userLogged) { - $query = sprintf("USE %s;", $wf); - } else { - $query = sprintf("USE %s;", trim($_REQUEST['wfDatabase'])); - } - $this->mysqlQuery($query); - $query = ("INSERT INTO OAUTH_CLIENTS (CLIENT_ID,CLIENT_SECRET,CLIENT_NAME,CLIENT_DESCRIPTION,CLIENT_WEBSITE,REDIRECT_URI,USR_UID ) VALUES - ('x-pm-local-client','179ad45c6ce2cb97cf1029e212046e81','PM Web Designer','ProcessMaker Web Designer App','www.processmaker.com','" . $endpoint . "','00000000000000000000000000000001' )"); - $this->mysqlQuery($query); + DB::connection(self::CONNECTION_INSTALL) + ->table('OAUTH_CLIENTS') + ->insert([ + 'CLIENT_ID' => 'x-pm-local-client', + 'CLIENT_SECRET' => '179ad45c6ce2cb97cf1029e212046e81', + 'CLIENT_NAME' => 'PM Web Designer', + 'CLIENT_DESCRIPTION' => 'ProcessMaker Web Designer App', + 'CLIENT_WEBSITE' => 'www.processmaker.com', + 'REDIRECT_URI' => $endpoint, + 'USR_UID' => '00000000000000000000000000000001' + ]); $indexFileUpdated = true; if (defined('PARTNER_FLAG') || isset($_REQUEST['PARTNER_FLAG'])) { @@ -1021,30 +1068,30 @@ class InstallerModule extends Controller G::update_php_ini($envFile, $updatedConf); } catch (Exception $e) { $info->result = false; - $info->message = G::LoadTranslation('ID_PROCESSMAKER_WRITE_CONFIG_INDEX', SYS_LANG, array($envFile)); + $info->message = G::LoadTranslation('ID_PROCESSMAKER_WRITE_CONFIG_INDEX', SYS_LANG, [$envFile]); $info->message .= G::LoadTranslation('ID_PROCESSMAKER_UI_NOT_INSTALL'); - $this->installLog(G::LoadTranslation('ID_INSTALL_BUT_ERROR', SYS_LANG, array('env.ini'))); + $this->installLog(G::LoadTranslation('ID_INSTALL_BUT_ERROR', SYS_LANG, ['env.ini'])); return $info; } try { // update the main index file - $indexFileUpdated = System::updateIndexFile(array('lang' => 'en', 'skin' => $updatedConf['default_skin'])); + $indexFileUpdated = System::updateIndexFile(['lang' => 'en', 'skin' => $updatedConf['default_skin']]); } catch (Exception $e) { $info->result = false; - $info->message = G::LoadTranslation('ID_PROCESSMAKER_WRITE_CONFIG_INDEX', SYS_LANG, array(PATH_HTML . "index.html.")); + $info->message = G::LoadTranslation('ID_PROCESSMAKER_WRITE_CONFIG_INDEX', SYS_LANG, [PATH_HTML . "index.html."]); $info->message .= G::LoadTranslation('ID_PROCESSMAKER_UI_NOT_INSTALL'); - $this->installLog(G::LoadTranslation('ID_INSTALL_BUT_ERROR', SYS_LANG, array('index.html'))); + $this->installLog(G::LoadTranslation('ID_INSTALL_BUT_ERROR', SYS_LANG, ['index.html'])); return $info; } } - $this->installLog(G::LoadTranslation('ID_INDEX_FILE_UPDATED', SYS_LANG, array($indexFileUpdated, $sysConf['default_lang'], $sysConf['default_skin']))); + $this->installLog(G::LoadTranslation('ID_INDEX_FILE_UPDATED', SYS_LANG, [$indexFileUpdated, $sysConf['default_lang'], $sysConf['default_skin']])); $this->installLog(G::LoadTranslation('ID_INSTALL_SUCESS')); $info->result = true; $info->message = G::LoadTranslation('ID_INSTALL_SUCESS'); - $info->messageFinish = G::LoadTranslation('ID_PROCESSMAKER_SUCCESS_INSTALLED', SYS_LANG, array($workspace));; + $info->messageFinish = G::LoadTranslation('ID_PROCESSMAKER_SUCCESS_INSTALLED', SYS_LANG, [$workspace]); } catch (Exception $e) { $info->canRedirect = false; $info->result = false; @@ -1185,7 +1232,7 @@ class InstallerModule extends Controller $this->mssqlQuery(@file_get_contents(PATH_HOME . 'engine/plugins/enterprise/data/triggerAppDelegationUpdate.sql')); $this->mssqlQuery(@file_get_contents(PATH_HOME . 'engine/plugins/enterprise/data/triggerApplicationUpdate.sql')); $this->mssqlQuery(@file_get_contents(PATH_HOME . 'engine/plugins/enterprise/data/triggerApplicationDelete.sql')); - $this->mysqlQuery(@file_get_contents(PATH_HOME . "engine/methods/setup/setupSchemas/triggerSubApplicationInsert.sql")); + $this->mssqlQuery(@file_get_contents(PATH_HOME . "engine/methods/setup/setupSchemas/triggerSubApplicationInsert.sql")); $this->mssqlQuery(@file_get_contents(PATH_HOME . 'engine/plugins/enterprise/data/triggerContentUpdate.sql')); $this->mssqlQuery("INSERT INTO CONFIGURATION ( CFG_UID, @@ -1197,7 +1244,7 @@ class InstallerModule extends Controller ))) . "' )"); - $this->mssqlQuery("INSERT INTO EMAIL_SERVER(MESS_UID, MESS_ENGINE) VALUES('" . \ProcessMaker\Util\Common::generateUID() . "','MAIL')"); + $this->mssqlQuery("INSERT INTO EMAIL_SERVER(MESS_UID, MESS_ENGINE) VALUES('" . Common::generateUID() . "','MAIL')"); } //change admin user @@ -1230,7 +1277,6 @@ class InstallerModule extends Controller $info->message = G::LoadTranslation('ID_INSTALL_SUCESS'); $info->url = '/sys' . $_REQUEST['workspace'] . '/en/neoclassic/login/login'; $info->messageFinish = G::LoadTranslation('ID_PROCESSMAKER_SUCCESS_INSTALLED', SYS_LANG, array($workspace)); - ; } catch (Exception $e) { $info->result = false; $info->message = $e->getMessage(); @@ -1254,10 +1300,15 @@ class InstallerModule extends Controller return $systemName; } + /** + * Get the Database engines list + * + * @return object + */ public function getEngines() { $this->setResponseType('json'); - $engines = array(); + $engines = []; if (function_exists('mysqli_query')) { $engine = new stdclass(); $engine->id = 'mysql'; @@ -1290,15 +1341,13 @@ class InstallerModule extends Controller switch ($_REQUEST['db_engine']) { case 'mysql': - if ($db_port !== '3306') { - $db_hostname = $db_hostname . ':' . $db_port; - } $wfDatabase = $filter->validateInput($_REQUEST['wfDatabase'], 'nosql'); - $link = mysqli_connect($db_hostname, $db_username, $db_password, $wfDatabase); - $query = "show databases like '%s' "; - $query = $filter->preventSqlInjection($query, array($wfDatabase), $link); - $dataSet = mysqli_query($link, $query); - $info->wfDatabaseExists = (mysqli_num_rows($dataSet) > 0); + + self::setNewConnection(self::CONNECTION_TEST_INSTALL, $db_hostname, $db_username, $db_password, '', $db_port); + $response = DB::connection(self::CONNECTION_TEST_INSTALL) + ->select("show databases like '$wfDatabase'"); + + $info->wfDatabaseExists = count($response) > 0; break; case 'mssql': $link = @mssql_connect($db_hostname, $db_username, $db_password); @@ -1332,51 +1381,53 @@ class InstallerModule extends Controller private function testMySQLConnection() { - $filter = new InputFilter(); - $info = new StdClass(); - $info->result = false; - $info->message = ''; - if (!function_exists('mysqli_connect')) { - $info->message = G::LoadTranslation('ID_PHP_MYSQLI_NOT_INSTALL'); - return $info; - } - $dataRequest = $_REQUEST; - $db_hostname = $filter->validateInput($dataRequest['db_hostname']); - $db_port = $filter->validateInput($dataRequest['db_port']); - $db_username = $filter->validateInput($dataRequest['db_username']); - $db_password = urlencode($dataRequest['db_password']); - $db_password = urldecode($filter->validateInput($db_password)); - $fp = @fsockopen($db_hostname, $db_port, $errno, $errstr, 30); - if (!$fp) { - $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR', SYS_LANG, array("$errstr ($errno)")); - return $info; - } + try { + $filter = new InputFilter(); + $info = new StdClass(); + $info->result = false; + $info->message = ''; + if (!function_exists('mysqli_connect')) { + $info->message = G::LoadTranslation('ID_PHP_MYSQLI_NOT_INSTALL'); + return $info; + } + $dataRequest = $_REQUEST; + $db_hostname = $filter->validateInput($dataRequest['db_hostname']); + $db_port = $filter->validateInput($dataRequest['db_port']); + $db_username = $filter->validateInput($dataRequest['db_username']); + $db_password = urlencode($dataRequest['db_password']); + $db_password = urldecode($filter->validateInput($db_password)); + $fp = @fsockopen($db_hostname, $db_port, $errno, $errstr, 30); + if (!$fp) { + $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR', SYS_LANG, ["$errstr ($errno)"]); + return $info; + } - $db_host = ($db_port !== '' && $db_port !== 1433) ? $db_hostname . ':' . $db_port : $db_hostname; + $db_username = $filter->validateInput($db_username, 'nosql'); + $db_hostname = $filter->validateInput($db_hostname, 'nosql'); - $link = new mysqli($db_host, $db_username, $db_password); - if ($link->connect_error) { - $info->message .= G::LoadTranslation('ID_MYSQL_CREDENTIALS_WRONG'); - return $info; + self::setNewConnection(self::CONNECTION_TEST_INSTALL, $db_hostname, $db_username, $db_password, '', $db_port); + $query = "SELECT * FROM `information_schema`.`USER_PRIVILEGES` where (GRANTEE = \"'$db_username'@'$db_hostname'\" OR GRANTEE = \"'$db_username'@'%%'\") "; + + $response = DB::connection(self::CONNECTION_TEST_INSTALL)->select($query); + + if (!is_array($response)) { + $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR_PRIVILEGE', SYS_LANG, [$db_username]); + return $info; + } + $info->message .= G::LoadTranslation('ID_MYSQL_SUCCESS_CONNECT'); + $info->result = true; + } catch (Exception $e) { + $info->result = false; + $info->message = G::LoadTranslation('ID_MYSQL_CREDENTIALS_WRONG'); } - $db_username = $filter->validateInput($db_username, 'nosql'); - $db_hostname = $filter->validateInput($db_hostname, 'nosql'); - $query = "SELECT * FROM `information_schema`.`USER_PRIVILEGES` where (GRANTEE = \"'%s'@'%s'\" OR GRANTEE = \"'%s'@'%%'\") "; - $query = $filter->preventSqlInjection($query, array($db_username, $db_hostname, $db_username), $link); - $res = $link->query($query); - $row = $res->fetch_array(); - $hasSuper = is_array($row); - $res->free(); - $link->close(); - if (!$hasSuper) { - $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR_PRIVILEGE', SYS_LANG, array($db_username)); - return $info; - } - $info->message .= G::LoadTranslation('ID_MYSQL_SUCCESS_CONNECT'); - $info->result = true; return $info; } + /** + * This function test a SQL Server connection + * + * @return object + */ private function testMSSQLConnection() { $filter = new InputFilter(); @@ -1400,6 +1451,7 @@ class InstallerModule extends Controller $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR', SYS_LANG, array("$errstr ($errno)")); return $info; } + \Illuminate\Support\Facades\DB::connection(); $db_host = ($db_port != '' && $db_port != 1433) ? $db_hostname . ':' . $db_port : $db_hostname; @@ -1454,13 +1506,18 @@ class InstallerModule extends Controller return $info; } - public function setPartner() + /** + * This function define the partner behaviour when the PARTNER_FLAG is defined + * Execute to change of skin + * + * @return void + */ + private function setPartner() { if (defined('PARTNER_FLAG') || isset($_REQUEST['PARTNER_FLAG'])) { // Execute sql for partner $pathMysqlPartner = PATH_CORE . 'data' . PATH_SEP . 'partner' . PATH_SEP . 'mysql' . PATH_SEP; if (G::verifyPath($pathMysqlPartner)) { - $res = array(); $filesSlq = glob($pathMysqlPartner . '*.sql'); foreach ($filesSlq as $value) { $this->mysqlFileQuery($value); @@ -1470,7 +1527,6 @@ class InstallerModule extends Controller // Execute to change of skin $pathSkinPartner = PATH_CORE . 'data' . PATH_SEP . 'partner' . PATH_SEP . 'skin' . PATH_SEP; if (G::verifyPath($pathSkinPartner)) { - $res = array(); $fileTar = glob($pathSkinPartner . '*.tar'); foreach ($fileTar as $value) { $dataFile = pathinfo($value); @@ -1503,10 +1559,19 @@ class InstallerModule extends Controller } } + /** + * Copy a directory or file + * + * @param string $fromDir + * @param string $toDir + * @param integer $chmod + * + * @return void + */ public function copyFile($fromDir, $toDir, $chmod = 0777) { - $errors = array(); - $messages = array(); + $errors = []; + $messages = []; if (!is_writable($toDir)) { $errors[] = 'target ' . $toDir . ' is not writable'; @@ -1546,32 +1611,33 @@ class InstallerModule extends Controller closedir($handle); } - public function setConfiguration() - { - //a:4:{s:26:"login_enableForgotPassword";b:0;s:27:"login_enableVirtualKeyboard";b:0;s:21:"login_defaultLanguage";s:5:"pt-BR";s:10:"dateFormat";s:15:"d \\d\\e F \\d\\e Y";} - $value = array( - 'login_defaultLanguage' => "pt-BR", - "dateFormat" => 'd \d\e F \d\e Y' - ); - - $value = serialize($value); - $query = "INSERT INTO CONFIGURATION (CFG_UID, CFG_VALUE) VALUES ('ENVIRONMENT_SETTINGS', '" . mysqli_real_escape_string($this->link, $value) . "')"; - - $this->mysqlQuery($query); - } - - public function buildParternExtras($username, $password, $workspace, $lang, $skinName) + /** + * Define build Pattern Extras related to: + * Upload translation .po file + * Upload skin file + * Upload plugin file + * Active plugins to enterprise + * + * @param string $username + * @param string $password + * @param string $workspace + * @param string $lang + * @param string $skinName + * + * @return void + */ + private function buildParternExtras($username, $password, $workspace, $lang, $skinName) { $filter = new InputFilter(); ini_set('max_execution_time', '0'); ini_set('memory_limit', '256M'); $serv = 'http://'; - if (isset($_SERVER['HTTPS']) && trim($_SERVER['HTTPS']) != '') { + if (isset($_SERVER['HTTPS']) && !empty(trim($_SERVER['HTTPS']))) { $serv = 'https://'; } $serv .= $_SERVER['SERVER_NAME']; - if (isset($_SERVER['SERVER_PORT']) && trim($_SERVER['SERVER_PORT']) != '') { + if (isset($_SERVER['SERVER_PORT']) && !empty(trim($_SERVER['SERVER_PORT']))) { $serv .= ':' . $_SERVER['SERVER_PORT']; } @@ -1610,7 +1676,7 @@ class InstallerModule extends Controller */ $ch = curl_init(); - $postData = array(); + $postData = []; // File to upload/post $postData['form[LANGUAGE_FILENAME]'] = "@" . PATH_CORE . "content/translations/processmaker.$lang.po"; @@ -1633,7 +1699,7 @@ class InstallerModule extends Controller */ $ch = curl_init(); - $postData = array(); + $postData = []; $skins = glob(PATH_CORE . "data/partner/*.tar"); if (count($skins) > 0) { @@ -1666,7 +1732,7 @@ class InstallerModule extends Controller */ $ch = curl_init(); - $postData = array(); + $postData = []; // resolv the plugin name $plugins = glob(PATH_CORE . "plugins/*.tar"); if (count($plugins) > 0) { @@ -1703,7 +1769,7 @@ class InstallerModule extends Controller foreach ($plugins as $value) { $dataPlugin = pathinfo($value); $namePlugin = $dataPlugin['filename']; - if ($value != 'enterprise') { + if ($value !== 'enterprise') { $db_hostname = trim($_REQUEST['db_hostname']); $db_hostname = $filter->validateInput($db_hostname); $db_port = trim($_REQUEST['db_port']); @@ -1717,12 +1783,15 @@ class InstallerModule extends Controller $db_host = ($db_port != '' && $db_port != 3306) ? $db_hostname . ':' . $db_port : $db_hostname; - $link = mysqli_connect($db_host, $db_username, $db_password, $wf); - mysqli_select_db($link, $wf); - $res = mysqli_query($link, "SELECT STORE_ID FROM ADDONS_MANAGER WHERE ADDON_NAME = '" . $namePlugin . "'"); - if ($row = mysqli_fetch_array($res)) { + $row = DB::connection(self::CONNECTION_INSTALL) + ->table('ADDONS_MANAGER') + ->select('STORE_ID') + ->where('ADDON_NAME', $namePlugin) + ->toArray(); + + if ($row) { $ch = curl_init(); - $postData = array(); + $postData = []; $postData['action'] = "enable"; $postData['addon'] = $namePlugin; $postData['store'] = $row['STORE_ID']; diff --git a/workflow/engine/methods/setup/upgrade_SystemAjax.php b/workflow/engine/methods/setup/upgrade_SystemAjax.php index 982ed4be2..a76bf82fe 100644 --- a/workflow/engine/methods/setup/upgrade_SystemAjax.php +++ b/workflow/engine/methods/setup/upgrade_SystemAjax.php @@ -1,64 +1,43 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ + global $DB_ADAPTER; global $DB_HOST; global $DB_USER; global $DB_PASS; global $DB_NAME; -set_time_limit( 0 ); +set_time_limit(0); $id = ''; -if (isset( $_POST['id'] )) +if (isset($_POST['id'])) $id = $_POST['id']; -$aUpgradeData = unserialize( file_get_contents( PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin" ) ); -$aWorkspaces = $aUpgradeData['workspaces']; +$upgradeData = unserialize(file_get_contents(PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin")); +$workspaces = $upgradeData['workspaces']; -if (is_array( $aWorkspaces ) && count( $aWorkspaces ) > 0) { - $workspace = array_shift( $aUpgradeData['workspaces'] ); +if (is_array($workspaces) && count($workspaces) > 0) { + $workspace = array_shift($upgradeData['workspaces']); - eval( getDatabaseCredentials( PATH_DB . $workspace . PATH_SEP . 'db.php' ) ); - $oDataBase = new database( $DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME ); - $oDataBase->iFetchType = MYSQL_NUM; + eval(getDatabaseCredentials(PATH_DB . $workspace . PATH_SEP . 'db.php')); + $database = new database($DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); + $database->iFetchType = MYSQLI_NUM; //processing .po file - if ($aUpgradeData['sPoFile'] != '') { + if (!empty($upgradeData['sPoFile'])) { $oLanguages = new languages(); - $oLanguages->importLanguage( $aUpgradeData['sPoFile'], $aUpgradeData['bForceXmlPoFile'] ); - $aUpgradeData['bForceXmlPoFile'] = false; + $oLanguages->importLanguage($upgradeData['sPoFile'], $upgradeData['bForceXmlPoFile']); + $upgradeData['bForceXmlPoFile'] = false; } - if ($aUpgradeData['sSchemaFile'] != '') - processMasterSchemaFile( $aUpgradeData['sSchemaFile'] ); + if ($upgradeData['sSchemaFile'] != '') + processMasterSchemaFile($upgradeData['sSchemaFile']); - //draw a gauge control indicating the progress in workspaces - $gauge = intval( (($aUpgradeData['wsQuantity'] - count( $aWorkspaces ) + 1) / $aUpgradeData['wsQuantity']) * 301 ); + //draw a gauge control indicating the progress in workspaces + $gauge = intval((($upgradeData['wsQuantity'] - count($workspaces) + 1) / $upgradeData['wsQuantity']) * 301); print "
"; print "
"; print "
"; - print "
Upgrading the workspace ".$filter->xssFilterHard($workspace)."| ".$filter->xssFilterHard($id)." Remaining
"; - file_put_contents( PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize( $aUpgradeData ) ); + print " Upgrading the workspace " . $filter->xssFilterHard($workspace) . "| " . $filter->xssFilterHard($id) . " Remaining"; + file_put_contents(PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize($upgradeData)); } else { print "
    "; print "
"; @@ -68,92 +47,92 @@ if (is_array( $aWorkspaces ) && count( $aWorkspaces ) > 0) { die(); -function getDatabaseCredentials ($dbFile) +function getDatabaseCredentials($dbFile) { - $sContent = file_get_contents( $dbFile ); - $sContent = str_replace( '', '', $sContent ); - $sContent = str_replace( 'define', '', $sContent ); - $sContent = str_replace( "('", '$', $sContent ); - $sContent = str_replace( "',", '=', $sContent ); - $sContent = str_replace( ");", ';', $sContent ); + $sContent = file_get_contents($dbFile); + $sContent = str_replace('', '', $sContent); + $sContent = str_replace('define', '', $sContent); + $sContent = str_replace("('", '$', $sContent); + $sContent = str_replace("',", '=', $sContent); + $sContent = str_replace(");", ';', $sContent); return $sContent; } -function processMasterSchemaFile ($sSchemaFile) +function processMasterSchemaFile($schemaFile) { global $DB_ADAPTER; global $DB_HOST; global $DB_USER; global $DB_PASS; global $DB_NAME; - global $aUpgradeData; + global $upgradeData; //convert newSchema to array - if (isset( $aUpgradeData['aNewSchema'] )) { - $aNewSchema = $aUpgradeData['aNewSchema']; + if (isset($upgradeData['aNewSchema'])) { + $newSchema = $upgradeData['aNewSchema']; } else { - $aNewSchema = schemaToArray( $sSchemaFile ); - $aUpgradeData['aNewSchema'] = $aNewSchema; + $newSchema = schemaToArray($schemaFile); + $upgradeData['aNewSchema'] = $newSchema; } - $aOldSchema = processSchemaFile(); - if (is_null( $aOldSchema )) { + $oldSchema = processSchemaFile(); + if (is_null($oldSchema)) { return; } - $aChanges = obtainChanges( $aOldSchema, $aNewSchema ); + $changes = obtainChanges($oldSchema, $newSchema); - $oDataBase = new database( $DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME ); - if (! $oDataBase->isConnected()) { + $database = new database($DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); + if (!$database->isConnected()) { return; } - $oDataBase->iFetchType = MYSQL_NUM; + $database->iFetchType = MYSQLI_NUM; - $oDataBase->logQuery( count( $aChanges ) ); + $database->logQuery(count($changes)); - foreach ($aChanges['tablesToAdd'] as $sTable => $aColumns) { - $oDataBase->executeQuery( $oDataBase->generateCreateTableSQL( $sTable, $aColumns ) ); - if (isset( $aChanges['tablesToAdd'][$sTable]['INDEXES'] )) { - foreach ($aChanges['tablesToAdd'][$sTable]['INDEXES'] as $indexName => $aIndex) { - $oDataBase->executeQuery( $oDataBase->generateAddKeysSQL( $sTable, $indexName, $aIndex ) ); + foreach ($changes['tablesToAdd'] as $table => $columns) { + $database->executeQuery($database->generateCreateTableSQL($table, $columns)); + if (isset($changes['tablesToAdd'][$table]['INDEXES'])) { + foreach ($changes['tablesToAdd'][$table]['INDEXES'] as $indexName => $attribute) { + $database->executeQuery($database->generateAddKeysSQL($table, $indexName, $attribute)); } } } - foreach ($aChanges['tablesToAlter'] as $sTable => $aActions) { - foreach ($aActions as $sAction => $aAction) { - foreach ($aAction as $sColumn => $vData) { - switch ($sAction) { + foreach ($changes['tablesToAlter'] as $table => $actions) { + foreach ($actions as $key => $action) { + foreach ($action as $column => $data) { + switch ($key) { case 'DROP': - $oDataBase->executeQuery( $oDataBase->generateDropColumnSQL( $sTable, $vData ) ); + $database->executeQuery($database->generateDropColumnSQL($table, $data)); break; case 'ADD': - $oDataBase->executeQuery( $oDataBase->generateAddColumnSQL( $sTable, $sColumn, $vData ) ); + $database->executeQuery($database->generateAddColumnSQL($table, $column, $data)); break; case 'CHANGE': - $oDataBase->executeQuery( $oDataBase->generateChangeColumnSQL( $sTable, $sColumn, $vData ) ); + $database->executeQuery($database->generateChangeColumnSQL($table, $column, $data)); break; } } } } - foreach ($aChanges['tablesWithNewIndex'] as $sTable => $aIndexes) { - foreach ($aIndexes as $sIndexName => $aIndexFields) { - $oDataBase->executeQuery( $oDataBase->generateAddKeysSQL( $sTable, $sIndexName, $aIndexFields ) ); + foreach ($changes['tablesWithNewIndex'] as $table => $index) { + foreach ($index as $indexName => $indexFields) { + $database->executeQuery($database->generateAddKeysSQL($table, $indexName, $indexFields)); } } - foreach ($aChanges['tablesToAlterIndex'] as $sTable => $aIndexes) { - foreach ($aIndexes as $sIndexName => $aIndexFields) { - $oDataBase->executeQuery( $oDataBase->generateDropKeySQL( $sTable, $sIndexName ) ); - $oDataBase->executeQuery( $oDataBase->generateAddKeysSQL( $sTable, $sIndexName, $aIndexFields ) ); + foreach ($changes['tablesToAlterIndex'] as $table => $index) { + foreach ($index as $indexName => $indexFields) { + $database->executeQuery($database->generateDropKeySQL($table, $indexName)); + $database->executeQuery($database->generateAddKeysSQL($table, $indexName, $indexFields)); } } - $oDataBase->close(); + $database->close(); } -function processSchemaFile () +function processSchemaFile() { global $DB_ADAPTER; global $DB_HOST; @@ -162,232 +141,210 @@ function processSchemaFile () global $DB_NAME; try { + $oldSchema = []; + $database = new database($DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); - - $aOldSchema = array (); - $oDataBase = new database( $DB_ADAPTER, $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME ); - - if (! $oDataBase->isConnected()) { - $oDataBase->logQuery( G::LoadTranslation('ID_DOES_NOT_EXIST_AVAILABLE_CONNECTION') ); + if (!$database->isConnected()) { + $database->logQuery(G::LoadTranslation('ID_DOES_NOT_EXIST_AVAILABLE_CONNECTION')); return null; } - $oDataBase->iFetchType = MYSQL_NUM; - $oDataset1 = $oDataBase->executeQuery( $oDataBase->generateShowTablesSQL() ); + $database->iFetchType = MYSQLI_NUM; + $result = $database->executeQuery($database->generateShowTablesSQL()); } catch (Exception $e) { - $oDataBase->logQuery( $e->getmessage() ); + $database->logQuery($e->getmessage()); return null; } //going thru all tables in current WF_ database - while ($aRow1 = $oDataBase->getRegistry( $oDataset1 )) { - $aPrimaryKeys = array (); - $sTable = strtoupper( $aRow1[0] ); + foreach ($result as $table) { + $table = strtoupper($table); //get description of each table, ( column and primary keys ) - //$oDataset2 = $oDataBase->executeQuery( $oDataBase->generateDescTableSQL($aRow1[0]) ); - $oDataset2 = $oDataBase->executeQuery( $oDataBase->generateDescTableSQL( $sTable ) ); - $aOldSchema[$sTable] = array (); - $oDataBase->iFetchType = MYSQL_ASSOC; - while ($aRow2 = $oDataBase->getRegistry( $oDataset2 )) { - $aOldSchema[$sTable][$aRow2['Field']]['Field'] = $aRow2['Field']; - $aOldSchema[$sTable][$aRow2['Field']]['Type'] = $aRow2['Type']; - $aOldSchema[$sTable][$aRow2['Field']]['Null'] = $aRow2['Null']; - $aOldSchema[$sTable][$aRow2['Field']]['Default'] = $aRow2['Default']; + $database->iFetchType = MYSQLI_ASSOC; + $description = $database->executeQuery($database->generateDescTableSQL($table)); + $oldSchema[$table] = []; + foreach ($description as $field) { + $oldSchema[$table][$field['Field']]['Field'] = $field['Field']; + $oldSchema[$table][$field['Field']]['Type'] = $field['Type']; + $oldSchema[$table][$field['Field']]['Null'] = $field['Null']; + $oldSchema[$table][$field['Field']]['Default'] = $field['Default']; } //get indexes of each table SHOW INDEX FROM `ADDITIONAL_TABLES`; -- WHERE Key_name <> 'PRIMARY' - $oDataset2 = $oDataBase->executeQuery( $oDataBase->generateTableIndexSQL( $aRow1[0] ) ); - $oDataBase->iFetchType = MYSQL_ASSOC; - while ($aRow2 = $oDataBase->getRegistry( $oDataset2 )) { - if (! isset( $aOldSchema[$sTable]['INDEXES'] )) { - $aOldSchema[$sTable]['INDEXES'] = array (); + $description = $database->executeQuery($database->generateTableIndexSQL($table)); + foreach ($description as $field) { + if (!isset($oldSchema[$table]['INDEXES'])) { + $oldSchema[$table]['INDEXES'] = []; } - if (! isset( $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']] )) { - $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']] = array (); + if (!isset($oldSchema[$table]['INDEXES'][$field['Key_name']])) { + $oldSchema[$table]['INDEXES'][$field['Key_name']] = []; } - $aOldSchema[$sTable]['INDEXES'][$aRow2['Key_name']][] = $aRow2['Column_name']; + $oldSchema[$table]['INDEXES'][$field['Key_name']][] = $field['Column_name']; } - - $oDataBase->iFetchType = MYSQL_NUM; //this line is neccesary because the next fetch needs to be with MYSQL_NUM } //finally return the array with old schema obtained from the Database - if (count( $aOldSchema ) == 0) - $aOldSchema = null; - return $aOldSchema; + if (count($oldSchema) === 0) { + $oldSchema = null; + } + return $oldSchema; } //process the schema file in the patch file, and obtain an array -function schemaToArray ($sSchemaFile) +function schemaToArray($schemaFile) { try { - $aSchema = array (); - $oXml = new DomDocument(); - $oXml->load( $sSchemaFile ); - $aTables = $oXml->getElementsByTagName( 'table' ); - foreach ($aTables as $oTable) { - $aPrimaryKeys = array (); - $sTableName = $oTable->getAttribute( 'name' ); - $aSchema[$sTableName] = array (); - $aColumns = $oTable->getElementsByTagName( 'column' ); - foreach ($aColumns as $oColumn) { - $sColumName = $oColumn->getAttribute( 'name' ); - $aSchema[$sTableName][$sColumName] = array (); - $aVendors = $oColumn->getElementsByTagName( 'vendor' ); - foreach ($aVendors as $oVendor) { - if ($oVendor->getAttribute( 'type' ) == DB_ADAPTER) { + $schema = []; + $xml = new DomDocument(); + $xml->load($schemaFile); + $tables = $xml->getElementsByTagName('table'); + foreach ($tables as $table) { + $primaryKeys = []; + $tableName = $table->getAttribute('name'); + $schema[$tableName] = []; + $columns = $table->getElementsByTagName('column'); + foreach ($columns as $column) { + $columnName = $column->getAttribute('name'); + $schema[$tableName][$columnName] = []; + $vendors = $column->getElementsByTagName('vendor'); + foreach ($vendors as $vendor) { + if ($vendor->getAttribute('type') == config('connections.driver')) { break; } } - $aParameters = $oColumn->getElementsByTagName( 'parameter' ); - foreach ($aParameters as $oParameter) { - $parameterName = ucwords( $oParameter->getAttribute( 'name' ) ); - if ($parameterName == 'Key' && strtoupper( $oParameter->getAttribute( 'value' ) ) == 'PRI') { - $aPrimaryKeys[] = $oColumn->getAttribute( 'name' ); + $parameters = $column->getElementsByTagName('parameter'); + foreach ($parameters as $oParameter) { + $parameterName = ucwords($oParameter->getAttribute('name')); + if ($parameterName == 'Key' && strtoupper($oParameter->getAttribute('value')) == 'PRI') { + $primaryKeys[] = $column->getAttribute('name'); } - if (in_array( $parameterName, array ('Field','Type','Null','Default' - ) )) { - $aSchema[$sTableName][$sColumName][$parameterName] = $oParameter->getAttribute( 'value' ); + if (in_array($parameterName, ['Field', 'Type', 'Null', 'Default'])) { + $schema[$tableName][$columnName][$parameterName] = $oParameter->getAttribute('value'); } } } - if (is_array( $aPrimaryKeys ) && count( $aPrimaryKeys ) > 0) { - $aSchema[$sTableName]['INDEXES']['PRIMARY'] = $aPrimaryKeys; + if (is_array($primaryKeys) && count($primaryKeys) > 0) { + $schema[$tableName]['INDEXES']['PRIMARY'] = $primaryKeys; } - $aIndexes = $oTable->getElementsByTagName( 'index' ); - foreach ($aIndexes as $oIndex) { - $aIndex = array (); - $aIndexesColumns = $oIndex->getElementsByTagName( 'index-column' ); + $index = $table->getElementsByTagName('index'); + foreach ($index as $fieldIndex) { + $attribute = []; + $aIndexesColumns = $fieldIndex->getElementsByTagName('index-column'); foreach ($aIndexesColumns as $oIndexColumn) { - $aIndex[] = $oIndexColumn->getAttribute( 'name' ); + $attribute[] = $oIndexColumn->getAttribute('name'); } - $aSchema[$sTableName]['INDEXES'][$oIndex->getAttribute( 'name' )] = $aIndex; + $schema[$tableName]['INDEXES'][$fieldIndex->getAttribute('name')] = $attribute; } } - return $aSchema; + return $schema; } catch (Exception $oError) { throw $oError; } } -function obtainChanges ($aOldSchema, $aNewSchema) +function obtainChanges($oldSchema, $newSchema) { - //$aChanges = array('tablesToDelete' => array(), 'tablesToAdd' => array(), 'tablesToAlter' => array()); - //Tables to delete, but this is disabled - //foreach ($aOldSchema as $sTableName => $aColumns) { - // if ( !isset($aNewSchema[$sTableName])) { - // if (!in_array($sTableName, array('KT_APPLICATION', 'KT_DOCUMENT', 'KT_PROCESS'))) { - // $aChanges['tablesToDelete'][] = $sTableName; - // } - // } - //} - - $aChanges = array ('tablesToAdd' => array (),'tablesToAlter' => array (),'tablesWithNewIndex' => array (),'tablesToAlterIndex' => array () - ); + $changes = ['tablesToAdd' => [], 'tablesToAlter' => [], 'tablesWithNewIndex' => [], 'tablesToAlterIndex' => []]; //new tables to create and alter - foreach ($aNewSchema as $sTableName => $aColumns) { - if (! isset( $aOldSchema[$sTableName] )) { - $aChanges['tablesToAdd'][$sTableName] = $aColumns; + foreach ($newSchema as $tableName => $columns) { + if (!isset($oldSchema[$tableName])) { + $changes['tablesToAdd'][$tableName] = $columns; } else { //drop old columns - foreach ($aOldSchema[$sTableName] as $sColumName => $aParameters) { - if (! isset( $aNewSchema[$sTableName][$sColumName] )) { - if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { - $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () - ); + foreach ($oldSchema[$tableName] as $columnName => $parameters) { + if (!isset($newSchema[$tableName][$columnName])) { + if (!isset($changes['tablesToAlter'][$tableName])) { + $changes['tablesToAlter'][$tableName] = ['DROP' => [], 'ADD' => [], 'CHANGE' => []]; } - $aChanges['tablesToAlter'][$sTableName]['DROP'][$sColumName] = $sColumName; + $changes['tablesToAlter'][$tableName]['DROP'][$columnName] = $columnName; } } //create new columns - //foreach ($aNewSchema[$sTableName] as $sColumName => $aParameters) { - foreach ($aColumns as $sColumName => $aParameters) { - if ($sColumName != 'INDEXES') { - if (! isset( $aOldSchema[$sTableName][$sColumName] )) { //this column doesnt exist in oldschema - if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { - $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () - ); + foreach ($columns as $columnName => $parameters) { + if ($columnName != 'INDEXES') { + if (!isset($oldSchema[$tableName][$columnName])) { //this column doesnt exist in oldschema + if (!isset($changes['tablesToAlter'][$tableName])) { + $changes['tablesToAlter'][$tableName] = ['DROP' => [], 'ADD' => [], 'CHANGE' => []]; } - $aChanges['tablesToAlter'][$sTableName]['ADD'][$sColumName] = $aParameters; + $changes['tablesToAlter'][$tableName]['ADD'][$columnName] = $parameters; } else { //the column exists - $newField = $aNewSchema[$sTableName][$sColumName]; - $oldField = $aOldSchema[$sTableName][$sColumName]; + $newField = $newSchema[$tableName][$columnName]; + $oldField = $oldSchema[$tableName][$columnName]; //both are null, no change is required - if (! isset( $newField['Default'] ) && ! isset( $oldField['Default'] )) + if (!isset($newField['Default']) && !isset($oldField['Default'])) $changeDefaultAttr = false; - //one of them is null, change IS required - if (! isset( $newField['Default'] ) && isset( $oldField['Default'] ) && $oldField['Default'] != '') + //one of them is null, change IS required + if (!isset($newField['Default']) && isset($oldField['Default']) && $oldField['Default'] != '') $changeDefaultAttr = true; - if (isset( $newField['Default'] ) && ! isset( $oldField['Default'] )) + if (isset($newField['Default']) && !isset($oldField['Default'])) $changeDefaultAttr = true; - //both are defined and they are different. - if (isset( $newField['Default'] ) && isset( $oldField['Default'] )) { - if ($newField['Default'] != $oldField['Default']) + //both are defined and they are different. + if (isset($newField['Default']) && isset($oldField['Default'])) { + $changeDefaultAttr = false; + if ($newField['Default'] != $oldField['Default']) { $changeDefaultAttr = true; - else - $changeDefaultAttr = false; + } } //special cases // BLOB and TEXT columns cannot have DEFAULT values. http://dev.mysql.com/doc/refman/5.0/en/blob.html - if (in_array( strtolower( $newField['Type'] ), array ('text','mediumtext' - ) )) + if (in_array(strtolower($newField['Type']), ['text', 'mediumtext'])) $changeDefaultAttr = false; - //#1067 - Invalid default value for datetime field - if (in_array( $newField['Type'], array ('datetime' - ) ) && isset( $newField['Default'] ) && $newField['Default'] == '') + //#1067 - Invalid default value for datetime field + if (in_array($newField['Type'], ['datetime']) && isset($newField['Default']) && $newField['Default'] == '') { $changeDefaultAttr = false; + } - //#1067 - Invalid default value for int field - if (substr( $newField['Type'], 0, 3 ) && isset( $newField['Default'] ) && $newField['Default'] == '') + //#1067 - Invalid default value for int field + if (substr($newField['Type'], 0, 3) && isset($newField['Default']) && $newField['Default'] == '') { $changeDefaultAttr = false; + } - //if any difference exists, then insert the difference in aChanges + //if any difference exists, then insert the difference in aChanges if ($newField['Field'] != $oldField['Field'] || $newField['Type'] != $oldField['Type'] || $newField['Null'] != $oldField['Null'] || $changeDefaultAttr) { - if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { - $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () - ); + if (!isset($changes['tablesToAlter'][$tableName])) { + $changes['tablesToAlter'][$tableName] = ['DROP' => [], 'ADD' => [], 'CHANGE' => []]; + } + $changes['tablesToAlter'][$tableName]['CHANGE'][$columnName]['Field'] = $newField['Field']; + $changes['tablesToAlter'][$tableName]['CHANGE'][$columnName]['Type'] = $newField['Type']; + $changes['tablesToAlter'][$tableName]['CHANGE'][$columnName]['Null'] = $newField['Null']; + if (isset($newField['Default'])) { + $changes['tablesToAlter'][$tableName]['CHANGE'][$columnName]['Default'] = $newField['Default']; + } else { + $changes['tablesToAlter'][$tableName]['CHANGE'][$columnName]['Default'] = null; } - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Field'] = $newField['Field']; - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Type'] = $newField['Type']; - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Null'] = $newField['Null']; - if (isset( $newField['Default'] )) - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = $newField['Default']; - else - $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = null; - } } } //only columns, no the indexes column - } //foreach $aColumns + } //foreach $columns //now check the indexes of table - if (isset( $aNewSchema[$sTableName]['INDEXES'] )) { - foreach ($aNewSchema[$sTableName]['INDEXES'] as $indexName => $indexFields) { - if (! isset( $aOldSchema[$sTableName]['INDEXES'][$indexName] )) { - if (! isset( $aChanges['tablesWithNewIndex'][$sTableName] )) { - $aChanges['tablesWithNewIndex'][$sTableName] = array (); + if (isset($newSchema[$tableName]['INDEXES'])) { + foreach ($newSchema[$tableName]['INDEXES'] as $indexName => $indexFields) { + if (!isset($oldSchema[$tableName]['INDEXES'][$indexName])) { + if (!isset($changes['tablesWithNewIndex'][$tableName])) { + $changes['tablesWithNewIndex'][$tableName] = []; } - $aChanges['tablesWithNewIndex'][$sTableName][$indexName] = $indexFields; + $changes['tablesWithNewIndex'][$tableName][$indexName] = $indexFields; } else { - if ($aOldSchema[$sTableName]['INDEXES'][$indexName] != $indexFields) { - if (! isset( $aChanges['tablesToAlterIndex'][$sTableName] )) { - $aChanges['tablesToAlterIndex'][$sTableName] = array (); + if ($oldSchema[$tableName]['INDEXES'][$indexName] != $indexFields) { + if (!isset($changes['tablesToAlterIndex'][$tableName])) { + $changes['tablesToAlterIndex'][$tableName] = []; } - $aChanges['tablesToAlterIndex'][$sTableName][$indexName] = $indexFields; + $changes['tablesToAlterIndex'][$tableName][$indexName] = $indexFields; } } } } } //for-else table exists } //for new schema - return $aChanges; + return $changes; } diff --git a/workflow/engine/src/ProcessMaker/Core/Installer.php b/workflow/engine/src/ProcessMaker/Core/Installer.php index 89a9e8a2b..896de30b4 100644 --- a/workflow/engine/src/ProcessMaker/Core/Installer.php +++ b/workflow/engine/src/ProcessMaker/Core/Installer.php @@ -4,9 +4,14 @@ namespace ProcessMaker\Core; use AppCacheView; use Archive_Tar; +use Bootstrap; use Configuration; use Exception; use G; +use Illuminate\Database\QueryException; +use Illuminate\Support\Facades\DB; +use InstallerModule; +use ProcessMaker\Util\Common; class Installer { @@ -16,6 +21,9 @@ class Installer public $report = []; private $connection_database; + const CONNECTION_INSTALL = 'install'; + const CONNECTION_TEST_INSTALL = 'testInstall'; + /** * construct of insert * @@ -31,18 +39,41 @@ class Installer * * @param array $config * @param boolean $confirmed - * @return void + * @return array */ - public function create_site($config = array(), $confirmed = false) + public function create_site($config = [], $confirmed = false) { - $this->options = G::array_concat(array('isset' => false, 'password' => G::generate_password(15), 'path_data' => @PATH_DATA, 'path_compiled' => @PATH_C, 'name' => $config['name'], 'database' => array(), 'admin' => array('username' => 'admin', 'password' => 'admin' - ), 'advanced' => array('ao_db_wf' => 'wf_' . $config['name'], 'ao_db_rb' => 'rb_' . $config['name'], 'ao_db_rp' => 'rp_' . $config['name'], 'ao_db_drop' => false - ) - ), $config); - $a = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); - $this->options['database'] = G::array_concat(array('username' => @$a[1], 'password' => @$a[2], 'hostname' => @$a[0] - ), $this->options['database']); - return ($confirmed === true) ? $this->make_site() : $this->create_site_test(); + $this->options = G::array_concat([ + 'isset' => false, + 'password' => G::generate_password(15), + 'path_data' => @PATH_DATA, + 'path_compiled' => @PATH_C, + 'name' => $config['name'], + 'database' => [], + 'admin' => ['username' => 'admin', 'password' => 'admin'], + 'advanced' => [ + 'ao_db_wf' => 'wf_' . $config['name'], + 'ao_db_rb' => 'rb_' . $config['name'], + 'ao_db_rp' => 'rp_' . $config['name'], + 'ao_db_drop' => false + ] + ], $config); + $configuration = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); + + $host = explode(':', $configuration[0]); + if (count($host) < 2) { + $host[1] = 3306; + } + $configuration[0] = $host[0]; + + $this->options['database'] = G::array_concat([ + 'username' => @$configuration[1], + 'password' => @$configuration[2], + 'hostname' => @$configuration[0], + 'port' => $host[1] + ], $this->options['database']); + + return $confirmed ? $this->make_site() : $this->create_site_test(); } /** @@ -67,30 +98,44 @@ class Installer /** * create_site_test * - * @return void + * @return array */ private function create_site_test() { - $name = (preg_match('/^[\w]+$/i', trim($this->options['name']))) ? true : false; - $result = array('path_data' => $this->is_dir_writable($this->options['path_data']), 'path_compiled' => $this->is_dir_writable($this->options['path_compiled']), 'database' => $this->check_connection(), 'access_level' => $this->cc_status, 'isset' => ($this->options['isset'] == true) ? $this->isset_site($this->options['name']) : false, 'microtime' => microtime(), 'workspace' => $this->options['name'], 'name' => array('status' => $name, 'message' => ($name) ? 'PASSED' : 'Workspace name invalid' - ), 'admin' => array('username' => (preg_match('/^[\w@\.-]+$/i', trim($this->options['admin']['username']))) ? true : false, 'password' => ((trim($this->options['admin']['password']) == '') ? false : true) - ) - ); - $result['name']['message'] = ($result['isset']) ? 'Workspace already exist' : $result['name']['message']; - $result['name']['status'] = ($result['isset']) ? false : $result['name']['status']; - return array('created' => G::var_compare( - true, - $result['path_data'], - $result['database']['connection'], - $result['name']['status'], - $result['database']['version'], - $result['database']['ao']['ao_db_wf']['status'], - $result['admin']['username'], - (($result['isset']) ? false : true), - $result['admin']['password'] - ), + $name = preg_match('/^[\w]+$/i', trim($this->options['name'])) ? true : false; + $result = [ + 'path_data' => $this->is_dir_writable($this->options['path_data']), + 'path_compiled' => $this->is_dir_writable($this->options['path_compiled']), + 'database' => $this->check_connection(self::CONNECTION_TEST_INSTALL), + 'access_level' => $this->cc_status, + 'isset' => $this->options['isset'] === true ? $this->isset_site($this->options['name']) : false, + 'microtime' => microtime(), + 'workspace' => $this->options['name'], + 'name' => [ + 'status' => $name, + 'message' => $name ? 'PASSED' : 'Workspace name invalid' + ], + 'admin' => [ + 'username' => preg_match('/^[\w@\.-]+$/i', trim($this->options['admin']['username'])) ? true : false, + 'password' => empty(trim($this->options['admin']['password'])) ? false : true + ] + ]; + $result['name']['message'] = $result['isset'] ? 'Workspace already exist' : $result['name']['message']; + $result['name']['status'] = $result['isset'] ? false : $result['name']['status']; + return [ + 'created' => G::var_compare( + true, + $result['path_data'], + $result['database']['connection'], + $result['name']['status'], + $result['database']['version'], + $result['database']['ao']['ao_db_wf']['status'], + $result['admin']['username'], + $result['isset'] ? false : true, + $result['admin']['password'] + ), 'result' => $result - ); + ]; } /** @@ -102,9 +147,10 @@ class Installer { $test = $this->create_site_test(); - if ($test["created"] == true || $this->options["advanced"]["ao_db_drop"] == true) { + if ($test["created"] === true || $this->options["advanced"]["ao_db_drop"] === true) { /* Check if the hostname is local (localhost or 127.0.0.1) */ - $islocal = (strcmp(substr($this->options['database']['hostname'], 0, strlen('localhost')), 'localhost') === 0) || (strcmp(substr($this->options['database']['hostname'], 0, strlen('127.0.0.1')), '127.0.0.1') === 0); + $islocal = (strcmp(substr($this->options['database']['hostname'], 0, strlen('localhost')), 'localhost') === 0) || + (strcmp(substr($this->options['database']['hostname'], 0, strlen('127.0.0.1')), '127.0.0.1') === 0); $this->wf_site_name = $wf = $this->options['advanced']['ao_db_wf']; $this->wf_user_db = isset($this->options['advanced']['ao_user_wf']) ? $this->options['advanced']['ao_user_wf'] : uniqid('wf_'); @@ -118,36 +164,39 @@ class Installer if ($this->options['advanced']['ao_db_drop'] === true) { //Delete workspace directory if exists //Drop databases - $this->run_query("DROP DATABASE IF EXISTS " . $wf, "Drop database $wf"); + $this->run_query('DROP DATABASE IF EXISTS ' . $wf, 'Drop database $wf', self::CONNECTION_TEST_INSTALL); } - $this->run_query("CREATE DATABASE IF NOT EXISTS " . $wf . " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci", "Create database $wf"); + $this->run_query('CREATE DATABASE IF NOT EXISTS ' . $wf . ' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci', "Create database $wf", self::CONNECTION_TEST_INSTALL); + if ($this->cc_status == 1) { $host = ($islocal) ? "localhost" : "%"; - $this->run_query("GRANT ALL PRIVILEGES ON `$wf`.* TO {$this->wf_user_db}@'$host' IDENTIFIED BY '{$this->options['password']}' WITH GRANT OPTION", "Grant privileges for user {$this->wf_user_db} on database $wf"); + $this->run_query("GRANT ALL PRIVILEGES ON `$wf`.* TO {$this->wf_user_db}@'$host' IDENTIFIED BY '{$this->options['password']}' WITH GRANT OPTION", "Grant privileges for user {$this->wf_user_db} on database $wf", self::CONNECTION_TEST_INSTALL); } + /* Dump schema workflow && data */ $this->log("Import database schema:\n"); - $myPortA = explode(":", $this->options['database']['hostname']); - if (count($myPortA) < 2) { - $myPortA[1] = "3306"; - } - $myPort = $myPortA[1]; - $this->options['database']['hostname'] = $myPortA[0]; - mysqli_select_db($this->connection_database, $wf); + InstallerModule::setNewConnection( + self::CONNECTION_INSTALL, + $this->options['database']['hostname'], + $this->options['database']['username'], + $this->options['database']['password'], + $this->wf_site_name, + $this->options['database']['port']); + $pws = PATH_WORKFLOW_MYSQL_DATA . $schema; - $qws = $this->query_sql_file(PATH_WORKFLOW_MYSQL_DATA . $schema, $this->connection_database); + $qws = $this->query_sql_file(PATH_WORKFLOW_MYSQL_DATA . $schema); $this->log($qws, isset($qws['errors'])); - $qwv = $this->query_sql_file(PATH_WORKFLOW_MYSQL_DATA . $values, $this->connection_database); + $qwv = $this->query_sql_file(PATH_WORKFLOW_MYSQL_DATA . $values); $this->log($qwv, isset($qwv['errors'])); - $http = (G::is_https() == true) ? 'https' : 'http'; + $http = G::is_https() ? 'https' : 'http'; $lang = defined('SYS_LANG') ? SYS_LANG : 'en'; - $host = $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] != '80' ? ':' . $_SERVER['SERVER_PORT'] : ''); + $host = $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] !== '80' ? ':' . $_SERVER['SERVER_PORT'] : ''); $workspace = $this->options['name']; $endpoint = sprintf( @@ -159,33 +208,37 @@ class Installer SYS_SKIN ); - // inserting the outh_client - $query = ("INSERT INTO OAUTH_CLIENTS (CLIENT_ID,CLIENT_SECRET,CLIENT_NAME,CLIENT_DESCRIPTION,CLIENT_WEBSITE,REDIRECT_URI,USR_UID ) VALUES - ('x-pm-local-client','179ad45c6ce2cb97cf1029e212046e81','PM Web Designer','ProcessMaker Web Designer App','www.processmaker.com','" . $endpoint . "','00000000000000000000000000000001' )"); - $this->run_query($query); + DB::connection(self::CONNECTION_INSTALL) + ->table('OAUTH_CLIENTS') + ->insert([ + 'CLIENT_ID' => 'x-pm-local-client', + 'CLIENT_SECRET' => '179ad45c6ce2cb97cf1029e212046e81', + 'CLIENT_NAME' => 'PM Web Designer', + 'CLIENT_DESCRIPTION' => 'ProcessMaker Web Designer App', + 'CLIENT_WEBSITE' => 'www.processmaker.com', + 'REDIRECT_URI' => $endpoint, + 'USR_UID' => '00000000000000000000000000000001' + ]); /* Dump schema rbac && data */ $pws = PATH_RBAC_MYSQL_DATA . $schema; - mysqli_select_db($this->connection_database, $rb); - $qrs = $this->query_sql_file(PATH_RBAC_MYSQL_DATA . $schema, $this->connection_database); + $qrs = $this->query_sql_file(PATH_RBAC_MYSQL_DATA . $schema); $this->log($qrs, isset($qrs['errors'])); - $qrv = $this->query_sql_file(PATH_RBAC_MYSQL_DATA . $values, $this->connection_database); + $qrv = $this->query_sql_file(PATH_RBAC_MYSQL_DATA . $values); $this->log($qrv, isset($qrv['errors'])); - mysqli_select_db($this->connection_database, $wf); - require_once("propel/Propel.php"); require_once('classes/model/AppCacheView.php'); $appCache = new AppCacheView(); $appCache->setPathToAppCacheFiles(PATH_METHODS . 'setup/setupSchemas/'); - $triggers = $appCache->getTriggers("en"); + $triggers = $appCache->getTriggers('en'); $this->log("Create 'cases list cache' triggers"); foreach ($triggers as $triggerName => $trigger) { - $this->run_query($trigger, "-> Trigger $triggerName"); + $this->runTrigger($trigger, "-> Trigger $triggerName"); } - $path_site = $this->options['path_data'] . "/sites/" . $this->options['name'] . "/"; + $path_site = $this->options['path_data'] . '/sites/' . $this->options['name'] . '/'; @mkdir($path_site, 0777, true); @mkdir($path_site . "files/", 0777, true); @@ -195,8 +248,27 @@ class Installer @mkdir($path_site . "xmlForms", 0777, true); //Generate the db.php file + $hostname = $this->options['database']['hostname'] . ':' . $this->options['database']['port']; + $username = $this->cc_status === 1 ? $this->wf_user_db : $this->options['database']['username']; + $password = $this->cc_status === 1 ? $this->options['password'] : $this->options['database']['password']; $db_file = $path_site . 'db.php'; - $db_text = "options['database']['hostname'] . ":" . $myPort . "' );\n" . "define ('DB_NAME', '" . $wf . "' );\n" . "define ('DB_USER', '" . (($this->cc_status == 1) ? $this->wf_user_db : $this->options['database']['username']) . "' );\n" . "define ('DB_PASS', '" . (($this->cc_status == 1) ? $this->options['password'] : $this->options['database']['password']) . "' );\n" . "define ('DB_RBAC_HOST', '" . $this->options['database']['hostname'] . ":" . $myPort . "' );\n" . "define ('DB_RBAC_NAME', '" . $rb . "' );\n" . "define ('DB_RBAC_USER', '" . (($this->cc_status == 1) ? $this->wf_user_db : $this->options['database']['username']) . "' );\n" . "define ('DB_RBAC_PASS', '" . (($this->cc_status == 1) ? $this->options['password'] : $this->options['database']['password']) . "' );\n" . "define ('DB_REPORT_HOST', '" . $this->options['database']['hostname'] . ":" . $myPort . "' );\n" . "define ('DB_REPORT_NAME', '" . $rp . "' );\n" . "define ('DB_REPORT_USER', '" . (($this->cc_status == 1) ? $this->wf_user_db : $this->options['database']['username']) . "' );\n" . "define ('DB_REPORT_PASS', '" . (($this->cc_status == 1) ? $this->options['password'] : $this->options['database']['password']) . "' );\n"; + $db_text = "log("Create: " . $db_file . " => " . ((!$fp) ? $fp : "OK") . "\n", $fp === false); - $ff = @fputs($fp, $db_text, strlen($db_text)); + $ff = @fwrite($fp, $db_text, strlen($db_text)); $this->log("Write: " . $db_file . " => " . ((!$ff) ? $ff : "OK") . "\n", $ff === false); fclose($fp); @@ -218,7 +290,7 @@ class Installer $fp = @fopen($envIniFile, 'w'); $this->log('Create: ' . $envIniFile . ' => ' . ((!$fp) ? $fp : 'OK') . "\n", $fp === false); - $ff = @fputs($fp, $content, strlen($content)); + $ff = @fwrite($fp, $content, strlen($content)); $this->log('Write: ' . $envIniFile . ' => ' . ((!$ff) ? $ff : 'OK') . "\n", $ff === false); fclose($fp); /*----------------------------------********---------------------------------*/ @@ -227,9 +299,12 @@ class Installer $this->setPartner(); $this->setAdmin(); - $querySql = "INSERT INTO EMAIL_SERVER(MESS_UID, MESS_ENGINE) VALUES('" . \ProcessMaker\Util\Common::generateUID() . "', 'MAIL')"; - - $this->run_query($querySql); + DB::connection(self::CONNECTION_INSTALL) + ->table('EMAIL_SERVER') + ->insert([ + 'MESS_UID' => Common::generateUID(), + 'MESS_ENGINE' => 'MAIL' + ]); } return $test; } @@ -246,10 +321,9 @@ class Installer // Execute sql for partner $pathMysqlPartner = PATH_CORE . 'data' . PATH_SEP . 'partner' . PATH_SEP . 'mysql' . PATH_SEP; if (G::verifyPath($pathMysqlPartner)) { - $res = []; $filesSlq = glob($pathMysqlPartner . '*.sql'); foreach ($filesSlq as $value) { - $this->query_sql_file($value, $this->connection_database); + $this->query_sql_file($value); } } @@ -406,10 +480,10 @@ class Installer */ public function setConfiguration() { - $oConf = new Configuration(); - $dataCondif = $oConf->getAll(); - if (count($dataCondif)) { - foreach ($dataCondif as $value) { + $configuration = new Configuration(); + $dataConfig = $configuration->getAll(); + if (count($dataConfig)) { + foreach ($dataConfig as $value) { if ($value['CFG_UID'] == 'ENVIRONMENT_SETTINGS') { $query = 'INSERT INTO CONFIGURATION (CFG_UID, OBJ_UID, CFG_VALUE, PRO_UID, USR_UID, APP_UID) VALUES'; $query .= "('" . @@ -419,7 +493,6 @@ class Installer $value['PRO_UID'] . "', '" . $value['USR_UID'] . "', '" . $value['APP_UID'] . "')"; - mysqli_select_db($this->connection_database, $this->wf_site_name); $this->run_query($query, "Copy configuracion environment"); break; } @@ -434,59 +507,92 @@ class Installer */ public function setAdmin() { - mysqli_select_db($this->connection_database, $this->wf_site_name); - // The mysql_escape_string function has been DEPRECATED as of PHP 5.3.0. - // $this->run_query('UPDATE USERS SET USR_USERNAME = \''.mysqli_escape_string($this->options['admin']['username']).'\', `USR_PASSWORD` = \''.md5($this->options['admin']['password']).'\' WHERE `USR_UID` = \'00000000000000000000000000000001\' LIMIT 1', - // "Add 'admin' user in ProcessMaker (wf)"); - $this->run_query('UPDATE USERS SET USR_USERNAME = \'' . mysqli_real_escape_string($this->connection_database, $this->options['admin']['username']) . '\', ' . ' `USR_PASSWORD` = \'' . G::encryptHash($this->options['admin']['password']) . '\' ' . ' WHERE `USR_UID` = \'00000000000000000000000000000001\' LIMIT 1', "Add 'admin' user in ProcessMaker (wf)"); - mysqli_select_db($this->connection_database, $this->rbac_site_name); - // The mysql_escape_string function has been DEPRECATED as of PHP 5.3.0. - // $this->run_query('UPDATE USERS SET USR_USERNAME = \''.mysqli_escape_string($this->options['admin']['username']).'\', `USR_PASSWORD` = \''.md5($this->options['admin']['password']).'\' WHERE `USR_UID` = \'00000000000000000000000000000001\' LIMIT 1', - // "Add 'admin' user in ProcessMaker (rb)"); - $this->run_query('UPDATE RBAC_USERS SET USR_USERNAME = \'' . mysqli_real_escape_string($this->connection_database, $this->options['admin']['username']) . '\', ' . ' `USR_PASSWORD` = \'' . G::encryptHash($this->options['admin']['password']) . '\' ' . ' WHERE `USR_UID` = \'00000000000000000000000000000001\' LIMIT 1', "Add 'admin' user in ProcessMaker (rb)"); + // Change admin user + DB::connection(self::CONNECTION_INSTALL) + ->table('USERS') + ->where('USR_UID', '00000000000000000000000000000001') + ->update([ + 'USR_USERNAME' => $this->options['admin']['username'], + 'USR_PASSWORD' => Bootstrap::hashPassword($this->options['admin']['password'], Bootstrap::hashBcrypt) + ]); + + DB::connection(self::CONNECTION_INSTALL) + ->table('RBAC_USERS') + ->where('USR_UID', '00000000000000000000000000000001') + ->update([ + 'USR_USERNAME' => $this->options['admin']['username'], + 'USR_PASSWORD' => Bootstrap::hashPassword($this->options['admin']['password'], Bootstrap::hashBcrypt) + ]); } /** - * Run a mysql query on the current database and take care of logging and + * Run a mysql script on the current database and take care of logging and * error handling. * * @param string $query SQL command * @param string $description Description to log instead of $query + * @param string $connection default connection install + * @throws Exception */ - private function run_query($query, $description = null) + private function runTrigger($query, $description = '', $connection = self::CONNECTION_INSTALL) { - $result = mysqli_query($this->connection_database, $query); - $error = $result ? false : mysqli_error($this->connection_database); - $this->log(($description ? $description : $query) . " => " . (($error) ? $error : "OK") . "\n", $error); + $this->run_query($query, $description, $connection, 'RAW'); } /** - * query_sql_file + * Run a mysql query on the current database and take care of logging and + * error handling. * - * @param string $file - * @param string $connection - * @return array $report + * @param string $query SQL command + * @param string $description Description to log instead of $query + * @param string $connection default connection install + * @param string $type STATEMENT|RAW */ - public function query_sql_file($file, $connection) + private function run_query($query, $description = '', $connection = self::CONNECTION_INSTALL, $type = 'STATEMENT') + { + try { + $message = ''; + switch ($type) { + case 'STATEMENT': + DB::connection($connection)->statement($query); + break; + case 'RAW': + DB::connection($connection)->raw($query); + break; + } + + } catch (QueryException $exception) { + $message = $exception->getMessage(); + } + $this->log(!empty($description) ? $description : $query . ' => ' . (!empty($message) ? $message : 'OK') . "\n", !empty($message)); + } + + /** + * Query sql file + * + * @param $file + * @param string $connection + */ + public function query_sql_file($file, $connection = self::CONNECTION_INSTALL) { $lines = file($file); $previous = null; $errors = ''; - mysqli_query($connection, "SET NAMES 'utf8';"); + DB::connection($connection) + ->statement("SET NAMES 'utf8'"); foreach ($lines as $j => $line) { $line = trim($line); // Remove comments from the script - - if (strpos($line, "--") === 0) { - $line = substr($line, 0, strpos($line, "--")); + if (strpos($line, '--') === 0) { + $line = substr($line, 0, strpos($line, '--')); } if (empty($line)) { continue; } - if (strpos($line, "#") === 0) { - $line = substr($line, 0, strpos($line, "#")); + if (strpos($line, '#') === 0) { + $line = substr($line, 0, strpos($line, '#')); } if (empty($line)) { @@ -495,32 +601,23 @@ class Installer // Concatenate the previous line, if any, with the current if ($previous) { - $line = $previous . " " . $line; + $line = $previous . ' ' . $line; } $previous = null; // If the current line doesnt end with ; then put this line together // with the next one, thus supporting multi-line statements. - if (strrpos($line, ";") != strlen($line) - 1) { + if (strrpos($line, ';') != strlen($line) - 1) { $previous = $line; continue; } - $line = substr($line, 0, strrpos($line, ";")); - mysqli_query($connection, $line); + $line = substr($line, 0, strrpos($line, ';')); + DB::connection($connection) + ->statement($line); } } - /** - * check_path - * - * @return void - * @todo Empty function - */ - private function check_path() - { - } - /** * function find_root_path * @@ -573,7 +670,7 @@ class Installer * getDirectoryFiles * * @param string $dir default value empty - * @return string $path + * @return array */ public function getDirectoryFiles($dir, $extension) { @@ -595,17 +692,24 @@ class Installer /** * check_db_empty * - * @param string $dbName + * @param string$dbName * @return boolean true or false + * @throws Exception */ public function check_db_empty($dbName) { - $a = mysqli_select_db($this->connection_database, $dbName); - if (!$a) { - return true; + try + { + $result = DB::connection(self::CONNECTION_TEST_INSTALL)->select("show databases like '$dbName'"); + if (!$result) { + return true; + } else { + $result = DB::connection(self::CONNECTION_TEST_INSTALL)->select("show tables from $dbName"); + return !$result; + } + } catch (QueryException $exception) { + throw new Exception('User without permissions. ' . $exception->getMessage()); } - $q = mysqli_query($this->connection_database, 'SHOW TABLES'); - return !(mysqli_num_rows($q) > 0); } /** @@ -621,10 +725,10 @@ class Installer $response['message'] = ''; if (!$this->connection_database) { //new verification if the mysql extension is enabled - $response['message'] = class_exists('mysql_error') ? mysqli_error() : 'Mysql Module for PHP is not enabled!'; + $response['message'] = 'Mysql Module for PHP is not enabled!'; } else { - if (!mysqli_select_db($this->connection_database, $dbName) && $this->cc_status != 1) { - $response['message'] = mysqli_error($this->connection_database); + if ($this->cc_status != 1) { + $result = DB::connection(self::CONNECTION_TEST_INSTALL)->select("show databases like '$dbName'"); } else { if ($this->options['advanced']['ao_db_drop'] === true || $this->check_db_empty($dbName)) { $response['status'] = true; @@ -640,52 +744,79 @@ class Installer /** * check_connection * - * @return Array $rt + * @return array $rt */ - private function check_connection() + private function check_connection($nameConnection) { - if (!function_exists('mysqli_connect')) { - $this->cc_status = 0; - $rt = array('connection' => false, 'grant' => 0, 'version' => false, 'message' => "ERROR: Mysql Module for PHP is not enabled, try install php-mysql package.", 'ao' => array('ao_db_wf' => false, 'ao_db_rb' => false, 'ao_db_rp' => false - ) - ); - } else { - $this->connection_database = mysqli_connect($this->options['database']['hostname'], $this->options['database']['username'], $this->options['database']['password']); - $rt = array('version' => false, 'ao' => array('ao_db_wf' => false, 'ao_db_rb' => false, 'ao_db_rp' => false - ) - ); - if (!$this->connection_database) { - $this->cc_status = 0; - $rt['connection'] = false; - $rt['grant'] = 0; - $rt['message'] = 'Mysql error: ' . mysqli_error($this->connection_database); - } else { - preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', mysqli_get_server_info($this->connection_database), $version); - $rt['version'] = version_compare(@$version[0], '4.1.0', '>='); + $this->cc_status = 0; + $rt = [ + 'connection' => false, + 'grant' => 0, + 'version' => false, + 'message' => 'ERROR: Mysql Module for PHP is not enabled, try install php-mysqli package.', + 'ao' => [ + 'ao_db_wf' => false, + 'ao_db_rb' => false, + 'ao_db_rp' => false + ] + ]; + + if (function_exists('mysqli_connect')) { + try { + InstallerModule::setNewConnection( + $nameConnection, + $this->options['database']['hostname'], + $this->options['database']['username'], + $this->options['database']['password'], + '', + $this->options['database']['port']); + $rt = [ + 'version' => false, + 'ao' => [ + 'ao_db_wf' => false, + 'ao_db_rb' => false, + 'ao_db_rp' => false + ] + ]; + + $results = DB::connection($nameConnection)->select(DB::raw('select version()')); + + preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $results[0]->{'version()'}, $version); + $rt['version'] = version_compare($mysql_version = $version[0], '4.1.0', '>='); $rt['connection'] = true; $dbNameTest = 'PROCESSMAKERTESTDC'; - $db = mysqli_query($this->connection_database, 'CREATE DATABASE ' . $dbNameTest); + $db = DB::connection($nameConnection)->statement("CREATE DATABASE IF NOT EXISTS $dbNameTest"); + $this->connection_database = true; + if (!$db) { $this->cc_status = 3; $rt['grant'] = 3; $rt['message'] = 'Successful connection'; } else { - $usrTest = "wfrbtest"; - $chkG = "GRANT ALL PRIVILEGES ON `" . $dbNameTest . "`.* TO " . $usrTest . "@'%' IDENTIFIED BY 'sample' WITH GRANT OPTION"; - $ch = mysqli_query($this->connection_database, $chkG); + $usrTest = 'wfrbtest'; + $chkG = "GRANT ALL PRIVILEGES ON `" . $dbNameTest . "`.* TO " . $usrTest . "@'%' IDENTIFIED BY '!Sample123' WITH GRANT OPTION"; + $ch = DB::connection($nameConnection) + ->statement($chkG); + if (!$ch) { $this->cc_status = 2; $rt['grant'] = 2; $rt['message'] = 'Successful connection'; } else { $this->cc_status = 1; - mysqli_query($this->connection_database, "DROP USER " . $usrTest . "@'%'"); + DB::connection($nameConnection) + ->statement("DROP USER " . $usrTest . "@'%'"); $rt['grant'] = 1; $rt['message'] = 'Successful connection'; } - mysqli_query($this->connection_database, 'DROP DATABASE ' . $dbNameTest); + DB::connection($nameConnection) + ->statement('DROP DATABASE ' . $dbNameTest); } + } catch (Exception $exception) { + $rt['connection'] = false; + $rt['grant'] = 0; + $rt['message'] = 'Mysql error: ' . $exception->getMessage(); } } $rt['ao']['ao_db_wf'] = $this->check_db($this->options['advanced']['ao_db_wf']); @@ -693,14 +824,15 @@ class Installer } /** - * log + * Log * * @param string $text - * @return void + * @param boolean $failed + * @throws Exception */ - public function log($text, $failed = null) + public function log($text, $failed = false) { - array_push($this->report, $text); + $this->report[] = $text; if ($failed) { throw new Exception(is_string($text) ? $text : var_export($text, true)); } diff --git a/workflow/engine/src/ProcessMaker/Core/System.php b/workflow/engine/src/ProcessMaker/Core/System.php index 4eca35d4c..0cabf7f8b 100644 --- a/workflow/engine/src/ProcessMaker/Core/System.php +++ b/workflow/engine/src/ProcessMaker/Core/System.php @@ -4,9 +4,14 @@ namespace ProcessMaker\Core; use Configurations; use DomDocument; use Exception; +use Faker; use G; use GzipFile; +use Illuminate\Database\QueryException; +use Illuminate\Support\Facades\DB; use InputFilter; +use InstallerModule; +use Net; use schema; use WorkspaceTools; @@ -66,7 +71,7 @@ class System */ public static function getPlugins() { - $plugins = array(); + $plugins = []; foreach (glob(PATH_PLUGINS . "*") as $filename) { $info = pathinfo($filename); @@ -90,7 +95,7 @@ class System public static function listWorkspaces() { $oDirectory = dir(PATH_DB); - $aWorkspaces = array(); + $aWorkspaces = []; foreach (glob(PATH_DB . "*") as $filename) { if (is_dir($filename) && file_exists($filename . "/db.php")) { $aWorkspaces[] = new WorkspaceTools(basename($filename)); @@ -150,7 +155,7 @@ class System */ public static function getSysInfo() { - $ipe = isset($_SERVER['SSH_CONNECTION']) ? explode(" ", $_SERVER['SSH_CONNECTION']) : array(); + $ipe = isset($_SERVER['SSH_CONNECTION']) ? explode(" ", $_SERVER['SSH_CONNECTION']) : []; if (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); @@ -194,7 +199,7 @@ class System */ $distro = trim($distro, "\"") . " (" . PHP_OS . ")"; - $Fields = array(); + $Fields = []; $Fields['SYSTEM'] = $distro; $Fields['PHP'] = phpversion(); $Fields['PM_VERSION'] = self::getVersion(); @@ -397,9 +402,9 @@ class System fwrite($fp, ""); fclose($fp); - $aEnvironmentsUpdated = array(); - $aEnvironmentsDiff = array(); - $aErrors = array(); + $aEnvironmentsUpdated = []; + $aEnvironmentsDiff = []; + $aErrors = []; //now will verify each folder and file has permissions to write and add files. if ($this->sUpgradeFileList != '') { @@ -557,13 +562,13 @@ class System $oDirectory = dir(PATH_DB); //count db.php files ( workspaces ) - $aWorkspaces = array(); + $aWorkspaces = []; while (($sObject = $oDirectory->read())) { if (is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' && file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php')) { $aWorkspaces[] = $sObject; } } - $aUpgradeData = array(); + $aUpgradeData = []; $aUpgradeData['workspaces'] = $aWorkspaces; $aUpgradeData['wsQuantity'] = count($aWorkspaces); $aUpgradeData['sPoFile'] = $sPoFile; @@ -732,19 +737,28 @@ class System public static function getSchema($sSchemaFile) { /* This is the MySQL mapping that Propel uses (from MysqlPlatform.php) */ - $mysqlTypes = array('NUMERIC' => "DECIMAL", 'LONGVARCHAR' => "MEDIUMTEXT", 'TIMESTAMP' => "DATETIME", 'BU_TIMESTAMP' => "DATETIME", 'BINARY' => "BLOB", 'VARBINARY' => "MEDIUMBLOB", 'LONGVARBINARY' => "LONGBLOB", 'BLOB' => "LONGBLOB", 'CLOB' => "LONGTEXT", + $mysqlTypes = [ + 'NUMERIC' => 'DECIMAL', + 'LONGVARCHAR' => 'MEDIUMTEXT', + 'TIMESTAMP' => 'DATETIME', + 'BU_TIMESTAMP' => 'DATETIME', + 'BINARY' => 'BLOB', + 'VARBINARY' => 'MEDIUMBLOB', + 'LONGVARBINARY' => 'LONGBLOB', + 'BLOB' => 'LONGBLOB', + 'CLOB' => 'LONGTEXT', /* This is not from Propel, but is required to get INT right */ - 'INTEGER' => "INT" - ); + 'INTEGER' => 'INT' + ]; - $aSchema = array(); + $aSchema = []; $oXml = new DomDocument(); $oXml->load($sSchemaFile); $aTables = $oXml->getElementsByTagName('table'); foreach ($aTables as $oTable) { - $aPrimaryKeys = array(); + $aPrimaryKeys = []; $sTableName = $oTable->getAttribute('name'); - $aSchema[$sTableName] = array(); + $aSchema[$sTableName] = []; $aColumns = $oTable->getElementsByTagName('column'); foreach ($aColumns as $oColumn) { $sColumName = $oColumn->getAttribute('name'); @@ -801,7 +815,7 @@ class System } $aIndexes = $oTable->getElementsByTagName('index'); foreach ($aIndexes as $oIndex) { - $aIndex = array(); + $aIndex = []; $aIndexesColumns = $oIndex->getElementsByTagName('index-column'); foreach ($aIndexesColumns as $oIndexColumn) { $aIndex[] = $oIndexColumn->getAttribute('name'); @@ -820,7 +834,7 @@ class System */ public static function verifyRbacSchema($aOldSchema) { - $aChanges = array(); + $aChanges = []; foreach ($aOldSchema as $sTableName => $aColumns) { if (substr($sTableName, 0, 4) != 'RBAC') { @@ -936,13 +950,13 @@ class System foreach ($aNewSchema[$sTableName]['INDEXES'] as $indexName => $indexFields) { if (!isset($aOldSchema[$sTableName]['INDEXES'][$indexName])) { if (!isset($aChanges['tablesWithNewIndex'][$sTableName])) { - $aChanges['tablesWithNewIndex'][$sTableName] = array(); + $aChanges['tablesWithNewIndex'][$sTableName] = []; } $aChanges['tablesWithNewIndex'][$sTableName][$indexName] = $indexFields; } else { if ($aOldSchema[$sTableName]['INDEXES'][$indexName] != $indexFields) { if (!isset($aChanges['tablesToAlterIndex'][$sTableName])) { - $aChanges['tablesToAlterIndex'][$sTableName] = array(); + $aChanges['tablesToAlterIndex'][$sTableName] = []; } $aChanges['tablesToAlterIndex'][$sTableName][$indexName] = $indexFields; } @@ -1007,11 +1021,11 @@ class System } //Get Skin Config files - $skinListArray = array(); + $skinListArray = []; $customSkins = glob(PATH_CUSTOM_SKINS . "*/config.xml"); if (!is_array($customSkins)) { - $customSkins = array(); + $customSkins = []; } // getting al base skins @@ -1045,7 +1059,7 @@ class System if (isset($xmlConfigurationObj->result['skinConfiguration'])) { $skinInformationArray = $skinFilesArray = $xmlConfigurationObj->result['skinConfiguration']['__CONTENT__']['information']['__CONTENT__']; - $res = array(); + $res = []; $res['SKIN_FOLDER_ID'] = strtolower($folderId); foreach ($skinInformationArray as $keyInfo => $infoValue) { @@ -1171,7 +1185,7 @@ class System */ public static function getQueryBlackList($globalIniFile = '') { - $config = array(); + $config = []; if (empty($globalIniFile)) { $blackListIniFile = PATH_CONFIG . 'execute-query-blacklist.ini'; $sysTablesIniFile = PATH_CONFIG . 'system-tables.ini'; @@ -1320,5 +1334,179 @@ class System return $serverVersion; } + + /** + * Generate user name for test + * + * @param int $length + * @return string + */ + public static function generateUserName($length = 10) + { + $userName = 'PM_'; + for ($i = 0; $i < $length - 3; $i++) { + $userName .= ($i % 3) === 0 ? '?' : '#'; + } + $faker = Faker\Factory::create(); + return $faker->bothify($userName); + } + + /** + * Check permission the user in db + * + * @param string $adapter + * @param string $serverName + * @param int $port + * @param string $userName + * @param string $pass + * @param string $dbName + * + * @return array + */ + public static function checkPermissionsDbUser($adapter = 'mysql', $serverName, $port = 3306, $userName, $pass, $dbName = '') + { + if (empty($port)) { + //setting defaults ports + switch ($adapter) { + case 'mysql': + $port = 3306; + break; + case 'pgsql': + $port = 5432; + break; + case 'mssql': + $port = 1433; + break; + case 'oracle': + $port = 1521; + break; + } + } + + $filter = new InputFilter(); + $serverName = $filter->validateInput($serverName); + $userName = $filter->validateInput($userName); + + $serverNet = new Net($serverName); + if ($serverNet->getErrno() !== 0) { + return [false, $serverNet->error]; + } + $serverNet->scannPort($port); + if ($serverNet->getErrno() !== 0) { + return [false, $serverNet->error]; + } + $serverNet->loginDbServer($userName, $pass); + $serverNet->setDataBase('', $port); + if ($serverNet->getErrno() !== 0) { + return [false, $serverNet->error]; + } + + $response = $serverNet->tryConnectServer($adapter); + if (!empty($response) && $response->status !== 'SUCCESS' && $serverNet->getErrno() !== 0) { + return [false, $serverNet->error]; + } + + $message = ''; + $success = false; + + $userName = $filter->validateInput($userName, 'nosql'); + try { + $connection = 'SYSTEM'; + InstallerModule::setNewConnection($connection, $serverName, $userName, $pass, $dbName, $port); + + //Test Create Database + $dbNameTest = 'PROCESSMAKERTESTDC'; + $result = DB::connection($connection)->statement("CREATE DATABASE $dbNameTest"); + if ($result) { + //Test set permissions user + $usrTest = self::generateUserName(strlen($userName)); + $passTest = '!Sample123_'; + $result = DB::connection($connection)->statement("GRANT ALL PRIVILEGES ON `$dbNameTest`.* TO $usrTest@'%%' IDENTIFIED BY '$passTest' WITH GRANT OPTION"); + + if ($result) { + //Test Create user + $userTestCreate = self::generateUserName(strlen($userName)); + $result = DB::connection($connection)->statement("CREATE USER '$userTestCreate'@'%%' IDENTIFIED BY '$passTest'"); + + if ($result) { + $success = true; + $message = G::LoadTranslation('ID_SUCCESSFUL_CONNECTION'); + } + + DB::connection($connection)->statement("DROP USER '$userTestCreate'@'%%'"); + DB::connection($connection)->statement("DROP USER '$usrTest'@'%%'"); + } + DB::connection($connection)->statement("DROP DATABASE $dbNameTest"); + } + } catch (Exception $exception) { + $success = false; + $message = $exception->getMessage(); + } + + return [$success, !empty($message) ? $message : $serverNet->error]; + } + + /** + * Regenerate credentials paths installed + * + * @param string $host + * @param string $user + * @param string $pass + * @return bool + */ + public static function regenerateCredentiaslPathInstalled($host, $user, $pass) + { + $hashOld = G::encryptOld(filemtime(PATH_GULLIVER . "/class.g.php")); + $hash = G::encrypt($host . $hashOld . $user . $hashOld . $pass . $hashOld . (1), $hashOld); + $insertStatements = "define ( 'HASH_INSTALLATION','{$hash}' ); \ndefine ( 'SYSTEM_HASH', '{$hashOld}' ); \n"; + $content = ''; + $filename = PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths_installed.php'; + $lines = file($filename); + + $count = 1; + foreach ($lines as $line_num => $line) { + $pos = strpos($line, 'define'); + if ($pos !== false && $count < 3) { + $content .= $line; + $count++; + } + } + $content = " $dbAdapter]); + config(['connections.workflow.host' => $dbHost]); + config(['connections.workflow.database' => $dbName]); + config(['connections.workflow.username' => $dbUser]); + config(['connections.workflow.password' => $dbPass]); + config(['connections.rbac.host' => $dbRbacHost]); + config(['connections.rbac.database' => $dbRbacName]); + config(['connections.rbac.username' => $dbRbacUser]); + config(['connections.rbac.password' => $dbRbacPass]); + config(['connections.report.host' => $dbReportHost]); + config(['connections.report.database' => $dbReportName]); + config(['connections.report.username' => $dbReportUser]); + config(['connections.report.password' => $dbReportPass]); + } } // end System class