Ejemplo n.º 1
0
 /**
  * @param string  $namespace
  * @param bool    $singleInstance
  */
 public function __construct($namespace = 'Default', $singleInstance = false)
 {
     if (Piwik_Common::isPhpCliMode()) {
         self::$_readable = true;
         return;
     }
     parent::__construct($namespace, $singleInstance);
 }
Ejemplo n.º 2
0
 /**
  * Formats data into a single line to be written by the writer.
  *
  * @param  array    $event    event data
  * @return string             formatted line to write to the log
  */
 public function format($event)
 {
     if (is_array($event['message'])) {
         $message = "<pre>" . var_export($event['message'], true) . "</pre>";
     } else {
         $message = $event['message'];
     }
     if (!Piwik_Common::isPhpCliMode()) {
         $message .= "<br/>";
     }
     $message .= "\n";
     $memory = '';
     // Hacky: let's hide the memory usage in CLI to hide from the archive.php output
     if (!Piwik_Common::isPhpCliMode()) {
         $memory = '[' . Piwik::getMemoryUsage() . '] ';
     }
     $message = '[' . $event['timestamp'] . '] [' . $event['requestKey'] . '] ' . $memory . $message;
     return parent::format($message);
 }
Ejemplo n.º 3
0
 public static function getFormattedString($string)
 {
     if (!Piwik_Common::isPhpCliMode()) {
         @header('Content-Type: text/html; charset=utf-8');
     }
     return $string;
 }
Ejemplo n.º 4
0
	/**
	 * Log a message
	 *
	 * @param string $message
	 */
	static public function log($message = '')
	{
		static $shouldLog = null;
		if(is_null($shouldLog))
		{
			$shouldLog = (Piwik_Common::isPhpCliMode()
							|| Zend_Registry::get('config')->log->log_only_when_cli == 0)
						&& 
						  ( Zend_Registry::get('config')->log->log_only_when_debug_parameter == 0
						  	|| isset($_REQUEST['debug']))
						;
			// It is possible that the logger is not setup:
			// - Tracker request, and debug disabled, 
			// - and some scheduled tasks call code that tries and log something  
			try {
				Zend_Registry::get('logger_message');
			} catch(Exception $e) {
				$shouldLog = false;
			}
		}
		if($shouldLog)
		{
			Zend_Registry::get('logger_message')->logEvent($message);
		}
	}
Ejemplo n.º 5
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.');
     }
 }
Ejemplo n.º 6
0
 /**
  * test of validity of an archive, for today's archive with toronto's timezone
  * @group Core
  * @group ArchiveProcessing
  */
 public function testInitTodayToronto()
 {
     if (!Piwik::isTimezoneSupportEnabled()) {
         $this->markTestSkipped('timezones needs to be supported');
     }
     $now = time();
     $siteTimezone = 'America/Toronto';
     $timestamp = Piwik_Date::factory('now', $siteTimezone)->getTimestamp();
     $dateLabel = date('Y-m-d', $timestamp);
     Piwik_ArchiveProcessing::setBrowserTriggerArchiving(true);
     $archiveProcessing = $this->_createArchiveProcessing('day', $dateLabel, $siteTimezone);
     $archiveProcessing->time = $now;
     // we look at anything processed within the time to live range
     $dateMinArchived = $now - Piwik_ArchiveProcessing::getTodayArchiveTimeToLive();
     $this->assertEquals($archiveProcessing->getMinTimeArchivedProcessed(), $dateMinArchived);
     $this->assertTrue($archiveProcessing->isArchiveTemporary());
     // when browsers don't trigger archives, we force ArchiveProcessing
     // to fetch any of the most recent archive
     Piwik_ArchiveProcessing::setBrowserTriggerArchiving(false);
     // see isArchivingDisabled()
     // Running in CLI doesn't impact the time to live today's archive we are loading
     // From CLI, we will not return data that is 'stale'
     if (!Piwik_Common::isPhpCliMode()) {
         $dateMinArchived = 0;
     }
     $this->assertEquals($archiveProcessing->getMinTimeArchivedProcessed(), $dateMinArchived);
     // this test varies with DST
     $this->assertTrue($archiveProcessing->getStartDatetimeUTC() == date('Y-m-d', $timestamp) . ' 04:00:00' || $archiveProcessing->getStartDatetimeUTC() == date('Y-m-d', $timestamp) . ' 05:00:00');
     $this->assertTrue($archiveProcessing->getEndDatetimeUTC() == date('Y-m-d', $timestamp + 86400) . ' 03:59:59' || $archiveProcessing->getEndDatetimeUTC() == date('Y-m-d', $timestamp + 86400) . ' 04:59:59');
     $this->assertTrue($archiveProcessing->isArchiveTemporary());
 }
