Example #1
0
 /**
  *
  */
 public function postPaste()
 {
     $postData = $this->app->request->post("paste");
     $timeout = $this->app->request->post("timeout");
     if (isset($_SESSION["characterName"])) {
         $user = $this->app->Users->getUserByName($_SESSION["characterName"]);
         $userID = $user["id"];
         $hash = md5(time() . $_SESSION["characterName"] . $_SESSION["characterID"]);
         $this->app->paste->createPaste($hash, $userID, $postData, $timeout);
         $this->app->redirect("/paste/{$hash}/");
     } else {
         render("/paste/paste.twig", array("error" => "Error, you need to be logged in to post data"));
     }
 }
Example #2
0
 /**
  * Tries to autologin the person
  */
 public function tryAutologin()
 {
     $cookieName = $this->config->getConfig("name", "cookies");
     $cookieData = $this->app->getEncryptedCookie($cookieName, false);
     if (!empty($cookieData) && !isset($_SESSION["loggedIn"])) {
         $userData = $this->getUserDataByLoginHash($cookieData);
         if ($userData) {
             $_SESSION["characterName"] = $userData["characterName"];
             $_SESSION["characterID"] = $userData["characterID"];
             $_SESSION["loggedIn"] = true;
             // Using $app to redirect causes a weird bug in slim, so use a header Location: instead
             header("Location: " . $this->app->request->getPath());
         }
     }
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Init rena
     /** @var RenaApp $app */
     $app = RenaApp::getInstance();
     $run = true;
     $oldKillID = 0;
     do {
         $p = \RedisQ\Action::listen("redisq.zkillboard.com");
         if ($p["killID"] > $oldKillID) {
             // Get the killmail data.
             $k = $app->CrestFunctions->generateFromCREST($p);
             // Poke statsd
             $app->StatsD->increment("zKillboardReceived");
             // Now lets make the json and hash
             $json = json_encode($k, JSON_NUMERIC_CHECK);
             $hash = $app->CrestFunctions->generateCRESTHash($k);
             //$hash = hash("sha256", ":" . $k["killTime"] . ":" . $k["solarSystemID"] . ":" . $k["moonID"] . "::" . $k["victim"]["characterID"] . ":" . $k["victim"]["shipTypeID"] . ":" . $k["victim"]["damageTaken"] . ":");
             // Lets insert the killmail!
             $insert = $app->killmails->insertIntoKillmails($p["killID"], 0, $hash, "zkillboardRedisQ", $json);
             // Upgrade it
             if ($insert > 0) {
                 \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $p["killID"]));
             }
         }
         $oldKillID = $p["killID"];
     } while ($run == true);
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Init rena
     /** @var RenaApp $app */
     $app = RenaApp::getInstance();
     $app->StatsD->increment("ccpRequests");
     $data = $app->EVEEVEAllianceList->getData();
     if (isset($data["result"]["alliances"])) {
         foreach ($data["result"]["alliances"] as $alliance) {
             $output->writeln("Updating/Adding: " . $alliance["name"]);
             // Update all the corporations in the alliance.. maybe we missed one?
             foreach ($alliance["memberCorporations"] as $corporation) {
                 \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\updateCorporation", array("corporationID" => $corporation["corporationID"]));
             }
             $allianceID = $alliance["allianceID"];
             $allianceName = $alliance["name"];
             $allianceTicker = $alliance["shortName"];
             $memberCount = $alliance["memberCount"];
             $executorCorporationID = $alliance["executorCorpID"];
             $information = json_decode($app->cURL->getData("https://public-crest.eveonline.com/alliances/{$allianceID}/"), true)["description"];
             $app->alliances->updateAllianceDetails($allianceID, $allianceName, $allianceTicker, $memberCount, $executorCorporationID, $information);
             $app->alliances->setLastUpdated($allianceID, date("Y-m-d H:i:s"));
         }
     }
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Init rena
     $app = RenaApp::getInstance();
     $run = true;
     $oldKillID = 0;
     do {
         $p = \RedisQ\Action::listen("redisq.zkillboard.com");
         if ($p["killID"] > $oldKillID) {
             // Get the killmail data.
             $k = $app->killmails->generateFromCREST($p);
             // Poke statsd
             $app->StatsD->increment("zKillboardReceived");
             // Now lets make the json and hash
             $json = json_encode($k, JSON_NUMERIC_CHECK);
             $hash = hash("sha256", ":" . $k["killTime"] . ":" . $k["solarSystemID"] . ":" . $k["moonID"] . "::" . $k["victim"]["characterID"] . ":" . $k["victim"]["shipTypeID"] . ":" . $k["victim"]["damageTaken"] . ":");
             // Push it over zmq to the websocket
             $context = new ZMQContext();
             $socket = $context->getSocket(ZMQ::SOCKET_PUSH, "rena");
             $socket->connect("tcp://localhost:5555");
             $socket->send($json);
             // Lets insert the killmail!
             $app->killmails->insertKillmail($p["killID"], 0, $hash, "zkillboardRedisQ", $json);
         }
         $oldKillID = $p["killID"];
     } while ($run == true);
 }
 /**
  * Executes the cronjob task
  *
  * @param mixed $pid
  * @param mixed $md5
  */
 public static function execute($pid, $md5)
 {
     /** @var RenaApp $app */
     $app = RenaApp::getInstance();
     // Foreach page, throw the war url in question at the Resque task
     $data = json_decode($app->cURL->getData("https://public-crest.eveonline.com/wars/", 0), true);
     $pageCount = $data["pageCount"];
     $currPage = 1;
     while ($currPage <= $pageCount) {
         // Get the data for the current page
         $data = json_decode($app->cURL->getData("https://public-crest.eveonline.com/wars/?page=" . $currPage, 0), true);
         foreach ($data["items"] as $war) {
             // Figure out if it's already inserted, and if it has ended (or has zero kills)
             $inserted = $app->wars->getWarByID($war["id"]);
             // If nothing is inserted we'll update
             if (empty($inserted)) {
                 \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\populateWars", array("url" => $war["href"]));
             }
             $date = new DateTime("+36 hour");
             $dateIn36Hours = $date->format("Y-m-d H:i:s");
             if (!empty($inserted) && $inserted["lastUpdated"] > $dateIn36Hours) {
                 \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\populateWars", array("url" => $war["href"]));
             }
         }
         // Increment the currentPage variable, so we can fetch the next set of wars
         $currPage++;
     }
     exit;
     // Keep this at the bottom, to make sure the fork exits
 }
 /**
  * @param $pid
  * @param $md5
  */
 public static function execute($pid, $md5)
 {
     $app = RenaApp::getInstance();
     if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) {
         return;
     }
     \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updateAlliances");
     exit;
 }
 /**
  * Executes the cronjob task
  *
  * @param mixed $pid
  * @param mixed $md5
  * @internal param RenaApp $app
  */
 public static function execute($pid, $md5)
 {
     /** @var RenaApp $app */
     $app = RenaApp::getInstance();
     $toUpgrade = $app->Db->query("SELECT killID FROM killmails WHERE upgraded = 0 AND processed != 1 ORDER BY dateAdded ASC LIMIT 100", array(), 1);
     if ($toUpgrade) {
         foreach ($toUpgrade as $kill) {
             \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $kill["killID"]));
         }
     }
     exit;
     // Keep this at the bottom, to make sure the fork exits
 }
 /**
  * @param $pid
  * @param $md5
  */
 public static function execute($pid, $md5)
 {
     $app = RenaApp::getInstance();
     if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) {
         return;
     }
     $toFetch = $app->Db->query("SELECT * FROM apiKeyCharacters WHERE cachedUntil < now() OR lastChecked < date_sub(now(), INTERVAL 24 HOUR) ORDER BY lastChecked LIMIT 500", array(), 1);
     if ($toFetch) {
         foreach ($toFetch as $apiFetches) {
             \Resque::enqueue("important", "\\ProjectRena\\Task\\Resque\\killMailFetcher", array("fetchData" => serialize($apiFetches)));
         }
     }
     exit;
     // Keep this at the bottom, to make sure the fork exits
 }
