function main() { require_once './inc/config.php'; require_once './inc/utils.php'; require_once UFLEX . 'autoload.php'; $utils = new Utils(); $utils->log($_SESSION, '$_SESSION', 'debug.html', 'w'); $utils->log($_SESSION[userData], '$_SESSION[userData'); // $utils->log('START', 'debug.html'); $utils->log('$_SESSION["attempts"] = ' . $_SESSION['attempts']); if ($_SESSION['redirect'] == true) { require_once 'inc/redirect.php'; $utils->log('**redirect control***', 'debug.html'); $utils->execute($vars['controller'], $vars['task'], $vars); // (controller, task) exit; } else { $url = $utils->urlToArray(); $utils->log($url, 'This should be the $url'); if (!isset($url['controller']) || !isset($url['task'])) { $utils->log('Controller or task not set', 'debug.html'); $_REQUEST['view'] = 'landing'; $utils->execute('landings', 'display'); // (controller, task) exit; } $utils->log('**Execute ' . $url['controller'] . '->' . $url['task'] . ' ***'); $result = $utils->execute($url['controller'], $url['task']); $utils->log($result, 'Execute success?'); exit; } }
function __autoload($className) { if (preg_match('/.*Dao$/', $className) > 0) { # Dao class if (file_exists(realpath(dirname(__FILE__)) . '/../dao/' . $className . '.php')) { include_once realpath(dirname(__FILE__)) . '/../dao/' . $className . '.php'; } } elseif (preg_match('/.*Manager$/', $className) > 0) { # Managers interfaces if (file_exists(realpath(dirname(__FILE__)) . '/../managers/' . $className . '.php')) { include_once realpath(dirname(__FILE__)) . '/../managers/' . $className . '.php'; } } elseif (preg_match('/.*Module$/', $className) > 0) { # Get the module name $moduleName = strtolower(preg_replace('/^(.*)Module$/', '\\1', $className)); if (file_exists(realpath(dirname(__FILE__)) . '/../../modules/' . $moduleName . '/' . $className . '.php')) { include_once realpath(dirname(__FILE__)) . '/../../modules/' . $moduleName . '/' . $className . '.php'; } } else { # Models if (file_exists(realpath(dirname(__FILE__)) . '/../model/' . $className . '.php')) { include_once realpath(dirname(__FILE__)) . '/../model/' . $className . '.php'; } } Utils::log(LOG_DEBUG, "Class {$className} loaded", __FILE__, __LINE__); }
/** * @desc Translate a key * @param $key The key to translate * @param $args Arguments to pass to sprintf */ public function translate($key, $args = false) { $arr = explode('.', $key); if (is_array($this->hash) && array_key_exists($arr[0], $this->hash) && array_key_exists($arr[1], $this->hash[$arr[0]])) { $skey = $this->hash[$arr[0]][$arr[1]]; if (is_array($this->translations) && array_key_exists($skey, $this->translations) && isset($this->translations[$skey])) { $string = $this->translations[$skey]; } else { if ($this->language != 'en') { \Utils::log('Locale: Translation not found in [' . $this->language . '] for "' . $key . '" : "' . $skey . '"'); } if (is_string($skey)) { $string = $skey; } else { \Utils::log('Locale: Double definition for "' . $key . '" got ' . serialize($skey)); $string = $skey[0]; } } if ($args != false) { array_unshift($args, $string); $string = call_user_func_array("sprintf", $args); } return $string; } else { \Utils::log('Locale: Translation key "' . $key . '" not found'); } }
protected function loadSubSources() { Utils::log(LOG_DEBUG, "Loading CVE sources", __FILE__, __LINE__); # List all files in the sources directory, each file represents submodule if (!file_exists(realpath(dirname(__FILE__)) . '/../sources/' . $this->getName() . 'SubSources/')) { mkdir(realpath(dirname(__FILE__)) . '/../sources/' . $this->getName() . 'SubSources/'); } $dir = realpath(dirname(__FILE__)) . '/../sources/' . $this->getName() . 'SubSources/'; if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { # Load only files and ommit the OvalSourceInterface if (is_file($dir . $file) && preg_match('/.php$/i', $file)) { require_once $dir . $file; # Get the filename and extension, filename represent the class name $className = preg_replace('/.php$/i', '', $file); eval("\$subSource = new {$className}(\$this->_pakiti);"); # Check if the module is already registered if (($id = $this->_pakiti->getManager("DbManager")->queryToSingleValue("select id from VdsSubSource where type='" . $this->_pakiti->getManager("DbManager")->escape($subSource->getType()) . "' and name='" . $this->_pakiti->getManager("DbManager")->escape($subSource->getName()) . "'")) == null) { # Module is not registered, so store the name and type into the DB # Start transaction $this->_pakiti->getManager("DbManager")->begin(); $this->_pakiti->getManager("DbManager")->query("insert into VdsSubSource set type='" . $subSource->getType() . "', name='" . $subSource->getName() . "', vdsSourceId=" . $this->getId()); $id = $this->_pakiti->getManager("DbManager")->getLastInsertedId(); # Commit transaction $this->_pakiti->getManager("DbManager")->commit(); } # Set the submodule ID $subSource->setId($id); # Finally add the CVE submodule array_push($this->_subSources, $subSource); } } } }
public function register() { Utils::log('Lets get You Registred!'); //Instantiate the User object $user = new ptejada\uFlex\User(); //Add database credentials $user->config->database->host = DB_HOST; $user->config->database->user = DB_USER; $user->config->database->password = DB_PASS; $user->config->database->name = DB_NAME; //Database name /* * You can update any customizable property of the class before starting the object * construction process */ //Start object construction $user->start(); $_POST['groupID'] = 0; $input = new ptejada\uFlex\Collection($_POST); Utils::log($input, 'This is the $input data'); $registered = $user->register(array('Username' => $input->username, 'Password' => $input->password, 'Password2' => $input->password2, 'Email' => $input->email, 'GroupID' => $input->groupID), true); if ($registered) { echo "User Registered"; } else { //Display Errors foreach ($user->log->getErrors() as $err) { echo "<b>Error:</b> {$err} <br/ >"; } } }
/** * Stores Exception into DB * @param CveException|Exception $exception * @return Exception * @throws Exception */ public function createCveException(CveException &$exception) { if ($exception == null) { Utils::log(LOG_DEBUG, "Exception", __FILE__, __LINE__); throw new Exception("Exception object is not valid"); } Utils::log(LOG_DEBUG, "Creating the exception", __FILE__, __LINE__); $this->getPakiti()->getDao("CveException")->create($exception); return $exception; }
public function getCveByNameAndCveDefId($name, $cveDefId) { Utils::log(LOG_DEBUG, "Getting CVE its name [name={$name}] and cveDefId [cveDefId={$cveDefId}]", __FILE__, __LINE__); $cve = $this->getPakiti()->getDao("Cve")->getCve(); if (is_object($cve)) { $cve->setTag($this->getPakiti()->getManager("TagsManager")->getCveTags($cve)); $cve->setCveExceptions($this->getPakiti()->getManager("CveExceptionsManager")->getCveExceptionsByCveName($cve->getName())); } return $cve; }
public static function query($sql) { Utils::log($sql); //echo $sql."\n"; $res = self::$db->query($sql); if ($res == FALSE) { Utils::log("DB ERROR"); Viewer::addMessage("Nastala chyba pri komunikácii s databázou, prosím kontaktuj administrátora !", Viewer::ERROR); } return $res; }
function __construct($page_cd = null) { if (Utils::isEmpty($page_cd)) { Utils::log(Message::MSG_PAGE_CD_NOT_FOUND); return false; } $db_mgr = new DbManager(); $this->mysqli = $db_mgr->getMysqli(); $ql = "select * from `pages` where `page_cd` = '{$page_cd}' "; $res = $this->mysqli->query($ql); $this->page = $res->fetch_assoc(); }
public function retrieveDefinitions() { Utils::log(LOG_DEBUG, "Retreiving definitions from the " . OvalRedHat::getName() . " OVAL", __FILE__, __LINE__); $defs = array(); foreach ($this->getSubSourceDefs() as $subSourceDef) { # Loading the defined file $oval = new DOMDocument(); libxml_set_streams_context(Utils::getStreamContext()); $oval->load($subSourceDef->getUri()); if ($oval === FALSE) { Utils::log(LOG_DEBUG, "Exception", __FILE__, __LINE__); throw new Exception("Cannot load OVAL [source URI=" . $subSourceDef->getUri() . "]"); } # Get the XPath $this->_xpath = new DOMXPath($oval); $this->_xpath->registerNamespace("def", "http://oval.mitre.org/XMLSchema/oval-definitions-5"); $xDefinitions = $this->_xpath->query("/def:oval_definitions/def:definitions/def:definition"); # Go through all definitions foreach ($xDefinitions as $xDefinition) { $def = array(); $def['subSourceDefId'] = $subSourceDef->getId(); $def['definition_id'] = $xDefinition->attributes->item(0)->value; $el_severity = $xDefinition->getElementsByTagName('severity')->item(0); if (!empty($el_severity)) { $def['severity'] = $el_severity->nodeValue; } else { $def['severity'] = "n/a"; } $def['title'] = rtrim($xDefinition->getElementsByTagName('title')->item(0)->nodeValue); $def['ref_url'] = $xDefinition->getElementsByTagName('reference')->item(0)->getAttribute('ref_url'); // Get associated CVEs $cve_query = 'def:metadata/def:advisory/def:cve'; $cves = $this->_xpath->query($cve_query, $xDefinition); $def['cves'] = array(); $def['os'] = array(); foreach ($cves as $cve) { array_push($def['cves'], $cve->nodeValue); } // Processing criteria $root_criterias_query = 'def:criteria'; $root_criterias = $this->_xpath->query($root_criterias_query, $xDefinition); foreach ($root_criterias as $root_criteria) { $os = null; $package = array(); $this->processCriterias($this->_xpath, $root_criteria, $def, $os, $package); } array_push($defs, $def); } $this->updateSubSourceLastChecked($subSourceDef); } return $defs; }
/** * @see Entity_Field::isValid() * @return type */ public function isValid() { if (!$this->isRequired() && $this->getValue() == null) { return true; } foreach ($this->getValue()->getFields() as $field) { if (!$field->isValid()) { Utils::log("Field " . $field->getName() . " is invalid"); return false; } } return true; }
public function isValid() { if ($this->getValue() == null && !$this->isRequired()) { return true; } foreach ($this->_validators as $validator) { if (!$validator->isValid($this->getValue())) { Utils::log("Field " . $this->getName() . " is invalid"); return false; } } return true; }
protected function curlPost($url, $data) { $ch = curl_init(); $postString = http_build_query($data, '&'); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); Utils::log($postString . "|||" . $url, "curlPost"); $return = curl_exec($ch); curl_close($ch); $result = json_decode($return, true); return $result ? $result : false; }
private function invoke(Route $route) { $className = 'AlfredSlack\\Controllers\\' . ucfirst($route->getController()) . 'Controller'; $actionName = $route->getAction() . 'Action'; $controller = new $className(); if (!$controller instanceof \AlfredSlack\Controllers\Controller) { throw new \Exception("{$className} must inherits from AlfredSlack\\Controllers\\Controller"); } Utils::log('ACTION: ' . $className . '::' . $actionName . '()'); Utils::log('SIMULATE: php -r \'$query="' . str_replace('"', '\\"', json_encode($route)) . '";include "scripts/index.php";\';'); $interruptAction = $controller->preDispatch($actionName, $route->getParams()) === false; if (!$interruptAction) { $actionResult = $controller->dispatch($actionName, $route->getParams()); $controller->postDispatch($actionName, $route->getParams(), $actionResult); } }
function __construct($location, $errorInfo = '[no info]') { //format info $errDesc = ''; if ($errorInfo instanceof PDOException) { $errDesc = $errorInfo->getMessage(); } elseif ($errorInfo instanceof PDOStatement) { $errArr = $errorInfo->errorInfo(); $errDesc = $errArr[2]; } else { $errDesc = $errorInfo; } $errDesc = str_replace(array("\r", "\n"), array('', ' '), $errDesc); $errDesc = $location . ' ' . $errDesc; //log it Utils::log($errDesc, 'dberror', true); }
private static function over() { //ak niesom prihlaseny tak ma prihlas if (!Auth::isAuth()) { Viewer::addMessage("Na zobrazenie tejto stránky musíš byť prihlásený/á !", Viewer::ERROR); Viewer::setPage(Viewer::LOGIN); return False; } //zistim si cislo pozadovaneho testu $testid = 0; if (isset($_GET['testid'])) { $testid = intval($_GET['testid']); } //overim ci exituje taky test pre mna $query = DB::query('SELECT * from `ucitelia` LEFT JOIN `tests` ON ucitelia.ucitelid=tests.ucitel LEFT JOIN `predmety` ON predmety.predmetid=tests.predmetid WHERE `trieda`=' . Auth::$userData['trieda']['id'] . " AND `testid`=" . $testid); //ak nie if ($query->num_rows == 0) { //idem s5 na zoznam testov Viewer::addMessage("Takýto dotazník neexistuje alebo naň nemáš právo!", Viewer::ERROR); TestList::init(); Viewer::setPage(Viewer::TEST_LIST); return False; } //ulozim si udaje o teste self::$testData = $query->fetch_array(); //zistim si groupid testu Utils::log(print_r(self::$testData, true)); $groupid = self::$testData['groupid']; //overim ci tento test neije vyplneny //ak grupy //$queryans = DB::query('SELECT * from `answered` WHERE `groupid`='.$groupid." AND `userid`=".Auth::$userData['id']['id']); $queryans = DB::query('SELECT * from `answered` WHERE `testid`=' . $testid . " AND `userid`=" . Auth::$userData['id']['id']); if ($queryans->num_rows != 0) { Viewer::addMessage("Tento dotazník si už vyplnil/a!", Viewer::ERROR); TestList::init(); Viewer::setPage(Viewer::TEST_LIST); return False; } return True; }
public static function initialize() { setlocale(LC_ALL, "sk_SK.utf8"); header("Content-Type: text/html; charset=utf-8"); date_default_timezone_set("Europe/Bratislava"); self::$paths["this"] = $_SERVER["SCRIPT_FILENAME"]; self::$paths["root"] = getcwd(); //zapiseme do logu vstupne premenne Utils::log($_GET); Utils::log($_POST); session_start(); //pripojime sa do databaazy DB::connect(); //autentizujeme pouzivatela so session Auth::authentificate(); //ak uzivatel pozaduje nejaky stranku tak ju nastavime ako predvolenu if (isset($_GET['page'])) { Viewer::setPage($_GET['page']); } //spustime spracovanie stránky Viewer::run(); //s logom to doriešim neskôr file_put_contents(self::$paths["root"] . "/" . Settings::$logFile, Utils::getLog(), FILE_APPEND | LOCK_EX); }
public function run($classname = null, $type = 'list') { if (empty($this->_warnings)) { $this->_resultset->execute(); } else { Utils::log($this->_warnings); } if ($classname == null && substr(get_class($this), -3, 3) == 'DAO') { // We strip Modl/ and DAO from the classname $classname = substr(get_class($this), 5, -3); } $this->_warnings = []; if ($this->_resultset != null) { $errors = $this->_resultset->errorInfo(); if ($errors[0] != '000000') { Utils::log($errors[1] . ' : ' . $errors[2]); Utils::log(trim(preg_replace('/\\s+/', ' ', $this->_sql)), $this->_params, $errors); } if ($this->_resultset->rowCount() == 0) { $this->_effective = false; } else { $this->_effective = true; } $ns_classname = 'Modl\\' . $classname; if (isset($classname) && class_exists($ns_classname) && $this->_resultset != null && $type != 'array') { $results = []; while ($row = $this->_resultset->fetch(\PDO::FETCH_NAMED)) { $obj = new $ns_classname(); foreach ($row as $key => $value) { if (isset($value)) { if (is_array($value)) { $value = current(array_filter($value)); } if (property_exists($obj, $key)) { if (isset($obj->_struct->{$key})) { switch ($obj->_struct->{$key}->type) { case 'int': $obj->{$key} = (int) $value; break; case 'bool': $obj->{$key} = (bool) $value; break; case 'date': case 'string': default: $obj->{$key} = (string) $value; break; } } else { $obj->{$key} = $value; } } } } array_push($results, $obj); } $i = 0; $empty = new $ns_classname(); foreach ($results as $obj) { if ($obj == $empty) { unset($results[$i]); } $i++; } if (empty($results)) { return null; } else { foreach ($results as $obj) { $obj->clean(); } if ($type == 'list') { return $results; } elseif ($type == 'item') { return $results[0]; } } } elseif ($type = 'array' && $this->_resultset != null) { $results = $this->_resultset->fetchAll(\PDO::FETCH_ASSOC); return $results; } else { return null; } } else { return null; } }
public function delete(Host &$host) { if ($host == null || $host->getId() == -1) { Utils::log(LOG_DEBUG, "Exception", __FILE__, __LINE__); throw new Exception("Host object is not valid or Host.id is not set"); } $this->db->query("delete from Host where id=" . $host->getId()); Utils::log(LOG_DEBUG, "Host deleted", __FILE__, __LINE__); }
public function removeHostFromHostGroups(Host &$host) { if ($host == null || $host->getId() == -1) { Utils::log(LOG_DEBUG, "Exception", __FILE__, __LINE__); throw new Exception("Host object is not valid or Host.id is not set"); } Utils::log(LOG_DEBUG, "Removing the host from all host groups [host=" . $host->getHostname() . "]", __FILE__, __LINE__); $this->getPakiti()->getDao("HostGroup")->removeHostFromHostGroups($host->getId()); }
$time = microtime(true); require realpath(dirname(__FILE__)) . '/../../../common/Loader.php'; require realpath(dirname(__FILE__)) . '/../FeederModule.php'; try { # Initialize $feeder = new FeederModule($pakiti); # Asynchronous mode - only store the results and exit #---------------------------------------------------- if (Config::$FEEDER_MODE == Constants::$FEEDER_ASYNCHRONOUS_MODE) { $feeder->storeReportToFile(); } elseif (Config::$FEEDER_MODE == Constants::$FEEDER_SYNCHRONOUS_MODE) { # Process incomming data $feeder->processReport(); # Should we send the results back to the client? if (Utils::getHttpVar(Constants::$REPORT_REPORT) == Constants::$SEND_REPORT) { //TODO $feeder->sendResultsBack(); } } else { Utils::log(LOG_ERROR, "Undefined feeder mode"); print Constants::$RETURN_ERROR; exit; } # End Utils::log(LOG_INFO, "Report done for [host=" . $feeder->getReportHost() . "] in " . Utils::getTimer($time) . "s\n"); print Constants::$RETURN_OK; exit; } catch (Exception $e) { Utils::log(LOG_ERR, $e->getMessage()); print Constants::$RETURN_ERROR; exit; }
public function execute($controller, $task, $arg = false) { Utils::log('Utils->execute'); if (!($controller = Utils::fetchController($controller, $task))) { return false; } if (!$controller->{$task}($value = $arg != false ? $arg : null)) { return false; } return true; }
public function retrieveDefinitions() { Utils::log(LOG_DEBUG, "Retreiving definitions from the " . Debian::getName(), __FILE__, __LINE__); $this->loadDSA(); return $this->processDSA(); }
/** * Project specific psr-4 autoloader * Based on example https://github.com/php-fig/fig-standards/blob/master/proposed/psr-4-autoloader/psr-4-autoloader-examples.md * * @param string $class The fully-qualified class name. * * @return void */ spl_autoload_register(function ($class) { // project-specific namespace prefix $prefix = 'ptejada\\uFlex\\'; // base directory for the namespace prefix $base_dir = __DIR__ . '/src/'; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $relative_class = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the file exists, require it if (file_exists($file)) { Utils::log($file, 'uFlex File'); require $file; } });
/** * Return array of Vulnerabilities by Cve name and Os name * Used by API * @param $cveName * @param $osName * @return array */ public function getVulnerabilitiesByCveNameAndOsName($cveName, $osName) { Utils::log(LOG_DEBUG, "Searching for vulnerable packages for all hosts", __FILE__, __LINE__); $os = $this->getPakiti()->getDao("Os")->getByName($osName); if (!is_object($os)) { return array(); } $cves = $this->getPakiti()->getDao("Cve")->getCvesByName($cveName); if (empty($cves)) { return array(); } $osGroup = $this->getPakiti()->getManager("OsGroupsManager")->getOsGroupByOsId($os->getId()); if (!is_object($osGroup)) { return array(); } $cveDefsIds = array_map(function ($cve) { return $cve->getCveDefId(); }, $cves); return $this->getPakiti()->getDao("Vulnerability")->getVulnerabilitiesByCveDefsIdsAndOsGroupId($cveDefsIds, $osGroup->getId()); }
public function createOsGroup($name) { Utils::log(LOG_DEBUG, "Creating osGroup {$name}", __FILE__, __LINE__); $osGroup = new OsGroup(); $osGroup->setName($name); $this->getPakiti()->getDao("OsGroup")->create($osGroup); return $osGroup; }
public function output() { Utils::log($this->getOutput()); if (null !== ($parent = $this->getParent())) { $parent->steps[] = $this; } return $this; }
public function invoke(Connection_Request_Interface $request) { if ($this->state != Connection_State::$established) { $this->connect(); } if (!$request->isValid()) { throw new Entities_Validator_Exception(sprintf("Request %s validation failed!", get_class($request))); } if ($request->isAuthRequired()) { $request->setHeader(Connection_Request_Headers::$login, $this->_login); $request->setHeader(Connection_Request_Headers::$authToken, $this->_authToken); $request->setHeader(Connection_Request_Headers::$applicationId, $this->_applicationId); } $data = $this->prepareRequest($request); Utils::log(sprintf("Sending data on gateway: %s", $data)); $status = fwrite($this->_socket, $data . "\n"); if (!$status) { throw new Connection_Exception(sprintf("Method %s invocation failed!", $request->getMethod())); } $responseBody = fread($this->_socket, 4096); Utils::log(sprintf("Received response body: \n %s", $responseBody)); $this->disconnect(); return $this->getProtocol()->hydrateResponse($request, $responseBody); }
public static function getStreamContext() { Utils::log(LOG_DEBUG, "Getting stream context", __FILE__, __LINE__); if (Config::$ENABLE_OUTGOING_PROXY == 1) { $opts = array('http' => array('proxy' => Config::$OUTGOING_PROXY, 'request_fulluri' => true)); Utils::log(LOG_DEBUG, "Using outgoing proxy: " . Config::$OUTGOING_PROXY); } else { $opts = array('http' => array('method' => "GET")); } return stream_context_create($opts); }
static function logException($e) { $msg = $e->getMessage() . "\n"; $msg .= $e->getTraceAsString() . "\n"; Utils::log($msg); }