Ejemplo n.º 7
0
 /**
  * View factory method
  *
  * @param string $templateName Template name (e.g., 'index')
  * @param int $viewType     View type (e.g., Piwik_View::CLI)
  */
 public static function factory($templateName = null, $viewType = null)
 {
     Piwik_PostEvent('View.getViewType', $viewType);
     // get caller
     $bt = @debug_backtrace();
     if ($bt === null || !isset($bt[0])) {
         throw new Exception("View factory cannot be invoked");
     }
     $path = dirname($bt[0]['file']);
     // determine best view type
     if ($viewType === null) {
         if (Piwik_Common::isPhpCliMode()) {
             $viewType = self::CLI;
         } else {
             $viewType = self::STANDARD;
         }
     }
     // get template filename
     if ($viewType == self::CLI) {
         $templateFile = $path . '/templates/cli_' . $templateName . '.tpl';
         if (file_exists($templateFile)) {
             return new Piwik_View($templateFile, array(), false);
         }
         $viewType = self::STANDARD;
     }
     if ($viewType == self::MOBILE) {
         $templateFile = $path . '/templates/mobile_' . $templateName . '.tpl';
         if (!file_exists($templateFile)) {
             $viewType = self::STANDARD;
         }
     }
     if ($viewType != self::MOBILE) {
         $templateFile = $path . '/templates/' . $templateName . '.tpl';
     }
     // Specified template not found
     // We allow for no specified template
     if (!empty($templateName) && !file_exists($templateFile)) {
         throw new Exception('Template not found: ' . $templateFile);
     }
     return new Piwik_View($templateFile);
 }
Ejemplo n.º 8
0
 public static function shouldLoggerLog()
 {
     try {
         $shouldLog = (Piwik_Common::isPhpCliMode() || Zend_Registry::get('config')->log->log_only_when_cli == 0) && (Zend_Registry::get('config')->log->log_only_when_debug_parameter == 0 || isset($_REQUEST['debug']));
     } catch (Exception $e) {
         $shouldLog = false;
     }
     return $shouldLog;
 }
 /**
  * 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));
 }
<?php

define('PIWIK_INCLUDE_PATH', realpath(dirname(__FILE__) . "/../.."));
define('PIWIK_ENABLE_DISPATCH', false);
define('PIWIK_ENABLE_ERROR_HANDLER', false);
define('PIWIK_ENABLE_SESSION_START', false);
require_once PIWIK_INCLUDE_PATH . "/index.php";
require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
require_once PIWIK_INCLUDE_PATH . "/libs/PiwikTracker/PiwikTracker.php";
Piwik_FrontController::getInstance()->init();
// SECURITY: DO NOT DELETE THIS LINE!
if (!Piwik_Common::isPhpCliMode()) {
    die("ERROR: Must be executed in CLI");
}
$process = new Piwik_StressTests_CopyLogs();
$process->init();
$process->run();
//$process->delete();
class Piwik_StressTests_CopyLogs
{
    function init()
    {
        $config = Piwik_Config::getInstance();
        $config->log['log_only_when_debug_parameter'] = 0;
        $config->log['logger_message'] = array("logger_message" => "screen");
        Piwik::createLogObject();
    }
    function run()
    {
        // Copy all visits in date range into TODAY
        $startDate = '2011-08-12';
Ejemplo n.º 11
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 (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);
     }
 }
Ejemplo n.º 12
0
	/**
	 * Main
	 */
	public function main()
	{
		$this->init();
		
		try {
			if( $this->isVisitValid() )
			{
				self::connectDatabase();
				
				$visit = $this->getNewVisitObject();
				$visit->setRequest($this->request);
				$visit->handle();
				unset($visit);
			}

			// don't run scheduled tasks in CLI mode from Tracker, this is the case 
			// where we bulk load logs & don't want to lose time with tasks
			if(!Piwik_Common::isPhpCliMode()
				&& !$this->authenticated)
			{
				Piwik_Common::runScheduledTasks($now = $this->getCurrentTimestamp());
			}
		} catch (Piwik_Tracker_Db_Exception $e) {
			printDebug("<b>".$e->getMessage()."</b>");
		} catch(Piwik_Tracker_Visit_Excluded $e) {
		} catch(Exception $e) {
			Piwik_Tracker_ExitWithException($e);
		}

		$this->end();
	}
