Example #1
0
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;
    }
}
Example #2
0
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");
    }
}
Example #3
0
 public function pluginUninstall($pluginName)
 {
     //define("PATH_PLUGINS", PATH_CORE . "plugins" . PATH_SEP);
     if (file_exists(PATH_CORE . "plugins" . PATH_SEP . $pluginName . ".php")) {
         require_once PATH_CORE . "plugins" . PATH_SEP . $pluginName . ".php";
         $pluginRegistry =& PMPluginRegistry::getSingleton();
         $pluginDetail = $pluginRegistry->getPluginDetails($pluginName . ".php");
         if ($pluginDetail) {
             $pluginRegistry->enablePlugin($pluginDetail->sNamespace);
             $pluginRegistry->disablePlugin($pluginDetail->sNamespace);
             ///////
             $plugin = new $pluginDetail->sClassName($pluginDetail->sNamespace, $pluginDetail->sFilename);
             //$this->_aPlugins[$pluginDetail->sNamespace] = $plugin;
             if (method_exists($plugin, "uninstall")) {
                 $plugin->uninstall();
             }
             ///////
             file_put_contents(PATH_DATA_SITE . "plugin.singleton", $pluginRegistry->serializeInstance());
         }
         ///////
         unlink(PATH_CORE . "plugins" . PATH_SEP . $pluginName . ".php");
         if (file_exists(PATH_CORE . "plugins" . PATH_SEP . $pluginName)) {
             G::rm_dir(PATH_CORE . "plugins" . PATH_SEP . $pluginName);
         }
     }
 }