Example #10
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return void
  * @throws Exception
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var RenaApp $app */
     $app = RenaApp::getInstance();
     // Setup the url and cache path
     $url = "https://www.fuzzwork.co.uk/dump/";
     $cache = __DIR__ . "/../../cache/update";
     // Create the cache dir if it doesn't exist
     if (!file_exists($cache)) {
         mkdir($cache);
     }
     // Fetch the md5
     $md5file = "mysql-latest.tar.bz2.md5";
     $md5 = explode(" ", $app->cURL->getData($url . $md5file, 0))[0];
     $lastSeenMD5 = $app->Storage->get("ccpdataMD5");
     if ($lastSeenMD5 !== $md5 || !$input->getOption("force") === false) {
         $output->writeln("Updating to latest CCP data dump");
         $dbFiles = array("dgmAttributeCategories", "dgmAttributeTypes", "dgmEffects", "dgmTypeAttributes", "dgmTypeEffects", "invFlags", "invGroups", "invTypes", "mapDenormalize", "mapRegions", "mapSolarSystems", "mapConstellations");
         $type = ".sql.bz2";
         foreach ($dbFiles as $file) {
             $output->writeln("Updating {$file}");
             $dataURL = $url . "latest/" . $file . $type;
             try {
                 file_put_contents("{$cache}/{$file}{$type}", $app->cURL->getData($dataURL, 0));
                 $sqlData = bzopen("{$cache}/{$file}{$type}", "r");
                 // Open the BZip data
                 // Read the BZip data and append it to data
                 $data = "";
                 while (!feof($sqlData)) {
                     $data .= bzread($sqlData, 4096);
                 }
             } catch (\Exception $e) {
                 throw new \Exception($e->getMessage());
             }
             // Since rena uses tokuDB, we'll replace InnoDB with TokuDB here, just because we can..
             $data = str_replace("ENGINE=InnoDB", "ENGINE=TokuDB", $data);
             $dataParts = explode(";\n", $data);
             foreach ($dataParts as $qry) {
                 $query = $qry . ";";
                 $app->Db->execute($query);
             }
             // Remove the stored BZip file from the drive - no need to store it..
             unlink("{$cache}/{$file}.sql.bz2");
         }
         $app->Storage->set("ccpdataMD5", $md5);
     }
 }
 /**
  * @param $pid
  * @param $md5
  */
 public static function execute($pid, $md5)
 {
     $app = RenaApp::getInstance();
     if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) {
         return;
     }
     $characters = $app->Db->query("SELECT characterID FROM characters WHERE lastUpdated < date_sub(now(), INTERVAL 7 DAY) AND characterID != 0 ORDER BY lastUpdated LIMIT 500", array(), 0);
     if ($characters) {
         foreach ($characters as $character) {
             // Get the characterID to update
             $characterID = $character["characterID"];
             // Throw the ID after Resque which will update the characters information
             \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\updateCharacter", array("characterID" => $characterID));
         }
     }
     exit;
 }
 /**
  * @param $pid
  * @param $md5
  */
 public static function execute($pid, $md5)
 {
     $app = RenaApp::getInstance();
     if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) {
         return;
     }
     $apiKeys = $app->Db->query("SELECT keyID, vCode FROM apiKeys WHERE lastValidation < date_sub(now(), INTERVAL 6 HOUR) ORDER BY lastValidation DESC LIMIT 500", array(), 0);
     if ($apiKeys) {
         foreach ($apiKeys as $api) {
             $keyID = $api["keyID"];
             $vCode = $api["vCode"];
             // Update the lastValidation to in ten minutes, just so we don't insert it again and again
             \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updateApiKeys", array("keyID" => $keyID, "vCode" => $vCode));
         }
     }
     exit;
 }
 /**
  * Executes the cronjob task
  *
  * @param mixed $pid
  * @param mixed $md5
  */
 public static function execute($pid, $md5)
 {
     $app = RenaApp::getInstance();
     $typeIDs = $app->Db->query("SELECT typeID FROM invTypes WHERE published = 1 AND marketGroupID != 0");
     $cnt = 0;
     $fetchIDs = array();
     foreach ($typeIDs as $row) {
         $typeID = $row["typeID"];
         $fetchIDs[] = $typeID;
         $cnt++;
         if ($cnt == 20) {
             \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updatePrices", array("typeIDs" => $fetchIDs));
             $fetchIDs = array();
             $cnt = 0;
         }
     }
     exit;
     // Keep this at the bottom, to make sure the fork exits
 }
