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

}
 public function __construct()
 {
     parent::__construct();
     // Load argc and argv
     $argc = Arr::get($_SERVER, 'argc') - 3;
     $argv = array_slice(Arr::get($_SERVER, 'argv'), 3);
     if ($argc > 0) {
         $extends = CLI::options('i');
         $extends = Arr::get($extends, 'i');
         $generate_all = CLI::options('i');
         for ($i = 0; $i < $argc; $i++) {
             if (strpos($argv[$i], '--') !== FALSE) {
                 unset($argv[$i]);
             }
         }
         $filename = Arr::get($argv, 0);
         $methods = array_slice($argv, 1);
         $this->generate($filename, $methods, $extends);
         if ($generate_all) {
             new Terminal_Model();
             new Terminal_View();
         }
     } else {
         $str = 'Missing controller name.';
         echo Terminal::color($str, 'red') . PHP_EOL;
     }
 }
Example #4
0
 public function execute($parameters, $db)
 {
     var_dump($db);
     $commands = array();
     $dir = __DIR__;
     if ($handle = opendir($dir)) {
         while (false !== ($entry = readdir($handle))) {
             if ($entry != "." && $entry != ".." && $entry != "base.php" && $entry != "cli_methods.php") {
                 $s1 = explode("cli_", $entry);
                 $s2 = explode(".php", $s1[1]);
                 if (sizeof($s2) == 2) {
                     require_once "{$dir}/{$entry}";
                     $command = $s2[0];
                     $className = "cli_{$command}";
                     $class = new $className();
                     if (is_a($class, "cliCommand")) {
                         $commands[] = $command;
                     }
                 }
             }
         }
         closedir($handle);
     }
     sort($commands);
     CLI::out("|g|Commands available: |n|" . implode(", ", $commands));
 }
Example #5
0
function run_update($command, $args)
{
    CLI::logging("Updating...\n");
    $language = new Language();
    $language->updateLanguagePlugin($command[0], $command[1]);
    CLI::logging("Update successful\n");
}
Example #6
0
 public static function warning($text)
 {
     $return = "\n";
     $return .= CLI::color($text, 'white', 'yellow') . "\n";
     $return .= "\n";
     return $return;
 }
Example #7
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;
    }
}
 public function execute($parameters, $db)
 {
     global $base;
     chdir($base);
     if (sizeof($parameters) == 0 || $parameters[0] == "") {
         CLI::out("Usage: |g|help <command>|n| To see a list of commands, use: |g|list", true);
     }
     $command = $parameters[0];
     switch ($command) {
         case "all":
             // Cleanup old sessions
             $db->execute("delete from zz_users_sessions where validTill < now()");
             $killsLastHour = $db->queryField("select count(*) count from zz_killmails where insertTime > date_sub(now(), interval 1 hour)", "count");
             Storage::store("KillsLastHour", $killsLastHour);
             $db->execute("delete from zz_analytics where dttm < date_sub(now(), interval 24 hour)");
             $fc = new FileCache("{$base}/cache/queryCache/");
             $fc->cleanUp();
             break;
         case "killsLastHour":
             $killsLastHour = $db->queryField("select count(*) count from zz_killmails where insertTime > date_sub(now(), interval 1 hour)", "count");
             Storage::store("KillsLastHour", $killsLastHour);
             break;
         case "fileCacheClean":
             $fc = new FileCache();
             $fc->cleanUp();
             break;
     }
 }