Example #4
0
 /**
  * rm_dir
  *
  * @param string $dirName
  *
  * @return void
  */
 public function rm_dir($dirName)
 {
     if (!is_writable($dirName)) {
         return false;
     }
     if (is_dir($dirName)) {
         foreach (glob($dirName . '/{,.}*', GLOB_BRACE) as $file) {
             if ($file == $dirName . '/.' || $file == $dirName . '/..') {
                 continue;
             }
             if (is_dir($file)) {
                 G::rm_dir($file);
             } else {
                 @unlink($file);
             }
         }
         if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
             $dirName = str_replace("/", "\\", $dirName);
             exec("DEL /F /S /Q " . $dirName . "", $res);
             exec("RD /S /Q " . $dirName . "", $res);
         } else {
             @rmdir($dirName);
         }
     } else {
         @unlink($dirName);
     }
 }
    public function uninstallPlugin ($sNamespace)
    {
        $pluginFile = $sNamespace . ".php";

        if (! file_exists( PATH_PLUGINS . $pluginFile )) {
            throw (new Exception( "File \"$pluginFile\" doesn't exist" ));
        }

        ///////
        $path = PATH_PLUGINS . $pluginFile;
        G::LoadSystem('inputfilter');
        $filter = new InputFilter();
        $path = $filter->validateInput($path, 'path');
        require_once ($path);

        foreach ($this->_aPluginDetails as $namespace => $detail) {
            if ($namespace == $sNamespace) {
                $this->enablePlugin( $detail->sNamespace );
                $this->disablePlugin( $detail->sNamespace );

                ///////
                $plugin = new $detail->sClassName( $detail->sNamespace, $detail->sFilename );
                $this->_aPlugins[$detail->sNamespace] = $plugin;

                if (method_exists( $plugin, "uninstall" )) {
                    $plugin->uninstall();
                }

                ///////
                $this->save();
                ///////
                $pluginDir = PATH_PLUGINS . $detail->sPluginFolder;

                if (isset( $detail->sFilename ) && ! empty( $detail->sFilename ) && file_exists( $detail->sFilename )) {
                    unlink( $detail->sFilename );
                }

                if (isset( $detail->sPluginFolder ) && ! empty( $detail->sPluginFolder ) && file_exists( $pluginDir )) {
                    G::rm_dir( $pluginDir );
                }

                ///////
                $this->uninstallPluginWorkspaces( array ($sNamespace
                ) );
                ///////
                break;
            }
        }
    }
                 if (strcasecmp(trim($params[0]), "filename") == 0) {
                     $fileName = trim($params[1], "\" ");
                 }
             }
         }
     }
 }
 if (preg_match("/^.*json.*\$/i", $fileContentType)) {
     $r = G::json_decode(stream_get_contents($fileData));
     if ($r->status == "ERROR") {
         throw new Exception($r->message);
     }
 }
 ///////
 $dir = PATH_DATA . "upgrade" . PATH_SEP . "processmaker";
 G::rm_dir($dir);
 G::mk_dir($dir);
 if (!file_exists($dir)) {
     throw new Exception("Could not create destination directory.");
 }
 ///////
 $fileName = $dir . PATH_SEP . $fileName;
 $file = @fopen($fileName, "wb");
 if ($file === false) {
     throw new Exception("Could not open destination file.");
 }
 while (!feof($fileData)) {
     $data = fread($fileData, BUFSIZE);
     //Just to be safe, check all error conditions
     if ($data === "" || $data === false) {
         break;
Example #7
0
 /**
  * This function does to clean up to the upgrate directory
  *
  *
  * @name cleanupUpgradeDirectory
  *
  * param
  * @return array
  */
 public function cleanupUpgradeDirectory()
 {
     G::rm_dir(PATH_DATA . "upgrade" . PATH_SEP . "processmaker");
 }
Example #8
0
function run_drafts_clean($args, $opts) {

  echo "Cleaning drafts\n";



  if (count($args) < 1)

    throw new Exception ("Please specify a workspace name");

  $workspace = $args[0];



  if (!file_exists(PATH_DB . $workspace . '/db.php')) {

    throw new Exception('Could not find workspace ' . $workspace);

  }



  $allDrafts = false;

  if (count($args) < 2) {

    echo "Cases older them this much days will be deleted (ENTER for all): ";

    $days = rtrim( fgets( STDIN ), "\n" );

    if ($days == "") {

      $allDrafts = true;

    }

  } else {

    $days = $args[1];

    if (strcmp($days, "all") == 0) {

      $allDrafts = true;

    }

  }



  if (!$allDrafts && (!is_numeric($days) || intval($days) <= 0)) {

    throw new Exception("Days value is not valid: " . $days);

  }



  if ($allDrafts)

    echo "Removing all drafts\n";

  else

    echo "Removing drafts older than " . $days . " days\n";



  /* Load the configuration from the workspace */

  require_once( PATH_DB . $workspace . '/db.php' );

  require_once( PATH_THIRDPARTY . 'propel/Propel.php');



  PROPEL::Init ( PATH_METHODS.'dbConnections/rootDbConnections.php' );

  $con = Propel::getConnection("root");



  $stmt = $con->createStatement();



  if (!$allDrafts)

    $dateSql = "AND DATE_SUB(CURDATE(),INTERVAL " . $days . " DAY) >= APP_CREATE_DATE";

  else

    $dateSql = "";

  /* Search for all the draft cases */

  $sql = "SELECT APP_UID FROM APPLICATION WHERE APP_STATUS='DRAFT'" . $dateSql;

  $appRows = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);



  /* Tables to remove the cases from */

  $tables = array(

      "APPLICATION",

      "APP_DELEGATION",

      "APP_CACHE_VIEW",

      "APP_THREAD",

      "APP_DOCUMENT",

      "APP_EVENT",

      "APP_HISTORY",

      "APP_MESSAGE"

  );



  echo "Found " . $appRows->getRecordCount() . " cases to remove";

  foreach ($appRows as $row) {

    echo ".";

    $appUid = $row['APP_UID'];

    foreach ($tables as $table) {

      delete_app_from_table($con, $table, $appUid);

    }

    delete_app_from_table($con, "CONTENT", $appUid, "CON_ID");

    if (file_exists(PATH_DB . $workspace . '/files/'. $appUid)) {

      echo "\nRemoving files from " . $appUid . "\n";

      G::rm_dir(PATH_DB . $workspace . '/files/'. $appUid);

    }

  }

  echo "\n";

}
            }
        } else {
            if (isset($_POST["metadataCache"])) {
                G::rm_dir(PATH_C . "xmlform");
                $response->xmlform = true;
                $msgLog = $msgLog . "Forms Metadata Cache";
                if (isset($_POST["htmlCache"])) {
                    G::rm_dir(PATH_C . "smarty");
                    $response->smarty = true;
                    $msgLog = $msgLog . " and Forms Html Templates Cache.";
                } else {
                    $msgLog = $msgLog . ".";
                }
            } else {
                if (isset($_POST["htmlCache"])) {
                    G::rm_dir(PATH_C . "smarty");
                    $response->smarty = true;
                    $msgLog = $msgLog . "Forms Html Templates Cache.";
                }
            }
        }
        $response->success = true;
        G::auditLog("ClearCache", $msgLog);
    } else {
        $response->success = false;
    }
} catch (Exception $e) {
    $response->success = false;
    $response->message = $e->getMessage();
}
echo G::json_encode($response);
Example #10
0
<?php

try {
    if (isset($_POST['javascriptCache']) || isset($_POST['metadataCache']) || isset($_POST['htmlCache'])) {
        if (isset($_POST['javascriptCache'])) {
            G::rm_dir(PATH_C . 'ExtJs');
            $response->javascript = true;
        }
        if (isset($_POST['metadataCache'])) {
            G::rm_dir(PATH_C . 'xmlform');
            $response->xmlform = true;
        }
        if (isset($_POST['htmlCache'])) {
            G::rm_dir(PATH_C . 'smarty');
            $response->smarty = true;
        }
        $response->success = true;
    } else {
        $response->success = false;
    }
} catch (Exception $e) {
    $response->success = false;
    $response->message = $e->getMessage();
}
echo G::json_encode($response);
Example #11
0
 /**
  * rm_dir
  *
  * @param  string $dirName
  *
  * @return void
  */
 function rm_dir($dirName)
 {
     if (!is_writable($dirName)) {
         return false;
     }
     if (is_dir($dirName)) {
         foreach (glob($dirName . '/*') as $file) {
             if (is_dir($file)) {
                 G::rm_dir($file);
                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                     exec('DEL /F /S /Q %' . $dirName . '%', $res);
                 } else {
                     @rmdir($file);
                 }
             } else {
                 @unlink($file);
             }
         }
     } else {
         @unlink($dirName);
     }
 }
