作者:FluentDevelopmen
项目:piwi
public function sendHeader()
{
if ($this->isJsonp()) {
Common::sendHeader('Content-Type: application/javascript; charset=utf-8');
} else {
Renderer\Json::sendHeaderJSON();
}
ProxyHttp::overrideCacheControlHeaders();
}
作者:piwi
项目:piwi
public function addJsGlobalVariables(&$out)
{
if (ProxyHttp::isHttps()) {
$isHttps = 'true';
} else {
$isHttps = 'false';
}
$out .= "piwik.hasServerDetectedHttps = {$isHttps};\n";
}
作者:Gabriel-Bowate
项目:piwi
private static function notifyIfURLIsNotSecure()
{
$isURLSecure = ProxyHttp::isHttps();
if ($isURLSecure) {
return;
}
if (!Piwik::hasUserSuperUserAccess()) {
return;
}
$message = Piwik::translate('General_CurrentlyUsingUnsecureHttp');
$message .= " ";
$message .= Piwik::translate('General_ReadThisToLearnMore', array('<a rel="noreferrer" target="_blank" href="https://piwik.org/faq/how-to/faq_91/">', '</a>'));
$notification = new Notification($message);
$notification->context = Notification::CONTEXT_WARNING;
$notification->raw = true;
Notification\Manager::notify('ControllerAdmin_HttpIsUsed', $notification);
}
作者:sgieh
项目:piwik-plugin-GoogleAuthenticato
/**
* Executed when the session was successfully authenticated.
*
* @param AuthResult $authResult The successful authentication result.
* @param bool $rememberMe Whether the authenticated session should be remembered after
* the browser is closed or not.
*/
protected function processSuccessfulSession(AuthResult $authResult, $rememberMe)
{
$storage = new Storage($authResult->getIdentity());
/**
* @deprecated Create a custom SessionInitializer instead.
*/
Piwik::postEvent('Login.authenticate.successful', array($authResult->getIdentity(), $authResult->getTokenAuth()));
$cookie = $this->getAuthCookie($rememberMe);
$cookie->set('login', $authResult->getIdentity());
$cookie->set('token_auth', $this->getHashTokenAuth($authResult->getIdentity(), $authResult->getTokenAuth()));
if ($storage->isActive()) {
$cookie->set('auth_code', $this->getHashTokenAuth($authResult->getIdentity(), $storage->getSecret()));
}
$cookie->setSecure(ProxyHttp::isHttps());
$cookie->setHttpOnly(true);
$cookie->save();
}
作者:brienomatt
项目:elmsl
/**
* Renders the current view. Also sends the stored 'Content-Type' HTML header.
* See {@link setContentType()}.
*
* @return string Generated template.
*/
public function render()
{
try {
$this->currentModule = Piwik::getModule();
$this->currentAction = Piwik::getAction();
$this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
$this->token_auth = Piwik::getCurrentUserTokenAuth();
$this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
$this->userIsSuperUser = Piwik::hasUserSuperUserAccess();
$this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
$this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
$this->isWidget = Common::getRequestVar('widget', 0, 'int');
$this->cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster();
$this->loginModule = Piwik::getLoginPluginName();
$user = APIUsersManager::getInstance()->getUser($this->userLogin);
$this->userAlias = $user['alias'];
} catch (Exception $e) {
// can fail, for example at installation (no plugin loaded yet)
}
try {
$this->totalTimeGeneration = Registry::get('timer')->getTime();
$this->totalNumberOfQueries = Profiler::getQueryCount();
} catch (Exception $e) {
$this->totalNumberOfQueries = 0;
}
ProxyHttp::overrideCacheControlHeaders('no-store');
@header('Content-Type: ' . $this->contentType);
// always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail)
@header('X-Frame-Options: ' . (string) $this->xFrameOptions);
return $this->renderTwigTemplate();
}
作者:jos
项目:CGE-File-Sharin
/**
* Sends the http headers for csv file
*/
protected function renderHeader()
{
$fileName = 'Piwik ' . Piwik::translate('General_Export');
$period = Common::getRequestVar('period', false);
$date = Common::getRequestVar('date', false);
if ($period || $date) {
if ($period == 'range') {
$period = new Range($period, $date);
} else {
if (strpos($date, ',') !== false) {
$period = new Range('range', $date);
} else {
$period = Period\Factory::build($period, Date::factory($date));
}
}
$prettyDate = $period->getLocalizedLongString();
$meta = $this->getApiMetaData();
$fileName .= ' _ ' . $meta['name'] . ' _ ' . $prettyDate . '.csv';
}
// silent fail otherwise unit tests fail
Common::sendHeader('Content-Disposition: attachment; filename="' . $fileName . '"', true);
ProxyHttp::overrideCacheControlHeaders();
}
作者:FluentDevelopmen
项目:piwi
public function sendHeader()
{
Common::sendHeader("Content-Type: application/vnd.ms-excel", true);
ProxyHttp::overrideCacheControlHeaders();
}
作者:KiwiJuice
项目:handball-dacha
/**
* Authenticates the user and initializes the session.
*/
public function initSession($login, $md5Password, $rememberMe)
{
$tokenAuth = API::getInstance()->getTokenAuth($login, $md5Password);
$this->setLogin($login);
$this->setTokenAuth($tokenAuth);
$authResult = $this->authenticate();
$authCookieName = Config::getInstance()->General['login_cookie_name'];
$authCookieExpiry = $rememberMe ? time() + Config::getInstance()->General['login_cookie_expire'] : 0;
$authCookiePath = Config::getInstance()->General['login_cookie_path'];
$cookie = new Cookie($authCookieName, $authCookieExpiry, $authCookiePath);
if (!$authResult->wasAuthenticationSuccessful()) {
$cookie->delete();
throw new Exception(Piwik::translate('Login_LoginPasswordNotCorrect'));
}
$cookie->set('login', $login);
$cookie->set('token_auth', $this->getHashTokenAuth($login, $authResult->getTokenAuth()));
$cookie->setSecure(ProxyHttp::isHttps());
$cookie->setHttpOnly(true);
$cookie->save();
@Session::regenerateId();
// remove password reset entry if it exists
Login::removePasswordResetInfo($login);
}
作者:piwi
项目:piwi
/**
* Executed when the session was successfully authenticated.
*
* @param AuthResult $authResult The successful authentication result.
* @param bool $rememberMe Whether the authenticated session should be remembered after
* the browser is closed or not.
*/
protected function processSuccessfulSession(AuthResult $authResult, $rememberMe)
{
$cookie = $this->getAuthCookie($rememberMe);
$cookie->set('login', $authResult->getIdentity());
$cookie->set('token_auth', $this->getHashTokenAuth($authResult->getIdentity(), $authResult->getTokenAuth()));
$cookie->setSecure(ProxyHttp::isHttps());
$cookie->setHttpOnly(true);
$cookie->save();
}
作者:a4tunad
项目:piwi
/**
* Returns image link tracking code for a given site with specified options.
*
* @param int $idSite The ID to generate tracking code for.
* @param string $piwikUrl The domain and URL path to the Piwik installation.
* @param int $idGoal An ID for a goal to trigger a conversion for.
* @param int $revenue The revenue of the goal conversion. Only used if $idGoal is supplied.
* @return string The HTML tracking code.
*/
public function getImageTrackingCode($idSite, $piwikUrl = '', $actionName = false, $idGoal = false, $revenue = false)
{
$urlParams = array('idsite' => $idSite, 'rec' => 1);
if ($actionName !== false) {
$urlParams['action_name'] = urlencode(Common::unsanitizeInputValue($actionName));
}
if ($idGoal !== false) {
$urlParams['idGoal'] = $idGoal;
if ($revenue !== false) {
$urlParams['revenue'] = $revenue;
}
}
/**
* Triggered when generating image link tracking code server side. Plugins can use
* this event to customise the image tracking code that is displayed to the
* user.
*
* @param string &$piwikHost The domain and URL path to the Piwik installation, eg,
* `'examplepiwik.com/path/to/piwik'`.
* @param array &$urlParams The query parameters used in the <img> element's src
* URL. See Piwik's image tracking docs for more info.
*/
Piwik::postEvent('SitesManager.getImageTrackingCode', array(&$piwikUrl, &$urlParams));
$piwikUrl = (ProxyHttp::isHttps() ? "https://" : "http://") . $piwikUrl . '/piwik.php';
return "<!-- Piwik Image Tracker-->\n<img src=\"{$piwikUrl}?" . Url::getQueryStringFromParameters($urlParams) . "\" style=\"border:0\" alt=\"\" />\n<!-- End Piwik -->";
}
作者:brienomatt
项目:elmsl
/**
* Write configuration file from session-store
*/
private function createConfigFile($dbInfos)
{
$config = Config::getInstance();
// make sure DB sessions are used if the filesystem is NFS
if (Filesystem::checkIfFileSystemIsNFS()) {
$config->General['session_save_handler'] = 'dbtable';
}
if (count($headers = ProxyHeaders::getProxyClientHeaders()) > 0) {
$config->General['proxy_client_headers'] = $headers;
}
if (count($headers = ProxyHeaders::getProxyHostHeaders()) > 0) {
$config->General['proxy_host_headers'] = $headers;
}
if (Common::getRequestVar('clientProtocol', 'http', 'string') == 'https') {
$protocol = 'https';
} else {
$protocol = ProxyHeaders::getProtocolInformation();
}
if (!empty($protocol) && !\Piwik\ProxyHttp::isHttps()) {
$config->General['assume_secure_protocol'] = '1';
}
$config->General['salt'] = Common::generateUniqId();
$config->General['installation_in_progress'] = 1;
$config->database = $dbInfos;
if (!DbHelper::isDatabaseConnectionUTF8()) {
$config->database['charset'] = 'utf8';
}
$config->forceSave();
}
作者:carriercom
项目:piwi
/**
* If the page is using HTTP, redirect to the same page over HTTPS
*/
public static function redirectToHttps()
{
if (ProxyHttp::isHttps()) {
return;
}
$url = self::getCurrentUrl();
$url = str_replace("http://", "https://", $url);
self::redirectToUrl($url);
}
作者:brienomatt
项目:elmsl
/**
* @param UIAsset $uiAsset
*/
private function serveJsFile($uiAsset)
{
ProxyHttp::serverStaticFile($uiAsset->getAbsoluteLocation(), self::JS_MIME_TYPE);
}
作者:carriercom
项目:piwi
/**
* Executed when the session was successfully authenticated
* @param $login
* @param $tokenAuth
* @param $rememberMe
*/
protected function processSuccessfullSession($login, $tokenAuth, $rememberMe)
{
$cookie = $this->getAuthCookie($rememberMe);
$cookie->set('login', $login);
$cookie->set('token_auth', $this->getHashTokenAuth($login, $tokenAuth));
$cookie->setSecure(ProxyHttp::isHttps());
$cookie->setHttpOnly(true);
$cookie->save();
// remove password reset entry if it exists
Login::removePasswordResetInfo($login);
}
作者:diosmosi
项目:piwi
/**
* Renders the current view. Also sends the stored 'Content-Type' HTML header.
* See {@link setContentType()}.
*
* @return string Generated template.
*/
public function render()
{
try {
$this->currentModule = Piwik::getModule();
$this->currentAction = Piwik::getAction();
$this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
$this->token_auth = Piwik::getCurrentUserTokenAuth();
$this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
$this->userIsAnonymous = Piwik::isUserIsAnonymous();
$this->userIsSuperUser = Piwik::hasUserSuperUserAccess();
$this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
$this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
$this->isWidget = Common::getRequestVar('widget', 0, 'int');
$piwikAds = StaticContainer::get('Piwik\\ProfessionalServices\\Advertising');
$this->areAdsForProfessionalServicesEnabled = $piwikAds->areAdsForProfessionalServicesEnabled();
if (Development::isEnabled()) {
$cacheBuster = rand(0, 10000);
} else {
$cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster();
}
$this->cacheBuster = $cacheBuster;
$this->loginModule = Piwik::getLoginPluginName();
$user = APIUsersManager::getInstance()->getUser($this->userLogin);
$this->userAlias = $user['alias'];
} catch (Exception $e) {
Log::debug($e);
// can fail, for example at installation (no plugin loaded yet)
}
ProxyHttp::overrideCacheControlHeaders('no-store');
Common::sendHeader('Content-Type: ' . $this->contentType);
// always sending this header, sometimes empty, to ensure that Dashboard embed loads
// - when calling sendHeader() multiple times, the last one prevails
Common::sendHeader('X-Frame-Options: ' . (string) $this->xFrameOptions);
return $this->renderTwigTemplate();
}
作者:piwi
项目:piwi
public function download()
{
Piwik::checkUserHasSuperUserAccess();
$this->dieIfPluginsAdminIsDisabled();
$pluginName = new PluginName();
$pluginName = $pluginName->getPluginName();
Nonce::checkNonce($pluginName);
$filename = $pluginName . '.zip';
try {
$pathToPlugin = $this->marketplaceApi->download($pluginName);
ProxyHttp::serverStaticFile($pathToPlugin, 'application/zip', $expire = 0, $start = false, $end = false, $filename);
} catch (Exception $e) {
Common::sendResponseCode(500);
Log::warning('Could not download file . ' . $e->getMessage());
}
if (!empty($pathToPlugin)) {
Filesystem::deleteFileIfExists($pathToPlugin);
}
}
作者:FluentDevelopmen
项目:piwi
/**
* Start the session
*
* @param array|bool $options An array of configuration options; the auto-start (bool) setting is ignored
* @return void
* @throws Exception if starting a session fails
*/
public static function start($options = false)
{
if (headers_sent() || self::$sessionStarted || defined('PIWIK_ENABLE_SESSION_START') && !PIWIK_ENABLE_SESSION_START) {
return;
}
self::$sessionStarted = true;
// use cookies to store session id on the client side
@ini_set('session.use_cookies', '1');
// prevent attacks involving session ids passed in URLs
@ini_set('session.use_only_cookies', '1');
// advise browser that session cookie should only be sent over secure connection
if (ProxyHttp::isHttps()) {
@ini_set('session.cookie_secure', '1');
}
// advise browser that session cookie should only be accessible through the HTTP protocol (i.e., not JavaScript)
@ini_set('session.cookie_httponly', '1');
// don't use the default: PHPSESSID
@ini_set('session.name', self::SESSION_NAME);
// proxies may cause the referer check to fail and
// incorrectly invalidate the session
@ini_set('session.referer_check', '');
$currentSaveHandler = ini_get('session.save_handler');
$config = Config::getInstance();
if (self::isFileBasedSessions()) {
// Note: this handler doesn't work well in load-balanced environments and may have a concurrency issue with locked session files
// for "files", use our own folder to prevent local session file hijacking
$sessionPath = self::getSessionsDirectory();
// We always call mkdir since it also chmods the directory which might help when permissions were reverted for some reasons
Filesystem::mkdir($sessionPath);
@ini_set('session.save_handler', 'files');
@ini_set('session.save_path', $sessionPath);
} elseif ($config->General['session_save_handler'] === 'dbtable' || in_array($currentSaveHandler, array('user', 'mm'))) {
// We consider these to be misconfigurations, in that:
// - user - we can't verify that user-defined session handler functions have already been set via session_set_save_handler()
// - mm - this handler is not recommended, unsupported, not available for Windows, and has a potential concurrency issue
$config = array('name' => Common::prefixTable('session'), 'primary' => 'id', 'modifiedColumn' => 'modified', 'dataColumn' => 'data', 'lifetimeColumn' => 'lifetime');
$saveHandler = new DbTable($config);
if ($saveHandler) {
self::setSaveHandler($saveHandler);
}
}
// garbage collection may disabled by default (e.g., Debian)
if (ini_get('session.gc_probability') == 0) {
@ini_set('session.gc_probability', 1);
}
try {
parent::start();
register_shutdown_function(array('Zend_Session', 'writeClose'), true);
} catch (Exception $e) {
Log::error('Unable to start session: ' . $e->getMessage());
$enableDbSessions = '';
if (DbHelper::isInstalled()) {
$enableDbSessions = "<br/>If you still experience issues after trying these changes,\n\t\t\t \t\t\twe recommend that you <a href='http://piwik.org/faq/how-to-install/#faq_133' rel='noreferrer' target='_blank'>enable database session storage</a>.";
}
$pathToSessions = Filechecks::getErrorMessageMissingPermissions(self::getSessionsDirectory());
$message = sprintf("Error: %s %s %s\n<pre>Debug: the original error was \n%s</pre>", Piwik::translate('General_ExceptionUnableToStartSession'), $pathToSessions, $enableDbSessions, $e->getMessage());
$ex = new MissingFilePermissionException($message, $e->getCode(), $e);
$ex->setIsHtmlMessage();
throw $ex;
}
}
作者:KiwiJuice
项目:handball-dacha
/**
* Check force_ssl_login and redirect if connection isn't secure and not using a reverse proxy
*
* @param none
* @return void
*/
protected function checkForceSslLogin()
{
$forceSslLogin = Config::getInstance()->General['force_ssl_login'];
if ($forceSslLogin && !ProxyHttp::isHttps()) {
$url = 'https://' . Url::getCurrentHost() . Url::getCurrentScriptName() . Url::getCurrentQueryString();
Url::redirectToUrl($url);
}
}
作者:carriercom
项目:piwi
// These constants define which action will be performed by the static server.
define("NULL_FILE_SRV_MODE", "nullFile");
define("GHOST_FILE_SRV_MODE", "ghostFile");
define("TEST_FILE_SRV_MODE", "testFile");
/**
* If the static file server has been requested, the response sent back to the browser will be the content produced by
* the execution of Piwik:serverStaticFile(). In this case, unit tests won't be executed
*/
// Getting the server mode
$staticFileServerMode = Common::getRequestVar(SRV_MODE_REQUEST_VAR, "");
// Setting zlib output compression as requested
ini_set('zlib.output_compression', Common::getRequestVar(ZLIB_OUTPUT_REQUEST_VAR, '0'));
if ($staticFileServerMode === "") {
throw new Exception("When this testing file is used as a static file server, the request parameter " . SRV_MODE_REQUEST_VAR . " must be provided.");
}
switch ($staticFileServerMode) {
// The static file server calls Piwik::serverStaticFile with a null file
case NULL_FILE_SRV_MODE:
ProxyHttp::serverStaticFile(null, TEST_FILE_CONTENT_TYPE);
break;
// The static file server calls Piwik::serverStaticFile with a non-existing file
// The static file server calls Piwik::serverStaticFile with a non-existing file
case GHOST_FILE_SRV_MODE:
ProxyHttp::serverStaticFile(TEST_FILE_LOCATION . ".ghost", TEST_FILE_CONTENT_TYPE);
break;
// The static file server calls Piwik::serverStaticFile with the test file
// The static file server calls Piwik::serverStaticFile with the test file
case TEST_FILE_SRV_MODE:
ProxyHttp::serverStaticFile(TEST_FILE_LOCATION, TEST_FILE_CONTENT_TYPE);
break;
}
作者:KiwiJuice
项目:handball-dacha
protected function handleSSLRedirection()
{
if (!Common::isPhpCliMode() && Config::getInstance()->General['force_ssl'] == 1 && !ProxyHttp::isHttps() && !(Common::getRequestVar('module', '') == 'CoreAdminHome' && Common::getRequestVar('action', '') == 'optOut')) {
$url = Url::getCurrentUrl();
$url = str_replace("http://", "https://", $url);
Url::redirectToUrl($url);
}
}