Example #9
0
 /**
  * Automatically executed after the task action.
  *
  * @return void
  */
 protected function after()
 {
     if ($this->auto_render === TRUE and $this->template instanceof View) {
         // Render and display template
         CLI::write($this->template->render());
     }
     parent::after();
 }
 function __construct($options = false, $handleUnknown = false)
 {
     global $argc, $argv;
     if ($options !== false) {
         self::$ACCEPTED = $options;
     }
     // Parse params
     if ($argc > 1) {
         $paramSwitch = false;
         for ($i = 1; $i < $argc; $i++) {
             $arg = $argv[$i];
             $isSwitch = preg_match('/^-+/', $arg);
             if ($isSwitch) {
                 $arg = preg_replace('/^-+/', '', $arg);
             }
             if ($paramSwitch and $isSwitch) {
                 $this->error("[param] expected after '{$paramSwitch}' switch (" . self::$ACCEPTED[1][$paramSwitch] . ')');
             } else {
                 if (!$paramSwitch and !$isSwitch) {
                     if ($handleUnknown) {
                         $this->params['unknown'][] = $arg;
                     } else {
                         $this->error("'{$arg}' is an invalid option, use --help to display valid switches.");
                     }
                 } else {
                     if (!$paramSwitch and $isSwitch) {
                         if (isset($this->params[$arg])) {
                             $this->error("'{$arg}' switch can't occur more than once");
                         }
                         $this->params[$arg] = true;
                         if (isset(self::$ACCEPTED[1][$arg])) {
                             $paramSwitch = $arg;
                         } else {
                             if (!isset(self::$ACCEPTED[0][$arg])) {
                                 $this->error("there's no '{$arg}' switch, use --help to display all switches.");
                             }
                         }
                     } else {
                         if ($paramSwitch and !$isSwitch) {
                             $this->params[$paramSwitch] = $arg;
                             $paramSwitch = false;
                         }
                     }
                 }
             }
         }
     }
     // Final check
     foreach ($this->params as $k => $v) {
         if (isset(self::$ACCEPTED[1][$k]) and $v === true) {
             $this->error("[param] expected after '{$k}' switch (" . self::$ACCEPTED[1][$k] . ')');
         }
     }
 }
Example #11
0
 public function before()
 {
     if (!Kohana::$is_cli) {
         Request::instance()->redirect('/');
         exit;
     }
     $auth = CLI::options('username', 'password');
     $user = ORM::factory('user');
     $status = $user->login($auth);
     if (!$status) {
         echo "You did not authenticate.\n";
         exit;
     }
 }
Example #12
0
 /**
  * Prevent Minion from being run over http
  */
 public function before()
 {
     if (!Kohana::$is_cli) {
         throw new Kohana_Exception("Minion can only be ran from the cli");
     }
     $this->_task = $this->request->param('task');
     $options = CLI::options('help', 'task');
     if (array_key_exists('help', $options)) {
         $this->request->action('help');
     }
     if (!empty($options['task'])) {
         $this->_task = $options['task'];
     }
     return parent::before();
 }
 public function execute($parameters, $db)
 {
     // Fix unknown group ID's
     $result = $db->query("select distinct killID from zz_participants where groupID != vGroupID and isVictim = 1 limit 1", array(), 0);
     foreach ($result as $row) {
         $killID = $row["killID"];
         $shipTypeID = $db->queryField("select shipTypeID from zz_participants where killID = {$killID} and isVictim = 1", "shipTypeID");
         if ($shipTypeID == 0) {
             continue;
         }
         $groupID = Info::getGroupID($shipTypeID);
         echo "Updating {$killID} to {$groupID}\n";
         $db->execute("update zz_participants set vGroupID = {$groupID} where killID = {$killID}");
     }
     CLI::out(sizeof($result) . " done!", true);
 }