Example #12
0
function workspaceRestore($backupFilename, $targetWorkspace, $overwrite)
{
    $tempDirectory = tempnam(__FILE__, '');
    if (file_exists($tempDirectory)) {
        unlink($tempDirectory);
    }
    if (file_exists($tempDirectory)) {
        G::rm_dir($tempDirectory);
    }
    G::mk_dir($tempDirectory);
    G::LoadThirdParty('pear/Archive', 'Tar');
    $tar = new Archive_Tar($backupFilename);
    $res = $tar->extract($tempDirectory);
    $metadataFilename = $tempDirectory . PATH_SEP . 'metadata.txt';
    if (!file_exists($metadataFilename)) {
        /* Look for legacy backups, where metadata was stored as a file with the
         * workspace name, such as workflow.txt
         * This means the backup filename must be the same as the metadata file.
         */
        $info = pathinfo($backupFilename);
        /* Check if it's a compressed backup, in which case we need to remove
         * both the gz and the tar extensions.
         */
        if ($info['extension'] == "gz") {
            $info = pathinfo(basename($backupFilename, '.' . $info['extension']));
        }
        $wsNameFromTar = basename($backupFilename, '.' . $info['extension']);
        $metadataFilename = $tempDirectory . PATH_SEP . $wsNameFromTar . '.txt';
        if (!file_exists($metadataFilename)) {
            throw new Exception("Metadata file was not found in backup");
        }
    }
    $metadata = unserialize(file_get_contents($metadataFilename));
    $backupWorkspace = $metadata['WORKSPACE_NAME'];
    $changeWorkspace = isset($targetWorkspace);
    if (!$changeWorkspace) {
        $targetWorkspace = $backupWorkspace;
    } else {
        echo "Restoring from workspace: " . pakeColor::colorize($backupWorkspace, 'INFO') . "\n";
    }
    echo "Restoring to workspace:   " . pakeColor::colorize($targetWorkspace, 'INFO') . "\n";
    //moving the site files
    $backupWorkspaceDir = $tempDirectory . PATH_SEP . $backupWorkspace;
    $targetWorkspaceDir = PATH_DATA . 'sites' . PATH_SEP . $targetWorkspace;
    if (!$overwrite && file_exists($targetWorkspaceDir)) {
        $overwrite = strtolower(prompt('Workspace already exists, do you want to overwrite? [Y/n]'));
        if (array_search(trim($overwrite), array("y", "")) === false) {
            die;
        }
        $overwrite = true;
    }
    printf("Moving files to %s \n", pakeColor::colorize($targetWorkspaceDir, 'INFO'));
    /* We already know we will be overwriting the new workspace if we reach this
     * point, so remove the workspace directory if it exists.
     */
    if (file_exists($targetWorkspaceDir)) {
        G::rm_dir($targetWorkspaceDir);
    }
    if (!rename($backupWorkspaceDir, $targetWorkspaceDir)) {
        throw new Exception("There was an error moving from {$backupWorkspaceDir} to {$targetWorkspaceDir}");
    }
    $dbOpt = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH));
    $dbHostname = $dbOpt[0];
    /* TODO: Check if database exists after updateDBfile */
    $config = updateDBfile($targetWorkspaceDir, $targetWorkspace, $dbHostname, $changeWorkspace);
    G::LoadSystem('dbMaintenance');
    $oDbMaintainer = new DataBaseMaintenance($dbOpt[0], $dbOpt[1], $dbOpt[2]);
    $dbName = $config['DB_NAME'];
    $dbUser = $config['DB_USER'];
    $dbPass = $config['DB_PASS'];
    restoreDB($dbHostname, $oDbMaintainer, $metadata['DB_NAME'], $dbName, $dbUser, $dbPass, $tempDirectory, $overwrite);
    $dbName = $config['DB_RBAC_NAME'];
    $dbUser = $config['DB_RBAC_USER'];
    $dbPass = $config['DB_RBAC_PASS'];
    restoreDB($dbHostname, $oDbMaintainer, $metadata['DB_RBAC_NAME'], $dbName, $dbUser, $dbPass, $tempDirectory, $overwrite);
    $dbName = $config['DB_REPORT_NAME'];
    $dbUser = $config['DB_REPORT_USER'];
    $dbPass = $config['DB_REPORT_PASS'];
    restoreDB($dbHostname, $oDbMaintainer, $metadata['DB_REPORT_NAME'], $dbName, $dbUser, $dbPass, $tempDirectory, $overwrite);
    echo "\n";
    $wsInfo = getSysInfo();
    $wsInfo['WORKSPACE_NAME'] = $targetWorkspace;
    $wsInfo = array_merge($wsInfo, $config);
    printInfoSites($metadata, $wsInfo);
    return true;
}
Example #13
0
G::mk_dir($pathPublic);
G::mk_dir($pathPublic . 'images');
//  file_put_contents ( PATH_DATA . 'skins' . PATH_SEP . $id  , "hello world" );
$fields['className'] = $id;
$fields['version'] = $oConf->version;
$fields['description'] = $oConf->description;
$fields['PMversion'] = System::getVersion();
savePluginFile('skinPluginMainClass', $pathHome . $id . '.php', $fields);
savePluginFile('skinPluginClass', $pathBase . 'class.' . $id . '.php', $fields);
copyFile(PATH_SKINS . $id . '.php', $pathBase . 'data');
copyFile(PATH_SKINS . $id . '.html', $pathBase . 'data');
copyFile(PATH_SKINS . $id . '.cnf', $pathBase . 'data');
copyFile(PATH_HTML . 'skins' . PATH_SEP . $id . PATH_SEP . 'iepngfix.htc', $pathPublic);
copyFile(PATH_HTML . 'skins' . PATH_SEP . $id . PATH_SEP . 'style.css', $pathPublic);
$aFiles = array();
if ($handle = opendir($pathImages)) {
    while (false !== ($file = readdir($handle))) {
        if (substr($file, 0, 1) != '.') {
            if (isset($aFiles[$file])) {
                $aFiles[$file] = 0;
            }
            copyFile($pathImages . $file, $pathPublic . 'images' . PATH_SEP);
        }
    }
    closedir($handle);
}
$fileTar = packPlugin($id, $oConf->version);
$bDownload = true;
G::streamFile($fileTar, $bDownload, basename($fileTar));
@G::rm_dir($pathHome);
@unlink($fileTar);
Example #14
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 #15
0
    for ($i = 1; $i <= count($argv) - 1; $i++) {
        if (strpos($argv[$i], "+force") !== false) {
            $force = true;
            unset($argv[$i]);
            break;
        }
    }
    if (!$force) {
        $arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
        $bCronIsRunning = (bool) $arrayCron["bCronIsRunning"];
        $sLastExecution = $arrayCron["sLastExecution"];
        $processcTimeProcess = isset($arrayCron["processcTimeProcess"]) ? intval($arrayCron["processcTimeProcess"]) : 10;
        //Minutes
        $processcTimeStart = isset($arrayCron["processcTimeStart"]) ? $arrayCron["processcTimeStart"] : 0;
    } else {
        G::rm_dir(PATH_DATA . "cron");
    }
}
if ($bCronIsRunning && $processcTimeStart != 0) {
    if (time() - $processcTimeStart > $processcTimeProcess * 60) {
        //Cron finished his execution for some reason
        $bCronIsRunning = false;
    }
}
if (!$bCronIsRunning) {
    //Start cron
    $arrayCron = array("bCronIsRunning" => "1", "sLastExecution" => date("Y-m-d H:i:s"));
    @file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
    try {
        //Data
        $ws = null;
Example #16
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"));

            }

        }

    }
    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 #18
