function run_flush_cache($args, $opts) { $rootDir = realpath(__DIR__."/../../../../"); $app = new Maveriks\WebApplication(); $app->setRootDir($rootDir); $loadConstants = false; $workspaces = get_workspaces_from_args($args); if (! defined("PATH_C")) { die("ERROR: seems processmaker is not properly installed (System constants are missing).".PHP_EOL); } CLI::logging("Flush ".pakeColor::colorize("system", "INFO")." cache ... "); G::rm_dir(PATH_C); G::mk_dir(PATH_C, 0777); echo "DONE" . PHP_EOL; foreach ($workspaces as $workspace) { echo "Flush workspace " . pakeColor::colorize($workspace->name, "INFO") . " cache ... "; G::rm_dir($workspace->path . "/cache"); G::mk_dir($workspace->path . "/cache", 0777); G::rm_dir($workspace->path . "/cachefiles"); G::mk_dir($workspace->path . "/cachefiles", 0777); echo "DONE" . PHP_EOL; } }
function run_create_translation($args, $opts) { G::LoadSystem('inputfilter'); $filter = new InputFilter(); $opts = $filter->xssFilterHard($opts); $args = $filter->xssFilterHard($args); $rootDir = realpath(__DIR__."/../../../../"); $app = new Maveriks\WebApplication(); $app->setRootDir($rootDir); $loadConstants = false; $workspaces = get_workspaces_from_args($args); $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; $translation = new Translation(); CLI::logging("Updating labels Mafe ...\n"); foreach ($workspaces as $workspace) { try { echo "Updating labels for workspace " . pakeColor::colorize($workspace->name, "INFO") . "\n"; $translation->generateTransaltionMafe($lang); } catch (Exception $e) { echo "Errors upgrading labels for workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"; } } CLI::logging("Create successful\n"); }
function runHotfixInstall($command, $args) { CLI::logging("HOTFIX", PATH_DATA . "log" . PATH_SEP . "upgrades.log"); CLI::logging("Install hotfix to system\n"); $arrayFile = $command; if (count($arrayFile) > 0) { //Install hotfix foreach ($arrayFile as $value) { $f = $value; $result = workspaceTools::hotfixInstall($f); CLI::logging($result["message"] . "\n"); } //Clear server's cache CLI::logging("\nClearing cache...\n"); if (defined("PATH_C")) { G::rm_dir(PATH_C); G::mk_dir(PATH_C, 0777); } //Safe upgrade for JavaScript files CLI::logging("\nSafe upgrade for files cached by the browser\n\n"); G::browserCacheFilesSetUid(); CLI::logging("HOTFIX done\n"); } else { CLI::logging("Please specify the hotfix to install\n"); } }
function run_update($command, $args) { CLI::logging("Updating...\n"); $language = new Language(); $language->updateLanguagePlugin($command[0], $command[1]); CLI::logging("Update successful\n"); }
function minify_javascript($command, $args) { CLI::logging("BUILD-JS\n"); //disabling the rakefile version, until we have updated the dev environment //CLI::logging("Checking if rake is installed...\n"); //$rakeFile = PROCESSMAKER_PATH . "workflow/engine/bin/tasks/Rakefile"; //system('rake -f ' . $rakeFile); require_once PATH_THIRDPARTY . 'jsmin/jsmin.php'; $libraries = json_decode(file_get_contents(PATH_HOME . 'engine/bin/tasks/libraries.json')); //print_r($libraries); foreach ($libraries as $k => $library) { $build = $library->build; if ($build) { $bufferMini = ""; $sum1 = 0; $sum2 = 0; $libName = $library->name; $files = $library->libraries; $js_path = $library->build_js_to; printf("Processing %s library:\n", $libName); foreach ($files as $file) { printf(" %-20s ", $file->name); $fileNameMini = PATH_TRUNK . $file->mini; if ($file->minify) { $minify = JSMin::minify(file_get_contents($fileNameMini)); } else { $minify = file_get_contents($fileNameMini); } $bufferMini .= $minify; $size1 = filesize($fileNameMini); $size2 = strlen($minify); $sum1 += $size1; $sum2 += $size2; printf("%7d -> %7d %5.2f%%\n", $size1, $size2, 100 - $size2 / $size1 * 100); } if (substr($library->build_js_to, -1) != '/') { $library->build_js_to .= '/'; } $outputMiniFile = PATH_TRUNK . $library->build_js_to . $libName . ".js"; file_put_contents($outputMiniFile, $bufferMini); printf(" -------------------- ------- ------- ------\n"); printf(" %-20s %7d -> %7d %6.2f%%\n", $libName . '.js', $sum1, $sum2, 100 - $sum2 / $sum1 * 100); print " {$outputMiniFile}\n"; } } CLI::logging("BUILD-JS DONE\n"); }
/** * restore an archive into a workspace * * Restores any database and files included in the backup, either as a new * workspace, or overwriting a previous one * * @param string $filename the backup filename * @param string $newWorkspaceName if defined, supplies the name for the * workspace to restore to */ public static function restore($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true) { G::LoadThirdParty('pear/Archive', 'Tar'); $backup = new Archive_Tar($filename); //Get a temporary directory in the upgrade directory $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); $parentDirectory = PATH_DATA . "upgrade"; if (is_writable($parentDirectory)) { mkdir($tempDirectory); } else { throw new Exception("Could not create directory:" . $parentDirectory); } //Extract all backup files, including database scripts and workspace files if (!$backup->extract($tempDirectory)) { throw new Exception("Could not extract backup"); } //Search for metafiles in the new standard (the old standard would contain //txt files). $metaFiles = glob($tempDirectory . "/*.meta"); if (empty($metaFiles)) { $metaFiles = glob($tempDirectory . "/*.txt"); if (!empty($metaFiles)) { return workspaceTools::restoreLegacy($tempDirectory); } else { throw new Exception("No metadata found in backup"); } } else { CLI::logging("Found " . count($metaFiles) . " workspaces in backup:\n"); foreach ($metaFiles as $metafile) { CLI::logging("-> " . basename($metafile) . "\n"); } } if (count($metaFiles) > 1 && !isset($srcWorkspace)) { throw new Exception("Multiple workspaces in backup but no workspace specified to restore"); } if (isset($srcWorkspace) && !in_array("{$srcWorkspace}.meta", array_map(BASENAME, $metaFiles))) { throw new Exception("Workspace {$srcWorkspace} not found in backup"); } foreach ($metaFiles as $metaFile) { $metadata = G::json_decode(file_get_contents($metaFile)); if ($metadata->version != 1) { throw new Exception("Backup version {$metadata->version} not supported"); } $backupWorkspace = $metadata->WORKSPACE_NAME; if (isset($dstWorkspace)) { $workspaceName = $dstWorkspace; $createWorkspace = true; } else { $workspaceName = $metadata->WORKSPACE_NAME; $createWorkspace = false; } if (isset($srcWorkspace) && strcmp($metadata->WORKSPACE_NAME, $srcWorkspace) != 0) { CLI::logging(CLI::warning("> Workspace {$backupWorkspace} found, but not restoring.") . "\n"); continue; } else { 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)"); } } if (file_exists($workspace->path)) { G::rm_dir($workspace->path); } foreach ($metadata->directories as $dir) { CLI::logging("+> Restoring directory '{$dir}'\n"); if (!rename("{$tempDirectory}/{$dir}", $workspace->path)) { throw new Exception("There was an error copying the backup files ({$tempDirectory}/{$dir}) to the workspace directory {$workspace->path}."); } } CLI::logging("> Changing file permissions\n"); $shared_stat = stat(PATH_DATA); if ($shared_stat !== false) { workspaceTools::dirPerms($workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); } else { CLI::logging(CLI::error("Could not get the shared folder permissions, not changing workspace permissions") . "\n"); } list($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); CLI::logging("> Connecting to system database in '{$dbHost}'\n"); $link = mysql_connect($dbHost, $dbUser, $dbPass); @mysql_query("SET NAMES 'utf8';"); @mysql_query("SET FOREIGN_KEY_CHECKS=0;"); if (!$link) { throw new Exception('Could not connect to system database: ' . mysql_error()); } $newDBNames = $workspace->resetDBInfo($dbHost, $createWorkspace); 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"); $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName); $workspace->createDBUser($dbName, $db->pass, "%", $dbName); } $workspace->upgradeCacheView(false); mysql_close($link); } CLI::logging("Removing temporary files\n"); G::rm_dir($tempDirectory); CLI::logging(CLI::info("Done restoring") . "\n"); }
function runStructureDirectories($command, $args) { $workspaces = get_workspaces_from_args($command); $count = count($workspaces); $errors = false; $countWorkspace = 0; foreach ($workspaces as $index => $workspace) { try { $countWorkspace++; CLI::logging("Updating workspaces ($countWorkspace/$count): " . CLI::info($workspace->name) . "\n"); $workspace->updateStructureDirectories($workspace->name); $workspace->close(); } catch (Exception $e) { CLI::logging("Errors upgrading workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"); $errors = true; } } }
static public function letsRestore ($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true) { // Needed info: // TEMPDIR /shared/workflow_data/upgrade/ // BACKUPS /shared/workflow_data/backups/ // Creating command cat myfiles_split.tgz_* | tar xz $DecommpressCommand = "cat " . $filename . ".* "; $DecommpressCommand .= " | tar xzv"; $tempDirectory = PATH_DATA . "upgrade/" . basename( tempnam( __FILE__, '' ) ); $parentDirectory = PATH_DATA . "upgrade"; if (is_writable( $parentDirectory )) { mkdir( $tempDirectory ); } else { throw new Exception( "Could not create directory:" . $parentDirectory ); } //Extract all backup files, including database scripts and workspace files CLI::logging( "Restoring into " . $tempDirectory . "\n" ); chdir( $tempDirectory ); echo exec( $DecommpressCommand ); CLI::logging( "\nUncompressed into: " . $tempDirectory . "\n" ); //Search for metafiles in the new standard (the old standard would contain meta files. $metaFiles = glob( $tempDirectory . "/*.meta" ); if (empty( $metaFiles )) { $metaFiles = glob( $tempDirectory . "/*.txt" ); if (! empty( $metaFiles )) { return workspaceTools::restoreLegacy( $tempDirectory ); } else { throw new Exception( "No metadata found in backup" ); } } else { CLI::logging( "Found " . count( $metaFiles ) . " workspaces in backup:\n" ); foreach ($metaFiles as $metafile) { CLI::logging( "-> " . basename( $metafile ) . "\n" ); } } if (count( $metaFiles ) > 1 && (! isset( $srcWorkspace ))) { throw new Exception( "Multiple workspaces in backup but no workspace specified to restore" ); } if (isset( $srcWorkspace ) && ! in_array( "$srcWorkspace.meta", array_map( basename, $metaFiles ) )) { throw new Exception( "Workspace $srcWorkspace not found in backup" ); } foreach ($metaFiles as $metaFile) { $metadata = G::json_decode( file_get_contents( $metaFile ) ); if ($metadata->version != 1) { throw new Exception( "Backup version {$metadata->version} not supported" ); } $backupWorkspace = $metadata->WORKSPACE_NAME; if (isset( $dstWorkspace )) { $workspaceName = $dstWorkspace; $createWorkspace = true; } else { $workspaceName = $metadata->WORKSPACE_NAME; $createWorkspace = false; } if (isset( $srcWorkspace ) && strcmp( $metadata->WORKSPACE_NAME, $srcWorkspace ) != 0) { CLI::logging( CLI::warning( "> Workspace $backupWorkspace found, but not restoring." ) . "\n" ); continue; } else { 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)" ); } } if (file_exists( $workspace->path )) { G::rm_dir( $workspace->path ); } foreach ($metadata->directories as $dir) { CLI::logging( "+> Restoring directory '$dir'\n" ); if (! rename( "$tempDirectory/$dir", $workspace->path )) { throw new Exception( "There was an error copying the backup files ($tempDirectory/$dir) to the workspace directory {$workspace->path}." ); } } CLI::logging( "> Changing file permissions\n" ); $shared_stat = stat( PATH_DATA ); if ($shared_stat !== false) { workspaceTools::dirPerms( $workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode'] ); } else { CLI::logging( CLI::error( "Could not get the shared folder permissions, not changing workspace permissions" ) . "\n" ); } list ($dbHost, $dbUser, $dbPass) = @explode( SYSTEM_HASH, G::decrypt( HASH_INSTALLATION, SYSTEM_HASH ) ); CLI::logging( "> Connecting to system database in '$dbHost'\n" ); $link = mysql_connect( $dbHost, $dbUser, $dbPass ); @mysql_query( "SET NAMES 'utf8';" ); @mysql_query( "SET FOREIGN_KEY_CHECKS=0;" ); if (! $link) { throw new Exception( 'Could not connect to system database: ' . mysql_error() ); } $newDBNames = $workspace->resetDBInfo( $dbHost, $createWorkspace ); 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" ); $workspace->createDBUser( $dbName, $db->pass, "localhost", $dbName ); $workspace->createDBUser( $dbName, $db->pass, "%", $dbName ); } $workspace->upgradeCacheView( false ); mysql_close( $link ); } CLI::logging( "Removing temporary files\n" ); G::rm_dir( $tempDirectory ); CLI::logging( CLI::info( "Done restoring" ) . "\n" ); }
/** * Migrate all cases to New list * * return all LIST TABLES with data */ public function migrateList ($workSpace) { if ($this->listFirstExecution('check')) { return 1; } $this->initPropel(true); $appCache = new AppCacheView(); $users = new Users(); G::LoadClass("case"); $case = new Cases(); //Select data CANCELLED $canCriteria = $appCache->getSelAllColumns(); $canCriteria->add(AppCacheViewPeer::APP_STATUS, "CANCELLED", CRITERIA::EQUAL); $canCriteria->add(AppCacheViewPeer::DEL_LAST_INDEX, "1", CRITERIA::EQUAL); $rsCriteria = AppCacheViewPeer::doSelectRS($canCriteria); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); //Insert data LIST_CANCELED while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); $listCanceled = new ListCanceled(); $listCanceled->remove($row["APP_UID"]); $listCanceled->setDeleted(false); $listCanceled->create($row); } CLI::logging("> Completed table LIST_CANCELED\n"); //Select data COMPLETED $comCriteria = $appCache->getSelAllColumns(); $comCriteria->add(AppCacheViewPeer::APP_STATUS, "COMPLETED", CRITERIA::EQUAL); $comCriteria->add(AppCacheViewPeer::DEL_LAST_INDEX, "1", CRITERIA::EQUAL); $rsCriteria = AppCacheViewPeer::doSelectRS($comCriteria); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); //Insert new data LIST_COMPLETED while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); $listCompleted = new ListCompleted(); $listCompleted->remove($row["APP_UID"]); $listCompleted->setDeleted(false); $listCompleted->create($row); } CLI::logging("> Completed table LIST_COMPLETED\n"); //Select data TO_DO OR DRAFT $inbCriteria = $appCache->getSelAllColumns(); $rsCriteria = AppCacheViewPeer::doSelectRS($inbCriteria); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); $criteriaUser = new Criteria(); $criteriaUser->addSelectColumn( UsersPeer::USR_UID ); $criteriaUser->addSelectColumn( UsersPeer::USR_FIRSTNAME ); $criteriaUser->addSelectColumn( UsersPeer::USR_LASTNAME ); $criteriaUser->addSelectColumn( UsersPeer::USR_USERNAME ); //Insert new data LIST_INBOX while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); $isSelfService = ($row['USR_UID'] == '') ? true : false; if($row["DEL_THREAD_STATUS"] == 'OPEN'){ //Update information about the previous_user $row["DEL_PREVIOUS_USR_UID"] = $row["PREVIOUS_USR_UID"]; $criteriaUser->add( UsersPeer::USR_UID, $row["PREVIOUS_USR_UID"] ); $datasetU = UsersPeer::doSelectRS($criteriaUser); $datasetU->setFetchmode(ResultSet::FETCHMODE_ASSOC); $datasetU->next(); $arrayUsers = $datasetU->getRow(); $row["DEL_PREVIOUS_USR_USERNAME"] = $arrayUsers["USR_USERNAME"]; $row["DEL_PREVIOUS_USR_FIRSTNAME"]= $arrayUsers["USR_FIRSTNAME"]; $row["DEL_PREVIOUS_USR_LASTNAME"] = $arrayUsers["USR_LASTNAME"]; //Update the due date $row["DEL_DUE_DATE"] = $row["DEL_TASK_DUE_DATE"]; $listInbox = new ListInbox(); $listInbox->remove($row["APP_UID"],$row["DEL_INDEX"]); $listInbox->setDeleted(false); $listInbox->create($row, $isSelfService); } else { // create participated List when the thread is CLOSED $listParticipatedHistory = new ListParticipatedHistory(); $listParticipatedHistory->remove($row['APP_UID'], $row['DEL_INDEX']); $listParticipatedHistory = new ListParticipatedHistory(); $listParticipatedHistory->create($row); $oCriteria = new Criteria('workflow'); $oCriteria->add(ListParticipatedLastPeer::APP_UID, $row['APP_UID']); $oCriteria->add(ListParticipatedLastPeer::USR_UID, $row['USR_UID']); ListParticipatedLastPeer::doDelete($oCriteria); $listParticipatedLast = new ListParticipatedLast(); $listParticipatedLast->create($row); $listParticipatedLast = new ListParticipatedLast(); $listParticipatedLast->refresh($row); } } CLI::logging("> Completed table LIST_INBOX\n"); //With this List is populated the LIST_PARTICIPATED_HISTORY and LIST_PARTICIPATED_LAST CLI::logging("> Completed table LIST_PARTICIPATED_HISTORY\n"); CLI::logging("> Completed table LIST_PARTICIPATED_LAST\n"); //Select data TO_DO OR DRAFT CASES CREATED BY AN USER $myiCriteria = $appCache->getSelAllColumns(); $myiCriteria->add(AppCacheViewPeer::DEL_INDEX, "1", CRITERIA::EQUAL); $rsCriteria = AppCacheViewPeer::doSelectRS($myiCriteria); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); //Insert new data LIST_MY_INBOX while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); $listMyInbox = new ListMyInbox(); $listMyInbox ->remove($row["APP_UID"],$row["USR_UID"]); $listMyInbox->setDeleted(false); $listMyInbox->create($row); } CLI::logging("> Completed table LIST_MY_INBOX\n"); //Select data PAUSED $delaycriteria = new Criteria("workflow"); $delaycriteria->addSelectColumn(AppDelayPeer::APP_UID); $delaycriteria->addSelectColumn(AppDelayPeer::PRO_UID); $delaycriteria->addSelectColumn(AppDelayPeer::APP_DEL_INDEX); $delaycriteria->addSelectColumn(AppCacheViewPeer::APP_NUMBER); $delaycriteria->addSelectColumn(AppCacheViewPeer::USR_UID); $delaycriteria->addSelectColumn(AppCacheViewPeer::APP_STATUS); $delaycriteria->addSelectColumn(AppCacheViewPeer::TAS_UID); $delaycriteria->addJoin( AppCacheViewPeer::APP_UID, AppDelayPeer::APP_UID . ' AND ' . AppCacheViewPeer::DEL_INDEX . ' = ' . AppDelayPeer::APP_DEL_INDEX, Criteria::INNER_JOIN ); $delaycriteria->add(AppDelayPeer::APP_DISABLE_ACTION_USER, "0", CRITERIA::EQUAL); $delaycriteria->add(AppDelayPeer::APP_TYPE, "PAUSE", CRITERIA::EQUAL); $rsCriteria = AppDelayPeer::doSelectRS($delaycriteria); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); //Insert new data LIST_PAUSED while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); $data = $row; $data["DEL_INDEX"] = $row["APP_DEL_INDEX"]; $listPaused = new ListPaused(); $listPaused ->remove($row["APP_UID"],$row["APP_DEL_INDEX"],$data); $listPaused->setDeleted(false); $listPaused->create($data); } CLI::logging("> Completed table LIST_PAUSED\n"); //Select and Insert LIST_UNASSIGNED $unaCriteria = $appCache->getSelAllColumns(); $unaCriteria->add(AppCacheViewPeer::USR_UID, "", CRITERIA::EQUAL); $rsCriteria = AppCacheViewPeer::doSelectRS($unaCriteria); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); $del = new ListUnassignedPeer(); $del->doDeleteAll(); $del = new ListUnassignedGroupPeer(); $del->doDeleteAll(); while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); $listUnassigned = new ListUnassigned(); $unaUid = $listUnassigned->generateData($row["APP_UID"],$row["PREVIOUS_USR_UID"]); } CLI::logging("> Completed table LIST_UNASSIGNED\n"); CLI::logging("> Completed table LIST_UNASSIGNED_GROUP\n"); // ADD LISTS COUNTS $aTypes = array( 'to_do', 'draft', 'cancelled', 'sent', 'paused', 'completed', 'selfservice' ); $users = new Users(); $criteria = new Criteria(); $criteria->addSelectColumn(UsersPeer::USR_UID); $dataset = UsersPeer::doSelectRS($criteria); $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); while($dataset->next()) { $aRow = $dataset->getRow(); $oAppCache = new AppCacheView(); $aCount = $oAppCache->getAllCounters( $aTypes, $aRow['USR_UID'] ); $newData = array( 'USR_UID' => $aRow['USR_UID'], 'USR_TOTAL_INBOX' => $aCount['to_do'], 'USR_TOTAL_DRAFT' => $aCount['draft'], 'USR_TOTAL_CANCELLED' => $aCount['cancelled'], 'USR_TOTAL_PARTICIPATED' => $aCount['sent'], 'USR_TOTAL_PAUSED' => $aCount['paused'], 'USR_TOTAL_COMPLETED' => $aCount['completed'], 'USR_TOTAL_UNASSIGNED' => $aCount['selfservice'] ); $users->update($newData); } $this->listFirstExecution('insert'); return true; }
function run_workspace_restore($args, $opts) { $filename = $args[0]; if (strpos($filename, "/") === false && strpos($filename, '\\') === false) { $filename = PATH_DATA . "backups/{$filename}"; if (!file_exists($filename) && substr_compare($filename, ".tar", -4, 4, true) != 0) { $filename .= ".tar"; } } $info = array_key_exists("info", $opts); if ($info) { workspaceTools::getBackupInfo($filename); } else { CLI::logging("Restoring from {$filename}\n"); $workspace = array_key_exists("workspace", $opts) ? $opts['workspace'] : NULL; $overwrite = array_key_exists("overwrite", $opts); $multiple = array_key_exists("multiple", $opts); $dstWorkspace = $args[1]; if (!empty($multiple)) { if (!G::isLinuxOs()) { CLI::error("This is not a Linux enviroment, cannot use this multiple [-m] feature.\n"); return; } multipleFilesBackup::letsRestore($filename, $workspace, $dstWorkspace, $overwrite); } else { $anotherExtention = ".*"; //if there are files with and extra extention: e.g. <file>.tar.number $multiplefiles = glob($filename . $anotherExtention); // example: //shared/workflow_data/backups/myWorkspace.tar.* if (count($multiplefiles) > 0) { CLI::error("Processmaker found these files: .\n"); foreach ($multiplefiles as $index => $value) { CLI::logging($value . "\n"); } CLI::error("Please, you should use -m parameter to restore them.\n"); return; } workspaceTools::restore($filename, $workspace, $dstWorkspace, $overwrite); } } }
function run_upgrade($command, $args) { CLI::logging("UPGRADE", PROCESSMAKER_PATH . "upgrade.log"); CLI::logging("Checking files integrity...\n"); //setting flag to true to check into sysGeneric.php $flag = G::isPMUnderUpdating(1); //start to upgrade $checksum = System::verifyChecksum(); if ($checksum === false) { CLI::logging(CLI::error("checksum.txt not found, integrity check is not possible") . "\n"); if (!CLI::question("Integrity check failed, do you want to continue the upgrade?")) { CLI::logging("Upgrade failed\n"); $flag = G::isPMUnderUpdating(0); die; } } else { if (!empty($checksum['missing'])) { CLI::logging(CLI::error("The following files were not found in the installation:") . "\n"); foreach ($checksum['missing'] as $missing) { CLI::logging(" {$missing}\n"); } } if (!empty($checksum['diff'])) { CLI::logging(CLI::error("The following files have modifications:") . "\n"); foreach ($checksum['diff'] as $diff) { CLI::logging(" {$diff}\n"); } } if (!(empty($checksum['missing']) || empty($checksum['diff']))) { if (!CLI::question("Integrity check failed, do you want to continue the upgrade?")) { CLI::logging("Upgrade failed\n"); $flag = G::isPMUnderUpdating(0); die; } } } CLI::logging("Clearing cache...\n"); if (defined('PATH_C')) { G::rm_dir(PATH_C); G::mk_dir(PATH_C, 0777); } $workspaces = get_workspaces_from_args($command); $count = count($workspaces); $first = true; $errors = false; $countWorkspace = 0; $buildCacheView = array_key_exists("buildACV", $args); foreach ($workspaces as $index => $workspace) { if (!defined("SYS_SYS")) { define("SYS_SYS", $workspace->name); } if (!defined("PATH_DATA_SITE")) { define("PATH_DATA_SITE", PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP); } try { $countWorkspace++; CLI::logging("Upgrading workspaces ({$countWorkspace}/{$count}): " . CLI::info($workspace->name) . "\n"); $workspace->upgrade($first, $buildCacheView, $workspace->name); $workspace->close(); $first = false; } catch (Exception $e) { CLI::logging("Errors upgrading workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"); $errors = true; } } // SAVE Upgrades/Patches $arrayPatch = glob(PATH_TRUNK . 'patch-*'); if ($arrayPatch) { foreach ($arrayPatch as $value) { if (file_exists($value)) { // copy content the patch $names = pathinfo($value); $nameFile = $names['basename']; $contentFile = file_get_contents($value); $contentFile = preg_replace("[\n|\r|\n\r]", '', $contentFile); CLI::logging($contentFile . ' installed (' . $nameFile . ')', PATH_DATA . 'log/upgrades.log'); // move file of patch $newFile = PATH_DATA . $nameFile; G::rm_dir($newFile); copy($value, $newFile); G::rm_dir($value); } } } else { CLI::logging('ProcessMaker ' . System::getVersion() . ' installed', PATH_DATA . 'log/upgrades.log'); } //Safe upgrade for JavaScript files CLI::logging("\nSafe upgrade for files cached by the browser\n\n"); G::browserCacheFilesSetUid(); //Status if ($errors) { CLI::logging("Upgrade finished but there were errors upgrading workspaces.\n"); CLI::logging(CLI::error("Please check the log above to correct any issues.") . "\n"); } else { CLI::logging("Upgrade successful\n"); } //setting flag to false $flag = G::isPMUnderUpdating(0); }
function run_upgrade($command, $args) { CLI::logging("UPGRADE", PROCESSMAKER_PATH . "upgrade.log"); CLI::logging("Checking files integrity...\n"); //setting flag to true to check into sysGeneric.php $flag = G::isPMUnderUpdating(1); //start to upgrade $checksum = System::verifyChecksum(); if ($checksum === false) { CLI::logging(CLI::error("checksum.txt not found, integrity check is not possible") . "\n"); if (!CLI::question("Integrity check failed, do you want to continue the upgrade?")) { CLI::logging("Upgrade failed\n"); die; } } else { if (!empty($checksum['missing'])) { CLI::logging(CLI::error("The following files were not found in the installation:") . "\n"); foreach ($checksum['missing'] as $missing) { CLI::logging(" {$missing}\n"); } } if (!empty($checksum['diff'])) { CLI::logging(CLI::error("The following files have modifications:") . "\n"); foreach ($checksum['diff'] as $diff) { CLI::logging(" {$diff}\n"); } } if (!(empty($checksum['missing']) || empty($checksum['diff']))) { if (!CLI::question("Integrity check failed, do you want to continue the upgrade?")) { CLI::logging("Upgrade failed\n"); die; } } } CLI::logging("Clearing cache...\n"); if (defined('PATH_C')) { rm_dir(PATH_C, true); } $workspaces = get_workspaces_from_args($command); $count = count($workspaces); $first = true; $errors = false; $buildCacheView = array_key_exists("buildACV", $args); foreach ($workspaces as $index => $workspace) { try { CLI::logging("Upgrading workspaces ({$index}/{$count}): " . CLI::info($workspace->name) . "\n"); $workspace->upgrade($first, $buildCacheView, $workspace->name); $workspace->close(); $first = false; } catch (Exception $e) { CLI::logging("Errors upgrading workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"); $errors = true; } } if ($errors) { CLI::logging("Upgrade finished but there were errors upgrading workspaces.\n"); CLI::logging(CLI::error("Please check the log above to correct any issues.") . "\n"); } else { CLI::logging("Upgrade successful\n"); } //setting flag to false $flag = G::isPMUnderUpdating(0); }
public function regenerateContent($langs, $workSpace = SYS_SYS) { //Search the language $key = array_search('en', $langs); if ($key === false) { $key = array_search(SYS_LANG, $langs); if ($key === false) { $key = '0'; } } $this->langsAsoc = array(); foreach ($langs as $key => $value) { $this->langsAsoc[$value] = $value; } $this->langs = $langs; $this->rowsProcessed = 0; $this->rowsInserted = 0; $this->rowsUnchanged = 0; $this->rowsClustered = 0; //Creating table CONTENT_BACKUP $connection = Propel::getConnection('workflow'); $oStatement = $connection->prepareStatement("CREATE TABLE IF NOT EXISTS `CONTENT_BACKUP` (\n `CON_CATEGORY` VARCHAR(30) default '' NOT NULL,\n `CON_PARENT` VARCHAR(32) default '' NOT NULL,\n `CON_ID` VARCHAR(100) default '' NOT NULL,\n `CON_LANG` VARCHAR(10) default '' NOT NULL,\n `CON_VALUE` MEDIUMTEXT NOT NULL,\n CONSTRAINT CONTENT_BACKUP_PK PRIMARY KEY (CON_CATEGORY,CON_PARENT,CON_ID,CON_LANG)\n )Engine=InnoDB DEFAULT CHARSET='utf8' COMMENT='Table for add content';"); $oStatement->executeQuery(); $sql = " SELECT DISTINCT CON_LANG\n 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']); } } $sql = " SELECT CON_ID, CON_CATEGORY, CON_LANG, CON_PARENT, CON_VALUE\n FROM CONTENT\n ORDER BY CON_ID, CON_CATEGORY, CON_PARENT, CON_LANG"; G::LoadClass("wsTools"); $workSpace = new workspaceTools($workSpace); $workSpace->getDBInfo(); $link = @mysql_pconnect($workSpace->dbHost, $workSpace->dbUser, $workSpace->dbPass) or die("Could not connect"); mysql_select_db($workSpace->dbName, $link); mysql_query("SET NAMES 'utf8';"); mysql_query("SET FOREIGN_KEY_CHECKS=0;"); mysql_query('SET OPTION SQL_BIG_SELECTS=1'); $result = mysql_unbuffered_query($sql, $link); $list = array(); $default = array(); $sw = array('CON_ID' => '', 'CON_CATEGORY' => '', 'CON_PARENT' => ''); while ($row = mysql_fetch_assoc($result)) { if ($sw['CON_ID'] == $row['CON_ID'] && $sw['CON_CATEGORY'] == $row['CON_CATEGORY'] && $sw['CON_PARENT'] == $row['CON_PARENT']) { $list[] = $row; } else { $this->rowsClustered++; if (count($langs) != count($list)) { $this->checkLanguage($list, $default); } else { $this->rowsUnchanged = $this->rowsUnchanged + count($langs); } $sw = array(); $sw['CON_ID'] = $row['CON_ID']; $sw['CON_CATEGORY'] = $row['CON_CATEGORY']; $sw['CON_LANG'] = $row['CON_LANG']; $sw['CON_PARENT'] = $row['CON_PARENT']; unset($list); unset($default); $list = array(); $default = array(); $list[] = $row; } if ($sw['CON_LANG'] == $langs[$key]) { $default = $row; } $this->rowsProcessed++; } if (count($langs) != count($list)) { $this->checkLanguage($list, $default); } else { $this->rowsUnchanged = $this->rowsUnchanged + count($langs); } mysql_free_result($result); $total = $this->rowsProcessed + $this->rowsInserted; $statement = $connection->prepareStatement("INSERT INTO CONTENT\n SELECT CON_CATEGORY, CON_PARENT, CON_ID , CON_LANG, CON_VALUE\n FROM CONTENT_BACKUP"); $statement->executeQuery(); $statement = $connection->prepareStatement("DROP TABLE CONTENT_BACKUP"); $statement->executeQuery(); //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(); } 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"); CLI::logging("Rows Inserted ---> {$this->rowsInserted} ..... \n"); CLI::logging("Rows Total ---> {$total} ..... \n"); } }
/** * restore an archive into a workspace * * Restores any database and files included in the backup, either as a new * workspace, or overwriting a previous one * * @param string $filename the backup filename * @param string $newWorkspaceName if defined, supplies the name for the * workspace to restore to */ public static function restore($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true, $lang = 'en') { G::LoadThirdParty('pear/Archive', 'Tar'); $backup = new Archive_Tar($filename); //Get a temporary directory in the upgrade directory $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); $parentDirectory = PATH_DATA . "upgrade"; if (is_writable($parentDirectory)) { mkdir($tempDirectory); } else { throw new Exception("Could not create directory:" . $parentDirectory); } //Extract all backup files, including database scripts and workspace files if (!$backup->extract($tempDirectory)) { throw new Exception("Could not extract backup"); } //Search for metafiles in the new standard (the old standard would contain //txt files). $metaFiles = glob($tempDirectory . "/*.meta"); if (empty($metaFiles)) { $metaFiles = glob($tempDirectory . "/*.txt"); if (!empty($metaFiles)) { return workspaceTools::restoreLegacy($tempDirectory); } else { throw new Exception("No metadata found in backup"); } } else { CLI::logging("Found " . count($metaFiles) . " workspaces in backup:\n"); foreach ($metaFiles as $metafile) { CLI::logging("-> " . basename($metafile) . "\n"); } } if (count($metaFiles) > 1 && !isset($srcWorkspace)) { throw new Exception("Multiple workspaces in backup but no workspace specified to restore"); } if (isset($srcWorkspace) && !in_array("{$srcWorkspace}.meta", array_map(BASENAME, $metaFiles))) { throw new Exception("Workspace {$srcWorkspace} not found in backup"); } $version = System::getVersion(); $version = explode('-', $version); $versionPresent = isset($version[0]) ? $version[0] : ''; CLI::logging(CLI::warning("\n Note.- If you try to execute a restore from a generated backup on a recent version of Processmaker\n than version you are using currently to restore it, it may be occur errors on the restore process,\n it shouldn't be restaured generated backups on later versions than version when the restore is executed") . "\n"); foreach ($metaFiles as $metaFile) { $metadata = G::json_decode(file_get_contents($metaFile)); if ($metadata->version != 1) { throw new Exception("Backup version {$metadata->version} not supported"); } $backupWorkspace = $metadata->WORKSPACE_NAME; if (isset($dstWorkspace)) { $workspaceName = $dstWorkspace; $createWorkspace = true; } else { $workspaceName = $metadata->WORKSPACE_NAME; $createWorkspace = false; } if (isset($srcWorkspace) && strcmp($metadata->WORKSPACE_NAME, $srcWorkspace) != 0) { CLI::logging(CLI::warning("> Workspace {$backupWorkspace} found, but not restoring.") . "\n"); continue; } else { 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)"); } } if (file_exists($workspace->path)) { G::rm_dir($workspace->path); } foreach ($metadata->directories as $dir) { CLI::logging("+> Restoring directory '{$dir}'\n"); if (file_exists("{$tempDirectory}/{$dir}" . "/ee")) { G::rm_dir("{$tempDirectory}/{$dir}" . "/ee"); } if (file_exists("{$tempDirectory}/{$dir}" . "/plugin.singleton")) { G::rm_dir("{$tempDirectory}/{$dir}" . "/plugin.singleton"); } if (!rename("{$tempDirectory}/{$dir}", $workspace->path)) { throw new Exception("There was an error copying the backup files ({$tempDirectory}/{$dir}) to the workspace directory {$workspace->path}."); } } CLI::logging("> Changing file permissions\n"); $shared_stat = stat(PATH_DATA); if ($shared_stat !== false) { workspaceTools::dirPerms($workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); } else { CLI::logging(CLI::error("Could not get the shared folder permissions, not changing workspace permissions") . "\n"); } list($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); $aParameters = array('dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass); CLI::logging("> Connecting to system database in '{$dbHost}'\n"); $link = mysql_connect($dbHost, $dbUser, $dbPass); @mysql_query("SET NAMES 'utf8';"); @mysql_query("SET FOREIGN_KEY_CHECKS=0;"); if (!$link) { throw new Exception('Could not connect to system database: ' . mysql_error()); } $newDBNames = $workspace->resetDBInfo($dbHost, $createWorkspace); 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); $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName); $workspace->createDBUser($dbName, $db->pass, "%", $dbName); } $version = explode('-', $metadata->PM_VERSION); $versionOld = isset($version[0]) ? $version[0] : ''; CLI::logging(CLI::info("{$versionOld} < {$versionPresent}") . "\n"); if ($versionOld < $versionPresent) { $start = microtime(true); CLI::logging("> Updating database...\n"); $workspace->upgradeDatabase(); $stop = microtime(true); $final = $stop - $start; CLI::logging("<*> Database Upgrade Process took {$final} seconds.\n"); } $start = microtime(true); CLI::logging("> Updating cache view...\n"); $workspace->upgradeCacheView(true, false, $lang); $stop = microtime(true); $final = $stop - $start; CLI::logging("<*> Updating cache view Process took {$final} seconds.\n"); mysql_close($link); } CLI::logging("Removing temporary files\n"); G::rm_dir($tempDirectory); CLI::logging(CLI::info("Done restoring") . "\n"); }
function run_workspace_restore($args, $opts) { $filename = $args[0]; if (strpos($filename, "/") === false && strpos($filename, '\\') === false) { $filename = PATH_DATA . "backups/{$filename}"; if (!file_exists($filename) && substr_compare($filename, ".tar", -4, 4, true) != 0) { $filename .= ".tar"; } } $info = array_key_exists("info", $opts); if ($info) { workspaceTools::getBackupInfo($filename); } else { CLI::logging("Restoring from {$filename}\n"); $workspace = array_key_exists("workspace", $opts) ? $opts['workspace'] : NULL; $overwrite = array_key_exists("overwrite", $opts); $dstWorkspace = $args[1]; workspaceTools::restore($filename, $workspace, $dstWorkspace, $overwrite); } }
function runBrowserCacheFiles($command, $args) { CLI::logging("Safe upgrade for files cached by the browser\n"); G::browserCacheFilesSetUid(); CLI::logging("Upgrade successful\n"); }