Example #14
0
function minify_javascript($command, $args)
{
    CLI::logging("BUILD-JS\n");
    //disabling the rakefile version, until we have updated the dev environment
    //CLI::logging("Checking if rake is installed...\n");
    //$rakeFile = PROCESSMAKER_PATH . "workflow/engine/bin/tasks/Rakefile";
    //system('rake -f ' . $rakeFile);
    require_once PATH_THIRDPARTY . 'jsmin/jsmin.php';
    $libraries = json_decode(file_get_contents(PATH_HOME . 'engine/bin/tasks/libraries.json'));
    //print_r($libraries);
    foreach ($libraries as $k => $library) {
        $build = $library->build;
        if ($build) {
            $bufferMini = "";
            $sum1 = 0;
            $sum2 = 0;
            $libName = $library->name;
            $files = $library->libraries;
            $js_path = $library->build_js_to;
            printf("Processing %s library:\n", $libName);
            foreach ($files as $file) {
                printf("    %-20s ", $file->name);
                $fileNameMini = PATH_TRUNK . $file->mini;
                if ($file->minify) {
                    $minify = JSMin::minify(file_get_contents($fileNameMini));
                } else {
                    $minify = file_get_contents($fileNameMini);
                }
                $bufferMini .= $minify;
                $size1 = filesize($fileNameMini);
                $size2 = strlen($minify);
                $sum1 += $size1;
                $sum2 += $size2;
                printf("%7d -> %7d %5.2f%%\n", $size1, $size2, 100 - $size2 / $size1 * 100);
            }
            if (substr($library->build_js_to, -1) != '/') {
                $library->build_js_to .= '/';
            }
            $outputMiniFile = PATH_TRUNK . $library->build_js_to . $libName . ".js";
            file_put_contents($outputMiniFile, $bufferMini);
            printf("    -------------------- -------    ------- ------\n");
            printf("    %-20s %7d -> %7d %6.2f%%\n", $libName . '.js', $sum1, $sum2, 100 - $sum2 / $sum1 * 100);
            print "    {$outputMiniFile}\n";
        }
    }
    CLI::logging("BUILD-JS DONE\n");
}
Example #15
0
 public function __construct()
 {
     parent::__construct();
     // Load argc and argv
     $argc = Arr::get($_SERVER, 'argc') - 3;
     $argv = array_slice(Arr::get($_SERVER, 'argv'), 3);
     if ($argc > 0) {
         // Get model file
         $filename = Arr::get($argv, 0);
         // Get model extends
         $extends = CLI::options('e');
         $extends = Arr::get($extends, 'e');
         $this->generate($filename, $extends);
     } else {
         $str = 'Missing model name.';
         echo Terminal::color($str, 'red') . PHP_EOL;
     }
 }
Example #16
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);
     }
 }
 public function execute($parameters, $db)
 {
     if (sizeof($parameters) == 0 || $parameters[0] == "") {
         CLI::out("Usage: |g|recentStatsAndRanks <type>|n| To see a list of commands, use: |g|methods calculateAllTimeStatsAndRanks", true);
     }
     $command = $parameters[0];
     switch ($command) {
         case "all":
             self::stats($db);
             self::ranks($db);
             break;
         case "ranks":
             self::ranks($db);
             break;
         case "stats":
             self::stats($db);
             break;
     }
 }
Example #18
0
 public function execute($parameters, $db)
 {
     if (sizeof($parameters) == 0 || $parameters[0] == "") {
         CLI::out("Usage: |g|help <command>|n| To see a list of commands, use: |g|list", true);
     }
     $command = $parameters[0];
     $base = __DIR__;
     $fileName = "{$base}/cli_{$command}.php";
     if (!file_exists($fileName)) {
         CLI::out("|r|Error running {$command}|n|. Please use list to show all commands, or help <command> to see information on how to use the command", true);
     }
     require_once $fileName;
     $className = "cli_{$command}";
     $class = new $className();
     if (!is_a($class, "cliCommand")) {
         CLI::out("|r| Module {$command} does not implement interface cliCommand", true);
     }
     $descr = $class->getDescription();
     CLI::out("|g|{$command}:|n| {$descr}");
 }