Example #14
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $app = RenaApp::getInstance();
     // Check if composer is in the dir
     if (!file_exists(__DIR__ . "/../../composer.phar")) {
         $output->writeln("Composer doesn't exist, downloading it");
         $composer = $app->cURL->getData("https://getcomposer.org/composer.phar", 0);
         file_put_contents(__DIR__ . "/../../composer.phar", $composer);
     }
     $output->writeln("Updating composer");
     exec("php " . __DIR__ . "/../../composer.phar update -o");
     // Generate an optimized loader
     $output->writeln("Generating Optimized Loader");
     $loaderCode = $this->generateOptimizedLoader($app);
     file_put_contents(__DIR__ . "/../OptimizedLoader.php", $loaderCode);
     // Update RenaApp
     $renaAppCode = $this->generateRenaApp();
     $output->writeln("Generating RenaApp");
     file_put_contents(__DIR__ . "/../RenaApp.php", $renaAppCode);
     // Do more stuff (Clear cache?)
 }
Example #15
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Init rena
     $app = RenaApp::getInstance();
     $startTime = time() + 3600;
     // Current time + 60 minutes
     $run = true;
     $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp"));
     $stomp->subscribe("/topic/kills", array("id" => "projectRena", "persistent" => "true", "ack" => "client", "prefetch-count" => 1));
     do {
         $frame = $stomp->readFrame();
         if (!empty($frame)) {
             $killdata = json_decode($frame->body, true);
             if (!empty($killdata)) {
                 $app->StatsD->increment("stompReceived");
                 if (isset($killdata["_stringValue"])) {
                     unset($killdata["_stringValue"]);
                 }
                 // Fix the killID
                 $killdata["killID"] = (int) $killdata["killID"];
                 $json = json_encode($killdata, JSON_NUMERIC_CHECK);
                 $hash = hash("sha256", ":" . $killdata["killTime"] . ":" . $killdata["solarSystemID"] . ":" . $killdata["moonID"] . "::" . $killdata["victim"]["characterID"] . ":" . $killdata["victim"]["shipTypeID"] . ":" . $killdata["victim"]["damageTaken"] . ":");
                 $inserted = $app->Db->execute("INSERT IGNORE INTO killmails (killID, hash, source, kill_json) VALUES (:killID, :hash, :source, :kill_json)", array(":killID" => $killdata["killID"], ":hash" => $hash, ":source" => "stomp", ":kill_json" => $json));
                 if ($inserted > 0) {
                     // Push it over zmq to the websocket
                     $context = new ZMQContext();
                     $socket = $context->getSocket(ZMQ::SOCKET_PUSH, "rena");
                     $socket->connect("tcp://localhost:5555");
                     $socket->send($json);
                 }
             }
             $stomp->ack($frame->headers["message-id"]);
         }
         // Kill it after an hour
         if ($startTime <= time()) {
             $run = false;
         }
     } while ($run == true);
 }