0
 /**
  * Run the CLI task, which will check which command is specified and run it.
  */
 public static function run()
 {
     CLI::taskName("help");
     CLI::taskRun(array('self', 'help'));
     global $argv;
     $args = $argv;
     $cliname = array_shift($args);
     $taskName = array_shift($args);
     while ($taskName[0] == '-') {
         $taskName = array_shift($args);
     }
     if (!$taskName) {
         echo self::error("Specify a task from the list below.") . "\n\n";
         self::help(null, null);
         return;
     }
     $taskData = null;
     foreach (self::$tasks as $name => $data) {
         if (strcasecmp($name, $taskName) === 0) {
             $taskData = $data;
             break;
         }
     }
     if (!$taskData) {
         echo self::error("Command not found: '{$taskName}'") . "\n\n";
         self::help(null, null);
         return;
     }
     G::LoadThirdParty('pear/Console', 'Getopt');
     $short = "h" . $taskData['opt']['short'];
     $long = array_merge(array("help"), $taskData['opt']['long']);
     $getopt = Console_GetOpt::getopt2($args, $short, $long);
     if (!is_array($getopt)) {
         echo self::error("Invalid options (" . $getopt->getMessage() . ")") . "\n\n";
         self::help($taskName);
         return;
     }
     list($options, $arguments) = $getopt;
     foreach ($taskData['opt']['descriptions'] as $optName => $optDescription) {
         $short = str_replace(":", "", $optDescription['short']);
         $long = str_replace("=", "", $optDescription['long']);
         $validOpts[$short] = $optName;
         $validOpts[$long] = $optName;
     }
     $taskOpts = array();
     try {
         foreach ($options as $opt) {
             list($optName, $optArg) = $opt;
             if ($optName === "h" || $optName === "--help") {
                 self::help($taskName);
                 return;
             }
             if (strpos($optName, '--') === 0) {
                 $optName = substr($optName, 2);
             }
             if (!array_key_exists($optName, $validOpts)) {
                 throw new Exception("option not found: {$optName}");
             }
             if (array_key_exists($validOpts[$optName], $taskOpts)) {
                 throw new Exception("'{$optName}' specified more then once");
             }
             $taskOpts[$validOpts[$optName]] = $optArg;
         }
     } catch (Exception $e) {
         echo self::error("Invalid options: " . $e->getMessage()) . "\n\n";
         self::help($taskName);
         return;
     }
     try {
         call_user_func($taskData['function'], $arguments, $taskOpts);
     } catch (Exception $e) {
         echo self::error("\n  Error executing '{$taskName}':\n\n  {$e->getMessage()}\n") . "\n";
         global $tempDirectory;
         if (!empty($tempDirectory)) {
             G::rm_dir($tempDirectory);
         }
     }
 }