Example #19
0
 public function testAppRoute()
 {
     CLI::bash(['php brood app:module test_module']);
     $has_file = file_exists($file = config()->path->app . 'TestModule/Routes.php');
     $this->assertTrue($has_file, 'check if [' . $file . '] were generated');
     $has_file = file_exists($file = config()->path->app . 'TestModule/Routes/RouteGroup.php');
     $this->assertTrue($has_file, 'check if [' . $file . '] were generated');
     $file_contents = file_get_contents($file);
     $this->assertContains('namespace App\\TestModule\\Routes;', $file_contents);
     $this->assertContains('use Phalcon\\Mvc\\Router\\Group as BaseRouteGroup;', $file_contents);
     $this->assertContains('class RouteGroup extends BaseRouteGroup', $file_contents);
     $has_file = file_exists($file = config()->path->app . 'TestModule/Providers/RouterServiceProvider.php');
     $this->assertTrue($has_file, 'check if [' . $file . '] were generated');
     $file_contents = file_get_contents($file);
     $this->assertContains('namespace App\\TestModule\\Providers;', $file_contents);
     $this->assertContains('use Phalcon\\Di\\FactoryDefault;', $file_contents);
     $this->assertContains('use Clarity\\Providers\\ServiceProvider;', $file_contents);
     $this->assertContains('use Clarity\\Contracts\\Providers\\ModuleInterface;', $file_contents);
     $this->assertContains('class RouterServiceProvider extends ServiceProvider implements ModuleInterface', $file_contents);
     $this->assertContains('public function module(FactoryDefault $di)', $file_contents);
     $this->assertContains('->setDefaultNamespace(\'App\\TestModule\\Controllers\');', $file_contents);
     $this->assertContains('public function afterModuleRun()', $file_contents);
     $this->assertContains('require_once realpath(__DIR__.\'/../\').\'/Routes.php\';', $file_contents);
     CLI::bash(['php brood app:route test test_module']);
     $has_file = file_exists($file = config()->path->app . 'TestModule/Routes/TestRoutes.php');
     $this->assertTrue($has_file, 'check if [' . $file . '] were generated');
     $file_contents = file_get_contents($file);
     $this->assertContains('namespace App\\TestModule\\Routes;', $file_contents);
     $this->assertContains('class TestRoutes extends RouteGroup', $file_contents);
     CLI::bash(['php brood app:controller test test_module']);
     $has_file = file_exists($file = config()->path->app . 'TestModule/Controllers/TestController.php');
     $this->assertTrue($has_file, 'check if [' . $file . '] were generated');
     $file_contents = file_get_contents($file);
     $this->assertContains('namespace App\\TestModule\\Controllers;', $file_contents);
     $this->assertContains('class TestController extends Controller', $file_contents);
 }