Example #16
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $app = RenaApp::getInstance();
     // Setup the url and cache path
     $url = "https://www.fuzzwork.co.uk/dump/";
     $cache = __DIR__ . "/../../cache/update";
     // Create the cache dir if it doesn't exist
     if (!file_exists($cache)) {
         mkdir($cache);
     }
     // Fetch the md5
     $md5file = "mysql-latest.tar.bz2.md5";
     $md5 = explode(" ", $app->cURL->getData($url . $md5file, 0))[0];
     $lastSeenMD5 = $app->Storage->get("ccpdataMD5");
     if ($lastSeenMD5 != $md5) {
         $output->writeln("Updating to latest CCP data dump");
         $dbFiles = array("dgmAttributeCategories", "dgmAttributeTypes", "dgmEffects", "dgmTypeAttributes", "dgmTypeEffects", "invFlags", "invGroups", "invTypes", "mapDenormalize", "mapRegions", "mapSolarSystems");
         $type = ".sql.bz2";
         foreach ($dbFiles as $file) {
             $dataURL = $url . "latest/" . $file . $type;
             try {
                 exec("wget -q {$dataURL} -O {$cache}/{$file}{$type}");
                 exec("bzip2 -q -d {$cache}/{$file}{$type}");
             } catch (\Exception $e) {
                 echo "Error";
             }
             $data = file_get_contents($cache . "/" . $file . ".sql");
             $data = str_replace("ENGINE=InnoDB", "ENGINE=TokuDB", $data);
             $dataParts = explode(";\n", $data);
             foreach ($dataParts as $qry) {
                 $query = $qry . ";";
                 $app->Db->execute($query);
             }
             unlink("{$cache}/{$file}.sql");
         }
         $app->Storage->set("ccpdataMD5", $md5);
     }
 }