Example #19
0
 public function removeTranslationEnvironment($locale)
 {
     $filePath = $this->envFilePath;
     if (strpos($locale, self::$localeSeparator) !== false) {
         list($LAN_ID, $IC_UID) = explode('-', strtoupper($locale));
     } else {
         $LAN_ID = $locale;
         $IC_UID = '__INTERNATIONAL__';
     }
     if (file_exists($filePath)) {
         $environments = unserialize(file_get_contents($filePath));
         if (!isset($environments[$LAN_ID][$IC_UID])) {
             return null;
         }
         unset($environments[$LAN_ID][$IC_UID]);
         file_put_contents($filePath, serialize($environments));
         if (file_exists(PATH_CORE . "META-INF" . PATH_SEP . "translation." . $locale)) {
             G::rm_dir(PATH_DATA . "META-INF" . PATH_SEP . "translation." . $locale);
         }
         if (file_exists(PATH_CORE . PATH_SEP . 'content' . PATH_SEP . 'translations' . PATH_SEP . 'processmaker' . $locale . '.po')) {
             G::rm_dir(PATH_CORE . PATH_SEP . 'content' . PATH_SEP . 'translations' . PATH_SEP . 'processmaker' . $locale . '.po');
         }
     }
 }
Example #20
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);
}
 /**
  * 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 #22
0
 /**
  *
  * @param string $sProcessUID {@min 32} {@max 32}
  * @param array  $path
  *
  * @access public
  */
 public function deleteFolderProcessFilesManager($sProcessUID, $path)
 {
     try {
         $sDirToDelete = end(explode("/",$path));
         $sPath = str_replace($sDirToDelete,'',$path);
         $sSubDirectory = substr(str_replace($sProcessUID,'',substr($sPath,(strpos($sPath, $sProcessUID)))),0,-1);
         $sMainDirectory = current(explode("/", $path));
         $sSubDirectory = substr(str_replace($sMainDirectory,'',$sSubDirectory),1);
         switch ($sMainDirectory) {
             case 'templates':
                 $sDirectory = PATH_DATA_MAILTEMPLATES . $sProcessUID . PATH_SEP . ($sSubDirectory != '' ? $sSubDirectory . PATH_SEP : '');
                 break;
             case 'public':
                 $sDirectory = PATH_DATA_PUBLIC . $sProcessUID . PATH_SEP . ($sSubDirectory != '' ? $sSubDirectory . PATH_SEP : '');
                 break;
             default:
                 die();
                 break;
         }
         if (file_exists($sDirectory.$sDirToDelete)) {
             \G::rm_dir($sDirectory.$sDirToDelete);
         } else {
             throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_FOR", array('path')));
         }
         $criteria = new \Criteria("workflow");
         $criteria->addSelectColumn(\ProcessFilesPeer::PRF_PATH);
         $criteria->add( \ProcessFilesPeer::PRF_PATH, '%' . $sDirectory.$sDirToDelete. PATH_SEP . '%', \Criteria::LIKE );
         $rs = \ProcessFilesPeer::doDelete($criteria);
         return $sDirectory.$sDirToDelete;
     } catch (Exception $e) {
         throw $e;
     }
 }
