public function __get($name)
 {
     if ($name == 'tpl') {
         if (!$this->_templateInitialized) {
             $this->initTemplate();
         }
         return $this->_template;
     }
     if ($name == 'router') {
         return Router::getInstance();
     }
     if ($name == 'session') {
         return Session::getInstance();
     }
     if ($name == 'config') {
         return Config::getInstance();
     }
     if ($name == 'log') {
         return Logger::getInstance();
     }
     if ($name == 'language') {
         return Language::getInstance();
     }
     if ($name == 'model') {
         return Model::getInstance();
     }
 }
예제 #2
0
 public static function sentHeader($directiveName, $directiveValue, $replace = true, $responseCode = null, $checkIfHeaderSent = true, $directiveSeparator = ':')
 {
     if (!is_bool($checkIfHeaderSent)) {
         throw new \Exception('CheckIfHeaderSent parameter must be an boolean');
     }
     if (!is_bool($replace)) {
         throw new \Exception('replace parameter must be an boolean');
     }
     if (!is_null($responseCode) && !ResponseCode::isValid($responseCode)) {
         throw new \Exception('forceResponseCode parameter must be a valid http response code');
     }
     if (!is_string($directiveValue)) {
         throw new \Exception('Directive value parameter must be a string');
     }
     if (!in_array(strtolower((string) $directiveName), self::$_directivesList)) {
         throw new \Exception('Directive name : "' . $directiveName . '" must be a valid directive');
     }
     if ($checkIfHeaderSent) {
         if (!headers_sent()) {
             self::_sentHeader($directiveName, $directiveValue, $replace, $responseCode, $directiveSeparator);
         } else {
             Logger::getInstance()->notice('Try to send header when is already sent');
         }
     } else {
         Logger::getInstance()->notice('Try to send header but you don\'t check if is already sent');
         self::_sentHeader($directiveName, $directiveValue, $replace, $responseCode, $directiveSeparator);
     }
 }
예제 #3
0
파일: Prompt.php 프로젝트: Cendre/Fw
 private function prompt()
 {
     echo $this->commandManager->getPromptString();
     $get = fgets($this->in);
     $get = str_replace("\n", "", $get);
     $get = str_replace("\r", "", $get);
     $params = explode(" ", $get);
     try {
         $this->out($this->getCommand($params[0], $params));
     } catch (CommandNotFoundException $e) {
         $this->out('Commande ' . $get . ' inconnue');
     } catch (\Exception $e) {
         $this->out($e->getMessage());
         $this->logger->warning($e->getMessage());
     }
     $this->prompt();
 }
예제 #4
0
 public static function defineCons()
 {
     foreach (self::$_constants as $name => $value) {
         if (defined($name)) {
             Logger::getInstance()->debug('Constant ' . $name . ' already defined');
             continue;
         }
         define($name, $value);
     }
 }
예제 #5
0
 public function update(\SplSubject $subject, $isException = false)
 {
     if (!$isException) {
         $error = $subject->getError();
         $typeLog = $error->code == 'E_FATAL' ? 'fatal' : 'error';
         Logger::getInstance()->{$typeLog}(ucfirst($error->type) . ' : ' . $error->message . ' in ' . $error->file . ' on line ' . $error->line, 'error');
     } else {
         $exception = $subject->getException();
         Logger::getInstance()->fatal('Exception' . ' : "' . $exception->message . '" in ' . $exception->file . ' on line ' . $exception->line . ' with trace : ' . chr(10) . $exception->trace, 'error');
     }
 }
예제 #6
0
 protected static function _factory($type, $options = array())
 {
     if (class_exists('framework\\security\\' . ucfirst($type))) {
         $class = 'framework\\security\\' . ucfirst($type);
     } else {
         $class = $type;
     }
     $classInstance = new \ReflectionClass($class);
     if (!in_array('framework\\security\\ISecurity', $classInstance->getInterfaceNames())) {
         throw new \Exception('Security class must be implement framework\\security\\ISecurity');
     }
     if ($classInstance->isAbstract()) {
         throw new \Exception('Security class must be not abstract class');
     }
     if ($classInstance->isInterface()) {
         throw new \Exception('Security class must be not interface');
     }
     Logger::getInstance()->addGroup('security', 'Security report', true, true);
     return $classInstance->newInstance($options);
 }
예제 #7
0
 public function parse()
 {
     ob_start();
     try {
         if (!is_null($this->_file)) {
             include $this->_path . $this->_file;
             $this->_content = ob_get_clean();
             Logger::getInstance()->debug('Parse template file', 'template' . $this->_name);
         }
     } catch (\Exception $e) {
         ob_end_clean();
         throw $e;
     }
 }