Example #17
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Init rena
     /** @var RenaApp $app */
     $app = RenaApp::getInstance();
     $startTime = time() + 3600;
     // Current time + 60 minutes
     $run = true;
     $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp"));
     $stomp->subscribe("/topic/kills", array("id" => $app->baseConfig->getConfig("queueName", "stomp", "projectRena"), "persistent" => "true", "ack" => "client", "prefetch-count" => 1));
     do {
         $frame = $stomp->readFrame();
         if (!empty($frame)) {
             $killdata = json_decode($frame->body, true);
             if (!empty($killdata)) {
                 $app->StatsD->increment("stompReceived");
                 if (isset($killdata["_stringValue"])) {
                     unset($killdata["_stringValue"]);
                 }
                 // Fix the killID
                 $killdata["killID"] = (int) $killdata["killID"];
                 $json = json_encode($killdata, JSON_NUMERIC_CHECK);
                 $hash = $app->CrestFunctions->generateCRESTHash($killdata);
                 $inserted = $app->killmails->insertIntoKillmails($killdata["killID"], 0, $hash, "stomp", $json);
                 if ($inserted > 0) {
                     \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $killdata["killID"]));
                 }
             }
             $stomp->ack($frame->headers["message-id"]);
         }
         // Kill it after an hour
         if ($startTime <= time()) {
             $run = false;
         }
     } while ($run == true);
 }
Example #18
0
 public function __construct()
 {
     $this->app = RenaApp::getInstance();
     $this->stomp = new Stomp($this->app->baseConfig->getConfig("server", "stomp"), $this->app->baseConfig->getConfig("username", "stomp"), $this->app->baseConfig->getConfig("password", "stomp"));
 }
Example #19
0
 /**
  *
  */
 public function setUp()
 {
     $this->app = \ProjectRena\RenaApp::getInstance();
 }
 /**
  * Sets up the task (Setup $this->crap and such here)
  */
 public function setUp()
 {
     $this->app = RenaApp::getInstance();
 }
Example #21
0
/**
 * Quick access to rendering templates, json, xml and probably more down the line.
 *
 * @param string $templateFile
 * @param array $dataArray
 * @param null $status
 * @param string $contentType
 */
function render($templateFile, $dataArray = array(), $status = null, $contentType = null)
{
    $app = \ProjectRena\RenaApp::getInstance();
    $app->out->render($templateFile, $dataArray, $status, $contentType);
}
Example #22
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Enable the garbage collector since this is a long running process
     //gc_enable();
     // Get the slim instance
     $app = RenaApp::getInstance();
     $run = true;
     $cnt = 0;
     $cronjobs = scandir(__DIR__ . '/Cronjobs/');
     do {
         $cnt++;
         if ($cnt > 50) {
             //gc_collect_cycles();
             $cnt = 0;
         }
         foreach ($cronjobs as $key => $cron) {
             // Unset anything that isn't .php!
             if (!preg_match('/^(.+)\\.php$/', $cron, $match)) {
                 unset($cronjobs[$key]);
                 continue;
             }
             if (isset($match[1])) {
                 $name = $match[1];
                 $md5 = md5($name);
                 // If the script is currently running, skip to the next script
                 if ($app->Cache->get($md5 . '_pid') !== false) {
                     $pid = $app->Cache->get($md5 . '_pid');
                     $status = pcntl_waitpid($pid, $status, WNOHANG);
                     if ($status == -1) {
                         $app->Cache->delete($md5 . '_pid');
                     }
                     usleep(500000);
                     //continue;
                 }
                 // Get last time this cronjob ran
                 $lastRan = $app->Cache->get($md5) > 0 ? $app->Cache->get($md5) : 0;
                 // Current Time
                 $currentTime = time();
                 // Load the cronjobs class and get the information needed
                 $import = '\\ProjectRena\\Task\\Cronjobs\\' . $name;
                 $class = new $import();
                 $interval = $class->getRunTimes();
                 // If the current time is larger than the lastRunTime and Interval, then we run it again!
                 if ($currentTime > $lastRan + $interval) {
                     $time = time();
                     $output->writeln("Time: {$time}: Running {$name} (Interval: {$interval})");
                     try {
                         // Time to fork it all!
                         $pid = pcntl_fork();
                         if ($pid === 0) {
                             // Get the PID
                             $pid = getmypid();
                             // Tell the cache that we're running the cronjobs will automatically remove it from the cache once they're done
                             $app->Cache->set($md5 . '_pid', $pid);
                             // Execute the cronjob
                             $class->execute($pid, $md5);
                             exit;
                         }
                         // Tell the cache when we ran last!
                         $app->Cache->set($md5, time());
                     } catch (\Exception $e) {
                         $output->writeln("ERROR!! (pid: " . getmypid() . ") " . $e->getMessage());
                         $run = false;
                         posix_kill(getmygid(), 9);
                         exit;
                     }
                 }
             }
             // Sleep for 500 milliseconds, so we don't go nuts with CPU
             usleep(500000);
         }
     } while ($run === true);
 }