Example #23
0
 /**
  * rm_dir
  *
  * @param string $dirName
  *
  * @return void
  */
 public function rm_dir($dirName)
 {
     if (!is_writable($dirName)) {
         return false;
     }
     if (is_dir($dirName)) {
         foreach (glob($dirName . '/{,.}*', GLOB_BRACE) as $file) {
             if ($file == $dirName . '/.' || $file == $dirName . '/..') {
                 continue;
             }
             if (is_dir($file)) {
                 G::rm_dir($file);
                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                     $dirNameWin = str_replace('/', '\\', $dirName);
                     exec('DEL /F /S /Q ' . $dirNameWin . '', $res);
                     exec('RD /S /Q ' . $dirNameWin . '', $res);
                 } else {
                     @rmdir($file);
                 }
             } else {
                 @unlink($file);
             }
         }
     } else {
         @unlink($dirName);
     }
 }
    /**

     * set_partner

     *

     * @return void

     */

    public function setPartner()

    {

        $partnerFlag = (defined('PARTNER_FLAG')) ? PARTNER_FLAG : false;

        if ($partnerFlag) {

            // 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->query_sql_file($value, $this->connection_database);

                }

            }



            // 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);

                    $nameSkinTmp = $dataFile['filename'];

                    G::LoadThirdParty( 'pear/Archive', 'Tar' );

                    $tar = new Archive_Tar( $value );



                    $pathSkinTmp = $pathSkinPartner . 'tmp' . PATH_SEP;

                    G::rm_dir($pathSkinTmp);

                    G::verifyPath($pathSkinTmp, true);

                    chmod( $pathSkinTmp, 0777);

                    $tar->extract($pathSkinTmp);



                    $pathSkinName = $pathSkinTmp . $nameSkinTmp . PATH_SEP;

                    chmod( $pathSkinName, 0777);

                    G::verifyPath(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', true);

                    $skinClassic = PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp' . PATH_SEP;



                    if (is_dir($pathSkinName)) {

                        $this->copyFile($pathSkinName, $skinClassic);

                    }



                    G::rm_dir(PATH_CORE . 'skinEngine' . PATH_SEP . 'base');

                    rename(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', PATH_CORE . 'skinEngine' . PATH_SEP . 'base');

                    G::rm_dir(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp');



                    break;

                }

            }



            //ACTIVE ENTERPRISE



            ini_set('max_execution_time', '0');

            ini_set('memory_limit', '256M');



            $serv = 'http://';

            if (isset($_SERVER['HTTPS']) && trim($_SERVER['HTTPS']) != '') {

                $serv = 'https://';

            }

            $serv .= $_SERVER['SERVER_NAME'];

            if (isset($_SERVER['SERVER_PORT']) && trim($_SERVER['SERVER_PORT']) != '') {

                $serv .= ':' . $_SERVER['SERVER_PORT'];

            }



            // create session

            $cookiefile =  sys_get_temp_dir() . PATH_SEP . 'curl-session';



            $fp = fopen($cookiefile, "w");

            fclose($fp);

            chmod($cookiefile, 0777);



            $user = urlencode($this->options['admin']['username']);

            $pass = urlencode($this->options['admin']['password']);

            $workspace = $this->options['name'];

            $lang = SYS_LANG;

            $skinName = SYS_SKIN;



            $ch = curl_init();



            // set URL and other appropriate options

            curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/login/authentication");

            curl_setopt($ch, CURLOPT_HEADER, 0);

            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

            curl_setopt($ch, CURLOPT_POST, true);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch, CURLOPT_POSTFIELDS, "form[USR_USERNAME]=$user&form[USR_PASSWORD]=$pass&form[USER_LANG]=$lang");

            curl_setopt($ch, CURLOPT_TIMEOUT, 90);



            $output = curl_exec($ch);

            curl_close($ch);



            $ch = curl_init();

            $postData = array();

            // resolv the plugin name

            $plugins = glob(PATH_CORE."plugins/*.tar");

            if (count($plugins) > 0) {

                $pluginName = $plugins[0];



                // File to upload/post

                $postData['form[PLUGIN_FILENAME]'] = "@{$pluginName}";

                curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/pluginsImportFile");

                curl_setopt($ch, CURLOPT_HEADER, 0);

                curl_setopt($ch, CURLOPT_VERBOSE, 0);

                curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

                curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

                curl_setopt($ch, CURLOPT_POST, true);

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

                curl_setopt($ch, CURLOPT_TIMEOUT, 90);



                $output = curl_exec($ch);

                curl_close($ch);

            }

        }

    }
Example #25
0
function deleteSkin()
{
    try {
        if (!isset($_REQUEST['SKIN_FOLDER_ID'])) {
            throw new Exception(G::LoadTranslation('ID_SKIN_FOLDER_REQUIRED'));
        }
        if ($_REQUEST['SKIN_FOLDER_ID'] == "classic") {
            throw new Exception(G::LoadTranslation('ID_SKIN_FOLDER_NOT_DELETEABLE'));
        }
        $folderId = $_REQUEST['SKIN_FOLDER_ID'];
        if (!is_dir(PATH_CUSTOM_SKINS . $folderId)) {
            throw new Exception(G::LoadTranslation('ID_SKIN_NOT_EXISTS'));
        }
        //Delete
        G::rm_dir(PATH_CUSTOM_SKINS . $folderId);
        $response['success'] = true;
        $response['message'] = "{$folderId} deleted";
    } catch (Exception $e) {
        $response['success'] = false;
        $response['error'] = $response['message'] = $e->getMessage();
        print_r(G::json_encode($response));
    }
}
 /**
  * deleteDirectory
  *
  * @param string $sProcessUID
  * @param string $sMainDirectory
  * @param string $sCurrentDirectory
  * @param string $sDirToDelete
  * @return void
  */
 public function deleteDirectory($sProcessUID, $sMainDirectory, $sCurrentDirectory, $sDirToDelete)
 {
     switch ($sMainDirectory) {
         case 'mailTemplates':
             $sDirectory = PATH_DATA_MAILTEMPLATES . $sProcessUID . PATH_SEP . ($sCurrentDirectory != '' ? $sCurrentDirectory . PATH_SEP : '');
             break;
         case 'public':
             $sDirectory = PATH_DATA_PUBLIC . $sProcessUID . PATH_SEP . ($sCurrentDirectory != '' ? $sCurrentDirectory . PATH_SEP : '');
             break;
         default:
             die;
             break;
     }
     if (file_exists($sDirectory . $sDirToDelete)) {
         G::rm_dir($sDirectory . $sDirToDelete);
     }
 }
