示例#1
0
 protected function _check($ip, $userAgent)
 {
     if (Http::getQuery($this->_trapName) && !Validate::isGoogleBot()) {
         $isBadCrawler = false;
         $isGoodCrawler = false;
         if ($this->_badCrawlerFile) {
             $badCrawlerXml = simplexml_load_file($this->_badCrawlerFile);
             if (is_null($badCrawlerXml) || !$badCrawlerXml) {
                 throw new \Exception('Invalid xml file : "' . $this->_badCrawlerFile . '"');
             }
         }
         if ($this->_goodCrawlerFile) {
             $goodCrawlerXml = simplexml_load_file($this->_goodCrawlerFile);
             if (is_null($goodCrawlerXml) || !$goodCrawlerXml) {
                 throw new \Exception('Invalid xml file : "' . $this->_goodCrawlerFile . '"');
             }
         }
         if ($badCrawlerXml) {
             $badCrawlerList = $badCrawlerXml->crawler;
             foreach ($badCrawlerList as $crawler) {
                 if (isset($crawler->ip) && (string) $crawler->ip == $ip) {
                     $isBadCrawler = true;
                 }
                 if (isset($crawler->userAgent) && strripos((string) $crawler->userAgent, $userAgent) !== false) {
                     $isBadCrawler = true;
                 }
                 if ($isBadCrawler) {
                     $this->_catch($ip, $userAgent, self::CRAWLER_BAD);
                     Session::getInstance()->add(md5($ip . 'badcrawler'), true, true, true);
                     Router::getInstance()->show403(true);
                     break;
                 }
             }
             unset($crawler);
         }
         if ($goodCrawlerXml) {
             $goodCrawlerList = $goodCrawlerXml->crawler;
             foreach ($goodCrawlerList as $crawler) {
                 if (isset($crawler->ip) && (string) $crawler->ip == $ip) {
                     $isGoodCrawler = true;
                 }
                 if (isset($crawler->userAgent) && strripos((string) $crawler->userAgent, $userAgent) !== false) {
                     $isGoodCrawler = true;
                 }
                 if ($isGoodCrawler) {
                     $this->_catch($ip, $userAgent, self::CRAWLER_BAD);
                     break;
                 }
             }
             unset($crawler);
         }
         // unknown
         if (!$isBadCrawler && !$isGoodCrawler) {
             $this->_catch($ip, $userAgent, self::CRAWLER_BAD);
         }
     }
 }
示例#2
0
 public function __destruct()
 {
     if (!empty($this->_logs)) {
         if (!Http::isAjax()) {
             if (!Cli::isCli()) {
                 echo '<pre>';
             }
             echo $this->_logs;
             if (!Cli::isCli()) {
                 echo '</pre>';
             }
         }
     }
 }
示例#3
0
 protected function __construct()
 {
     if (!is_null(self::$_path)) {
         // Check config default path
         if (!is_dir(self::$_path . 'default')) {
             throw new \Exception('Config error, please set default config directory');
         }
         //load default config
         $this->loadPath(self::$_path . 'default');
         //load by host
         $hostname = Http::getServer('HTTP_HOST');
         if ($hostname && is_dir(self::$_path . $hostname)) {
             $this->loadPath(self::$_path . $hostname);
         }
         // Define default constants
         Constant::defineCons();
     }
 }
 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;
     }
 }
示例#5
0
 public function getUrlAsset($type, $ssl = false)
 {
     if (!is_string($type)) {
         throw new \Exception('Asset type must be a string');
     }
     if (Http::isHttps()) {
         $ssl = true;
     }
     if (!is_array($this->_assets)) {
         return false;
     }
     if (!array_key_exists($type, $this->_assets)) {
         return false;
     }
     $asset = $this->_assets[$type];
     return Router::getHost(true, $ssl) . str_replace(DS, '/', str_replace(PATH_ROOT, '', $asset['directory']));
 }
示例#6
0
 public static function get($key = null, $default = null, $allowHtmlTags = false)
 {
     return Http::getCookie($key, $default, $allowHtmlTags);
 }