Example #20
0
      {$create}
    ');
  }

  public static function validate(\$data){
    return Check::valid([
      {$valids}
    ], \$data);
  }

}
EOC;
                $models[$table] = $model;
            }
            $force = CLI::input('force', false);
            foreach ($models as $table => $model) {
                $file = dirname(__DIR__) . "/models/{$model->name}.php";
                if (!$force && file_exists($file)) {
                    CLI::writeln("<red>Already founded a model named <b>{$model->name}</b>, skipping...</red>");
                } else {
                    CLI::writeln("<green>Compiling</green> model : <b>{$model->name}</b>");
                    file_put_contents($file, $model->code);
                }
            }
            break;
        default:
            echo "Model utilities.", PHP_EOL;
            echo "- Available actions: generate --force", PHP_EOL;
            break;
    }
});
Example #21
0
    /**

     * Migrate all cases to New list

     *

     * return all LIST TABLES with data

     */

    public function migrateList ($workSpace)

    {

        if ($this->listFirstExecution('check')) {

            return 1;

        }

        $this->initPropel(true);

        $appCache = new AppCacheView();

        $users    = new Users();

        G::LoadClass("case");

        $case = new Cases();



        //Select data CANCELLED

        $canCriteria = $appCache->getSelAllColumns();

        $canCriteria->add(AppCacheViewPeer::APP_STATUS, "CANCELLED", CRITERIA::EQUAL);

        $canCriteria->add(AppCacheViewPeer::DEL_LAST_INDEX, "1", CRITERIA::EQUAL);

        $rsCriteria = AppCacheViewPeer::doSelectRS($canCriteria);

        $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        //Insert data LIST_CANCELED

        while ($rsCriteria->next()) {

              $row = $rsCriteria->getRow();

              $listCanceled = new ListCanceled();

              $listCanceled->remove($row["APP_UID"]);

              $listCanceled->setDeleted(false);

              $listCanceled->create($row);

        }

        CLI::logging("> Completed table LIST_CANCELED\n");



        //Select data COMPLETED

        $comCriteria = $appCache->getSelAllColumns();

        $comCriteria->add(AppCacheViewPeer::APP_STATUS, "COMPLETED", CRITERIA::EQUAL);

        $comCriteria->add(AppCacheViewPeer::DEL_LAST_INDEX, "1", CRITERIA::EQUAL);

        $rsCriteria = AppCacheViewPeer::doSelectRS($comCriteria);

        $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        //Insert new data LIST_COMPLETED

        while ($rsCriteria->next()) {

              $row = $rsCriteria->getRow();

              $listCompleted = new ListCompleted();

              $listCompleted->remove($row["APP_UID"]);

              $listCompleted->setDeleted(false);

              $listCompleted->create($row);

        }

        CLI::logging("> Completed table LIST_COMPLETED\n");



        //Select data TO_DO OR DRAFT

        $inbCriteria = $appCache->getSelAllColumns();

        $rsCriteria = AppCacheViewPeer::doSelectRS($inbCriteria);

        $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);



        $criteriaUser = new Criteria();

        $criteriaUser->addSelectColumn( UsersPeer::USR_UID );

        $criteriaUser->addSelectColumn( UsersPeer::USR_FIRSTNAME );

        $criteriaUser->addSelectColumn( UsersPeer::USR_LASTNAME );

        $criteriaUser->addSelectColumn( UsersPeer::USR_USERNAME );

        //Insert new data LIST_INBOX

        while ($rsCriteria->next()) {

            $row = $rsCriteria->getRow();

            $isSelfService = ($row['USR_UID'] == '') ? true : false;

            if($row["DEL_THREAD_STATUS"] == 'OPEN'){

                //Update information about the previous_user

                $row["DEL_PREVIOUS_USR_UID"] = $row["PREVIOUS_USR_UID"];

                $criteriaUser->add( UsersPeer::USR_UID, $row["PREVIOUS_USR_UID"] );

                $datasetU = UsersPeer::doSelectRS($criteriaUser);

                $datasetU->setFetchmode(ResultSet::FETCHMODE_ASSOC);

                $datasetU->next();

                $arrayUsers = $datasetU->getRow();

                $row["DEL_PREVIOUS_USR_USERNAME"] = $arrayUsers["USR_USERNAME"];

                $row["DEL_PREVIOUS_USR_FIRSTNAME"]= $arrayUsers["USR_FIRSTNAME"];

                $row["DEL_PREVIOUS_USR_LASTNAME"] = $arrayUsers["USR_LASTNAME"];

                //Update the due date

                $row["DEL_DUE_DATE"]         = $row["DEL_TASK_DUE_DATE"];

                $listInbox = new ListInbox();

                $listInbox->remove($row["APP_UID"],$row["DEL_INDEX"]);

                $listInbox->setDeleted(false);

                $listInbox->create($row, $isSelfService);

            } else {

                // create participated List when the thread is CLOSED

                $listParticipatedHistory = new ListParticipatedHistory();

                $listParticipatedHistory->remove($row['APP_UID'], $row['DEL_INDEX']);

                $listParticipatedHistory = new ListParticipatedHistory();

                $listParticipatedHistory->create($row);



                $oCriteria = new Criteria('workflow');

                $oCriteria->add(ListParticipatedLastPeer::APP_UID, $row['APP_UID']);

                $oCriteria->add(ListParticipatedLastPeer::USR_UID, $row['USR_UID']);

                ListParticipatedLastPeer::doDelete($oCriteria);



                $listParticipatedLast = new ListParticipatedLast();

                $listParticipatedLast->create($row);

                $listParticipatedLast = new ListParticipatedLast();

                $listParticipatedLast->refresh($row);

            }



        }



        CLI::logging("> Completed table LIST_INBOX\n");

        //With this List is populated the LIST_PARTICIPATED_HISTORY and LIST_PARTICIPATED_LAST

        CLI::logging("> Completed table LIST_PARTICIPATED_HISTORY\n");

        CLI::logging("> Completed table LIST_PARTICIPATED_LAST\n");



        //Select data TO_DO OR DRAFT CASES CREATED BY AN USER

        $myiCriteria = $appCache->getSelAllColumns();

        $myiCriteria->add(AppCacheViewPeer::DEL_INDEX, "1", CRITERIA::EQUAL);

        $rsCriteria = AppCacheViewPeer::doSelectRS($myiCriteria);

        $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        //Insert new data LIST_MY_INBOX

        while ($rsCriteria->next()) {

              $row = $rsCriteria->getRow();

              $listMyInbox = new ListMyInbox();

              $listMyInbox ->remove($row["APP_UID"],$row["USR_UID"]);

              $listMyInbox->setDeleted(false);

              $listMyInbox->create($row);

        }

        CLI::logging("> Completed table LIST_MY_INBOX\n");



        //Select data PAUSED

        $delaycriteria = new Criteria("workflow");

        $delaycriteria->addSelectColumn(AppDelayPeer::APP_UID);

        $delaycriteria->addSelectColumn(AppDelayPeer::PRO_UID);

        $delaycriteria->addSelectColumn(AppDelayPeer::APP_DEL_INDEX);

        $delaycriteria->addSelectColumn(AppCacheViewPeer::APP_NUMBER);

        $delaycriteria->addSelectColumn(AppCacheViewPeer::USR_UID);

        $delaycriteria->addSelectColumn(AppCacheViewPeer::APP_STATUS);

        $delaycriteria->addSelectColumn(AppCacheViewPeer::TAS_UID);



        $delaycriteria->addJoin( AppCacheViewPeer::APP_UID, AppDelayPeer::APP_UID . ' AND ' . AppCacheViewPeer::DEL_INDEX . ' = ' . AppDelayPeer::APP_DEL_INDEX, Criteria::INNER_JOIN );

        $delaycriteria->add(AppDelayPeer::APP_DISABLE_ACTION_USER, "0", CRITERIA::EQUAL);

        $delaycriteria->add(AppDelayPeer::APP_TYPE, "PAUSE", CRITERIA::EQUAL);

        $rsCriteria = AppDelayPeer::doSelectRS($delaycriteria);

        $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        //Insert new data LIST_PAUSED

        while ($rsCriteria->next()) {

              $row = $rsCriteria->getRow();

              $data = $row;

              $data["DEL_INDEX"] = $row["APP_DEL_INDEX"];

              $listPaused = new ListPaused();

              $listPaused ->remove($row["APP_UID"],$row["APP_DEL_INDEX"],$data);

              $listPaused->setDeleted(false);

              $listPaused->create($data);

        }

        CLI::logging("> Completed table LIST_PAUSED\n");



        //Select and Insert LIST_UNASSIGNED

        $unaCriteria = $appCache->getSelAllColumns();

        $unaCriteria->add(AppCacheViewPeer::USR_UID, "", CRITERIA::EQUAL);

        $rsCriteria = AppCacheViewPeer::doSelectRS($unaCriteria);

        $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        $del = new ListUnassignedPeer();

        $del->doDeleteAll();

        $del = new ListUnassignedGroupPeer();

        $del->doDeleteAll();

        while ($rsCriteria->next()) {

            $row = $rsCriteria->getRow();

            $listUnassigned = new ListUnassigned();

            $unaUid = $listUnassigned->generateData($row["APP_UID"],$row["PREVIOUS_USR_UID"]);

        }

        CLI::logging("> Completed table LIST_UNASSIGNED\n");

        CLI::logging("> Completed table LIST_UNASSIGNED_GROUP\n");



        // ADD LISTS COUNTS

        $aTypes = array(

            'to_do',

            'draft',

            'cancelled',

            'sent',

            'paused',

            'completed',

            'selfservice'

        );



        $users = new Users();

        $criteria = new Criteria();

        $criteria->addSelectColumn(UsersPeer::USR_UID);

        $dataset = UsersPeer::doSelectRS($criteria);

        $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC);

        while($dataset->next()) {

            $aRow = $dataset->getRow();

            $oAppCache = new AppCacheView();

            $aCount = $oAppCache->getAllCounters( $aTypes, $aRow['USR_UID'] );

            $newData = array(

                'USR_UID'                   => $aRow['USR_UID'],

                'USR_TOTAL_INBOX'           => $aCount['to_do'],

                'USR_TOTAL_DRAFT'           => $aCount['draft'],

                'USR_TOTAL_CANCELLED'       => $aCount['cancelled'],

                'USR_TOTAL_PARTICIPATED'    => $aCount['sent'],

                'USR_TOTAL_PAUSED'          => $aCount['paused'],

                'USR_TOTAL_COMPLETED'       => $aCount['completed'],

                'USR_TOTAL_UNASSIGNED'      => $aCount['selfservice']

            );

            $users->update($newData);

        }

        $this->listFirstExecution('insert');

        return true;

    }