예제 #8
0
}
// Autoloader cache
if (defined('AUTOLOADER_CACHE') && !static::getDebug()) {
    Autoloader::setCache(AUTOLOADER_CACHE);
    //Globalize essentials classes
    if (defined('AUTOLOADER_GLOBALIZER') && AUTOLOADER_GLOBALIZER) {
        $globalizer = new Globalizer(static::getGlobalizeClassList(), true);
        $globalizer->loadGlobalizedClass();
    }
}
// Add vendors directory
Autoloader::addDirectory(PATH_VENDORS);
// Exception, Error and Logger management
$exc = ExceptionManager::getInstance()->start();
$err = ErrorManager::getInstance()->start(true, static::getDebug(), static::getDebug());
$log = Logger::getInstance();
// Set language
if (!defined('PATH_LANGUAGE')) {
    throw new \Exception('Miss language path datas');
}
Language::setDatasPath(PATH_LANGUAGE);
$language = Language::getInstance();
if (!defined('LANGUAGE_DEFAULT')) {
    throw new \Exception('Miss language default');
}
$language->setLanguage(LANGUAGE_DEFAULT, true, true);
// Set default template
if (defined('TEMPLATE_DEFAULT')) {
    Template::setTemplate(TEMPLATE_DEFAULT);
}
//Enable debug tools
예제 #9
0
 public function clearGroups()
 {
     foreach ($this->_groups as &$group) {
         $this->clearGroup($group);
     }
     Logger::getInstance()->debug('Cache cleared groups', 'cache' . $this->_name);
 }
예제 #10
0
 public function logQuery($query, $params = array(), $bindParamType = null, $lastError = null)
 {
     if (!is_array($params)) {
         throw new \Exception('Params must be an array');
     }
     // Query
     Logger::getInstance()->debug('Query : ' . $query, 'database' . $this->getName());
     if (count($params) > 0) {
         // Parameters
         Logger::getInstance()->debug('Params (' . count($params) . ') bind by ' . $this->_getBindParamType($bindParamType), 'database' . $this->getName());
         if ($bindParamType == self::PARAM_BIND_POSITIONAL) {
             $i = 0;
         }
         foreach ($params as &$param) {
             $key = $bindParamType == self::PARAM_BIND_POSITIONAL ? $i : $param['key'];
             Logger::getInstance()->debug('Key : ' . $key . ', Value : ' . $param['value'] . ', Type : ' . (int) $param['type'] . ' (' . self::$_paramTypeName[$param['type']] . '), IsParam : ' . (int) $param['isParam'], 'database' . $this->getName());
             if ($bindParamType == self::PARAM_BIND_POSITIONAL) {
                 $i++;
             }
         }
     }
     // Benchmark
     $time = Benchmark::getInstance($this->getName())->stopTime()->getStatsTime();
     $ram = Benchmark::getInstance($this->getName())->stopRam()->getStatsRam();
     Logger::getInstance()->debug('Benchmark time : ' . $time . ' ms Ram : ' . $ram, 'database' . $this->getName());
     // Error
     if (!is_null($lastError)) {
         Logger::getInstance()->debug('Error : ' . $lastError, 'database' . $this->getName());
     }
     // increment stats
     $this->setStats($time, $ram);
     $this->incrementQueryCount();
 }
예제 #11
0
 public function check($checkingValue, $flush = false)
 {
     if (is_null($this->_token)) {
         return false;
     }
     $tokenRealValue = Session::getInstance()->get($this->getFormName() . 'CsrfToken');
     $tokenTimeRealValue = Session::getInstance()->get($this->getFormName() . 'CsrfTokenTime');
     if ($flush) {
         $this->flush();
     }
     if (is_null($tokenRealValue)) {
         Logger::getInstance()->debug('Crsf : "' . $this->getFormName() . '" token miss"', 'security');
         return false;
     }
     if ($this->_timeValidity > 0 && is_null($tokenTimeRealValue)) {
         Logger::getInstance()->debug('Crsf : "' . $this->getFormName() . '" tokenTime miss"', 'security');
         return false;
     }
     if (!empty($this->_urlsReferer)) {
         foreach ($this->_urlsReferer as &$url) {
             if (stripos(Http::getServer('HTTP_REFERER'), $url) !== false || Http::getServer('HTTP_REFERER') == $url) {
                 $match = true;
                 break;
             }
         }
         if (!isset($match)) {
             Logger::getInstance()->debug('Crsf : "' . $this->getFormName() . '" url referer : "' . Http::getServer('HTTP_REFERER'), 'security');
             return false;
         }
     }
     if ($tokenRealValue != $checkingValue) {
         Logger::getInstance()->debug('Crsf : "' . $this->getFormName() . '" token : "' . $checkingValue . '" invalid, need : "' . $tokenRealValue . '" value', 'security');
         return false;
     }
     if ($tokenTimeRealValue <= time() - $this->_timeValidity) {
         Logger::getInstance()->debug('Crsf : "' . $this->getFormName() . '" tokenTime too old"', 'security');
         return false;
     }
     return true;
 }
