Beispiel #1
0
 /**
  * Checks that the directories Piwik needs write access are actually writable
  * Displays a nice error page if permissions are missing on some directories
  *
  * @param array $directoriesToCheck Array of directory names to check
  */
 public static function dieIfDirectoriesNotWritable($directoriesToCheck = null)
 {
     $resultCheck = self::checkDirectoriesWritable($directoriesToCheck);
     if (array_search(false, $resultCheck) === false) {
         return;
     }
     $directoryList = '';
     foreach ($resultCheck as $dir => $bool) {
         $realpath = Filesystem::realpath($dir);
         if (!empty($realpath) && $bool === false) {
             $directoryList .= self::getMakeWritableCommand($realpath);
         }
     }
     // Also give the chown since the chmod is only 755
     if (!SettingsServer::isWindows()) {
         $realpath = Filesystem::realpath(PIWIK_INCLUDE_PATH . '/');
         $directoryList = "<code>chown -R www-data:www-data " . $realpath . "</code><br />" . $directoryList;
     }
     if (function_exists('shell_exec')) {
         $currentUser = trim(shell_exec('whoami'));
         if (!empty($currentUser)) {
             $optionalUserInfo = " (running as user '" . $currentUser . "')";
         }
     }
     $directoryMessage = "<p><b>Piwik couldn't write to some directories {$optionalUserInfo}</b>.</p>";
     $directoryMessage .= "<p>Try to Execute the following commands on your server, to allow Write access on these directories" . ":</p>" . "<blockquote>{$directoryList}</blockquote>" . "<p>If this doesn't work, you can try to create the directories with your FTP software, and set the CHMOD to 0755 (or 0777 if 0755 is not enough). To do so with your FTP software, right click on the directories then click permissions.</p>" . "<p>After applying the modifications, you can <a href='index.php'>refresh the page</a>.</p>" . "<p>If you need more help, try <a href='?module=Proxy&action=redirect&url=http://piwik.org'>Piwik.org</a>.</p>";
     Piwik_ExitWithMessage($directoryMessage, false, true);
 }
Beispiel #2
0
 /**
  * Checks that the directories Piwik needs write access are actually writable
  * Displays a nice error page if permissions are missing on some directories
  * 
  * @return void
  */
 public static function checkDirectoriesWritableOrDie($directoriesToCheck = null)
 {
     $resultCheck = Piwik::checkDirectoriesWritable($directoriesToCheck);
     if (array_search(false, $resultCheck) !== false) {
         $directoryList = '';
         foreach ($resultCheck as $dir => $bool) {
             $realpath = Piwik_Common::realpath($dir);
             if (!empty($realpath) && $bool === false) {
                 $directoryList .= "<code>chmod 777 {$realpath}</code><br>";
             }
         }
         $directoryList .= '';
         $directoryMessage = "<p><b>Piwik couldn't write to some directories</b>.</p> <p>Try to Execute the following commands on your Linux server:</P>";
         $directoryMessage .= $directoryList;
         $directoryMessage .= "<p>If this doesn't work, you can try to create the directories with your FTP software, and set the CHMOD to 777 (with your FTP software, right click on the directories, permissions).";
         $directoryMessage .= "<p>After applying the modifications, you can <a href='index.php'>refresh the page</a>.";
         $directoryMessage .= "<p>If you need more help, try <a href='misc/redirectToUrl.php?url=http://piwik.org'>Piwik.org</a>.";
         Piwik_ExitWithMessage($directoryMessage, false, true);
     }
 }