示例#7
0
 public function contact()
 {
     //get security
     $security = Security::getSecurity(Security::TYPE_FORM);
     $crsf = $security->getProtection('form1', Form::PROTECTION_CSRF);
     $captcha = $security->getProtection('form1', Form::PROTECTION_CAPTCHA);
     //create new and add to ajax data
     $crsf->create();
     $this->addAjaxDatas('token', $crsf->get());
     $error = false;
     //check security
     if (!$crsf->check(Http::getPost('token'))) {
         $error = true;
     }
     if (!$captcha->check(Http::getPost('captcha'))) {
         $this->addError($this->language->getVar('validate_security'), 'captcha');
         $error = true;
     }
     // send mail
     if ($error) {
         $this->notifyError($this->language->getVar('validate_error'));
     } else {
         //send mail
         SwiftMailer::getInstance();
         $mail = \Swift_Message::newInstance();
         $mail->setFrom(array(ADMIN_EMAIL => $this->language->getVar('site_name')));
         $mail->setTo(CONTACT_EMAIL);
         $mail->setSubject($this->language->getVar('site_name') . ' demande de contact');
         $contents = new MailContents($this->tpl->getPath() . 'mails' . DS . 'contact.tpl.php');
         $contents->addVar('message', nl2br(Http::getPost('message')))->addVar('name', Http::getPost('name'))->addVar('email', Http::getPost('email'))->addVar('subject', Http::getPost('subject'));
         $mail->addPart($contents->getMailContents(), 'text/html');
         $transport = defined('SMTP_SERVER') && !is_null(SMTP_SERVER) && SMTP_SERVER != '' ? \Swift_SmtpTransport::newInstance(SMTP_SERVER, 25) : \Swift_MailTransport::newInstance();
         $mailer = \Swift_Mailer::newInstance($transport);
         $mailer->send($mail);
         $this->notifySuccess($this->language->getVar('validate_success'));
     }
     //set in session
     $crsf->set();
 }
示例#8
0
 public static function setResponseStatusCode($code, $sentHttpStatus = false, $checkIfHeaderSent = true, $httpProtocol = null)
 {
     if (!ResponseCode::isValid($code)) {
         throw new \Exception('Response Code parameter must be a valid http response code');
     }
     if (!is_bool($sentHttpStatus)) {
         throw new \Exception('withHttpStatus parameter must be an boolean');
     }
     http_response_code($code);
     if ($sentHttpStatus) {
         $httpProtocolVersion = !is_null($httpProtocol) && Protocol::isValid($httpProtocol) ? $httpProtocol : str_replace('HTTP/', '', Http::getServer('SERVER_PROTOCOL'));
         $statusMessage = ResponseCode::getMessage($code, false);
         self::sentHeader('HTTP', '/' . (string) $httpProtocolVersion . ' ' . $statusMessage, true, $code, $checkIfHeaderSent, null);
         self::sentHeader('Status', $statusMessage, true, $code, $checkIfHeaderSent);
     }
 }
 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;
     }
 }
示例#10
0
 protected function _getContent()
 {
     if ($this->_type == Template::ASSET_CSS) {
         $content = '';
         foreach ($this->_files as $file) {
             $f = file_get_contents($file['name']);
             if ($this->_compress && !$file['alreadyCompressed']) {
                 $f = $this->_compressCss($f);
             }
             $content .= $f;
         }
         //rewrite url path
         if ($this->getRewriteUrls()) {
             return preg_replace("#\\[HOSTNAME]#", Router::getHost(true, Http::isHttps()), $content);
         }
         return $content;
     } elseif ($this->_type == Template::ASSET_JS) {
         $notCompressed = $content = '';
         foreach ($this->_files as $file) {
             $js = file_get_contents($file['name']);
             if ($this->_compress && !$file['alreadyCompressed']) {
                 // Compress file with Javascript Packer plugin
                 $packer = new JavaScriptPacker($js);
                 $notCompressed .= trim($packer->pack());
             } else {
                 $content .= $js;
             }
             if (substr($notCompressed, -1) != ';') {
                 $notCompressed .= ';';
             }
         }
         //rewrite url path
         if ($this->getRewriteUrls()) {
             return preg_replace("#\\[HOSTNAME]#", Router::getHost(true, Http::isHttps()), $content . $notCompressed);
         }
         return $content . $notCompressed;
     }
 }
示例#11
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();
     }
 }
 public function setAjaxController($ajaxDatasType = self::JSON, $ajaxDatasCache = false, $ajaxAutoAddDatas = array())
 {
     if (!Http::isAjax()) {
         $this->log->debug('Trying set controller on ajax when resquest isn\'t ajax', 'router');
     }
     if ($ajaxDatasType != self::HTML && $ajaxDatasType != self::XML && $ajaxDatasType != self::JSON) {
         throw new \Exception('ajax datas type parameter must be a valid data type : htmt(1), xml(2) or json(3)');
     }
     if (!is_bool($ajaxDatasCache)) {
         throw new \Exception('ajaxDatasCache parameter must be a boolean');
     }
     $this->_ajaxDatasCache = $ajaxDatasCache;
     $this->_ajaxDatasType = $ajaxDatasType;
     $this->_isAjax = true;
     if (!is_array($ajaxAutoAddDatas)) {
         throw new \Exception('ajaxAutoAddDatasparameter must be a boolean');
     }
     if (!empty($ajaxAutoAddDatas)) {
         $this->setAjaxAutoAddDatas(extract($ajaxAutoAddDatas));
     }
     $this->log->debug('Set controller in ajax', 'router');
 }
示例#13
0
 public static function isGoogleBot()
 {
     if (stripos(Http::getServer('HTTP_USER_AGENT'), 'Googlebot') !== false) {
         return true;
     }
     return false;
 }
示例#14
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;
 }
示例#15
0
 protected function _generateSecurity()
 {
     self::_checkState();
     return md5(Tools::getUserIp() . Http::getServer('HTTP_USER_AGENT'));
 }