예제 #12
0
 public function execute($returnTransfer = false, $includeHeader = false, $timeOut = false, $encodePostFieldsJson = false)
 {
     if (!$this->_getCurlInitialized()) {
         throw new \Exception('Curl must be initialized');
     }
     if (!is_bool($includeHeader)) {
         throw new \Exception('Include header parameter must be a boolean');
     }
     if (!is_bool($returnTransfer)) {
         throw new \Exception('ReturnTransfer parameter must be a boolean');
     }
     if ($timeOut && !is_int($timeOut)) {
         throw new \Exception('TimeOut parameter must be an integer');
     }
     $this->setCurlOpt(CURLOPT_URL, $this->getUrl() . $this->getArgumentsGet(true));
     $this->setCurlOpt(CURLOPT_HEADER, $includeHeader);
     $this->setCurlOpt(CURLOPT_RETURNTRANSFER, $returnTransfer);
     if ($this->getArgumentsPost() !== array()) {
         $posts = $encodePostFieldsJson ? json_encode($this->getArgumentsPost()) : $this->getArgumentsPost(true);
         $this->setCurlOpt(CURLOPT_POST, 1);
         $this->setCurlOpt(CURLOPT_POSTFIELDS, $posts);
     }
     if ($timeOut) {
         $this->setCurlOpt(CURLOPT_TIMEOUT, $timeOut);
     }
     $this->_response = curl_exec($this->getCurl());
     if (!$this->getResponse()) {
         Logger::getInstance()->error('Curl error message : "' . $this->getCurlErrorMsg() . '" and code : "' . $this->getCurlErrorCode() . '"');
         return false;
     } else {
         $info = curl_getinfo($this->getCurl());
         Logger::getInstance()->debug('Curl query took ' . $info['total_time'] . ' seconds to be sent to the url: "' . $info['url'] . '"');
         return true;
     }
 }
예제 #13
0
 public function expand($shortUrlHash, $returnFullReponse = false)
 {
     if (!is_string($shortUrlHash)) {
         throw new \Exception('shortUrl parameter must be a string');
     }
     if (!is_bool($returnFullReponse)) {
         throw new \Exception('returnFullReponse parameter must be an boolean');
     }
     $curl = new Curl($this->getApiUrl());
     if ($this->getApiKey()) {
         $curl->addArgument('apiKey', $this->getApiKey(), 'GET');
     }
     $curl->addArgument('shortUrl', 'http://goo.gl/' . $shortUrlHash, 'GET');
     $curl->execute(true);
     $reponse = json_decode($curl->getResponse());
     if ($returnFullReponse) {
         return $reponse;
     } else {
         if (isset($reponse->error)) {
             Logger::getInstance()->debug('Goo.gl expand url error, code : "' . $reponse->error->code . '" and message : "' . $reponse->error->message . '"');
             return false;
         }
         if ($reponse->status == 'OK') {
             Logger::getInstance()->debug('Goo.gl expand url  : "http://goo.gl/' . $shortUrlHash . '" result is : "' . $reponse->longUrl . '"');
             return $reponse->longUrl;
         }
         return false;
     }
 }