Example #22
0
 /**
  * Runs the application by retrieving and calling the method for the current action.
  *
  * @author Yorick Peterse
  * @return void
  */
 public function run()
 {
     if (empty($this->mappings)) {
         throw new Exception\MappingException("No methods have been mapped to any URL");
     }
     // Set the PATH_INFO based on the CLI arguments.
     if (defined('KOI_DEBUG') != TRUE and PHP_SAPI === 'cli') {
         $_SERVER['PATH_INFO'] = CLI::uri();
     }
     // Route the call
     $result = Router::route($this->mappings);
     if ($result === FALSE) {
         throw new Exception\MappingException("No methods have been bound to {$_SERVER['PATH_INFO']}");
     }
     $this->render($result['body'], $result['status'], $result['content_type']);
 }
Example #23
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 #25
0
define('DEBUG_SQL_LOG', $config['debug_sql']);
define('DEBUG_TIME_LOG', $config['debug_time']);
define('DEBUG_CALENDAR_LOG', $config['debug_calendar']);
define('MEMCACHED_ENABLED', $config['memcached']);
define('MEMCACHED_SERVER', $config['memcached_server']);
define('TIME_ZONE', $config['time_zone']);
G::LoadClass("cli");
// trap -V before pake
if (in_array('-v', $argv) || in_array('-V', $argv) || in_array('--version', $argv)) {
    printf("ProcessMaker version %s\n", pakeColor::colorize(trim(file_get_contents(PATH_GULLIVER . 'VERSION')), 'INFO'));
    exit(0);
}
// register tasks
//TODO: include plugins
$directories = array(PATH_HOME . 'engine/bin/tasks');
$pluginsDirectories = glob(PATH_PLUGINS . "*");
foreach ($pluginsDirectories as $dir) {
    if (!is_dir($dir)) {
        continue;
    }
    if (is_dir("{$dir}/bin/tasks")) {
        $directories[] = "{$dir}/bin/tasks";
    }
}
foreach ($directories as $dir) {
    foreach (glob("{$dir}/*.php") as $filename) {
        include_once $filename;
    }
}
CLI::run();
exit(0);
Example #26
0
$fragNum = 0;
$logfile = STDERR;
$manifest = "";
$outDir = "";
$outFile = "";
$play = false;
$quiet = false;
$referrer = "";
$rename = false;
$showHeader = true;
$start = 0;
$update = false;
// Set large enough memory limit
ini_set("memory_limit", "512M");
// Check if STDOUT is available
$cli = new CLI();
if ($cli->getParam('play')) {
    $play = true;
    $quiet = true;
    $showHeader = false;
}
if ($cli->getParam('help')) {
    $cli->displayHelp();
    exit(0);
}
// Check for required extensions
$extensions = array("bcmath", "curl", "SimpleXML");
foreach ($extensions as $extension) {
    if (!extension_loaded($extension)) {
        LogError("You don't have '{$extension}' extension installed. please install it before continuing.");
    }
    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 #28
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";

    }

}
 /**
  * Creates a json file of ships to be used on the star map page
  * @return [type] [description]
  */
 public function generateShipDataFile($db)
 {
     CLI::out('|g|Loading ships|n|');
     //get a list of all the published ships
     $ships_results = $db->query('SELECT ccp_invTypes.typeID, typeName, groupName, COALESCE(valueInt, valueFloat) AS metaLevel FROM ccp_invTypes INNER JOIN ccp_invGroups ON ccp_invGroups.groupID = ccp_invTypes.groupID INNER JOIN ccp_dgmTypeAttributes ON ccp_dgmTypeAttributes.typeID = ccp_invTypes.typeID AND ccp_dgmTypeAttributes.attributeID = 633 WHERE (categoryID IN (6, 23, 40) AND ccp_invTypes.published = 1 AND ccp_invGroups.published = 1 OR ccp_invTypes.groupID = 29)');
     $ships = array();
     foreach ($ships_results as $ship) {
         $ships[$ship['typeID']] = array('name' => $ship['typeName'], 'group' => strtolower(str_replace(' ', '-', $ship['groupName'])), 'meta' => $this->meta_names[$ship['metaLevel']]);
     }
     //create the new file asset
     $this->writeStaticData('starmap-ships', $ships);
 }