Beispiel #3
0
 function redirectToIndex()
 {
     $sitesId = Piwik_SitesManager_API::getSitesIdWithAtLeastViewAccess();
     if (!empty($sitesId)) {
         $firstSiteId = $sitesId[0];
         $firstSite = new Piwik_Site($firstSiteId);
         if ($firstSite->getCreationDate()->isToday()) {
             $defaultDate = 'today';
         } else {
             $defaultDate = Zend_Registry::get('config')->General->default_day;
         }
         header("Location:index.php?module=Home&action=index&idSite={$firstSiteId}&period=day&date={$defaultDate}");
     } else {
         if (($currentLogin = Piwik::getCurrentUserLogin()) != 'anonymous') {
             Piwik_ExitWithMessage(sprintf(Piwik_Translate('Home_NoPrivileges'), $currentLogin) . "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='?module=Login&action=logout'>&rsaquo; " . Piwik_Translate('General_Logout') . "</a></b><br />");
         } else {
             Piwik_FrontController::dispatch('Login');
         }
     }
     exit;
 }
 /**
  * Must be called before dispatch()
  * - checks that directories are writable,
  * - loads the configuration file,
  * - loads the plugin,
  * - inits the DB connection,
  * - etc.
  *
  * @throws Exception
  * @return void
  */
 public function init()
 {
     static $initialized = false;
     if ($initialized) {
         return;
     }
     $initialized = true;
     try {
         Registry::set('timer', new Timer());
         $directoriesToCheck = array('/tmp/', '/tmp/assets/', '/tmp/cache/', '/tmp/logs/', '/tmp/tcpdf/', '/tmp/templates_c/');
         Filechecks::dieIfDirectoriesNotWritable($directoriesToCheck);
         Translate::loadEnglishTranslation();
         $exceptionToThrow = self::createConfigObject();
         $this->handleMaintenanceMode();
         $this->handleProfiler();
         $this->handleSSLRedirection();
         Plugin\Manager::getInstance()->loadPluginTranslations('en');
         Plugin\Manager::getInstance()->loadActivatedPlugins();
         if ($exceptionToThrow) {
             throw $exceptionToThrow;
         }
         // try to connect to the database
         try {
             Db::createDatabaseObject();
             Db::fetchAll("SELECT DATABASE()");
         } catch (Exception $exception) {
             if (self::shouldRethrowException()) {
                 throw $exception;
             }
             Log::debug($exception);
             /**
              * Triggered when Piwik cannot connect to the database.
              *
              * This event can be used to start the installation process or to display a custom error
              * message.
              *
              * @param Exception $exception The exception thrown from creating and testing the database
              *                             connection.
              */
             Piwik::postEvent('Db.cannotConnectToDb', array($exception), $pending = true);
             throw $exception;
         }
         // try to get an option (to check if data can be queried)
         try {
             Option::get('TestingIfDatabaseConnectionWorked');
         } catch (Exception $exception) {
             if (self::shouldRethrowException()) {
                 throw $exception;
             }
             Log::debug($exception);
             /**
              * Triggered when Piwik cannot access database data.
              *
              * This event can be used to start the installation process or to display a custom error
              * message.
              *
              * @param Exception $exception The exception thrown from trying to get an option value.
              */
             Piwik::postEvent('Config.badConfigurationFile', array($exception), $pending = true);
             throw $exception;
         }
         // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs
         Access::getInstance();
         /**
          * Triggered just after the platform is initialized and plugins are loaded.
          *
          * This event can be used to do early initialization.
          *
          * _Note: At this point the user is not authenticated yet._
          */
         Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen');
         \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
         // ensure the current Piwik URL is known for later use
         if (method_exists('Piwik\\SettingsPiwik', 'getPiwikUrl')) {
             SettingsPiwik::getPiwikUrl();
         }
         /**
          * Triggered before the user is authenticated, when the global authentication object
          * should be created.
          *
          * Plugins that provide their own authentication implementation should use this event
          * to set the global authentication object (which must derive from {@link Piwik\Auth}).
          *
          * **Example**
          *
          *     Piwik::addAction('Request.initAuthenticationObject', function() {
          *         Piwik\Registry::set('auth', new MyAuthImplementation());
          *     });
          */
         Piwik::postEvent('Request.initAuthenticationObject');
         try {
             $authAdapter = 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                                <br />You can activate the plugin by adding:<br />\n                                <code>Plugins[] = Login</code><br />\n                                under the <code>[Plugins]</code> section in your config/config.ini.php");
         }
         Access::getInstance()->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 (Common::getRequestVar('token_auth', false, 'string') !== false) {
             Request::reloadAuthUsingTokenAuth();
         }
         SettingsServer::raiseMemoryLimitIfNecessary();
         Translate::reloadLanguage();
         \Piwik\Plugin\Manager::getInstance()->postLoadPlugins();
         /**
          * Triggered after the platform is initialized and after the user has been authenticated, but
          * before the platform has handled the request.
          *
          * Piwik uses this event to check for updates to Piwik.
          */
         Piwik::postEvent('Platform.initialized');
     } catch (Exception $e) {
         if (self::shouldRethrowException()) {
             throw $e;
         }
         $debugTrace = $e->getTraceAsString();
         Piwik_ExitWithMessage($e->getMessage(), $debugTrace, true);
     }
 }
 /**
  * Read configuration from files into memory
  *
  * @throws Exception if local config file is not readable; exits for other errors
  */
 public function init()
 {
     $this->initialized = true;
     // read defaults from global.ini.php
     if (!is_readable($this->pathGlobal)) {
         Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal)));
     }
     $this->configGlobal = _parse_ini_file($this->pathGlobal, true);
     if (empty($this->configGlobal)) {
         Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionUnreadableFileDisabledMethod', array($this->pathGlobal, "parse_ini_file()")));
     }
     // read the local settings from config.ini.php
     if (!is_readable($this->pathLocal)) {
         throw new Exception(Piwik_TranslateException('General_ExceptionConfigurationFileNotFound', array($this->pathLocal)));
     }
     $this->configLocal = _parse_ini_file($this->pathLocal, true);
     if (empty($this->configLocal)) {
         Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionUnreadableFileDisabledMethod', array($this->pathLocal, "parse_ini_file()")));
     }
 }