예제 #14
0
 public function stop()
 {
     if ($this->_isInit && $this->_isRun) {
         // run caches gc
         $caches = Cache::getCaches();
         foreach ($caches as $cache) {
             $cache->runGc();
         }
         //profiling
         if (self::getProfiler()) {
             // Caches
             foreach ($caches as $cache) {
                 Logger::getInstance()->debug('Adaptater : "' . get_class($cache) . '"', 'cache' . $cache->getName());
             }
             // Databases
             $databases = Database::getDatabases();
             foreach ($databases as $database) {
                 Logger::getInstance()->debug('Type : ' . $database->getType(), 'database' . $database->getName());
                 Logger::getInstance()->debug('Adaptater : ' . get_class($database->getAdaptater()), 'database' . $database->getName());
                 $stats = $database->getStats();
                 Logger::getInstance()->debug('Queries : ' . (string) $database->getQueryCount() . ' (Aproximately memory used  : ' . $stats['ram'] . ' KB in aproximately ' . $stats['time'] . ' ms)', 'database' . $database->getName());
                 Logger::getInstance()->debug('Servers : ' . $database->countServers() . ' (Masters : ' . $database->countServers(Server::TYPE_MASTER) . '  Slaves : ' . $database->countServers(Server::TYPE_SLAVE) . ')', 'database' . $database->getName());
             }
             // Templates
             $templates = Template::getTemplates();
             foreach ($templates as $template) {
                 Logger::getInstance()->debug('Adaptater : ' . get_class($template), 'template' . $template->getName());
             }
             // Language
             Logger::getInstance()->debug('Language default is : "' . Language::getInstance()->getDefaultLanguage() . '"', 'language');
             Logger::getInstance()->debug(Language::getInstance()->countVars() . ' vars defined', 'language');
             // Router
             Logger::getInstance()->debug('Current url : ' . Http::getCurrentUrl(), 'router');
             Logger::getInstance()->debug('Current route : ' . Router::getInstance()->getCurrentRoute(), 'router');
             Logger::getInstance()->debug('Current route rule : ' . Router::getInstance()->getCurrentRule(), 'router');
             Logger::getInstance()->debug('Ajax request : ' . (int) Http::isAjax(), 'router');
             Logger::getInstance()->debug('Ssl request : ' . (int) Http::isHttps(), 'router');
             Logger::getInstance()->debug('Request dispatched in aproximately : ' . Benchmark::getInstance('router')->stopTime()->getStatsTime() . ' ms', 'router');
             Logger::getInstance()->debug('Aproximately memory used  : ' . Benchmark::getInstance('router')->stopRam()->getStatsRam() . ' KB', 'router');
             // Logger debug informations and benchmark
             Logger::getInstance()->addGroup('logger', 'Logger Benchmark and Informations', true);
             Logger::getInstance()->debug(Logger::getInstance()->countObservers() . ' observers registered', 'logger');
             Logger::getInstance()->debug(Logger::getInstance()->countGroups() . ' groups and ' . (Logger::getInstance()->countLogs() + 3) . ' logs', 'logger');
             Logger::getInstance()->debug('In aproximately ' . Benchmark::getInstance('logger')->stopTime()->getStatsTime() . ' ms', 'logger');
             Logger::getInstance()->debug('Aproximately memory used  : ' . Benchmark::getInstance('logger')->stopRam()->getStatsRam() . ' KB', 'logger');
             // Autoloader
             Logger::getInstance()->addGroup('autoloader', 'Autoloader report', true);
             $logs = Autoloader::getLogs();
             foreach ($logs as &$log) {
                 Logger::getInstance()->debug($log, 'autoloader');
             }
             Logger::getInstance()->debug(count(Autoloader::getAutoloaders()) . ' autoloader adaptaters, ' . count(Autoloader::getDirectories()) . ' directories and ' . count(Autoloader::getNamespaces()) . ' namespaces registered', 'autoloader');
             Logger::getInstance()->debug('Loading ' . count(Autoloader::getClasses()) . ' classes (' . Autoloader::countGlobalizedClasses() . ' globalized classes)  in aproximately ' . round(Autoloader::getBenchmark('time') * 1000, 4) . ' ms', 'autoloader');
             Logger::getInstance()->debug('Aproximately memory used  : ' . round(Autoloader::getBenchmark('memory') / 1024, 4) . ' KB', 'autoloader');
             Autoloader::purgeLogs();
             Autoloader::purgeBenchmark();
             // Global informations && Benchmark
             Logger::getInstance()->addGroup('global', 'Global Benchmark and Informations', true);
             Logger::getInstance()->debug('Page generated in aproximately : ' . Benchmark::getInstance('global')->stopTime()->getStatsTime() . ' ms', 'global');
             Logger::getInstance()->debug('Aproximately memory used  : ' . Benchmark::getInstance('global')->stopRam()->getStatsRam() . ' KB - Memory allocated : ' . memory_get_peak_usage(true) / 1024 . ' KB', 'global');
         }
         //notify logger
         Logger::getInstance()->notify();
         // Stop managers
         ExceptionManager::getInstance()->stop();
         ErrorManager::getInstance()->stop();
         // avoid multi call
         $this->_isInit = false;
         $this->_isRun = false;
     }
 }
예제 #15
0
 public function clearGroup($groupName)
 {
     $dirs = Tools::cleanScanDir($this->_path);
     foreach ($dirs as &$f) {
         if (is_file($this->_path . $f)) {
             //is not a lock
             if (stripos($f, $this->_prefix . $this->_prefixGroups . md5('lock')) == false) {
                 // find
                 if (stripos($f, $groupName) !== false) {
                     $file = new \SplFileObject($this->_path . $f, 'r');
                     $data = unserialize(base64_decode($file->fgets()));
                     $key = isset($data[1]) ? $data[1] : $f;
                     $this->delete($key);
                 }
             }
         }
     }
     Logger::getInstance()->debug('Cache cleared group : "' . $groupName . '"', 'cache' . $this->_name);
 }
예제 #16
0
 public function setLanguage($language, $setAsDefault = false)
 {
     if (!Validate::isLanguage($language)) {
         throw new \Exception('Invalid lang format');
     }
     Logger::getInstance()->debug('Try load language : "' . $language . '"', 'language');
     //check datas files
     $file = self::getDatasPath() . $language . '.xml';
     if (!file_exists($file)) {
         if (!$setAsDefault) {
             Logger::getInstance()->debug('Invalid lang : "' . $language . '", have not xml datas file', 'language');
             return;
         }
         throw new \Exception('Invalid lang : "' . $language . '", have not xml datas file');
     }
     $xml = simplexml_load_file($file);
     if (is_null($xml) || !$xml) {
         throw new \Exception('Invalid lang : "' . $language . '" invalid xml file');
     }
     Logger::getInstance()->debug('Load datas file : "' . $file . '"', 'language');
     //delete comment
     unset($xml->comment);
     // set language
     self::$_languageVars = $xml;
     $this->_language = $language;
     if ($setAsDefault) {
         $this->_defaultLanguage = $this->_language;
         self::$_defaultLanguageVars = self::$_languageVars;
         Logger::getInstance()->debug('Language : "' . $this->_language . '" defined as default', 'language');
     }
     //Check if alls vars defined
     if ($this->_defaultLanguage != $this->_language) {
         foreach (self::$_defaultLanguageVars as $name => $value) {
             if (!property_exists(self::$_languageVars, $name)) {
                 Logger::getInstance()->debug('Miss language var : "' . $name . '" on new language : "' . $language . '"', 'language');
                 // restore var, by default language
                 self::$_languageVars->{$name} = self::$_defaultLanguageVars->{$name};
             }
         }
     }
     Logger::getInstance()->debug('Current language is : "' . $this->_language . '"', 'language');
 }
