function isAuthorized() { if (Reg::isRegistered(ConfigManager::getConfig("Users", "Users")->ObjectsIgnored->User)) { return true; } return false; }
protected function loadYubikeyUserAuthorization() { $usersConfig = ConfigManager::getConfig("Users", "Users"); $resultingConfig = ConfigManager::mergeConfigs($usersConfig->AuxConfig, $this->config->AuxConfig); $yubikeyUserAuthorization = new YubikeyUserAuthorization(Reg::get($usersConfig->Objects->UserManagement), $resultingConfig); $this->register($yubikeyUserAuthorization); }
protected function loadrewriteAliasURL() { $rewriteURLconfig = $this->packageManager->getPluginConfig("RewriteURL", "RewriteURL")->AuxConfig; $hostConfig = ConfigManager::getConfig("Host", "Host"); $this->rewriteAliasURL = new RewriteAliasURL($rewriteURLconfig, $this->aliasMap->getAliasMap(Reg::get($hostConfig->Objects->Host))); $this->register($this->rewriteAliasURL); }
protected function loadGeoIPGps() { $geoIPConfig = ConfigManager::getConfig("GeoIP", "GeoIP"); $gpsConfig = ConfigManager::getConfig("Gps", "Gps"); $geoIpGps = new GeoIPGps(Reg::get($geoIPConfig->Objects->GeoIP), Reg::get($gpsConfig->Objects->Gps)); $this->register($geoIpGps); }
public static function decrypt($string, $key = null, $salt = null, $iv = null) { $config = ConfigManager::getConfig('Crypto', 'AES256')->AuxConfig; if ($key === null) { $key = $config->key; } if ($salt === null) { $salt = $config->salt; } if ($iv === null) { $iv = $config->iv; } $td = mcrypt_module_open('rijndael-128', '', MCRYPT_MODE_CBC, ''); $ks = mcrypt_enc_get_key_size($td); $bs = mcrypt_enc_get_block_size($td); $iv = substr(hash("sha256", $iv), 0, $bs); // Create key $key = Crypto::pbkdf2("sha512", $key, $salt, $config->pbkdfRounds, $ks); // Initialize encryption module for decryption mcrypt_generic_init($td, $key, $iv); $decryptedString = ""; // Decrypt encrypted string try { if (ctype_xdigit($string)) { $decryptedString = trim(mdecrypt_generic($td, pack("H*", $string))); } } catch (ErrorException $e) { } // Terminate decryption handle and close module mcrypt_generic_deinit($td); mcrypt_module_close($td); // Show string return $decryptedString; }
/** * Does login operation * @param string $username * @param string $password * @param bool $writeCookie * @param bool $isPasswordEncrypted * * @throws RuntimeException (Codes: 1 - Incorrect login/password combination, 2 - Account is disabled) */ public function doLogin($username, $password, $writeCookie = false, $isPasswordEncrypted = false) { if ($this->um->checkCredentials($username, $password, $isPasswordEncrypted)) { $this->usr = $this->um->getObjectByLogin($username); $this->authorize($this->usr); $this->saveUserId($this->usr->getId()); if ($writeCookie) { $secs = getdate(); $exp_time = $secs[0] + 60 * 60 * 24 * $this->config->rememberDaysCount; $cookie_value = $this->usr->getId() . ":" . hash('sha256', $username . ":" . md5($password)); setcookie($this->config->loginCookieName, $cookie_value, $exp_time, '/'); } if (Reg::get('packageMgr')->isPluginLoaded("Security", "RequestLimiter") and $this->config->bruteForceProtectionEnabled) { $this->query->exec("DELETE FROM `" . Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG') . "` WHERE `ip`='" . $_SERVER['REMOTE_ADDR'] . "'"); } } else { if (Reg::get('packageMgr')->isPluginLoaded("Security", "RequestLimiter") and $this->config->bruteForceProtectionEnabled) { $this->query->exec("SELECT `count` \n\t\t\t\t\t\t\t\t\t\t\tFROM `" . Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG') . "` \n\t\t\t\t\t\t\t\t\t\t\tWHERE `ip`='" . $_SERVER['REMOTE_ADDR'] . "'"); $failedAuthCount = $this->query->fetchField('count'); $newFailedAuthCount = $failedAuthCount + 1; if ($newFailedAuthCount >= $this->config->failedAuthLimit) { Reg::get(ConfigManager::getConfig("Security", "RequestLimiter")->Objects->RequestLimiter)->blockIP(); $this->query->exec("DELETE FROM `" . Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG') . "` WHERE `ip`='" . $_SERVER['REMOTE_ADDR'] . "'"); throw new RequestLimiterTooManyAuthTriesException("Too many unsucessful authorization tries."); } $this->query->exec("INSERT INTO `" . Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG') . "` (`ip`) \n\t\t\t\t\t\t\t\t\t\tVALUES ('" . $_SERVER['REMOTE_ADDR'] . "')\n\t\t\t\t\t\t\t\t\t\tON DUPLICATE KEY UPDATE `count` = `count` + 1"); } throw new RuntimeException("Incorrect login/password combination", static::EXCEPTION_INCORRECT_LOGIN_PASSWORD); } }
public function updateAttachmentMessageId($attachmentId, $newMessageId) { if (empty($attachmentId) or !is_numeric($attachmentId)) { throw new InvalidIntegerArgumentException("\$attachmentId have to be non zero integer."); } if (empty($newMessageId) or !is_numeric($newMessageId)) { throw new InvalidIntegerArgumentException("\$newMessageId have to be non zero integer."); } $convMgr = Reg::get(ConfigManager::getConfig("Messaging", "Conversations")->Objects->ConversationManager); $filter = new ConversationMessagesFilter(); $filter->setId($newMessageId); $message = $convMgr->getConversationMessage($filter); $qb = new QueryBuilder(); $qb->update(Tbl::get('TBL_CONVERSATION_ATTACHEMENTS'))->set(new Field('message_id'), $message->id)->where($qb->expr()->equal(new Field('id'), $attachmentId)); MySqlDbManager::getDbObject()->startTransaction(); try { $convMgr->setMessageHasAttachment($message); $affected = $this->query->exec($qb->getSQL())->affected(); if (!MySqlDbManager::getDbObject()->commit()) { MySqlDbManager::getDbObject()->rollBack(); } } catch (Exception $e) { MySqlDbManager::getDbObject()->rollBack(); throw $e; } }
public function hookSetTemplateByHost() { $smarty = Reg::get(ConfigManager::getConfig("Smarty", "Smarty")->Objects->Smarty); $host = Reg::get(ConfigManager::getConfig("Host", "Host")->Objects->Host); $templateByHost = SmartyHostTpl::getTemplateByHost($host); if ($templateByHost !== false) { $smarty->setTemplate($templateByHost); } }
/** * Make Json output and disable Smarty output * @param array $array */ public static function jsonOutput($array) { $smartyConfig = ConfigManager::getConfig("Output", "Smarty"); Reg::get($smartyConfig->Objects->Smarty)->disableOutput(); header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); echo self::jsonEncode($array); }
/** * Function get random username * @param string $prefix is name of current external plugin * @return string */ private static function findFreeRandomUsername($prefix) { $um = Reg::get(ConfigManager::getConfig("Users", "Users")->Objects->UserManager); $possibleUsername = $prefix . "_" . generateRandomString(6); if (!$um->isLoginExists($possibleUsername, 0)) { return $possibleUsername; } else { return static::findFreeRandomUsername($prefix); } }
public function __construct() { $this->memcacheConfig = ConfigManager::getConfig("Db", "Memcache")->AuxConfig; if (strpos($this->memcacheConfig->keyPrefix, ":")) { throw new RuntimeException("Memcache key prefix can't contain colon \":\"!"); } if ($this->memcacheConfig->enabled) { $this->memcache = new MemcacheWrapper($this->memcacheConfig->host, $this->memcacheConfig->port); } }
public function enableMemcache() { $this->memcacheConfig = ConfigManager::getConfig("Db", "Memcache")->AuxConfig; if ($this->memcacheConfig->enabled) { $memcache = new Memcache(); if ($memcache->pconnect($this->memcacheConfig->host, $this->memcacheConfig->port)) { Minify::setCache(new Minify_Cache_Memcache($memcache)); } } }
public function hookClearUserSmartyCache($params) { if (isset($params["userId"]) && !empty($params["userId"]) && is_numeric($params["userId"])) { $memcacheConfig = ConfigManager::getConfig('Db', 'Memcache')->AuxConfig; if (!empty($memcacheConfig) and $memcacheConfig->enabled == true) { $memcached = new MemcacheWrapper($memcacheConfig->host, $memcacheConfig->port); $memcached->invalidateCacheByTag("smrt:u" . $params["userId"]); } } }
protected function getTextAliasObjectFromData($data, $cacheMinutes = null) { $textAlias = new TextAlias(); $hostLanguagePair = HostLanguageManager::getHostLanguagePair($data['host_language'], $cacheMinutes); $textAlias->id = $data['id']; $textAlias->textValue = Reg::get(ConfigManager::getConfig("Texts")->Objects->TextsValuesManager)->getTextValueById($data['value_id'], $cacheMinutes); $textAlias->language = $hostLanguagePair['language']; $textAlias->host = $hostLanguagePair['host']; $textAlias->hostLanguageId = $data['host_language']; return $textAlias; }
/** * Class constructor * * @param MySqlDatabase db * @param Logger $logger * @param bool $memcahe_on * */ public function __construct(MySqlDatabase $db, Logger $logger = null) { parent::__construct($db, $logger); $this->memcacheConfig = ConfigManager::getConfig("Db", "Memcache")->AuxConfig; if (strpos($this->memcacheConfig->keyPrefix, ":")) { throw new RuntimeException("Memcache key prefix can't contain colon \":\"!"); } if ($this->memcacheConfig->enabled) { $this->memcache = new MemcacheWrapper($this->memcacheConfig->host, $this->memcacheConfig->port); } }
public function hookSetPageInfo() { $smartyConfig = ConfigManager::getConfig("Smarty"); $siteNavConfig = ConfigManager::getConfig("SiteNavigation"); $module = Reg::get($siteNavConfig->ObjectsIgnored->Nav)->module; $page = Reg::get($siteNavConfig->ObjectsIgnored->Nav)->page; $pageInfo = $this->pageInfo->getInfo($module, $page); Reg::get($smartyConfig->Objects->Smarty)->setPageTitle($pageInfo['title']); Reg::get($smartyConfig->Objects->Smarty)->setPageKeywords($pageInfo['meta_keywords']); Reg::get($smartyConfig->Objects->Smarty)->setPageDescription($pageInfo['meta_description']); }
/** * Call other controller with given URI. * Can be used to call different controller using some logic. * WARNING! All GET parameters are being lost upon redirection. * * @param string $uri */ function redirectController($uri) { $_SERVER['REQUEST_URI'] = SITE_PATH . $uri; $_GET = array(); if (Reg::get('packageMgr')->isPluginLoaded("RewriteURL", "RewriteURL")) { Reg::get(ConfigManager::getConfig("RewriteURL", "RewriteURL")->Objects->rewriteURL)->parseURL(); } $newNav = Reg::get(ConfigManager::getConfig("SiteNavigation", "SiteNavigation")->Objects->RequestParser)->parse(); Reg::register(ConfigManager::getConfig("SiteNavigation", "SiteNavigation")->ObjectsIgnored->Nav, $newNav, true); Reg::get(ConfigManager::getConfig("SiteNavigation", "SiteNavigation")->Objects->Controller)->exec(); }
/** * Blacklist given country * * @param string $countryCode * @throws InvalidArgumentException * @throws RuntimeException */ public function blackListCountry($countryCode) { if (!Reg::get(ConfigManager::getConfig('GeoIP', 'GeoIP')->Objects->GeoIP)->isValidCountryCode($countryCode)) { throw new InvalidArgumentException("Invalid country code specified for blacklisting"); } $this->query->exec("SELECT count(*) as `count` FROM `" . Tbl::get('TBL_SECURITY_BLACKLISTED_COUNTRIES', 'IpFilter') . "`\n\t\t\t\t\t\t\t\tWHERE `country`='{$countryCode}'"); if ($this->query->fetchField('count') != 0) { throw new RuntimeException("Sorry, this country already blacklisted!"); } $this->query->exec("INSERT INTO `" . Tbl::get('TBL_SECURITY_BLACKLISTED_COUNTRIES', 'IpFilter') . "` \n\t\t\t\t\t\t\t\t(`country`) VALUES ('{$countryCode}') "); }
protected function customInitAfterObjects() { $hostLangId = null; $configDBFilter = new ConfigDBFilter(); if (Reg::get('packageMgr')->isPluginLoaded("Language", "HostLanguage")) { $hostName = ConfigManager::getConfig("Host", "Host")->Objects->Host; $languageName = ConfigManager::getConfig("Language", "Language")->ObjectsIgnored->Language; $hostLangId = HostLanguageManager::getHostLanguageId(Reg::get($hostName), Reg::get($languageName)); $configDBFilter->setCommonOrHostLang($hostLangId); } ConfigDBManager::initDBConfig($configDBFilter); }
public static function logRequest($dbInstanceKey = null) { $sql = MySqlDbManager::getQueryObject($dbInstanceKey); $userId = "NULL"; $userObjectSerialized = "''"; $userObj = Reg::get(ConfigManager::getConfig("Users", "Users")->ObjectsIgnored->User); if ($userObj->isAuthorized()) { $userId = $userObj->getId(); $userObjectSerialized = "'" . mysql_real_escape_string(serialize($userObj)) . "'"; } $sql->exec("INSERT DELAYED INTO `" . Tbl::get("TBL_REQUEST_LOG") . "` \n\t\t\t\t\t\t(`user_id`, `user_obj`,`session_id`, `get`, `post`, `server`, `cookies`, `session`, `response`)\n\t\t\t\t\t\tVALUES\t(\n\t\t\t\t\t\t\t\t\t{$userId},\n\t\t\t\t\t\t\t\t\t{$userObjectSerialized},\n\t\t\t\t\t\t\t\t\t'" . session_id() . "',\n\t\t\t\t\t\t\t\t\t'" . mysql_real_escape_string(serialize($_GET)) . "',\n\t\t\t\t\t\t\t\t\t'" . mysql_real_escape_string(serialize($_POST)) . "',\n\t\t\t\t\t\t\t\t\t'" . mysql_real_escape_string(serialize($_SERVER)) . "',\n\t\t\t\t\t\t\t\t\t'" . mysql_real_escape_string(serialize($_COOKIE)) . "',\n\t\t\t\t\t\t\t\t\t'" . mysql_real_escape_string(serialize($_SESSION)) . "',\n\t\t\t\t\t\t\t\t\t'" . mysql_real_escape_string(ob_get_contents()) . "'\n\t\t\t\t\t\t\t\t)"); }
/** * Return text for currect host/language * * @param string $name * @param string $group * @return string */ function smarty_modifier_text($name, $group) { try { $textValMgr = Reg::get(ConfigManager::getConfig("Texts", "Texts")->Objects->TextsValuesManager); return $textValMgr->getTextValue($name, $group); } catch (Exception $e) { if (Debug::getMode()) { return "_~#~_"; } else { return ""; } } }
public function __construct($runInteval = null, $timeout = null) { if (!empty($runInteval) and is_numeric($runInteval)) { $this->runInteval = $runInteval; } else { $this->runInteval = ConfigManager::getConfig("Comet", "Comet")->AuxConfig->runInterval; } if (!empty($timeout) and is_numeric($timeout)) { $this->timeout = $timeout; } else { $this->timeout = ConfigManager::getConfig("Comet", "Comet")->AuxConfig->timeout; } }
public static function logRequest($dbInstanceKey = null) { $sql = MySqlDbManager::getQueryObject($dbInstanceKey); $userId = "NULL"; $userObjectSerialized = "''"; $userObj = Reg::get(ConfigManager::getConfig("Users", "Users")->ObjectsIgnored->User); if ($userObj->isAuthorized()) { $userId = $userObj->id; $userObjectSerialized = "'" . mysql_real_escape_string(serialize($userObj)) . "'"; } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_REQUEST_LOG'))->values(array("user_id" => $userId, "user_obj" => $userObjectSerialized, "session_id" => session_id(), "get" => serialize($_GET), "post" => serialize($_POST), "server" => serialize($_SERVER), "cookies" => serialize($_COOKIE), "session" => serialize($_SESSION), "response" => ob_get_contents())); $sql->exec($qb->getSQL()); }
/** * @param string $string * @return string */ function smarty_modifier_img($filename, $backupFileName = null) { /* @var $smarty SamrtyWrapper */ $smarty = Reg::get(ConfigManager::getConfig("Output", "Smarty")->Objects->Smarty); try { return SITE_PATH . $smarty->findFilePath('img/' . $filename); } catch (Exception $e) { if ($backupFileName !== null) { return SITE_PATH . $smarty->findFilePath('img/' . $backupFileName); } else { throw $e; } } }
public function hookSetTemplateByHost() { $controller = Reg::get(ConfigManager::getConfig("SiteNavigation", "SiteNavigation")->Objects->Controller); $smarty = Reg::get(ConfigManager::getConfig("Output", "Smarty")->Objects->Smarty); $host = Reg::get(ConfigManager::getConfig("Host", "Host")->Objects->Host); $result = HostControllerTemplate::getControllerTemplateByHost($host); if ($result !== false) { if (isset($result['controller']) and !empty($result['controller'])) { $controller->setControllersPath($result['controller']); } if (isset($result['template']) and !empty($result['template'])) { $smarty->setTemplate($result['template']); } } }
/** * Is remote IP blocked by country * * @return boolean */ private function isBlockedByCountry($cacheMinutes = null) { $myLocation = Reg::get(ConfigManager::getConfig('GeoIP', 'GeoIP')->Objects->GeoIP)->getLocation(); if (empty($myLocation)) { return false; } $countryCode = $myLocation->country; if (empty($countryCode)) { return false; } $this->query->exec("SELECT count(*) as `count` \n\t\t\t\t\t\t\t\tFROM `" . Tbl::get('TBL_SECURITY_BLACKLISTED_COUNTRIES') . "` \n\t\t\t\t\t\t\t\tWHERE `country` = '{$countryCode}'", $cacheMinutes); $count = $this->query->fetchField('count'); if ($count > 0) { return true; } return false; }
public static function deleteFile($fileName, $uploadDir = null) { if ($uploadDir === null) { $fileUploaderConfig = ConfigManager::getConfig("FileUploader", "FileUploader")->AuxConfig; if (isset($fileUploaderConfig->uploadDir)) { $uploadDir = $fileUploaderConfig->uploadDir; } } if (empty($uploadDir)) { throw new RuntimeException("Unable to get any appropriate uploadDir!"); } if (!file_exists($uploadDir)) { throw new InvalidArgumentException("Upload directory {$uploadDir} doesn't exists."); } $imagePath = $uploadDir . $fileName; @unlink($imagePath); }
protected function getEventObjectFromData($eventRow, $reduced = false) { $event = $this->getNewEventObject(); $event->id = $eventRow['id']; $event->date = $eventRow['date']; $event->selfUserId = $eventRow['self_user_id']; $event->userId = $eventRow['user_id']; if (!$reduced) { $UserManager = Reg::get(ConfigManager::getConfig("Users", "Users")->Objects->UserManager); $event->selfUser = $UserManager->getUserById($eventRow['self_user_id']); if (!empty($eventRow['user_id'])) { $event->user = $UserManager->getUserById($eventRow['user_id']); } } $event->name = $eventRow['name']; $event->data = unserialize($eventRow['data']); return $event; }
/** * Smarty plugin * @package Smarty * @subpackage plugins */ function smarty_function_chunk($params, &$smarty) { $cacheEnabled = false; if (!isset($params['file'])) { throw new InvalidArgumentException("You have tom specify 'file' parameter for the chunk"); } $file = $params['file']; unset($params['file']); if (isset($params['cache']) and $params['cache'] == true) { $smarty->setCachingOn(); $cacheEnabled = true; if (isset($params['cacheTime']) and is_int($params['cacheTime'])) { $smarty->setCacheTime($params['cacheTime']); } } foreach ($params as $key => $value) { $smarty->assign($key, $value); } $path = $smarty->getChunkPath($file); if (!empty($path)) { $cacheId = null; if (isset($params['cacheId']) and !empty($params['cacheId'])) { $cacheId = $params['cacheId']; } elseif (isset($params['targetId']) and !empty($params['targetId'])) { $cacheId = 'id:' . getSmartyCacheId($params['targetId']); } elseif (!fempty($targetIdFromParent = $smarty->getTemplateVars('targetId'))) { $cacheId = 'id:' . getSmartyCacheId($targetIdFromParent); } elseif (!fempty($cacheIdFromParent = $smarty->getTemplateVars('cacheId'))) { $cacheId = $cacheIdFromParent; } if ($cacheId != null) { $result = $smarty->fetch($path, $cacheId); } else { $result = $smarty->fetch($path); } if ($cacheEnabled) { if (ConfigManager::getConfig("Output", "Smarty")->AuxConfig->caching == Smarty::CACHING_OFF) { $smarty->setCachingOff(); } } return $result; } return ""; }
/** * Is remote IP blocked by country * * @return boolean */ private function isBlockedByCountry($cacheMinutes = null) { $myLocation = Reg::get(ConfigManager::getConfig('GeoIP', 'GeoIP')->Objects->GeoIP)->getLocation(); if (empty($myLocation)) { return false; } $countryCode = $myLocation->country; if (empty($countryCode)) { return false; } $qb = new QueryBuilder(); $qb->select($qb->expr()->count('*', 'count'))->from(Tbl::get('TBL_SECURITY_BLACKLISTED_COUNTRIES'))->where($qb->expr()->equal(new Field('country'), $countryCode)); $this->query->exec($qb->getSQL(), $cacheMinutes); $count = $this->query->fetchField('count'); if ($count > 0) { return true; } return false; }