/** * Authenticate user and initializes the session. * Listens to Login.initSession hook. * * @param Piwik_Event_Notification $notification notification object * @throws Exception */ function initSession($notification) { $info = $notification->getNotificationObject(); $login = $info['login']; $md5Password = $info['md5Password']; $rememberMe = $info['rememberMe']; $tokenAuth = Piwik_UsersManager_API::getInstance()->getTokenAuth($login, $md5Password); $auth = Zend_Registry::get('auth'); $auth->setLogin($login); $auth->setTokenAuth($tokenAuth); $authResult = $auth->authenticate(); $authCookieName = Piwik_Config::getInstance()->General['login_cookie_name']; $authCookieExpiry = $rememberMe ? time() + Piwik_Config::getInstance()->General['login_cookie_expire'] : 0; $authCookiePath = Piwik_Config::getInstance()->General['login_cookie_path']; $cookie = new Piwik_Cookie($authCookieName, $authCookieExpiry, $authCookiePath); if (!$authResult->isValid()) { $cookie->delete(); throw new Exception(Piwik_Translate('Login_LoginPasswordNotCorrect')); } $cookie->set('login', $login); $cookie->set('token_auth', $auth->getHashTokenAuth($login, $authResult->getTokenAuth())); $cookie->setSecure(Piwik::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); @Piwik_Session::regenerateId(); // remove password reset entry if it exists self::removePasswordResetInfo($login); }
/** * Clear session information * * @param none * @return void */ public static function clearSession() { $authCookieName = Zend_Registry::get('config')->General->login_cookie_name; $cookie = new Piwik_Cookie($authCookieName); $cookie->delete(); Piwik_Session::expireSessionCookie(); }
/** * Dispatches the request to the right plugin and executes the requested action on the plugin controller. * * @throws Exception in case the plugin doesn't exist, the action doesn't exist, there is not enough permission, etc. * * @param string $module * @param string $action * @param array $parameters * @return mixed The returned value of the calls, often nothing as the module print but don't return data * @see fetchDispatch() */ function dispatch( $module = null, $action = null, $parameters = null) { static $sessionStarted = false; if( self::$enableDispatch === false) { return; } if(is_null($module)) { $defaultModule = 'CoreHome'; $module = Piwik_Common::getRequestVar('module', $defaultModule, 'string'); } if(is_null($action)) { $action = Piwik_Common::getRequestVar('action', false); } if(($module !== 'API' || ($action && $action !== 'index')) && !$sessionStarted && (!defined('PIWIK_ENABLE_SESSION_START') || PIWIK_ENABLE_SESSION_START)) { Piwik_Session::start(); $sessionStarted = true; } if(is_null($parameters)) { $parameters = array(); } if(!ctype_alnum($module)) { throw new Exception("Invalid module name '$module'"); } if( ! Piwik_PluginsManager::getInstance()->isPluginActivated( $module )) { throw new Piwik_FrontController_PluginDeactivatedException($module); } $controllerClassName = 'Piwik_'.$module.'_Controller'; // FrontController's autoloader if(!class_exists($controllerClassName, false)) { $moduleController = PIWIK_INCLUDE_PATH . '/plugins/' . $module . '/Controller.php'; if(!is_readable($moduleController)) { throw new Exception("Module controller $moduleController not found!"); } require_once $moduleController; // prefixed by PIWIK_INCLUDE_PATH } $controller = new $controllerClassName(); if($action === false) { $action = $controller->getDefaultAction(); } // Piwik::log("Dispatching $module / $action, parameters: ".var_export($parameters, $return = true)); if( !is_callable(array($controller, $action))) { throw new Exception("Action $action not found in the controller $controllerClassName."); } try { return call_user_func_array( array($controller, $action ), $parameters); } catch(Piwik_Access_NoAccessException $e) { Piwik_PostEvent('FrontController.NoAccessException', $e); } catch(Exception $e) { Piwik_ExitWithMessage($e->getMessage(), false /* DEBUG ONLY $e->getTraceAsString() */, true); } }
/** * Clear session information * * @param none * @return void */ public static function clearSession() { $authCookieName = Piwik_Config::getInstance()->General['login_cookie_name']; $cookie = new Piwik_Cookie($authCookieName); $cookie->delete(); Piwik_Session::expireSessionCookie(); }
/** * Must be called before dispatch() * - checks that directories are writable, * - loads the configuration file, * - loads the plugin, * - inits the DB connection, * - etc. */ function init() { static $initialized = false; if ($initialized) { return; } $initialized = true; try { Zend_Registry::set('timer', new Piwik_Timer()); $directoriesToCheck = array('/tmp/', '/tmp/templates_c/', '/tmp/cache/', '/tmp/assets/', '/tmp/tcpdf/'); Piwik::checkDirectoriesWritableOrDie($directoriesToCheck); Piwik_Common::assignCliParametersToRequest(); Piwik_Translate::getInstance()->loadEnglishTranslation(); $exceptionToThrow = false; try { Piwik::createConfigObject(); } catch (Exception $e) { Piwik_PostEvent('FrontController.NoConfigurationFile', $e, $info = array(), $pending = true); $exceptionToThrow = $e; } if (Piwik_Session::isFileBasedSessions()) { Piwik_Session::start(); } if (Piwik_Config::getInstance()->General['maintenance_mode'] == 1 && !Piwik_Common::isPhpCliMode()) { $format = Piwik_Common::getRequestVar('format', ''); $exception = new Exception("Piwik is in scheduled maintenance. Please come back later."); if (empty($format)) { throw $exception; } $response = new Piwik_API_ResponseBuilder($format); echo $response->getResponseException($exception); exit; } if (!Piwik_Common::isPhpCliMode() && Piwik_Config::getInstance()->General['force_ssl'] == 1 && !Piwik::isHttps()) { $url = Piwik_Url::getCurrentUrl(); $url = str_replace("http://", "https://", $url); Piwik_Url::redirectToUrl($url); } $pluginsManager = Piwik_PluginsManager::getInstance(); $pluginsToLoad = Piwik_Config::getInstance()->Plugins['Plugins']; $pluginsManager->loadPlugins($pluginsToLoad); if ($exceptionToThrow) { throw $exceptionToThrow; } try { Piwik::createDatabaseObject(); } catch (Exception $e) { if (self::shouldRethrowException()) { throw $e; } Piwik_PostEvent('FrontController.badConfigurationFile', $e, $info = array(), $pending = true); throw $e; } Piwik::createLogObject(); // creating the access object, so that core/Updates/* can enforce Super User and use some APIs Piwik::createAccessObject(); Piwik_PostEvent('FrontController.dispatchCoreAndPluginUpdatesScreen'); Piwik_PluginsManager::getInstance()->installLoadedPlugins(); Piwik::install(); // ensure the current Piwik URL is known for later use if (method_exists('Piwik', 'getPiwikUrl')) { $host = Piwik::getPiwikUrl(); } Piwik_PostEvent('FrontController.initAuthenticationObject'); try { $authAdapter = Zend_Registry::get('auth'); } catch (Exception $e) { throw new Exception("Authentication object cannot be found in the Registry. Maybe the Login plugin is not activated?\n\t\t\t\t\t\t\t\t\t<br />You can activate the plugin by adding:<br />\n\t\t\t\t\t\t\t\t\t<code>Plugins[] = Login</code><br />\n\t\t\t\t\t\t\t\t\tunder the <code>[Plugins]</code> section in your config/config.ini.php"); } Zend_Registry::get('access')->reloadAccess($authAdapter); Piwik::raiseMemoryLimitIfNecessary(); Piwik_Translate::getInstance()->reloadLanguage(); $pluginsManager->postLoadPlugins(); Piwik_PostEvent('FrontController.checkForUpdates'); } catch (Exception $e) { if (self::shouldRethrowException()) { throw $e; } Piwik_ExitWithMessage($e->getMessage(), false, true); } // Piwik::log('End FrontController->init() - Request: '. var_export($_REQUEST, true)); }
/** * Start the session * * @param array|bool $options An array of configuration options; the auto-start (bool) setting is ignored * @return void */ public static function start($options = false) { if (Piwik_Common::isPhpCliMode() || 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 (Piwik::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 $sessionName = defined('PIWIK_SESSION_NAME') ? PIWIK_SESSION_NAME : 'PIWIK_SESSID'; @ini_set('session.name', $sessionName); // 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 = Piwik_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 = PIWIK_USER_PATH . '/tmp/sessions'; // We always call mkdir since it also chmods the directory which might help when permissions were reverted for some reasons Piwik_Common::mkdir($sessionPath); @ini_set('session.save_handler', 'files'); @ini_set('session.save_path', $sessionPath); } else { if ($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 $db = Zend_Registry::get('db'); $config = array('name' => Piwik_Common::prefixTable('session'), 'primary' => 'id', 'modifiedColumn' => 'modified', 'dataColumn' => 'data', 'lifetimeColumn' => 'lifetime', 'db' => $db); $saveHandler = new Piwik_Session_SaveHandler_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 { Zend_Session::start(); register_shutdown_function(array('Zend_Session', 'writeClose'), true); } catch (Exception $e) { Piwik::log('Unable to start session: ' . $e->getMessage()); $enableDbSessions = ''; if (Piwik::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' target='_blank'>enable database session storage</a>."; } $message = 'Error: ' . Piwik_Translate('General_ExceptionUnableToStartSession') . ' ' . Piwik::getErrorMessageMissingPermissions(Piwik_Common::getPathToPiwikRoot() . '/tmp/sessions/') . $enableDbSessions . "\n<pre>Debug: the original error was \n" . $e->getMessage() . "</pre>"; Piwik_ExitWithMessage($message); } }
error_reporting(E_ALL | E_NOTICE); @ini_set('display_errors', !defined('PIWIK_DISPLAY_ERRORS') || PIWIK_DISPLAY_ERRORS ? 1 : 0); @ini_set('xdebug.show_exception_trace', 0); @ini_set('magic_quotes_runtime', 0); define('PIWIK_DOCUMENT_ROOT', dirname(__FILE__) == '/' ? '' : dirname(__FILE__)); if (!defined('PIWIK_USER_PATH')) { define('PIWIK_USER_PATH', PIWIK_DOCUMENT_ROOT); } if (!defined('PIWIK_INCLUDE_PATH')) { define('PIWIK_INCLUDE_PATH', PIWIK_DOCUMENT_ROOT); } require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php'; require_once PIWIK_INCLUDE_PATH . '/core/testMinimumPhpVersion.php'; // NOTE: the code above this comment must be PHP4 compatible session_cache_limiter('nocache'); @date_default_timezone_set('UTC'); require_once PIWIK_INCLUDE_PATH . '/core/Loader.php'; if (!defined('PIWIK_ENABLE_SESSION_START') || PIWIK_ENABLE_SESSION_START) { Piwik_Session::start(); } if (!defined('PIWIK_ENABLE_ERROR_HANDLER') || PIWIK_ENABLE_ERROR_HANDLER) { require_once PIWIK_INCLUDE_PATH . '/core/ErrorHandler.php'; require_once PIWIK_INCLUDE_PATH . '/core/ExceptionHandler.php'; set_error_handler('Piwik_ErrorHandler'); set_exception_handler('Piwik_ExceptionHandler'); } if (!defined('PIWIK_ENABLE_DISPATCH') || PIWIK_ENABLE_DISPATCH) { $controller = Piwik_FrontController::getInstance(); $controller->init(); $controller->dispatch(); }
/** * Must be called before dispatch() * - checks that directories are writable, * - loads the configuration file, * - loads the plugin, * - inits the DB connection, * - etc. * @throws Exception * @throws Exception * @throws bool|Exception * @return */ function init() { static $initialized = false; if ($initialized) { return; } $initialized = true; try { Zend_Registry::set('timer', new Piwik_Timer()); $directoriesToCheck = array('/tmp/', '/tmp/templates_c/', '/tmp/cache/', '/tmp/assets/', '/tmp/tcpdf/'); Piwik::checkDirectoriesWritableOrDie($directoriesToCheck); Piwik_Common::assignCliParametersToRequest(); Piwik_Translate::getInstance()->loadEnglishTranslation(); $exceptionToThrow = $this->createConfigObject(); if (Piwik_Session::isFileBasedSessions()) { Piwik_Session::start(); } $this->handleMaintenanceMode(); $this->handleSSLRedirection(); $pluginsManager = Piwik_PluginsManager::getInstance(); $pluginsToLoad = Piwik_Config::getInstance()->Plugins['Plugins']; $pluginsManager->loadPlugins($pluginsToLoad); if ($exceptionToThrow) { throw $exceptionToThrow; } try { Piwik::createDatabaseObject(); } catch (Exception $e) { if (self::shouldRethrowException()) { throw $e; } Piwik_PostEvent('FrontController.badConfigurationFile', $e, $info = array(), $pending = true); throw $e; } Piwik::createLogObject(); // creating the access object, so that core/Updates/* can enforce Super User and use some APIs $this->createAccessObject(); Piwik_PostEvent('FrontController.dispatchCoreAndPluginUpdatesScreen'); Piwik_PluginsManager::getInstance()->installLoadedPlugins(); Piwik::install(); // ensure the current Piwik URL is known for later use if (method_exists('Piwik', 'getPiwikUrl')) { $host = Piwik::getPiwikUrl(); } Piwik_PostEvent('FrontController.initAuthenticationObject'); try { $authAdapter = Zend_Registry::get('auth'); } catch (Exception $e) { throw new Exception("Authentication object cannot be found in the Registry. Maybe the Login plugin is not activated?\n\t\t\t\t\t\t\t\t\t<br />You can activate the plugin by adding:<br />\n\t\t\t\t\t\t\t\t\t<code>Plugins[] = Login</code><br />\n\t\t\t\t\t\t\t\t\tunder the <code>[Plugins]</code> section in your config/config.ini.php"); } Zend_Registry::get('access')->reloadAccess($authAdapter); // Force the auth to use the token_auth if specified, so that embed dashboard // and all other non widgetized controller methods works fine if (($token_auth = Piwik_Common::getRequestVar('token_auth', false, 'string')) !== false) { Piwik_API_Request::reloadAuthUsingTokenAuth(); } Piwik::raiseMemoryLimitIfNecessary(); Piwik_Translate::getInstance()->reloadLanguage(); $pluginsManager->postLoadPlugins(); Piwik_PostEvent('FrontController.checkForUpdates'); } catch (Exception $e) { if (self::shouldRethrowException()) { throw $e; } Piwik_ExitWithMessage($e->getMessage(), false, true); } // Piwik::log('End FrontController->init() - Request: '. var_export($_REQUEST, true)); }