Ejemplo n.º 13
0
 public static function shouldLoggerLog()
 {
     try {
         $shouldLog = (Piwik_Common::isPhpCliMode() || Piwik_Config::getInstance()->log['log_only_when_cli'] == 0) && (Piwik_Config::getInstance()->log['log_only_when_debug_parameter'] == 0 || isset($_REQUEST['debug']));
     } catch (Exception $e) {
         $shouldLog = false;
     }
     return $shouldLog;
 }
Ejemplo n.º 14
0
 /**
  * Returns true if, for some reasons, triggering the archiving is disabled.
  * Note that when a segment is passed to the function, archiving will always occur 
  * (since segments are by default not pre-processed)
  *
  * @return bool
  */
 public function isArchivingDisabled()
 {
     // If segment or range is requested, we allow archiving since it will only archive the minimum data
     if (!$this->shouldProcessReportsAllPlugins($this->getSegment(), $this->period)) {
         return false;
     }
     if (!self::isBrowserTriggerArchivingEnabled() && !Piwik_Common::isPhpCliMode()) {
         return true;
     }
     return false;
 }
Ejemplo n.º 15
0
 protected function runUpdaterAndExit()
 {
     $updater = new Piwik_Updater();
     $componentsWithUpdateFile = Piwik_CoreUpdater::getComponentUpdates($updater);
     if (empty($componentsWithUpdateFile)) {
         Piwik::redirectToModule('CoreHome');
     }
     Piwik::setMaxExecutionTime(0);
     $sqlQueries = $updater->getSqlQueriesToExecute();
     if (Piwik_Common::isPhpCliMode()) {
         $view = Piwik_View::factory('update_welcome');
         $this->doWelcomeUpdates($view, $componentsWithUpdateFile);
         if (!$this->coreError) {
             $view = Piwik_View::factory('update_database_done');
             $this->doExecuteUpdates($view, $updater, $componentsWithUpdateFile);
         }
     } else {
         if (Piwik_Common::getRequestVar('updateCorePlugins', 0, 'integer') == 1 || count($sqlQueries) == 1) {
             $this->warningMessages = array();
             $view = Piwik_View::factory('update_database_done');
             $this->doExecuteUpdates($view, $updater, $componentsWithUpdateFile);
         } else {
             $view = Piwik_View::factory('update_welcome');
             $view->queries = $sqlQueries;
             $this->doWelcomeUpdates($view, $componentsWithUpdateFile);
         }
     }
     exit;
 }
Ejemplo n.º 16
0
Archivo: Log.php Proyecto: ntulip/piwik
 public static function getFormattedString($string)
 {
     if (Piwik_Common::isPhpCliMode()) {
         $string = str_replace(array('<br>', '<br />', '<br/>'), "\n", $string);
         $string = strip_tags($string);
     }
     return $string;
 }
Ejemplo n.º 17
0
	protected function isRequestAuthorizedToArchive()
	{
		return self::isBrowserTriggerArchivingEnabled()
				|| Piwik_Common::isPhpCliMode();
	}
Ejemplo n.º 18
0
 /**
  * Returns if the requested parameter is defined in the command line arguments.
  * If $valuePossible is true, then a value is possibly set for this parameter, 
  * ie. --force-timeout-for-periods=3600 would return 3600
  * 
  * @return true or the value (int,string) if set, false otherwise
  */
 private function isParameterSet($parameter, $valuePossible = false)
 {
     if (!Piwik_Common::isPhpCliMode()) {
         return false;
     }
     $parameters = array("--{$parameter}", "-{$parameter}", $parameter);
     foreach ($parameters as $parameter) {
         foreach ($_SERVER['argv'] as $arg) {
             if (strpos($arg, $parameter) === 0) {
                 if ($valuePossible) {
                     $parameterFound = $arg;
                     if (($posEqual = strpos($parameterFound, '=')) !== false) {
                         $return = substr($parameterFound, $posEqual + 1);
                         if ($return !== false) {
                             return $return;
                         }
                     }
                 }
                 return true;
             }
         }
     }
     return false;
 }
Ejemplo n.º 19
0
 /**
  * Returns true if PHP was invoked as CGI or command-line interface (shell)
  *
  * @deprecated deprecated in 0.4.4
  * @see Piwik_Common::isPhpCliMode()
  * @return bool true if PHP invoked as a CGI or from CLI
  */
 public static function isPhpCliMode()
 {
     return Piwik_Common::isPhpCliMode();
 }