Example #27
0
function deleteSkin()
{
    G::LoadSystem('inputfilter');
    $filter = new InputFilter();
    try {
        $_REQUEST['SKIN_FOLDER_ID'] = $filter->xssFilterHard($_REQUEST['SKIN_FOLDER_ID']);
        if (!isset($_REQUEST['SKIN_FOLDER_ID'])) {
            throw new Exception(G::LoadTranslation('ID_SKIN_FOLDER_REQUIRED'));
        }
        if ($_REQUEST['SKIN_FOLDER_ID'] == "classic") {
            throw new Exception(G::LoadTranslation('ID_SKIN_FOLDER_NOT_DELETEABLE'));
        }
        $folderId = $_REQUEST['SKIN_FOLDER_ID'];
        if (!is_dir(PATH_CUSTOM_SKINS . $folderId)) {
            throw new Exception(G::LoadTranslation('ID_SKIN_NOT_EXISTS'));
        }
        //Delete
        G::rm_dir(PATH_CUSTOM_SKINS . $folderId);
        $response['success'] = true;
        $response['message'] = "{$folderId} deleted";
        G::auditLog("DeleteSkin", "Skin Name: " . $folderId);
    } catch (Exception $e) {
        $response['success'] = false;
        $response['error'] = $response['message'] = $e->getMessage();
        $response = $filter->xssFilterHard($response);
        print_r(G::json_encode($response));
    }
}
Example #28
0
    public 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);

                }

            }



            // 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);

                    $nameSkinTmp = $dataFile['filename'];

                    G::LoadThirdParty( 'pear/Archive', 'Tar' );

                    $tar = new Archive_Tar( $value );



                    $pathSkinTmp = $pathSkinPartner . 'tmp' . PATH_SEP;

                    G::rm_dir($pathSkinTmp);

                    G::verifyPath($pathSkinTmp, true);

                    chmod( $pathSkinTmp, 0777);

                    $tar->extract($pathSkinTmp);



                    $pathSkinName = $pathSkinTmp . $nameSkinTmp . PATH_SEP;

                    chmod( $pathSkinName, 0777);

                    G::verifyPath(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', true);

                    $skinClassic = PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp' . PATH_SEP;



                    if (is_dir($pathSkinName)) {

                        $this->copyFile($pathSkinName, $skinClassic);

                    }



                    G::rm_dir(PATH_CORE . 'skinEngine' . PATH_SEP . 'base');

                    rename(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', PATH_CORE . 'skinEngine' . PATH_SEP . 'base');

                    G::rm_dir(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp');



                    break;

                }

            }

        }

    }
 function uninstallPlugin($sNamespace)
 {
     $pluginFile = $sNamespace . ".php";
     if (!file_exists(PATH_PLUGINS . $pluginFile)) {
         throw new Exception("File \"{$pluginFile}\" doesn't exist");
     }
     ///////
     require_once PATH_PLUGINS . $pluginFile;
     foreach ($this->_aPluginDetails as $namespace => $detail) {
         if ($namespace == $sNamespace) {
             $this->enablePlugin($detail->sNamespace);
             $this->disablePlugin($detail->sNamespace);
             ///////
             $plugin = new $detail->sClassName($detail->sNamespace, $detail->sFilename);
             $this->_aPlugins[$detail->sNamespace] = $plugin;
             if (method_exists($plugin, "uninstall")) {
                 $plugin->uninstall();
             }
             ///////
             $this->save();
             ///////
             $pluginDir = PATH_PLUGINS . $detail->sPluginFolder;
             if (isset($detail->sFilename) && !empty($detail->sFilename) && file_exists($detail->sFilename)) {
                 unlink($detail->sFilename);
             }
             if (isset($detail->sPluginFolder) && !empty($detail->sPluginFolder) && file_exists($pluginDir)) {
                 G::rm_dir($pluginDir);
             }
             ///////
             $this->uninstallPluginWorkspaces(array($sNamespace));
             ///////
             break;
         }
     }
 }