예제 #17
0
 public function clearGroup($groupName)
 {
     $this->purge($groupName);
     Logger::getInstance()->debug('Cache cleared group : "' . $groupName . '"', 'cache' . $this->_name);
 }
예제 #18
0
 public function login($username = '******', $password = '******')
 {
     if (!$this->getConn()) {
         throw new \Exception('No etablished connexion ...');
     }
     $this->setUsername($username);
     $this->setPassword($password);
     ftp_raw($this->getConn(), 'USER ' . $this->getUsername());
     $logRep = ftp_raw($this->getConn(), 'PASS ' . $this->getPassword());
     if (strpos($logRep[0], '230') !== false) {
         Logger::getInstance()->debug('Login to the ftp server with username "' . $this->getUsername() . '" and password "' . $this->getPassword() . '" succefull');
         return true;
     } else {
         Logger::getInstance()->debug('Login to the ftp server with username "' . $this->getUsername() . '" and password "' . $this->getPassword() . '" failed');
         return false;
     }
 }
예제 #19
0
 protected function _runController($controller, $methods = array(), $vars = array(), $requireSsl = false, $requireAjax = false, $autoSetAjax = true, $requireHttpMethod = null, $httpResponseStatusCode = null, $httpProtocol = null)
 {
     $controllerExplode = explode($this->getNamespaceSeparator(), (string) $controller);
     if (is_array($controllerExplode) && count($controllerExplode) > 1) {
         $controllerName = $this->getNamespaceSeparator() . ucfirst(array_pop($controllerExplode));
         $controller = implode($this->getNamespaceSeparator(), $controllerExplode) . $controllerName;
     } else {
         $controller = (string) ucfirst($controller);
     }
     Logger::getInstance()->debug('Run controller : "' . $controller . '"', 'router');
     $controllerClass = $this->getControllersNamespace(true) . $controller;
     // Check if controller exists (with controllers namespace)
     if (!class_exists($controllerClass)) {
         throw new \Exception('Controller "' . $controllerClass . '" not found');
     }
     $controller = $controllerClass;
     if (!is_array($vars)) {
         throw new \Exception('Controller : "' . $controller . '" vars must be an array');
     }
     if (!is_array($methods)) {
         throw new \Exception('Controller : "' . $controller . '" methodes must be an array');
     }
     $inst = new \ReflectionClass($controller);
     if ($inst->isInterface() || $inst->isAbstract()) {
         throw new \Exception('Controller "' . $controller . '" cannot be an interface of an abstract class');
     }
     $ctrl = $inst->newInstance();
     if ($ctrl->getAutoCallDisplay()) {
         if (!$inst->hasMethod('display')) {
             throw new \Exception('Controller "' . $controller . '" must be implement method "Diplay');
         }
         if (!$inst->hasMethod('initTemplate')) {
             throw new \Exception('Controller "' . $controller . '" must be implement method "initTemplate');
         }
     }
     if (!Cli::isCli()) {
         if (!Http::isHttps() && $requireSsl) {
             Logger::getInstance()->debug('Controller "' . $controller . '" need ssl http request', 'router');
             $this->show400(true);
         }
         if (!is_null($requireHttpMethod)) {
             if ($requireHttpMethod != Http::getMethod()) {
                 Logger::getInstance()->debug('Controller "' . $controller . '" invalid http method');
                 $this->show405(true);
             }
         }
         if (!Http::isAjax() && $requireAjax) {
             Logger::getInstance()->debug('Controller "' . $controller . '" need ajax http request');
             $this->show400(true);
         }
         if (Http::isAjax() && $autoSetAjax) {
             $ctrl->setAjaxController();
         }
         if (!is_null($httpResponseStatusCode) || !is_null($httpProtocol)) {
             Header::setResponseStatusCode(is_null($httpResponseStatusCode) ? 200 : $httpResponseStatusCode, true, true, $httpProtocol);
         }
     }
     if ($methods) {
         foreach ($methods as $methodName => $methodParams) {
             Logger::getInstance()->debug('Call method : "' . $methodName . '"', 'router');
             if (!method_exists($ctrl, $methodName) || !$inst->getMethod($methodName)->isPublic()) {
                 throw new \Exception('Method "' . $methodName . '" don\'t exists or isn\'t public on controller "' . $controller . '"');
             }
             $args = array();
             if (!is_array($methodParams)) {
                 $args[] = $methodParams;
             } else {
                 foreach ($methodParams as $parameter) {
                     //check if is [['key']] type, or direct value
                     if (stripos($parameter, '[[') === false) {
                         $args[] = $parameter;
                     } else {
                         if (count($vars) > 0) {
                             $key = (int) str_replace(array('[', ']'), '', $parameter);
                             if (array_key_exists($key, $vars)) {
                                 $args[] = $vars[$key];
                             }
                         } else {
                             $args[] = $parameter;
                         }
                     }
                 }
             }
             foreach ($args as $arg) {
                 Logger::getInstance()->debug('Add argument : "' . $arg . '"', 'router');
             }
             // Call method with $args
             \call_user_func_array(array($ctrl, $methodName), $args);
         }
     }
     $this->_controller = $ctrl;
     //call display only when have a template
     if ($ctrl->getAutoCallDisplay() && Template::getTemplate()) {
         Logger::getInstance()->debug('Call method "display"', 'router');
         $ctrl->display();
     }
 }