Beispiel #6
0
	public static function start($options = false)
	{
		if(Piwik_Common::isPhpCliMode() || version_compare(Piwik_GetOption('version_core'), '1.5-b5') < 0)
		{
			return;
		}

		// 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_Url::getCurrentScheme() === 'https')
		{
			@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', '');

		// we consider these to be misconfigurations, in that
		// - user  - we can't verify that user-defined session handler functions have been set via session_set_save_handler()
		// - mm    - this handler is not recommended, unsupported, not available for Windows, and has a potential concurrency issue
		// - files - this handler doesn't work well in load-balanced environments and may have a concurrency issue with locked session files
		$currentSaveHandler = ini_get('session.save_handler');
		if(in_array($currentSaveHandler, array('user', 'mm', 'files')))
		{
			$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());
			Piwik_ExitWithMessage(Piwik_Translate('General_ExceptionUnableToStartSession'));
		}
	}
 /**
  * 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));
 }
Beispiel #8
0
 public function displayDbConnectionMessage($exception = null)
 {
     $view = new PiwikView("@Installation/cannotConnectToDb");
     $view->exceptionMessage = $exception->getMessage();
     Piwik_ExitWithMessage($view->render());
 }
Beispiel #9
0
 /**
  * Read configuration from files into memory
  *
  * @throws Exception if local config file is not readable; exits for other errors
  */
 public function init()
 {
     $this->initialized = true;
     $reportError = !empty($GLOBALS['PIWIK_TRACKER_MODE']);
     // read defaults from global.ini.php
     if (!is_readable($this->pathGlobal) && $reportError) {
         Piwik_ExitWithMessage(Piwik::translate('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal)));
     }
     $this->configGlobal = _parse_ini_file($this->pathGlobal, true);
     if (empty($this->configGlobal) && $reportError) {
         Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathGlobal, "parse_ini_file()")));
     }
     $this->configCommon = _parse_ini_file($this->pathCommon, true);
     if ($reportError) {
         $this->checkLocalConfigFound();
     }
     $this->configLocal = _parse_ini_file($this->pathLocal, true);
     if (empty($this->configLocal) && $reportError) {
         Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathLocal, "parse_ini_file()")));
     }
 }
	/**
	 * 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/'
			);
			
			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(Zend_Registry::get('config')->General->maintenance_mode == 1
				&& !Piwik_Common::isPhpCliMode())
			{
				throw new Exception("Piwik is in scheduled maintenance. Please come back later.");
			}
			
			$pluginsManager = Piwik_PluginsManager::getInstance();
			$pluginsManager->loadPlugins( Zend_Registry::get('config')->Plugins->Plugins->toArray() );

			if($exceptionToThrow)
			{
				throw $exceptionToThrow;
			}

			try {
				Piwik::createDatabaseObject();
			} catch(Exception $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?
									<br />You can activate the plugin by adding:<br />
									<code>Plugins[] = Login</code><br />
									under the <code>[Plugins]</code> section in your config/config.inc.php");
			}
			
			Zend_Registry::get('access')->reloadAccess($authAdapter);
			
			Piwik_Translate::getInstance()->reloadLanguage();

			Piwik::raiseMemoryLimitIfNecessary();

			$pluginsManager->postLoadPlugins();
			
			Piwik_PostEvent('FrontController.checkForUpdates');
		} catch(Exception $e) {
			Piwik_ExitWithMessage($e->getMessage(), false, true);
		}
		
		Piwik::log('End FrontController->init() - Request: '. var_export($_REQUEST, true));
	}
 /**
  * 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));
 }
Beispiel #12
0
 public function init()
 {
     if (!is_readable($this->pathIniFileDefaultConfig)) {
         Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionConfigurationFileNotFound', array($this->pathIniFileDefaultConfig)));
     }
     $this->defaultConfig = new Piwik_Config_Ini($this->pathIniFileDefaultConfig, null, true);
     if (is_null($this->defaultConfig) || count($this->defaultConfig->toArray()) == 0) {
         Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionUnreadableFileDisabledMethod', array($this->pathIniFileDefaultConfig, "parse_ini_file()")));
     }
     if (!is_readable($this->pathIniFileUserConfig)) {
         throw new Exception(Piwik_TranslateException('General_ExceptionConfigurationFileNotFound', array($this->pathIniFileUserConfig)));
     }
     $this->userConfig = new Piwik_Config_Ini($this->pathIniFileUserConfig, null, true);
     if (is_null($this->userConfig) || count($this->userConfig->toArray()) == 0) {
         Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionUnreadableFileDisabledMethod', array($this->pathIniFileUserConfig, "parse_ini_file()")));
     }
 }
Beispiel #13
0
 /**
  * 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 (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);
     } 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
             $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::warning('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' target='_blank'>enable database session storage</a>.";
         }
         $pathToSessions = Filechecks::getErrorMessageMissingPermissions(Filesystem::getPathToPiwikRoot() . '/tmp/sessions/');
         $pathToSessions = SettingsPiwik::rewriteTmpPathWithInstanceId($pathToSessions);
         $message = sprintf("Error: %s %s %s\n<pre>Debug: the original error was \n%s</pre>", Piwik::translate('General_ExceptionUnableToStartSession'), $pathToSessions, $enableDbSessions, $e->getMessage());
         Piwik_ExitWithMessage($message, $e->getTraceAsString());
     }
 }
Beispiel #14
0
	/**
	 * Helper method used to redirect the current http request to another module/action
	 * If specified, will also redirect to a given website, period and /or date
	 * 
	 * @param string $moduleToRedirect Module, eg. "MultiSites"
	 * @param string $actionToRedirect Action, eg. "index"
	 * @param string $websiteId Website ID, eg. 1
	 * @param string $defaultPeriod Default period, eg. "day"
	 * @param string $defaultDate Default date, eg. "today"
	 */
	function redirectToIndex($moduleToRedirect, $actionToRedirect, $websiteId = null, $defaultPeriod = null, $defaultDate = null, $parameters = array())
	{
		if(is_null($websiteId))
		{
			$websiteId = $this->getDefaultWebsiteId();
		}
		if(is_null($defaultDate))
		{
			$defaultDate = $this->getDefaultDate();
		}
		if(is_null($defaultPeriod))
		{
			$defaultPeriod = $this->getDefaultPeriod();
		}
		$parametersString = '';
		if(!empty($parameters))
		{
			$parametersString = '&' . Piwik_Url::getQueryStringFromParameters($parameters);
		}

		if($websiteId) {
			$url = "Location: index.php?module=".$moduleToRedirect
									."&action=".$actionToRedirect
									."&idSite=".$websiteId
									."&period=".$defaultPeriod
									."&date=".$defaultDate
									.$parametersString;
			header($url);
			exit;
		}
		
		if(Piwik::isUserIsSuperUser())
		{
			Piwik_ExitWithMessage("Error: no website was found in this Piwik installation. 
			<br />Check the table '". Piwik_Common::prefixTable('site') ."' that should contain your Piwik websites.", false, true);
		}
		
		$currentLogin = Piwik::getCurrentUserLogin();
		if(!empty($currentLogin)
			&& $currentLogin != 'anonymous')
		{
			$errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:".Piwik::getSuperUserEmail()."?subject=Access to Piwik for user $currentLogin'>", "</a>");
			$errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='index.php?module=". Zend_Registry::get('auth')->getName() ."&amp;action=logout'>&rsaquo; ". Piwik_Translate('General_Logout'). "</a></b><br />";
			Piwik_ExitWithMessage($errorMessage, false, true);
		}

		Piwik_FrontController::getInstance()->dispatch(Piwik::getLoginPluginName(), false);
		exit;
	}
Beispiel #15
0
/**
 * Converts PHP variable or array into a "JSON" (JavaScript value expression
 * or "object notation") string.
 *
 * @compat
 *    Output seems identical to PECL versions. "Only" 20x slower than PECL version.
 * @bugs
 *    Doesn't take care with unicode too much - leaves UTF-8 sequences alone.
 *
 * @param  $var mixed  PHP variable/array/object
 * @return string      transformed into JSON equivalent
 */
if (!function_exists("json_encode")) {
    if (!function_exists('utf8_decode')) {
        Piwik_ExitWithMessage('
		When using PHP < 5.2.0, Piwik requires the PHP extension XML. 
		<br>Please install this extension to continue using Piwik. 
		<br>More information on <a href="http://php.net/manual/en/xml.installation.php">http://php.net/manual/en/xml.installation.php</a>.');
    }
    function json_encode($var, $obj = FALSE)
    {
        #-- prepare JSON string
        $json = "";
        #-- add array entries
        if (is_array($var) || ($obj = is_object($var))) {
            #-- check if array is associative
            if (!$obj) {
                foreach ((array) $var as $i => $v) {
                    if (!is_int($i)) {
                        $obj = 1;
                        break;
                    }
Beispiel #16
0
 /**
  * Checks that the directories Piwik needs write access are actually writable
  * Displays a nice error page if permissions are missing on some directories
  *
  * @param array $directoriesToCheck Array of directory names to check
  */
 public static function checkDirectoriesWritableOrDie($directoriesToCheck = null)
 {
     $resultCheck = Piwik::checkDirectoriesWritable($directoriesToCheck);
     if (array_search(false, $resultCheck) === false) {
         return;
     }
     $directoryList = '';
     foreach ($resultCheck as $dir => $bool) {
         $realpath = Piwik_Common::realpath($dir);
         if (!empty($realpath) && $bool === false) {
             $directoryList .= self::getMakeWritableCommand($realpath);
         }
     }
     // Also give the chown since the chmod is only 755
     if (!Piwik_Common::isWindows()) {
         $realpath = Piwik_Common::realpath(PIWIK_INCLUDE_PATH . '/');
         $directoryList = "<code>chown -R www-data:www-data " . $realpath . "</code><br/>" . $directoryList;
     }
     // The error message mentions chmod 777 in case users can't chown
     $directoryMessage = "<p><b>Piwik couldn't write to some directories</b>.</p> \n\t\t\t\t\t\t\t<p>Try to Execute the following commands on your server:</p>" . "<blockquote>{$directoryList}</blockquote>" . "<p>If this doesn't work, you can try to create the directories with your FTP software, and set the CHMOD to 0777 (with your FTP software, right click on the directories, permissions).</p>" . "<p>After applying the modifications, you can <a href='index.php'>refresh the page</a>.</p>" . "<p>If you need more help, try <a href='?module=Proxy&action=redirect&url=http://piwik.org'>Piwik.org</a>.</p>";
     Piwik_ExitWithMessage($directoryMessage, false, true);
 }
Beispiel #17
0
 /**
  * Read configuration from files into memory
  *
  * @throws Exception if local config file is not readable; exits for other errors
  */
 public function init()
 {
     $this->initialized = true;
     $reportError = SettingsServer::isTrackerApiRequest();
     // read defaults from global.ini.php
     if (!is_readable($this->pathGlobal) && $reportError) {
         Piwik_ExitWithMessage(Piwik::translate('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal)));
     }
     $this->configGlobal = _parse_ini_file($this->pathGlobal, true);
     if (empty($this->configGlobal) && $reportError) {
         Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathGlobal, "parse_ini_file()")));
     }
     $this->configCommon = _parse_ini_file($this->pathCommon, true);
     // Check config.ini.php last
     $this->checkLocalConfigFound();
     $this->configLocal = _parse_ini_file($this->pathLocal, true);
     if (empty($this->configLocal) && $reportError) {
         Piwik_ExitWithMessage(Piwik::translate('General_ExceptionUnreadableFileDisabledMethod', array($this->pathLocal, "parse_ini_file()")));
     }
 }
Beispiel #18
0
 /**
  * Helper method used to redirect the current HTTP request to another module/action.
  *
  * This function will exit immediately after executing.
  *
  * @param string $moduleToRedirect The plugin to redirect to, eg. `"MultiSites"`.
  * @param string $actionToRedirect Action, eg. `"index"`.
  * @param int|null $websiteId The new idSite query parameter, eg, `1`.
  * @param string|null $defaultPeriod The new period query parameter, eg, `'day'`.
  * @param string|null $defaultDate The new date query parameter, eg, `'today'`.
  * @param array $parameters Other query parameters to append to the URL.
  * @api
  */
 public function redirectToIndex($moduleToRedirect, $actionToRedirect, $websiteId = null, $defaultPeriod = null, $defaultDate = null, $parameters = array())
 {
     try {
         $this->doRedirectToUrl($moduleToRedirect, $actionToRedirect, $websiteId, $defaultPeriod, $defaultDate, $parameters);
     } catch (Exception $e) {
         // no website ID to default to, so could not redirect
     }
     if (Piwik::hasUserSuperUserAccess()) {
         Piwik_ExitWithMessage("Error: no website was found in this Piwik installation.\n\t\t\t<br />Check the table '" . Common::prefixTable('site') . "' in your database, it should contain your Piwik websites.", false, true);
     }
     if (!Piwik::isUserIsAnonymous()) {
         $emails = implode(',', Piwik::getAllSuperUserAccessEmailAddresses());
         $errorMessage = sprintf(Piwik::translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:" . $emails . "?subject=Access to Piwik for user {$currentLogin}'>", "</a>");
         $errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='index.php?module=" . Registry::get('auth')->getName() . "&amp;action=logout'>&rsaquo; " . Piwik::translate('General_Logout') . "</a></b><br />";
         Piwik_ExitWithMessage($errorMessage, false, true);
     }
     echo FrontController::getInstance()->dispatch(Piwik::getLoginPluginName(), false);
     exit;
 }
Beispiel #19
0
                            <li><a target="_blank" href="http://piwik.org/faq/">Piwik Frequently Asked Questions</a></li>
                            <li><a target="_blank" href="http://piwik.org/docs/">Piwik Documentation</a></li>
                            <li><a target="_blank" href="http://forum.piwik.org/">Piwik Forums</a></li>
                            <li><a target="_blank" href="http://demo.piwik.org">Piwik Online Demo</a></li>
                            </ul>';
        }
        if ($optionalLinkBack) {
            $optionalLinkBack = '<a href="javascript:window.history.back();">Go Back</a><br/>';
        }
        $headerPage = file_get_contents(PIWIK_INCLUDE_PATH . '/plugins/Morpheus/templates/simpleLayoutHeader.tpl');
        $footerPage = file_get_contents(PIWIK_INCLUDE_PATH . '/plugins/Morpheus/templates/simpleLayoutFooter.tpl');
        $headerPage = str_replace('{$HTML_TITLE}', PAGE_TITLE_WHEN_ERROR, $headerPage);
        $content = '<p>' . $message . '</p>
                    <p>' . $optionalLinkBack . '<a href="index.php">Go to Piwik</a><br/>
                       <a href="index.php?module=Login">Login</a>' . '</p>' . ' ' . (Piwik_ShouldPrintBackTraceWithMessage() ? $optionalTrace : '') . ' ' . $optionalLinks;
        $message = str_replace(array("<br />", "<br>", "<br/>", "</p>"), "\n", $message);
        $message = str_replace("\t", "", $message);
        $message = strip_tags($message);
        if ($isCli) {
            echo $message;
        } else {
            echo $headerPage . $content . $footerPage;
        }
        echo "\n";
        error_log(sprintf("Error in Piwik: %s", str_replace("\n", " ", $message)));
        exit(1);
    }
}
if (!empty($piwik_errorMessage)) {
    Piwik_ExitWithMessage($piwik_errorMessage, false, true);
}
Beispiel #20
0
 function redirectToIndex($moduleToRedirect, $actionToRedirect)
 {
     $sitesId = Piwik_SitesManager_API::getSitesIdWithAtLeastViewAccess();
     if (!empty($sitesId)) {
         $firstSiteId = $sitesId[0];
         $firstSite = new Piwik_Site($firstSiteId);
         if ($firstSite->getCreationDate()->isToday()) {
             $defaultDate = 'today';
         } else {
             $defaultDate = Zend_Registry::get('config')->General->default_day;
         }
         $defaultPeriod = Zend_Registry::get('config')->General->default_period;
         header("Location:index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite={$firstSiteId}&period={$defaultPeriod}&date={$defaultDate}");
     } else {
         if (Piwik::isUserIsSuperUser()) {
             Piwik_ExitWithMessage("Error: no website were found in this Piwik installation. \n\t\t\t\t<br>Check the table '" . Piwik::prefixTable('site') . "' that should contain your Piwik websites.", false, true);
         }
         $currentLogin = Piwik::getCurrentUserLogin();
         if (!empty($currentLogin) && $currentLogin != 'anonymous') {
             $errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivileges'), $currentLogin);
             $errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='?module=" . Zend_Registry::get('auth')->getName() . "&amp;action=logout'>&rsaquo; " . Piwik_Translate('General_Logout') . "</a></b><br />";
             Piwik_ExitWithMessage($errorMessage, false, true);
         } else {
             Piwik_FrontController::dispatch('Login', false);
         }
     }
     exit;
 }
Beispiel #21
0
 public static function start($options = false)
 {
     if (Piwik_Common::isPhpCliMode()) {
         return;
     }
     // 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_Url::getCurrentScheme() === 'https') {
         @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);
     // we consider these to be misconfigurations, in that
     //  - user - Piwik doesn't implement user-defined session handler functions
     // -  mm - is not recommended, not supported, not available for Windows, and has a potential concurrency issue
     $currentSaveHandler = ini_get('session.save_handler');
     if ($currentSaveHandler == 'user' || $currentSaveHandler == 'mm') {
         @ini_set('session.save_handler', 'files');
         @ini_set('session.save_path', '');
     }
     // for "files", we want a writeable folder;
     // for shared hosting, we assume the web server has been securely configured to prevent local session file hijacking
     if (ini_get('session.save_handler') == 'files') {
         $sessionPath = ini_get('session.save_path');
         if (preg_match('/^[0-9]+;(.*)/', $sessionPath, $matches)) {
             $sessionPath = $matches[1];
         }
         if (ini_get('safe_mode') || ini_get('open_basedir') || empty($sessionPath) || !@is_readable($sessionPath) || !@is_writable($sessionPath)) {
             $sessionPath = PIWIK_USER_PATH . '/tmp/sessions';
             $ok = true;
             if (!is_dir($sessionPath)) {
                 Piwik_Common::mkdir($sessionPath);
                 if (!is_dir($sessionPath)) {
                     // Unable to mkdir $sessionPath
                     $ok = false;
                 }
             } else {
                 if (!@is_writable($sessionPath)) {
                     // $sessionPath is not writable
                     $ok = false;
                 }
             }
             if ($ok) {
                 @ini_set('session.save_path', $sessionPath);
                 // garbage collection may disabled by default (e.g., Debian)
                 if (ini_get('session.gc_probability') == 0) {
                     @ini_set('session.gc_probability', 1);
                 }
             }
             // else rely on default setting (assuming it is configured to a writeable folder)
         }
     }
     try {
         Zend_Session::start();
     } catch (Exception $e) {
         // This message is not translateable because translations haven't been loaded yet.
         Piwik_ExitWithMessage('Unable to start session.  Check that session.save_path or tmp/sessions is writeable, and session.auto_start = 0.');
     }
 }
 public function uninstall($redirectAfter = true)
 {
     $pluginName = $this->initPluginModification(static::UNINSTALL_NONCE);
     $this->dieIfPluginsAdminIsDisabled();
     $uninstalled = \Piwik\Plugin\Manager::getInstance()->uninstallPlugin($pluginName);
     if (!$uninstalled) {
         $path = Filesystem::getPathToPiwikRoot() . '/plugins/' . $pluginName . '/';
         $messagePermissions = Filechecks::getErrorMessageMissingPermissions($path);
         $messageIntro = Piwik::translate("Warning: \"%s\" could not be uninstalled. Piwik did not have enough permission to delete the files in {$path}. ", $pluginName);
         $exitMessage = $messageIntro . "<br/><br/>" . $messagePermissions;
         $exitMessage .= "<br> Or manually delete this directory (using FTP or SSH access)";
         Piwik_ExitWithMessage($exitMessage, $optionalTrace = false, $optionalLinks = false, $optionalLinkBack = true);
     }
     $this->redirectAfterModification($redirectAfter);
 }
				}				
				#subh1 {
					color: #879DBD;
					font-size: 25px;
					font-weight: lighter;
				}
				p, li, dt {
					line-height: 140%;
					padding-bottom: 2px;
				}
				ul, ol { padding: 5px 5px 5px 20px; }
				</style>
				</head>
				<body>
					<span id="h1">Piwik </span><span id="subh1"> # open source web analytics</span>
					<p>' . $message . '</p>				
					<ul>
						<li><a href="http://piwik.org">Piwik homepage</a></li>
						<li><a href="http://piwik.org/demo">Piwik demo</a></li>
					</ul>
				</body>
				</html>';
    echo $html;
    exit;
}
if (isset($piwik_errorMessage)) {
    Piwik_ExitWithMessage($piwik_errorMessage);
}
// we now include the upgradephp package to define some functions used in piwik
// that may not be defined in the current php version
require_once "libs/upgradephp/upgrade.php";
Beispiel #24
0
 /**
  * Helper method used to redirect the current HTTP request to another module/action.
  * 
  * This function will exit immediately after executing.
  *
  * @param string $moduleToRedirect The plugin to redirect to, eg. `"MultiSites"`.
  * @param string $actionToRedirect Action, eg. `"index"`.
  * @param int|null $websiteId The new idSite query parameter, eg, `1`.
  * @param string|null $defaultPeriod The new period query parameter, eg, `'day'`.
  * @param string|null $defaultDate The new date query parameter, eg, `'today'`.
  * @param array $parameters Other query parameters to append to the URL.
  * @api
  */
 public function redirectToIndex($moduleToRedirect, $actionToRedirect, $websiteId = null, $defaultPeriod = null, $defaultDate = null, $parameters = array())
 {
     $userPreferences = new UserPreferences();
     if (empty($websiteId)) {
         $websiteId = $userPreferences->getDefaultWebsiteId();
     }
     if (empty($defaultDate)) {
         $defaultDate = $userPreferences->getDefaultDate();
     }
     if (empty($defaultPeriod)) {
         $defaultPeriod = $userPreferences->getDefaultPeriod();
     }
     $parametersString = '';
     if (!empty($parameters)) {
         $parametersString = '&' . Url::getQueryStringFromParameters($parameters);
     }
     if ($websiteId) {
         $url = "index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite=" . $websiteId . "&period=" . $defaultPeriod . "&date=" . $defaultDate . $parametersString;
         Url::redirectToUrl($url);
         exit;
     }
     if (Piwik::hasUserSuperUserAccess()) {
         Piwik_ExitWithMessage("Error: no website was found in this Piwik installation.\n\t\t\t<br />Check the table '" . Common::prefixTable('site') . "' in your database, it should contain your Piwik websites.", false, true);
     }
     $currentLogin = Piwik::getCurrentUserLogin();
     if (!empty($currentLogin) && $currentLogin != 'anonymous') {
         $emails = implode(',', Piwik::getAllSuperUserAccessEmailAddresses());
         $errorMessage = sprintf(Piwik::translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:" . $emails . "?subject=Access to Piwik for user {$currentLogin}'>", "</a>");
         $errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='index.php?module=" . Registry::get('auth')->getName() . "&amp;action=logout'>&rsaquo; " . Piwik::translate('General_Logout') . "</a></b><br />";
         Piwik_ExitWithMessage($errorMessage, false, true);
     }
     echo FrontController::getInstance()->dispatch(Piwik::getLoginPluginName(), false);
     exit;
 }
Beispiel #25
0
 /**
  * Must be called before dispatch()
  * - checks that directories are writable,
  * - loads the configuration file,
  * - loads the plugin, 
  * - inits the DB connection,
  * - etc.
  */
 function init()
 {
     try {
         Zend_Registry::set('timer', new Piwik_Timer());
         $directoriesToCheck = array('/tmp', '/tmp/templates_c', '/tmp/cache');
         Piwik::checkDirectoriesWritableOrDie($directoriesToCheck);
         self::assignCliParametersToRequest();
         Piwik_Translate::getInstance()->loadEnglishTranslation();
         $exceptionToThrow = false;
         try {
             Piwik::createConfigObject();
         } catch (Exception $e) {
             Piwik_PostEvent('FrontController.NoConfigurationFile', $e);
             $exceptionToThrow = $e;
         }
         $pluginsManager = Piwik_PluginsManager::getInstance();
         $pluginsManager->setPluginsToLoad(Zend_Registry::get('config')->Plugins->Plugins->toArray());
         if ($exceptionToThrow) {
             throw $exceptionToThrow;
         }
         Piwik_Translate::getInstance()->loadUserTranslation();
         try {
             Piwik::createDatabaseObject();
         } catch (Exception $e) {
             Piwik_PostEvent('FrontController.badConfigurationFile', $e);
             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();
         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.inc.php");
         }
         Zend_Registry::get('access')->reloadAccess($authAdapter);
         Piwik::raiseMemoryLimitIfNecessary();
         $pluginsManager->setLanguageToLoad(Piwik_Translate::getInstance()->getLanguageToLoad());
         $pluginsManager->postLoadPlugins();
         Piwik_PostEvent('FrontController.checkForUpdates');
     } catch (Exception $e) {
         Piwik_ExitWithMessage($e->getMessage(), $e->getTraceAsString(), true);
     }
 }
Beispiel #26
0
 /**
  * Checks that the directories Piwik needs write access are actually writable
  * Displays a nice error page if permissions are missing on some directories
  *
  * @param array $directoriesToCheck Array of directory names to check
  */
 public static function checkDirectoriesWritableOrDie($directoriesToCheck = null)
 {
     $resultCheck = Piwik::checkDirectoriesWritable($directoriesToCheck);
     if (array_search(false, $resultCheck) === false) {
         return;
     }
     $directoryList = '';
     foreach ($resultCheck as $dir => $bool) {
         $realpath = Piwik_Common::realpath($dir);
         if (!empty($realpath) && $bool === false) {
             if (Piwik_Common::isWindows()) {
                 $directoryList .= "<code>cacls {$realpath} /t /g " . get_current_user() . ":f</code><br />";
             } else {
                 $directoryList .= "<code>chmod 0777 {$realpath}</code><br />";
             }
         }
     }
     $directoryMessage = "<p><b>Piwik couldn't write to some directories</b>.</p> <p>Try to Execute the following commands on your server:</p>" . "<blockquote>{$directoryList}</blockquote>" . "<p>If this doesn't work, you can try to create the directories with your FTP software, and set the CHMOD to 0777 (with your FTP software, right click on the directories, permissions).</p>" . "<p>After applying the modifications, you can <a href='index.php'>refresh the page</a>.</p>" . "<p>If you need more help, try <a href='?module=Proxy&action=redirect&url=http://piwik.org'>Piwik.org</a>.</p>";
     Piwik_ExitWithMessage($directoryMessage, false, true);
 }
Beispiel #27
0
 function redirectToIndex($moduleToRedirect, $actionToRedirect)
 {
     $websiteId = $this->getDefaultWebsiteId();
     $defaultDate = $this->getDefaultDate();
     $defaultPeriod = $this->getDefaultPeriod();
     if ($websiteId) {
         header("Location:index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite=" . $websiteId . "&period=" . $defaultPeriod . "&date=" . $defaultDate);
         exit;
     }
     if (Piwik::isUserIsSuperUser()) {
         Piwik_ExitWithMessage("Error: no website were found in this Piwik installation. \n\t\t\t<br>Check the table '" . Piwik::prefixTable('site') . "' that should contain your Piwik websites.", false, true);
     }
     $currentLogin = Piwik::getCurrentUserLogin();
     if (!empty($currentLogin) && $currentLogin != 'anonymous') {
         $errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivileges'), $currentLogin);
         $errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='index.php?module=" . Zend_Registry::get('auth')->getName() . "&amp;action=logout'>&rsaquo; " . Piwik_Translate('General_Logout') . "</a></b><br />";
         Piwik_ExitWithMessage($errorMessage, false, true);
     }
     Piwik_FrontController::dispatch('Login', false);
     exit;
 }