Ejemplo n.º 20
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()
	{
		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));
	}
 protected static function isRequestAuthorizedToArchive()
 {
     return !self::$forceDisableArchiving && (self::isBrowserTriggerArchivingEnabled() || Piwik_Common::isPhpCliMode() || Piwik::isUserIsSuperUser() && Piwik_Common::isArchivePhpTriggered());
 }
Ejemplo n.º 22
0
 public static function getFormattedString($string)
 {
     if (Piwik_Common::isPhpCliMode()) {
         $string = str_replace(array('<br>', '<br />', '<br/>'), "\n", $string);
         if (is_array($string)) {
             for ($i = 0; $i < count($string); $i++) {
                 $string[$i] = strip_tags($string[$i]);
             }
         } else {
             $string = strip_tags($string);
         }
     }
     return $string;
 }
Ejemplo n.º 23
0
 /**
  * Log a message
  *
  * @param string $message
  */
 public static function log($message = '')
 {
     static $shouldLog = null;
     if (is_null($shouldLog)) {
         $shouldLog = (Piwik_Common::isPhpCliMode() || Zend_Registry::get('config')->log->log_only_when_cli == 0) && (Zend_Registry::get('config')->log->log_only_when_debug_parameter == 0 || isset($_REQUEST['debug']));
     }
     if ($shouldLog) {
         Zend_Registry::get('logger_message')->logEvent($message);
     }
 }
Ejemplo n.º 24
0
 /**
  * Returns true if, for some reasons, triggering the archiving is disabled.
  *
  * @return bool
  */
 protected function isArchivingDisabled()
 {
     static $archivingIsDisabled = null;
     if (is_null($archivingIsDisabled)) {
         $archivingIsDisabled = false;
         $enableBrowserArchivingTriggering = (bool) Zend_Registry::get('config')->General->enable_browser_archiving_triggering;
         if ($enableBrowserArchivingTriggering == false) {
             if (!Piwik_Common::isPhpCliMode()) {
                 $archivingIsDisabled = true;
             }
         }
     }
     return $archivingIsDisabled;
 }
Ejemplo n.º 25
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'));
		}
	}
Ejemplo n.º 26
0
 /**
  * Main - tracks the visit/action
  *
  * @param array $args Optional Request Array
  */
 public function main($args = null)
 {
     $displayedGIF = false;
     $this->initRequests($args);
     if (!empty($this->requests)) {
         // handle all visits
         foreach ($this->requests as $request) {
             $this->init($request);
             if (!$displayedGIF && !$this->authenticated) {
                 $this->outputTransparentGif();
                 $displayedGIF = true;
             }
             try {
                 if ($this->isVisitValid()) {
                     self::connectDatabaseIfNotConnected();
                     $visit = $this->getNewVisitObject();
                     $visit->setRequest($request);
                     $visit->handle();
                     unset($visit);
                 } else {
                     printDebug("The request is invalid: empty request, or maybe tracking is disabled in the config.ini.php via record_statistics=0");
                 }
             } catch (Piwik_Tracker_Db_Exception $e) {
                 printDebug("<b>" . $e->getMessage() . "</b>");
                 $this->exitWithException($e, $this->authenticated);
             } catch (Piwik_Tracker_Visit_Excluded $e) {
             } catch (Exception $e) {
                 $this->exitWithException($e, $this->authenticated);
             }
             $this->clear();
             // increment successfully logged request count. make sure to do this after try-catch,
             // since an excluded visit is considered 'successfully logged'
             ++$this->countOfLoggedRequests;
         }
         if (!$displayedGIF) {
             $this->outputTransparentGif();
             $displayedGIF = true;
         }
     } else {
         $this->handleEmptyRequest($_GET + $_POST);
     }
     // run scheduled task
     try {
         // don't run scheduled tasks in CLI mode from Tracker, this is the case
         // where we bulk load logs & don't want to lose time with tasks
         if (!Piwik_Common::isPhpCliMode() && !$this->authenticated) {
             Piwik_Common::runScheduledTasks($now = $this->getCurrentTimestamp());
         }
     } catch (Exception $e) {
         $this->exitWithException($e, $this->authenticated);
     }
     $this->end();
 }
Ejemplo n.º 27
0
 protected function handleSSLRedirection()
 {
     if (!Piwik_Common::isPhpCliMode() && Piwik_Config::getInstance()->General['force_ssl'] == 1 && !Piwik::isHttps() && !(Piwik_Common::getRequestVar('module', '') == 'CoreAdminHome' && Piwik_Common::getRequestVar('action', '') == 'optOut')) {
         $url = Piwik_Url::getCurrentUrl();
         $url = str_replace("http://", "https://", $url);
         Piwik_Url::redirectToUrl($url);
     }
 }