예제 #20
0
 private function _displayLog($message, $level, $date, $isTrace = false)
 {
     $name = $isTrace ? 'TRACE' : Logger::getLevelName($level);
     $head = '[' . $date . '][' . $name . '] ';
     echo $head . $message . chr(10);
 }
예제 #21
0
 public function execute($checkBindNumber = true)
 {
     if (Application::getDebug()) {
         Benchmark::getInstance($this->_configName)->startTime()->startRam();
     }
     if (is_null($this->_query) || !$this->_statement) {
         throw new \Exception('Prepare query before execute');
     }
     if ($checkBindNumber) {
         if (count($this->_params) < $this->_paramsNumberNecesary) {
             throw new \Exception('Miss bind parameters');
         }
     }
     // Bind parameters
     $i = 0;
     foreach ($this->_params as $param) {
         $bindName = $this->_bindParamType === Database::PARAM_BIND_POSITIONAL ? $i + 1 : ':' . $this->_namedParamOrder[$i];
         if ($param['isParam']) {
             $this->_statement->bindParam($bindName, $param['value'], $param['type']);
         } else {
             $this->_statement->bindValue($bindName, $param['value'], $param['type']);
         }
         $i++;
     }
     // Execute
     $this->_execute = $this->_statement->execute();
     //check error
     $lastError = $this->getLastError(true);
     if (!is_null($lastError)) {
         Logger::getInstance()->error('Sql query : ' . $this->_query . ' has error : ' . $lastError);
     }
     // Debug
     if (Application::getDebug()) {
         Database::getDatabase($this->_configName)->logQuery($this->_query, $this->_params, $this->_bindParamType, $lastError);
     }
     return $this->_execute;
 }
예제 #22
0
 protected function _createAudio()
 {
     if (is_null($this->_key)) {
         throw new \Exception('Key must be generated');
     }
     // TODO need get IT, DE and ES audio files
     //http://www.gilles-joyeux.fr/MP3/NEn.mp3 letters
     //http://www.gilles-joyeux.fr/MP3/ten.mp3 numbers
     // revoir les sons S et F en anglais ...
     try {
         $globalWavFile = new \WavFile();
         // Set sample rate, bits/sample, and Num of channels // TODO setter and getter this params ?
         $globalWavFile->setSampleRate(8000);
         $globalWavFile->setBitsPerSample(8);
         $globalWavFile->setNumChannels(1);
         $letters = str_split(strtoupper($this->_key));
         foreach ($letters as $letter) {
             if (!file_exists($this->_audioLangDirectory . $letter . '.wav')) {
                 throw new \Exception('Audio file : "' . $this->_audioLangDirectory . $letter . '.wav' . '" miss');
             }
             $l = new \WavFile($this->_audioLangDirectory . $letter . '.wav');
             // append letter to the captcha audio
             $globalWavFile->appendWav($l);
             // random silence  between letters
             $globalWavFile->insertSilence(mt_rand($this->_audioLettersGapMin, $this->_audioLettersGapMax) / 1000.0);
             //rand min and max
         }
         // Add filters
         $filters = array();
         // noise by sound file
         if ($this->_audioNoise) {
             // use background audio
             $wavNoise = new \WavFile($this->_audioNoiseFile, false);
             $wavNoise->setSampleRate($globalWavFile->getSampleRate())->setBitsPerSample($globalWavFile->getBitsPerSample())->setNumChannels($globalWavFile->getNumChannels());
             // start at a random offset from the beginning of the wav file in order to add more randomness
             $randOffset = 0;
             if ($wavNoise->getNumBlocks() > 2 * $globalWavFile->getNumBlocks()) {
                 $randBlock = rand(0, $wavNoise->getNumBlocks() - $globalWavFile->getNumBlocks());
                 $wavNoise->readWavData($randBlock * $wavNoise->getBlockAlign(), $globalWavFile->getNumBlocks() * $wavNoise->getBlockAlign());
             } else {
                 $wavNoise->readWavData();
                 $randOffset = rand(0, $wavNoise->getNumBlocks() - 1);
             }
             $mixOpts = array('wav' => $wavNoise, 'loop' => true, 'blockOffset' => $randOffset);
             $filters[\WavFile::FILTER_MIX] = $mixOpts;
             $filters[\WavFile::FILTER_NORMALIZE] = $this->_audioNoiseMixNormalization;
         }
         // add random noise. Any noise level below 95% is intensely distorted and not pleasing to the ear
         if ($this->_audioDegrade) {
             $filters[\WavFile::FILTER_DEGRADE] = rand(95, 98) / 100.0;
         }
         // apply filters to audio file
         if (count($filters) > 0) {
             $globalWavFile->filter($filters);
         }
         // save
         $this->_audioContents = $globalWavFile->makeHeader();
         $this->_audioContents .= $globalWavFile->getDataSubchunk();
         unset($globalWavFile);
     } catch (\Exception $e) {
         Logger::getInstance()->debug('Security captcha generate audio file for form : "' . $this->getFormName() . '" error : "' . $e . '"', 'security');
         if (file_exists($this->_audioLangDirectory . 'error.wav')) {
             $this->_audioContents = file_get_contents($this->_audioLangDirectory . 'error.wav');
         }
     }
 }