Example #23
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $table = prompt("Table to create model for");
     $this->description["description"] = prompt("Description");
     if (!$table) {
         $output->writeln("Error, table name is not supplied.");
         exit;
     }
     // Setup the path and make sure it doesn't already exist
     $path = __DIR__ . "/../Model/Database/{$table}.php";
     if (file_exists($path)) {
         return $output->writeln("Error, file already exists");
     }
     // Load app
     $app = \ProjectRena\RenaApp::getInstance();
     // Load the table, if it exists in the first place
     $tableColums = $app->Db->query("SHOW COLUMNS FROM {$table}");
     // Generate the start of the model code
     $class = new PhpClass();
     $class->setQualifiedName("ProjectRena\\Model\\Database\\{$table}")->setProperty(PhpProperty::create("app")->setVisibility("private")->setDescription("The Slim Application"))->setProperty(PhpProperty::create("db")->setVisibility("private")->setDescription("The database connection"))->setMethod(PhpMethod::create("__construct")->addParameter(PhpParameter::create("app")->setType("RenaApp"))->setBody("\$this->app = \$app;\n\r\n                \$this->db = \$app->Db;\n"))->setDescription($this->description)->declareUse("ProjectRena\\RenaApp");
     $nameFields = array();
     $idFields = array();
     foreach ($tableColums as $get) {
         // This is for the getByName selector(s)
         if (stristr($get["Field"], "name")) {
             $nameFields[] = $get["Field"];
         }
         // This is for the getByID selector(s)
         if (strstr($get["Field"], "ID")) {
             $idFields[] = $get["Field"];
         }
     }
     // Get generator
     foreach ($nameFields as $name) {
         // get * by Name
         $class->setMethod(PhpMethod::create("getAllBy" . ucfirst($name))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("return \$this->db->query(\"SELECT * FROM {$table} WHERE {$name} = :{$name}\", array(\":{$name}\" => \${$name}));"));
     }
     foreach ($idFields as $id) {
         // get * by ID,
         $class->setMethod(PhpMethod::create("getAllBy" . ucfirst($id))->addParameter(PhpParameter::create($id)->setType("int"))->setVisibility("public")->setBody("return \$this->db->query(\"SELECT * FROM {$table} WHERE {$id} = :{$id}\", array(\":{$id}\" => \${$id}));"));
     }
     foreach ($nameFields as $name) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $name) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("get" . ucfirst($get["Field"]) . "By" . ucfirst($name))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("return \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$name} = :{$name}\", \"{$get["Field"]}\", array(\":{$name}\" => \${$name}));"));
         }
     }
     foreach ($idFields as $id) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $id) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("get" . ucfirst($get["Field"]) . "By" . ucfirst($id))->addParameter(PhpParameter::create($id))->setVisibility("public")->setBody("return \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$id} = :{$id}\", \"{$get["Field"]}\", array(\":{$id}\" => \${$id}));"));
         }
     }
     // Update generator
     foreach ($nameFields as $name) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $name) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("update" . ucfirst($get["Field"]) . "By" . ucfirst($name))->addParameter(PhpParameter::create($get["Field"]))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("\$exists = \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$name} = :{$name}\", \"{$get["Field"]}\", array(\":{$name}\" => \${$name}));\r\n                     if(!empty(\$exists)){\r\n                        \$this->db->execute(\"UPDATE {$table} SET {$get["Field"]} = :{$get["Field"]} WHERE {$name} = :{$name}\", array(\":{$name}\" => \${$name}, \":{$get["Field"]}\" => \${$get["Field"]}));}\r\n                    "));
         }
     }
     foreach ($idFields as $id) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $id) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("update" . ucfirst($get["Field"]) . "By" . ucfirst($id))->addParameter(PhpParameter::create($get["Field"]))->addParameter(PhpParameter::create($id))->setVisibility("public")->setBody("\$exists = \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$id} = :{$id}\", \"{$get["Field"]}\", array(\":{$id}\" => \${$id}));\r\n                     if(!empty(\$exists))\r\n                     {\r\n                        \$this->db->execute(\"UPDATE {$table} SET {$get["Field"]} = :{$get["Field"]} WHERE {$id} = :{$id}\", array(\":{$id}\" => \${$id}, \":{$get["Field"]}\" => \${$get["Field"]}));}\r\n                    "));
         }
     }
     // Global insert generator (Yes it's ugly as shit..)
     $inserter = "public function insertInto" . ucfirst($table) . "(";
     foreach ($tableColums as $field) {
         // Skip the ID field
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= "\${$field["Field"]}, ";
     }
     $inserter = rtrim(trim($inserter), ",") . ")";
     $inserter .= "{";
     $inserter .= "\$this->db->execute(\"INSERT INTO {$table} (";
     foreach ($tableColums as $field) {
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= $field["Field"] . ", ";
     }
     $inserter = rtrim(trim($inserter), ",") . ") ";
     $inserter .= "VALUES (";
     foreach ($tableColums as $field) {
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= ":" . $field["Field"] . ", ";
     }
     $inserter = rtrim(trim($inserter), ",") . ")\", ";
     $inserter .= "array(";
     foreach ($tableColums as $field) {
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= "\":" . $field["Field"] . "\" => \${$field["Field"]}, ";
     }
     $inserter = rtrim(trim($inserter), ",") . "));";
     $inserter .= "}}";
     $generator = new CodeFileGenerator();
     $code = $generator->generate($class);
     $code = rtrim(trim($code), "}");
     $code .= $inserter;
     $formatter = new Formatter();
     $code = $formatter->format($code);
     file_put_contents($path, $code);
     chmod($path, 0777);
     $output->writeln("Model created: {$path}");
 }
