/** * * @param mixed $pmLine * @param string $psFileName * @param string $psSeparate * @param boolean $pbForceLog */ public static function log($pmLine, $psFileName = 'log', $psSeparate = "\t", $pbForceLog = false) { $laLogConf = Config::getOptions('log'); $lsFileName = $laLogConf['folder']; if (!empty($psFileName)) { $lsFileName .= DS . $psFileName; } else { $lsFileName .= DS . 'log'; } if (Util::toBoolean($laLogConf['enable']) || $pbForceLog) { $lsLine = $pmLine; if (is_array($pmLine)) { $lsLine = implode($psSeparate, $pmLine); } $lsLog = date('Y-m-d H:i:s', time()) . $psSeparate . $lsLine . "\n"; if (file_exists($lsFileName)) { self::saveFile($lsFileName, $lsLog, 'APPEND'); } else { self::saveFile($lsFileName, $lsLog); } } else { Debug::debug($pmLine); } }
public static function hasAccess() { $lsIp = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ""; $lsClient = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ""; $lsToken = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : ""; $lbReturn = false; $lsStatus = "DENIED"; Debug::debug(array($lsIp, $lsClient, $lsToken)); $laAccess = Config::getOptions('access'); Debug::debug($laAccess); if (isset($laAccess[$lsIp])) { Debug::debug('1'); if (isset($laAccess[$lsIp]['user-agent'][$lsClient])) { Debug::debug('1.1'); if ($laAccess[$lsIp]['user-agent'][$lsClient] == $lsToken) { Debug::debug('1.1.1'); $lbReturn = true; } } elseif (isset($laAccess[$lsIp]['user-agent']['*'])) { Debug::debug('1.2'); if ($laAccess[$lsIp]['user-agent']['*'] == $lsToken) { Debug::debug('1.2.1'); $lbReturn = true; } } } elseif (isset($laAccess['*'])) { Debug::debug('2'); if (isset($laAccess['*']['user-agent'][$lsClient])) { Debug::debug('2.1'); if ($laAccess['*']['user-agent'][$lsClient] == $lsToken) { Debug::debug('2.1.1'); $lbReturn = true; } } elseif (isset($laAccess['*']['user-agent']['*'])) { Debug::debug('2.2'); if ($laAccess['*']['user-agent']['*'] == $lsToken) { Debug::debug('2.2.2'); $lbReturn = true; } } } if ($lbReturn) { $lsStatus = "PERMITED"; } Event::log(array("ip:[{$lsIp}]", "user-agent:[{$lsClient}]", "token:[{$lsToken}]", "status:[{$lsStatus}]"), 'access'); return $lbReturn; }
/** * * @param mixed $pmView */ public function httpView($pmView) { if ($_SERVER['HTTP_ACCEPT'] == 'application/json') { header('Content-type: application/json'); echo json_encode($pmView); } else { Debug::display($pmView); } }
/** * * @param string $psPath * @param string $psName */ public static function tarGz($psPath, $psDir) { if (file_exists($psPath)) { Debug::debug("cd {$psPath}; tar -czf {$psDir}.tar.gz {$psDir}"); self::execute("cd {$psPath}; tar -czf {$psDir}.tar.gz {$psDir}"); } else { Debug::debug($psPath . ' not found.'); } }
/** * */ public function createUserDbAction() { $lsDbDriver = $this->getRequestArg('driver', 'PDOMySql'); $lsDbCharset = $this->getRequestArg('charset', 'UTF8'); $lsDbHost = $this->getRequestArg('host', 'localhost'); $lsDbUser = $this->getRequestArg('user', null, true); $lsDbPass = $this->getRequestArg('pass', null, true); $lsDbName = $this->getRequestArg('dbname', null, true); $lsDbTable = $this->getRequestArg('table', '*'); $laDbConf = array('driver' => $lsDbDriver, 'charset' => $lsDbCharset, 'hostname' => '', 'port' => '', 'username' => '', 'password' => '', 'database' => ''); $this->_aRepository['Db'] = new InstallRepository($laDbConf); $lsScript = $this->_aRepository['Db']->createUser($lsDbHost, $lsDbUser, $lsDbPass, $lsDbName, $lsDbTable); Debug::display($lsScript); }
/** * Metodo de requisição ao servidor ou local * * @param string $psLink link para conexão e requisição ao servidor * @return string|boolean */ public function urlrequest($psLink) { $lsStream = null; $laLink = parse_url($psLink); //interpreta o link e retorna seus componentes if (isset($laLink['port'])) { //Se a porta não estiver setada no link é considerada a porta padrão $this->_nPort = $laLink['port']; } Debug::debug($laLink); //Verificando se o host está setado if (isset($laLink['host'])) { //Tentando abrir uma conexão com o servidor até o prazo limit (_nTimeOut), retornando um token de conexão //Caso ocorra algum erro, é retornado false e o número ($lnErrNo) e mensagem ($lsErrStr) do erro $lrConnection = fsockopen($laLink['host'], $this->_nPort, $lnErrNo, $lsErrStr, $this->_nTimeOut); if (!$lrConnection) { //Se a conexão não tiver sido estabelecida é gerado um log de erro Debug::debug(array("Failed to connect on server (" . $psLink . ")", $lsErrStr)); } else { $lsPost = ""; $lsGet = ""; $lsQuery = ""; $lsPath = ""; if (isset($laLink['query'])) { $lsPost = "Content-length: " . strlen($laLink['query']) . "\r\n"; $lsGet = "?" . $laLink['query']; $lsQuery = $laLink['query']; } if (isset($laLink['path'])) { $lsPath = $laLink['path']; } //Caso a conexão tenha sido estabelecida verifica o metodo de requisição if ($this->_sMethod === "POST") { $lsRequest = "POST " . $lsPath . " {$this->_sHttpVersion}\r\n"; $lsRequest .= "Host: " . $laLink['host'] . "\r\n"; $lsRequest .= "User-Agent: " . $this->_sUserAgent . "\r\n"; if (!empty($this->_sUUID)) { $lsRequest .= "UUID: " . $this->_sUUID . "\r\n"; } if (!empty($this->_sAccept)) { $lsRequest .= "Accept: " . $this->_sAccept . "\r\n"; } if (!empty($this->_sAcceptLanguage)) { $lsRequest .= "Accept-Language: " . $this->_sAcceptLanguage . "\r\n"; } if (!empty($this->_sAcceptEncoding)) { $lsRequest .= "Accept-Encoding: " . $this->_sAcceptEncoding . "\r\n"; } if (!empty($this->_sToken)) { $lsRequest .= "Token: " . $this->_sToken . "\r\n"; } if (!empty($this->_sJson)) { $lsRequest .= "Json: " . $this->_sJson . "\r\n"; } $lsRequest .= "Content-type: application/x-www-form-urlencoded; charset=" . $this->_sCharset . "\r\n"; $lsRequest .= $lsPost; $lsRequest .= "Connection: Close\r\n\r\n"; $lsRequest .= $lsQuery; } elseif ($this->_sMethod === "JSON") { $lsRequest = "POST " . $lsPath . " {$this->_sHttpVersion}\r\n"; $lsRequest .= "Host: " . $laLink['host'] . "\r\n"; $lsRequest .= "User-Agent: " . $this->_sUserAgent . "\r\n"; if (!empty($this->_sUUID)) { $lsRequest .= "UUID: " . $this->_sUUID . "\r\n"; } if (!empty($this->_sAccept)) { $lsRequest .= "Accept: " . $this->_sAccept . "\r\n"; } if (!empty($this->_sAcceptLanguage)) { $lsRequest .= "Accept-Language: " . $this->_sAcceptLanguage . "\r\n"; } if (!empty($this->_sAcceptEncoding)) { $lsRequest .= "Accept-Encoding: " . $this->_sAcceptEncoding . "\r\n"; } if (!empty($this->_sToken)) { $lsRequest .= "Token: " . $this->_sToken . "\r\n"; } $lsRequest .= "Data-type: json\r\n"; $lsRequest .= "Content-type: application/x-www-form-urlencoded; charset=" . $this->_sCharset . "\r\n"; $lsRequest .= "Content-length: " . strlen($this->_sJson) . "\r\n"; $lsRequest .= "Connection: " . $this->_sConnection . "\r\n\r\n"; $lsRequest .= "data=" . $this->_sJson . "\r\n"; } elseif ($this->_sMethod === "PUT") { $lsRequest = "PUT " . $lsPath . " {$this->_sHttpVersion}\r\n"; $lsRequest .= "Host: " . $laLink['host'] . "\r\n"; $lsRequest .= "User-Agent: " . $this->_sUserAgent . "\r\n"; if (!empty($this->_sUUID)) { $lsRequest .= "UUID: " . $this->_sUUID . "\r\n"; } if (!empty($this->_sAccept)) { $lsRequest .= "Accept: " . $this->_sAccept . "\r\n"; } if (!empty($this->_sAcceptLanguage)) { $lsRequest .= "Accept-Language: " . $this->_sAcceptLanguage . "\r\n"; } if (!empty($this->_sAcceptEncoding)) { $lsRequest .= "Accept-Encoding: " . $this->_sAcceptEncoding . "\r\n"; } if (!empty($this->_sReferer)) { $lsRequest .= "Referer: " . $this->_sReferer . "\r\n"; } if (!empty($this->_sToken)) { $lsRequest .= "Token: " . $this->_sToken . "\r\n"; } $lsRequest .= "Content-type: application/x-www-form-urlencoded; charset=" . $this->_sCharset . "\r\n"; $lsRequest .= "Content-length: " . strlen($this->_sFile) . "\r\n"; $lsRequest .= "Connection: " . $this->_sConnection . "\r\n\r\n"; $lsRequest .= $this->_sFile; } else { $lsRequest = "GET " . $lsPath . $lsGet . " {$this->_sHttpVersion}\r\n"; $lsRequest .= "Host: " . $laLink['host'] . "\r\n"; $lsRequest .= "User-Agent: " . $this->_sUserAgent . "\r\n"; if (!empty($this->_sUUID)) { $lsRequest .= "UUID: " . $this->_sUUID . "\r\n"; } if (!empty($this->_sAccept)) { $lsRequest .= "Accept: " . $this->_sAccept . "\r\n"; } if (!empty($this->_sAcceptLanguage)) { $lsRequest .= "Accept-Language: " . $this->_sAcceptLanguage . "\r\n"; } if (!empty($this->_sAcceptEncoding)) { $lsRequest .= "Accept-Encoding: " . $this->_sAcceptEncoding . "\r\n"; } if (!empty($this->_sToken)) { $lsRequest .= "Token: " . $this->_sToken . "\r\n"; } $lsRequest .= "Connection: " . $this->_sConnection . "\r\n\r\n"; } Debug::debug($lsRequest); $lbErro = false; $lbHeaderSection = true; $lsLastHeader = ""; $this->_aResponseHeader = array(); //Enviando requisição para o servidor if (!fwrite($lrConnection, $lsRequest)) { //Se a requisição falhar retorna um erro Debug::debug(array("Failed to write on server (" . $psLink . ")")); $lbErro = true; } $lsHeaderStatusLine = ''; //Lendo a requisição do servidor em pacotes while (!feof($lrConnection) && !$lbErro) { if ($lbHeaderSection) { //Lendo o cabeçado da requisição $lsHeader = fgets($lrConnection, $this->_nGetLength); if ($lsHeader !== "\r\n") { //Enquanto não chegar ao fim do cabeçalho, atribuir cada linha a um array $laHeaderLine = explode(': ', trim($lsHeader)); $lsValue = isset($laHeaderLine[1]) ? $laHeaderLine[1] : $laHeaderLine[0]; $lsVar = isset($laHeaderLine[1]) ? $laHeaderLine[0] : ''; if (!empty($lsValue) && empty($lsVar)) { $lsVar = 'Status' . $lsHeaderStatusLine; $lsHeaderStatusLine++; } if (isset($this->_aResponseHeader[$lsVar])) { $this->_aResponseHeader[$lsVar][] = $lsValue; } else { $this->_aResponseHeader[$lsVar] = $lsValue; } } else { //Se a leitura do cabeçalho chegar ao fim, fechar a seção para a leitura do conteúdo $lbHeaderSection = false; } if (!$lbHeaderSection) { //Se o cabeçalho da requisição tiver acabado, verifica o status da requisição if (!preg_match("/HTTP.*200 OK/", $this->_aResponseHeader['Status'])) { $this->_aResponseHeader['Error'] = true; //Se a requisição não encontar o arquivo e retornar um código diferente de 200, é gerado um log de erro Debug::debug(array($this->_aResponseHeader['Status'] . " (" . $psLink . ")")); $lbErro = true; } if ($this->_bCheckOnly) { //Se _bCheckOnly estiver setada como true, verifica somente o cabeçalho return !$lbErro; } } } else { //if(is_object($this->_oObj) && method_exists($this->_oObj, "trata_linha_request")) if (is_object($this->_oObject) && method_exists($this->_oObject, $this->_sCallBackMethod)) { $lsMethod = $this->_sCallBackMethod; //Lendo o arquivo do servidor e tratando linha a linha através da função callback $this->_sObject->{$lsMethod}(fgets($lrConnection, $this->_nGetLength)); } else { //Lendo o arquivo do servidor e armazenando em uma string $lsStream .= fgets($lrConnection, $this->_nGetLength); } } } if ($this->_bClose) { //Se a conexão deve ser fechada ao final da requisição e leitura fclose($lrConnection); } if (!$lbErro && isset($this->_aResponseHeader['Content-Encoding']) && $this->_aResponseHeader['Content-Encoding'] == 'gzip') { $lsStream = gzdecode($lsStream); } //Retornando o conteúdo do arquivo return $lsStream; } } //Retorno falso caso não tenha estabelicido a conexão com o servidor return false; }
$gbDebug = true; $gbTime = true; } if (isset($_GET['time'])) { $gbTime = true; } if (isset($_GET['test'])) { $gbTest = true; } } use OnionSrv\Config; Config::setDebugMod($gbDebug, $gbPhpError, $gbTime, $gbTest, $gbPrompt); Config::setTimeZone(); OnionSrv\Autoload::autoload($goLoader); use OnionSrv\Debug; Debug::debugTimeStart("init"); if (PHP_SAPI == "cli") { $goService = new OnionSrv\LineService(); $goService->serviceRoute(); } else { if (OnionSrv\Access::hasAccess()) { $goService = new OnionSrv\HttpService(); $goService->serviceRoute(); } else { header('HTTP/1.1 403 Forbidden'); exit(403); } } Debug::debugTimeEnd("init"); Debug::debug($gaTimer, TIMESHOW);
/** * * @param string $psCommand * @return bool */ public function checkCommandLine($psCommand) { $laCommandReturn = System::execute("command -v {$psCommand}"); Debug::debug($laCommandReturn); if (is_array($laCommandReturn) && count($laCommandReturn) > 0) { return true; } return false; }
/** * */ public static function serviceRoute() { global $goLoader; Debug::debug($_SERVER['argv']); if (isset($_SERVER['argv']) && is_array($_SERVER['argv'])) { $lsModule = ''; $lsController = ''; $lsAction = ''; $laParams = array(); foreach ($_SERVER['argv'] as $lsArg) { $laArg = explode("=", $lsArg); switch ($laArg[0]) { case '--module': case '--m': case '-m': $lsModule = $laArg[1]; break; case '--controller': case '--c': case '-c': $lsController = $laArg[1]; break; case '--action': case '--a': case '-a': $lsAction = $laArg[1]; break; default: if (isset($laArg[1])) { $laParams['ARG'][$laArg[0]] = $laArg[1]; } break; } } if (empty($lsModule)) { $lsModule = $lsAction; } if (empty($lsController)) { $lsController = $lsModule; } if (empty($lsAction)) { $lsAction = $lsController; } if (empty($lsModule) && empty($lsController) && empty($lsAction)) { $lsModule = $lsController = $lsAction = 'index'; } $lsPath = Autoload::getNamespace(ucfirst($lsModule), $goLoader); $lsService = $lsPath . DS . ucfirst($lsModule) . DS . 'Controller' . DS . ucfirst($lsController) . "Controller.php"; $lsClass = '\\' . ucfirst($lsModule) . '\\' . 'Controller' . '\\' . ucfirst($lsController) . "Controller"; if (TESTMOD) { $lsMethod = $lsAction . 'Test'; } else { $lsMethod = $lsAction . 'Action'; } $laService['service'] = $lsService; $laService['class'] = $lsClass; $laService['method'] = $lsMethod; $laService['module'] = ucfirst($lsModule); $laService['controller'] = ucfirst($lsController); $laService['action'] = $lsAction; Debug::debug($laService); Debug::debug($laParams); self::run($laService, $laParams); } else { //Se o service não foi encontrado System::exitError("Params not found!"); } }
/** * * @param array $paError */ public function setError($paError) { $this->_aError = $paError; Debug::debug($this->_aError); return $this; }
public static function serviceRoute() { global $goLoader; Debug::debug($_SERVER['REQUEST_URI']); if (isset($_SERVER['REQUEST_URI'])) { $laParams = null; if (isset($_GET)) { $laParams['GET'] = $_GET; } if (isset($_POST)) { $laParams['POST'] = $_POST; } if (isset($_SERVER['Data-type']) && $_SERVER['Data-type'] == 'json' && isset($_SERVER['data'])) { $laParams['JSON'] = $_SERVER['data']; } if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'PUT') { $laParams['PUT'] = System::getPutData(); } if (isset($_FILES)) { $laParams['FILES'] = $_FILES; } //Separando o caminho e verificando quantos elementos tem $laRequestUri = explode("/", $_SERVER['REQUEST_URI']); $lnCount = 0; $lsQueryString = "?" . $_SERVER['QUERY_STRING']; //Removendo elementos vazios foreach ($laRequestUri as $lsPathUrl) { if (!empty($lsPathUrl) && $lsPathUrl != $lsQueryString) { $laPathUrl = explode('-', $lsPathUrl); $lsValueName = $laPathUrl[0]; unset($laPathUrl[0]); if (count($laPathUrl) > 0) { foreach ($laPathUrl as $lsValue) { $lsValueName .= ucfirst($lsValue); } } $laPath[] = $lsValueName; $lnCount++; } } if ($lnCount == 0) { $laPath[0] = 'index'; $lnCount = 1; } $laService['module'] = ucfirst($laPath[0]); $lsPath = Autoload::getNamespace($laService['module'], $goLoader); switch ($lnCount) { case 1: $lsService = $lsPath . DS . $laService['module'] . DS . 'Controller' . DS . $laService['module'] . "Controller.php"; $lsClass = '\\' . $laService['module'] . '\\Controller\\' . $laService['module'] . 'Controller'; $laService['controller'] = $laService['module']; $laService['action'] = $laPath[0]; break; case 2: $lsService = $lsPath . DS . $laService['module'] . DS . 'Controller' . DS . $laService['module'] . "Controller.php"; $lsClass = '\\' . $laService['module'] . '\\Controller\\' . $laService['module'] . 'Controller'; $laService['controller'] = $laService['module']; $laService['action'] = $laPath[1]; break; default: $lsService = $lsPath . DS . $laService['module'] . DS . 'Controller' . DS . ucfirst($laPath[1]) . "Controller.php"; $lsClass = '\\' . $laService['module'] . '\\' . 'Controller' . '\\' . ucfirst($laPath[1]) . "Controller"; $laService['controller'] = ucfirst($laPath[1]); $laService['action'] = $laPath[2]; } if (TESTMOD) { $lsMethod = $laService['action'] . 'Test'; } else { $lsMethod = $laService['action'] . 'Action'; } $laService['service'] = $lsService; $laService['class'] = $lsClass; $laService['method'] = $lsMethod; Debug::debug($laService); Debug::debug($laParams); self::run($laService, $laParams); } else { //Se o service não foi encontrado, retornar 404 not found para o client if (DEBUG) { Debug::debug("Service Not Found"); } else { header("HTTP/1.1 404 Service Not Found"); } exit(404); } }
/** * * @param object $poEntity * @return boolean */ public function delete($poEntity) { $lsWhere = $this->getWhere($poEntity); if ($this->createQueryDelete($poEntity, $lsWhere, 1)) { if ($this->connect()) { $loStantement = $this->prepare(); $lbReturn = $loStantement->execute(); if ($lbReturn) { Debug::debug("SQL delete OK"); } else { $this->setError($loStantement->errorInfo()); } } } $this->close(); return $lbReturn; }