예제 #23
0
 protected function _check($generateValue)
 {
     if ($this->getChecked()) {
         return true;
     }
     switch ($this->getBruteType()) {
         case self::FTP:
             if (!$this->_ftp) {
                 $this->_ftp = new Ftp($this->_bruteTypeOptions['host'], 21, 10, false);
                 $this->_ftp->setDebug(true);
                 if (!$this->_ftp->connect()) {
                     $this->_ftp = false;
                     Logger::getInstance()->debug('BruteForce error: connection on ftp server failed');
                     exit;
                 }
             }
             if ($this->_ftp->login($this->_bruteTypeOptions['username'], $generateValue)) {
                 $this->_setChecked(true);
                 $this->_setFoundValue($generateValue);
                 return true;
             } else {
                 return false;
             }
             break;
         case self::WEB:
             if (!$this->_curl) {
                 $this->_curl = new Curl($this->_bruteTypeOptions['url']);
                 if (isset($this->_bruteTypeOptions['userAgent'])) {
                     $this->_curl->setUserAgent($this->_bruteTypeOptions['url']);
                 }
                 if (isset($this->_bruteTypeOptions['proxy'])) {
                     $this->_curl->setProxy($this->_bruteTypeOptions['proxy']['host'], $this->_bruteTypeOptions['proxy']['pass'], $this->_bruteTypeOptions['proxy']['port']);
                 }
                 if (isset($this->_bruteTypeOptions['formInputs'])) {
                     $inputs = $this->_bruteTypeOptions['formInputs'];
                     foreach ($inputs as $input => $inputValue) {
                         $this->_curl->addArgument($input, $inputValue);
                     }
                 }
             }
             if (isset($this->_bruteTypeOptions['inputCheck'])) {
                 $this->_curl->addArgument($this->_bruteTypeOptions['inputCheck'], $generateValue);
             }
             $this->_curl->execute(false, true);
             $curlReponse = $this->_curl->getResponse();
             while ($curlReponse == false) {
                 $this->_curl->execute(false, true);
                 $curlReponse = $this->_curl->getResponse();
             }
             $stringPresent = false;
             foreach ($this->_bruteTypeOptions['checkStringsIntoCurlReturn'] as $string) {
                 if (stripos($curlReponse, $string)) {
                     $stringPresent = true;
                 }
             }
             if (!$stringPresent) {
                 $this->_setChecked(true);
                 $this->_setFoundValue($generateValue);
                 Logger::getInstance()->debug('BruteForcing OK, found value : "' . $generateValue . '" with ' . $this->getProcess() . ' process');
                 /* $file = new \SplFileObject('foundvalue.txt', 'w+');
                    if ($file->flock(LOCK_EX)) {
                    $file->fwrite($generateValue);
                    $file->flock(LOCK_UN);
                    } */
                 return true;
             } else {
                 Logger::getInstance()->debug('BruteForcing echec, unfound value : "' . $generateValue . '" with ' . $this->getProcess() . ' process');
                 return false;
             }
             return false;
             break;
         default:
             throw new \Exception('invalid brute type');
             break;
     }
     return false;
 }
