Example #1
0
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");

}
Example #2
0
 /**
  * Inline exception handler.
  * 
  * - Display the error message, source of the exception
  * - Stack trace of the error
  * - Write error in [Log]
  * 
  * @param  Exception $e 
  * @return void
  */
 public static function handler(Exception $e)
 {
     try {
         $error = $e instanceof CLI_Exception ? $e->_cli_text() : parent::text($e);
         CLI::error($error);
         $exit_code = $e->getCode();
         if ($exit_code == 0) {
             // Never exit '0' after an exception
             $exit_code = 1;
         }
         exit($exit_code);
     } catch (Exception $e) {
         // Display the exception text
         CLI::error(parent::text($e));
         // Exit with an error status
         exit(1);
     }
 }
Example #3
0
    /**
     * Edit a temporary block of text with $EDITOR (or nano as fallback)
     * @param string $text The initial text of the document.
     * @param string $filename The (fake) filename passed to the editor (for syntax highlighting hint).
     * @return string The edited contents
     */
    public static function edit($text, $filename = '')
    {
        $EDITOR = getenv('EDITOR') ?: 'nano';
        $tmp = tempnam(sys_get_temp_dir(), "E-") . strtr($filename, '/', '_');
        file_put_contents($tmp, $text);
        passthru("{$EDITOR} {$tmp}");
        $result = file_get_contents($tmp);
        unlink($tmp);
        return $result;
    }
}
// Standard Help Message
CLI::help(function () {
    echo 'Usage: ', CLI::name(), ' [commands]', PHP_EOL, 'Commands:', PHP_EOL;
    foreach (CLI::commands() as $cmd) {
        echo "\t", $cmd['name'], ' ', $cmd['params'], PHP_EOL;
        if ($cmd['description']) {
            echo "\t\t- ", str_replace("\n", "\n\t\t  ", $cmd['description']), PHP_EOL, PHP_EOL;
        }
    }
});
// Standard Error Message
CLI::error(function ($message) {
    echo 'Error: ', $message, PHP_EOL;
});
 /**
  * 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");
 }
Example #5
0
function run_database_generate_self_service_by_value($args, $opts)

{

    G::LoadSystem('inputfilter');

    $filter = new InputFilter();

    $opts = $filter->xssFilterHard($opts);

    $args = $filter->xssFilterHard($args);

    try {

        $arrayWorkspace = get_workspaces_from_args($args);



        foreach ($arrayWorkspace as $value) {

            $workspace = $value;



            try {

                echo "Generating the table \"self-service by value\" for " . pakeColor::colorize($workspace->name, "INFO") . "\n";

                $workspace->appAssignSelfServiceValueTableGenerateData();

            } catch (Exception $e) {

                echo "Errors generating the table \"self-service by value\" of workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n";

            }



            echo "\n";

        }



        echo "Done!\n";

    } catch (Exception $e) {

        echo CLI::error($e->getMessage()) . "\n";

    }

}
    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" );
    }
Example #7
0
    public function verifyFilesOldEnterprise ($workspace)

    {

        $this->initPropel( true );

        $pathBackup = PATH_DATA . 'backups';

        if (!file_exists($pathBackup)) {

            G::mk_dir($pathBackup, 0777);

        }

        $pathNewFile = PATH_DATA . 'backups' . PATH_SEP . 'enterpriseBackup';

        $pathDirectoryEnterprise = PATH_CORE . 'plugins' . PATH_SEP . 'enterprise';

        $pathFileEnterprise = PATH_CORE . 'plugins' . PATH_SEP . 'enterprise.php';



        if (!file_exists($pathDirectoryEnterprise) && !file_exists($pathFileEnterprise)) {

            CLI::logging("    Without changes... \n");

            return true;

        }

        CLI::logging("    Migrating Enterprise Core version...\n");

        if (!file_exists($pathNewFile)) {

            CLI::logging("    Creating folder in $pathNewFile\n");

            G::mk_dir($newDiretory, 0777);

        }

        $shared_stat = stat(PATH_DATA);

        if (file_exists($pathDirectoryEnterprise)) {

            CLI::logging("    Copying Enterprise Directory to $pathNewFile...\n");



            if ($shared_stat !== false) {

                workspaceTools::dirPerms($pathDirectoryEnterprise, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']);

            } else {

                CLI::logging(CLI::error("Could not get shared folder permissions, workspace permissions couldn't be changed") . "\n");

            }

            if (G::recursive_copy($pathDirectoryEnterprise, $pathNewFile . PATH_SEP. 'enterprise')) {

                CLI::logging("    Removing $pathDirectoryEnterprise...\n");

                G::rm_dir($pathDirectoryEnterprise);

            } else {

                CLI::logging(CLI::error("    Error: Failure to copy from $pathDirectoryEnterprise...\n"));

            }

            if (file_exists($pathDirectoryEnterprise)) {

                CLI::logging(CLI::info("    Remove manually $pathDirectoryEnterprise...\n"));

            }

        }

        if (file_exists($pathFileEnterprise)) {

            CLI::logging("    Copying Enterprise.php file to $pathNewFile...\n");

            if ($shared_stat !== false) {

                workspaceTools::dirPerms($pathFileEnterprise, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']);

            } else {

                CLI::logging(CLI::error("Could not get shared folder permissions, workspace permissions couldn't be changed") . "\n");

            }

            CLI::logging("    Removing $pathFileEnterprise...\n");

            copy($pathFileEnterprise , $pathNewFile. PATH_SEP . 'enterprise.php');

            G::rm_dir($pathFileEnterprise);

            if (file_exists($pathFileEnterprise)) {

                CLI::logging(CLI::info("    Remove manually $pathFileEnterprise...\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);
        $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);
        }
    }
}
Example #9
0
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;
        }
    }
}
Example #10
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");
            $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);
}
Example #11
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);
}
Example #12
0
 /**
  * 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");
 }
Example #13
0
function database_upgrade($command, $args)
{
    $workspaces = get_workspaces_from_args($args);
    $checkOnly = strcmp($command, "check") == 0;
    foreach ($workspaces as $workspace) {
        if ($checkOnly) {
            print_r("Checking database in " . pakeColor::colorize($workspace->name, "INFO") . "\n");
        } else {
            print_r("Upgrading database in " . pakeColor::colorize($workspace->name, "INFO") . "\n");
        }
        try {
            $changes = $workspace->upgradeDatabase($checkOnly);
            if ($changes != false) {
                if ($checkOnly) {
                    echo "> " . pakeColor::colorize("Run upgrade", "INFO") . "\n";
                    echo "  Tables (add = " . count($changes['tablesToAdd']);
                    echo ", alter = " . count($changes['tablesToAlter']) . ") ";
                    echo "- Indexes (add = " . count($changes['tablesWithNewIndex']) . "";
                    echo ", alter = " . count($changes['tablesToAlterIndex']) . ")\n";
                } else {
                    echo "-> Schema fixed\n";
                }
            } else {
                echo "> OK\n";
            }
        } catch (Exception $e) {
            echo "> Error: " . CLI::error($e->getMessage()) . "\n";
        }
    }
}