Example #30
0
 /**
  * Creates a new request object for the given URI. New requests should be
  * created using the [Request::instance] or [Request::factory] methods.
  *
  *     $request = Request::factory($uri);
  *
  * If $cache parameter is set, the response for the request will attempt to
  * be retrieved from the cache.
  *
  * @param   string  $uri URI of the request
  * @param   Cache   $cache
  * @param   array   $injected_routes an array of routes to use, for testing
  * @return  void
  * @throws  Request_Exception
  * @uses    Route::all
  * @uses    Route::matches
  */
 public static function factory($uri = TRUE, HTTP_Cache $cache = NULL, $injected_routes = array())
 {
     // If this is the initial request
     if (!Request::$initial) {
         if (Kohana::$is_cli) {
             // Default protocol for command line is cli://
             $protocol = 'cli';
             // Get the command line options
             $options = CLI::options('uri', 'method', 'get', 'post', 'referrer');
             if (isset($options['uri'])) {
                 // Use the specified URI
                 $uri = $options['uri'];
             } elseif ($uri === TRUE) {
                 $uri = '';
             }
             if (isset($options['method'])) {
                 // Use the specified method
                 $method = strtoupper($options['method']);
             } else {
                 // Default to GET requests
                 $method = HTTP_Request::GET;
             }
             if (isset($options['get'])) {
                 // Overload the global GET data
                 parse_str($options['get'], $_GET);
             }
             if (isset($options['post'])) {
                 // Overload the global POST data
                 parse_str($options['post'], $_POST);
             }
             if (isset($options['referrer'])) {
                 $referrer = $options['referrer'];
             }
         } else {
             if (isset($_SERVER['SERVER_PROTOCOL'])) {
                 $protocol = $_SERVER['SERVER_PROTOCOL'];
             } else {
                 $protocol = HTTP::$protocol;
             }
             if (isset($_SERVER['REQUEST_METHOD'])) {
                 // Use the server request method
                 $method = $_SERVER['REQUEST_METHOD'];
             } else {
                 // Default to GET requests
                 $method = HTTP_Request::GET;
             }
             if (!empty($_SERVER['HTTPS']) and filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) {
                 // This request is secure
                 $secure = TRUE;
             }
             if (isset($_SERVER['HTTP_REFERER'])) {
                 // There is a referrer for this request
                 $referrer = $_SERVER['HTTP_REFERER'];
             }
             if (isset($_SERVER['HTTP_USER_AGENT'])) {
                 // Browser type
                 Request::$user_agent = $_SERVER['HTTP_USER_AGENT'];
             }
             if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
                 // Typically used to denote AJAX requests
                 $requested_with = $_SERVER['HTTP_X_REQUESTED_WITH'];
             }
             if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) {
                 // Use the forwarded IP address, typically set when the
                 // client is using a proxy server.
                 // Format: "X-Forwarded-For: client1, proxy1, proxy2"
                 $client_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                 Request::$client_ip = array_shift($client_ips);
                 unset($client_ips);
             } elseif (isset($_SERVER['HTTP_CLIENT_IP']) and isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'], Request::$trusted_proxies)) {
                 // Use the forwarded IP address, typically set when the
                 // client is using a proxy server.
                 $client_ips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
                 Request::$client_ip = array_shift($client_ips);
                 unset($client_ips);
             } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                 // The remote IP address
                 Request::$client_ip = $_SERVER['REMOTE_ADDR'];
             }
             if ($method !== HTTP_Request::GET) {
                 // Ensure the raw body is saved for future use
                 $body = file_get_contents('php://input');
             }
             if ($uri === TRUE) {
                 // Attempt to guess the proper URI
                 $uri = Request::detect_uri();
             }
         }
         // Create the instance singleton
         Request::$initial = $request = new Request($uri, $cache);
         // Store global GET and POST data in the initial request only
         $request->protocol($protocol)->query($_GET)->post($_POST);
         if (isset($secure)) {
             // Set the request security
             $request->secure($secure);
         }
         if (isset($method)) {
             // Set the request method
             $request->method($method);
         }
         if (isset($referrer)) {
             // Set the referrer
             $request->referrer($referrer);
         }
         if (isset($requested_with)) {
             // Apply the requested with variable
             $request->requested_with($requested_with);
         }
         if (isset($body)) {
             // Set the request body (probably a PUT type)
             $request->body($body);
         }
     } else {
         $request = new Request($uri, $cache, $injected_routes);
     }
     return $request;
 }