예제 #24
0
 public function initAssets()
 {
     Logger::getInstance()->debug('Initialize assets', 'template' . $this->_name);
     foreach ($this->_assets as $assetType => $assetDatas) {
         if (!isset($assetDatas['directory'])) {
             throw new \Exception('Miss asset : "' . $assetType . '" directory for template : "' . $this->_name . '"');
         }
         //check directory
         if (!is_dir($assetDatas['directory'])) {
             throw new \Exception('Invalid asset : "' . $assetType . '" directory for template : "' . $this->_name . '"');
         }
         //cache
         if ($assetType == self::ASSET_CSS || $assetType == self::ASSET_JS) {
             if (isset($assetDatas['cache'])) {
                 $compress = isset($assetDatas['cache']['compress']) ? $assetDatas['cache']['compress'] : false;
                 $rewriteUrls = isset($assetDatas['cache']['rewriteUrls']) ? $assetDatas['cache']['rewriteUrls'] : false;
                 $minify = new Minify($assetDatas['cache']['name'], $assetDatas['directory'], $assetType, $compress, $rewriteUrls, $this->_name);
                 if ($assetType == self::ASSET_CSS) {
                     $this->_css = $minify->minify();
                 }
                 if ($assetType == self::ASSET_JS) {
                     $this->_js = $minify->minify();
                 }
             }
         }
         //loadUrls and Langs into js
         if ($assetType == self::ASSET_JS) {
             if (isset($assetDatas['loadUrls'])) {
                 $this->_js .= 'var urls = {};';
                 foreach ($this->_vars->urls as $urlName => $urlValue) {
                     $this->_js .= 'urls["' . $urlName . '"] = "' . $urlValue . '";';
                 }
                 //add img, css, js .. urls
                 if ($img = $this->getUrlAsset(self::ASSET_IMG, Http::isHttps())) {
                     $this->_js .= 'urls["' . self::ASSET_IMG . '"] = "' . $img . '";';
                 }
                 if ($css = $this->getUrlAsset(self::ASSET_CSS, Http::isHttps())) {
                     $this->_js .= 'urls["' . self::ASSET_CSS . '"] = "' . $css . '";';
                 }
                 if ($js = $this->getUrlAsset(self::ASSET_JS, Http::isHttps())) {
                     $this->_js .= 'urls["' . self::ASSET_JS . '"] = "' . $js . '";';
                 }
                 if ($font = $this->getUrlAsset(self::ASSET_FONT, Http::isHttps())) {
                     $this->_js .= 'urls["' . self::ASSET_FONT . '"] = "' . $font . '";';
                 }
                 if ($sound = $this->getUrlAsset(self::ASSET_SOUND, Http::isHttps())) {
                     $this->_js .= 'urls["' . self::ASSET_SOUND . '"] = "' . $sound . '";';
                 }
             }
             if (isset($assetDatas['loadLangs'])) {
                 $this->_js .= 'var langs = {};';
                 foreach ($this->_vars->langs as $langName => $langValue) {
                     $this->_js .= 'langs["' . $langName . '"] = "' . $langValue . '";';
                 }
             }
         }
         //add asset
         $this->_assets[$assetType] = $assetDatas;
     }
 }
예제 #25
0
 public function expand($shortUrlHash, $returnFullReponse = false)
 {
     if (!is_string($shortUrlHash)) {
         throw new \Exception('shortUrl parameter must be a string');
     }
     if (!is_bool($returnFullReponse)) {
         throw new \Exception('returnFullReponse parameter must be an boolean');
     }
     $curl = new Curl($this->getApiUrl() . 'expand');
     $curl->addArgument('version', $this->getApiVersion(), 'GET');
     $curl->addArgument('hash', $shortUrlHash, 'GET');
     $curl->addArgument('login', $this->getApiLogin(), 'GET');
     $curl->addArgument('apiKey', $this->getApiKey(), 'GET');
     $curl->execute(true);
     $reponse = json_decode($curl->getResponse());
     if ($returnFullReponse) {
         return $reponse;
     } else {
         if ($reponse->errorCode != 0) {
             Logger::getInstance()->debug('Bit.Ly expand url error, code : "' . $reponse->errorCode . '" and message : "' . $reponse->errorMessage . '"');
             return false;
         }
         if ($reponse->statusCode == 'OK') {
             Logger::getInstance()->debug('Bit.Ly expand url  : "http://bit.ly/' . $shortUrlHash . '" result is : "' . $reponse->results->{$shortUrlHash}->longUrl . '"');
             return $reponse->results->{$shortUrlHash}->longUrl;
         }
         return false;
     }
 }
예제 #26
0
 protected function _addLog($message, $level, $date, $isTrace = false)
 {
     $name = $isTrace ? 'TRACE' : Logger::getLevelName($level);
     $head = '[' . $date . '][' . $name . '] ';
     $this->_logs .= $head . $message . chr(10);
 }
예제 #27
0
 public function stop()
 {
     self::$_isRun = false;
     Logger::getInstance()->debug('Sniffer security was stopped', 'security');
 }
예제 #28
0
 public function decrement($key, $offset = 1, $startValue = 1, $returnValue = false)
 {
     $this->_crement($key, $offset, false, $startValue);
     Logger::getInstance()->debug('Decrement : "' . $key . '"', 'session');
     if ($returnValue) {
         return $this->get($key);
     }
 }