Example #30
0
 public function generateInfoSupport()
 {
     require_once PATH_CONTROLLERS . "installer.php";
     $params = array();
     $oServerConf =& serverConf::getSingleton();
     $pluginRegistry =& PMPluginRegistry::getSingleton();
     $licenseManager =& pmLicenseManager::getSingleton();
     //License Information:
     $activeLicense = $licenseManager->getActiveLicense();
     $licenseInfo = array();
     $noInclude = array('licensedfeaturesList', 'result', 'serial');
     foreach ($licenseManager as $index => $value) {
         if (!in_array($index, $noInclude)) {
             $licenseInfo[$index] = G::sanitizeInput($value);
         }
     }
     $params['l'] = $licenseInfo;
     //Operative System version (Linux, Windows)
     try {
         $os = '';
         if (file_exists('/etc/redhat-release')) {
             $fnewsize = filesize('/etc/redhat-release');
             $fp = fopen('/etc/redhat-release', 'r');
             $os = trim(fread($fp, $fnewsize));
             fclose($fp);
         }
         $os .= " (" . PHP_OS . ")";
     } catch (Exception $e) {
     }
     $params['s'] = $os;
     //On premise or cloud
     $licInfo = $oServerConf->getProperty('LICENSE_INFO');
     $params['lt'] = isset($licInfo[SYS_SYS]) ? isset($licInfo[SYS_SYS]['TYPE']) ? $licInfo[SYS_SYS]['TYPE'] : '' : '';
     //ProcessMaker Version
     $params['v'] = System::getVersion();
     if (file_exists(PATH_DATA . 'log/upgrades.log')) {
         $params['pmu'] = serialize(file_get_contents(PATH_DATA . 'log/upgrades.log', 'r'));
     } else {
         $params['pmu'] = serialize(G::LoadTranslation('ID_UPGRADE_NEVER_UPGRADE'));
     }
     //Database server Version (MySQL version)
     $installer = new Installer();
     $systemInfo = $installer->getSystemInfo();
     try {
         $params['mysql'] = mysql_get_server_info();
     } catch (Exception $e) {
         $params['mysql'] = '';
     }
     //PHP Version
     $params['php'] = $systemInfo->php->version;
     //Apache - IIS Version
     try {
         $params['apache'] = apache_get_version();
     } catch (Exception $e) {
         $params['apache'] = '';
     }
     //Installed Plugins (license info?)
     $arrayAddon = array();
     if (file_exists(PATH_DATA_SITE . "ee")) {
         $arrayAddon = unserialize(trim(file_get_contents(PATH_DATA_SITE . "ee")));
     }
     $plugins = array();
     foreach ($arrayAddon as $addon) {
         $sFileName = substr($addon["sFilename"], 0, strpos($addon["sFilename"], "-"));
         if (file_exists(PATH_PLUGINS . $sFileName . ".php")) {
             $plugin = array();
             $addonDetails = $pluginRegistry->getPluginDetails($sFileName . ".php");
             $plugin['name'] = $addonDetails->sNamespace;
             $plugin['description'] = $addonDetails->sDescription;
             $plugin['version'] = $addonDetails->iVersion;
             $plugin['enable'] = $addonDetails->enabled;
             $plugins[] = $plugin;
         }
     }
     $params['pl'] = $plugins;
     //Number of Users registered in PM. Including LDAP users and PM users.
     require_once "classes/model/RbacUsers.php";
     $criteria = new Criteria("rbac");
     $criteria->addSelectColumn(RbacUsersPeer::USR_AUTH_TYPE);
     $criteria->addSelectColumn("COUNT(" . RbacUsersPeer::USR_UID . ") AS USERS_NUMBER");
     $criteria->add(RbacUsersPeer::USR_UID, null, Criteria::ISNOTNULL);
     $criteria->addGroupByColumn(RbacUsersPeer::USR_AUTH_TYPE);
     $rs = RbacUsersPeer::doSelectRS($criteria);
     $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
     $users = array('local' => 0);
     while ($rs->next()) {
         $row = $rs->getRow();
         if ($row['USR_AUTH_TYPE'] == '' || $row['USR_AUTH_TYPE'] == 'MYSQL') {
             $users['local'] = (int) $users['local'] + (int) $row['USERS_NUMBER'];
         } else {
             $users['USR_AUTH_TYPE'] = $row['USERS_NUMBER'];
         }
     }
     $params['u'] = $users;
     //Number of cases.
     $oSequences = new Sequences();
     $maxNumber = $oSequences->getSequeceNumber("APP_NUMBER");
     $params['c'] = $maxNumber - 1;
     //Number of active processes.
     $criteria = new Criteria("workflow");
     $criteria->addSelectColumn(ProcessPeer::PRO_STATUS);
     $criteria->addSelectColumn("COUNT(PROCESS.PRO_UID) AS NUMBER_PROCESS");
     $criteria->addGroupByColumn(ProcessPeer::PRO_STATUS);
     $rs = UsersPeer::doSelectRS($criteria);
     $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
     $process = array();
     while ($rs->next()) {
         $row = $rs->getRow();
         $process[$row['PRO_STATUS']] = $row['NUMBER_PROCESS'];
     }
     $params['p'] = $process;
     //Country/city (Timezone)
     $params['t'] = defined('TIME_ZONE') && TIME_ZONE != "Unknown" ? TIME_ZONE : date_default_timezone_get();
     $params['w'] = count(System::listWorkspaces());
     $support = PATH_DATA_SITE . G::sanitizeString($licenseManager->info['FIRST_NAME'] . '-' . $licenseManager->info['LAST_NAME'] . '-' . SYS_SYS . '-' . date('YmdHis'), false, false) . '.spm';
     file_put_contents($support, serialize($params));
     G::streamFile($support, true);
     G::rm_dir($support);
 }