Example #24
0
 /**
  * Inserts data into the slim flasher.
  *
  * @static
  *
  * @param string $logType the type of logging, debug, info, warning, error
  * @param string $logMessage the message for the log
  */
 public function flasher($logType, $logMessage)
 {
     $this->app->flash($logType, $logMessage);
 }
Example #25
0
 /**
  * @param $code
  * @param $state
  */
 public function SSOLogin($code, $state)
 {
     // Get the login token
     $tokenURL = "https://login.eveonline.com/oauth/token";
     $base64 = base64_encode($this->config->getConfig("clientID", "crestsso") . ":" . $this->config->getConfig("secretKey", "crestsso"));
     $data = json_decode($this->app->cURL->sendData($tokenURL, array("grant_type" => "authorization_code", "code" => $code), array("Authorization: Basic {$base64}")));
     $accessToken = $data->access_token;
     $refreshToken = $data->refresh_token;
     //$expiresIn = $data->expires_in;
     // Verify token
     $verifyURL = "https://login.eveonline.com/oauth/verify";
     $data = json_decode($this->app->cURL->sendData($verifyURL, array(), array("Authorization: Bearer {$accessToken}")));
     $characterID = $data->CharacterID;
     $characterName = $data->CharacterName;
     $characterOwnerHash = $data->CharacterOwnerHash;
     //$expiresOn = $data->ExpiresOn;
     $scopes = $data->Scopes;
     $tokenType = $data->TokenType;
     // Generate a unique id
     $uniqueID = uniqid("", true);
     // Insert it all to the table
     $this->app->Db->execute("INSERT INTO users (characterName, characterID, characterOwnerHash, loginHash, accessToken, refreshToken, scopes, tokenType) VALUES (:characterName, :characterID, :characterOwnerHash, :loginHash, :accessToken, :refreshToken, :scopes, :tokenType) ON DUPLICATE KEY UPDATE characterName = :characterName, characterID = :characterID, characterOwnerHash = :characterOwnerHash, loginHash = :loginHash, accessToken = :accessToken, refreshToken = :refreshToken, scopes = :scopes, tokenType = :tokenType", array(":characterName" => $characterName, ":characterID" => $characterID, ":characterOwnerHash" => $characterOwnerHash, ":loginHash" => $uniqueID, ":accessToken" => $accessToken, ":refreshToken" => $refreshToken, ":scopes" => $scopes, ":tokenType" => $tokenType));
     // Create the auto login cookie
     $this->app->setEncryptedCookie($this->config->getConfig("name", "cookies", "rena"), $uniqueID, time() + $this->config->getConfig("time", "cookies", 3600 * 24 * 30), "/", $this->app->request->getHost(), $this->config->getConfig("ssl", "cookies", true), "true");
     // Setup the groups (corp and alli)
     $data = $this->app->characters->getAllByID($characterID);
     // Tell resque to do stuff
     if (!$data["characterID"]) {
         \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updateCharacter", array("characterID" => $characterID));
         sleep(6);
         // Sleep for 6 seconds, not ideal but whatever
         $data = $this->app->characters->getAllByID($characterID, 0);
         // Refetch the data, just this time we skip the cache!
     }
     // Only do all of the group stuff if the character exists in the database.. if said character doesn't exist, we'll push the character to resque and do it all there!
     if ($data) {
         // Check if the user is in groups they're not allowed to be in.. this goes for corporation and alliance only!
         $validGroups = array("corporation" => $data["corporationID"], "alliance" => $data["allianceID"]);
         foreach ($validGroups as $type => $id) {
             $innerData = $this->db->query("SELECT groupID, groupType FROM usersGroups WHERE userID = :id", array(":id" => $this->app->Users->getUserByName($characterName)["id"]));
             foreach ($innerData as $check) {
                 if ($check["groupType"] == $type) {
                     if ($check["groupID"] != $id) {
                         $this->db->execute("DELETE FROM usersGroups WHERE userID = :id AND groupID = :groupID", array(":id" => $this->app->Users->getUserByName($characterName)["id"], ":groupID" => $check["groupID"]));
                     }
                 }
             }
         }
         // Now add the user to the groups they're allowed to be in, this doesn't happen on anything but login so that we are a bit sql heavy there is fine!
         $this->app->Groups->updateGroup($data["corporationID"], $this->app->corporations->getAllByID($data["corporationID"])["corporationName"]);
         $this->app->UsersGroups->setGroup($this->app->Users->getUserByName($characterName)["id"], $data["corporationID"], "corporation");
         $this->app->Groups->setAdmins($data["corporationID"], array($this->app->corporations->getAllByID($data["corporationID"])["ceoID"]));
         if ($data["allianceID"] > 0) {
             $this->app->Groups->updateGroup($data["allianceID"], $this->app->alliances->getAllByID($data["allianceID"])["allianceName"]);
             $this->app->UsersGroups->setGroup($this->app->Users->getUserByName($characterName)["id"], $data["allianceID"], "alliance");
             $this->app->Groups->setAdmins($data["allianceID"], array($this->app->corporations->getAllByID($this->app->alliances->getAllByID($data["allianceID"])["executorCorporationID"])["ceoID"]));
         }
     }
     // Set the session
     $_SESSION["characterName"] = $characterName;
     $_SESSION["characterID"] = $characterID;
     $_SESSION["loggedIn"] = true;
     // Insert the IP
     $this->app->UsersLogins->updateIP($this->app->Users->getUserByName($characterName)["id"], $this->app->request->getIp());
     \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\ipUpdater", array("userID" => $this->app->Users->getUserByName($characterName)["id"], "ip" => $this->app->request->getIp()));
     // Redirect back to where the person came from
     $this->app->redirect($state);
 }