Example #1
0
 /**
  * Returns array containing data about the website: goals, URLs, etc.
  *
  * @param int $idSite
  * @return array
  */
 static function getCacheWebsiteAttributes($idSite)
 {
     require_once PIWIK_INCLUDE_PATH . '/core/Loader.php';
     static $cache = null;
     if (is_null($cache)) {
         $cache = new Piwik_CacheFile('tracker');
     }
     $filename = $idSite;
     $cacheContent = $cache->get($filename);
     if ($cacheContent !== false) {
         return $cacheContent;
     }
     if (defined('PIWIK_TRACKER_MODE') && PIWIK_TRACKER_MODE) {
         require_once PIWIK_INCLUDE_PATH . '/core/PluginsManager.php';
         require_once PIWIK_INCLUDE_PATH . '/core/Translate.php';
         require_once PIWIK_INCLUDE_PATH . '/core/Option.php';
         Zend_Registry::set('db', Piwik_Tracker::getDatabase());
         Piwik::createAccessObject();
         Piwik::createConfigObject();
         Piwik::setUserIsSuperUser();
         $pluginsManager = Piwik_PluginsManager::getInstance();
         $pluginsManager->setPluginsToLoad(Zend_Registry::get('config')->Plugins->Plugins->toArray());
     }
     $content = array();
     Piwik_PostEvent('Common.fetchWebsiteAttributes', $content, $idSite);
     // if nothing is returned from the plugins, we don't save the content
     // this is not expected: all websites are expected to have at least one URL
     if (!empty($content)) {
         $cache->set($filename, $content);
     }
     return $content;
 }
Example #2
0
	static function update()
	{
		$config = Zend_Registry::get('config');
		$salt = Piwik_Common::generateUniqId();
		try {
			if(isset($config->superuser->salt))
			{
				return;
			}

			if(is_writable( Piwik_Config::getDefaultUserConfigPath() ))
			{
				$superuser_info = $config->superuser->toArray();
				$superuser_info['salt'] = $salt;
				$config->superuser = $superuser_info;
				$config->__destruct();

				Piwik::createConfigObject();

				return;
			}
		} catch(Exception $e) { }

		throw new Piwik_Updater_UpdateErrorException("Edit config.ini.php and add below <code>[superuser]</code> the following line <br/><code>salt = $salt</code>");
	}
Example #3
0
	static function update()
	{
		$config = Zend_Registry::get('config');
		$dbInfos = $config->database->toArray();
		if(!isset($dbInfos['schema']))
		{
			try {
				if(is_writable( Piwik_Config::getDefaultUserConfigPath() ))
				{
					$dbInfos['schema'] = 'Myisam';
					$config->database = $dbInfos;

					$config->__destruct();
					Piwik::createConfigObject();
				}
				else
				{
					throw new Exception('mandatory update failed');
				}
			} catch(Exception $e) {
				throw new Piwik_Updater_UpdateErrorException("Please edit your config/config.ini.php file and add below <code>[database]</code> the following line: <br /><code>schema = Myisam</code>");
			}
		}

		Piwik_Updater::updateDatabase(__FILE__, self::getSql());
	}
Example #4
0
 public function setUp()
 {
     parent::setUp();
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     Piwik_DataTable_Manager::getInstance()->deleteAll();
 }
Example #5
0
 protected static function initCorePiwikInTrackerMode()
 {
     static $init = false;
     if (!empty($GLOBALS['PIWIK_TRACKER_MODE']) && $init === false) {
         $init = true;
         require_once PIWIK_INCLUDE_PATH . '/core/Loader.php';
         require_once PIWIK_INCLUDE_PATH . '/core/Translate.php';
         require_once PIWIK_INCLUDE_PATH . '/core/Option.php';
         try {
             $access = Zend_Registry::get('access');
         } catch (Exception $e) {
             Piwik::createAccessObject();
         }
         try {
             $config = Zend_Registry::get('config');
         } catch (Exception $e) {
             Piwik::createConfigObject();
         }
         try {
             $db = Zend_Registry::get('db');
         } catch (Exception $e) {
             Piwik::createDatabaseObject();
         }
         $pluginsManager = Piwik_PluginsManager::getInstance();
         $pluginsToLoad = Zend_Registry::get('config')->Plugins->Plugins->toArray();
         $pluginsForcedNotToLoad = Piwik_Tracker::getPluginsNotToLoad();
         $pluginsToLoad = array_diff($pluginsToLoad, $pluginsForcedNotToLoad);
         $pluginsManager->loadPlugins($pluginsToLoad);
     }
 }
Example #6
0
 public function test_fetchRemoteFile()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $methods = array('curl', 'fopen', 'socket');
     $this->assertTrue(in_array(Piwik_Http::getTransportMethod(), $methods));
     foreach ($methods as $method) {
         $version = '';
         try {
             $version = Piwik_Http::sendHttpRequestBy($method, 'http://api.piwik.org/1.0/getLatestVersion/', 5);
         } catch (Exception $e) {
             var_dump($e->getMessage());
         }
         $this->assertTrue(preg_match('/^([0-9.]+)$/', $version), $method);
     }
     $destinationPath = PIWIK_USER_PATH . '/tmp/latest/LATEST';
     try {
         Piwik_Http::fetchRemoteFile('http://api.piwik.org/1.0/getLatestVersion/', $destinationPath, 3);
     } catch (Exception $e) {
         var_dump($e->getMessage());
     }
     $this->assertTrue(filesize($destinationPath) > 0);
     $destinationPath = PIWIK_USER_PATH . '/tmp/latest/latest.zip';
     try {
         Piwik_Http::fetchRemoteFile('http://piwik.org/latest.zip', $destinationPath, 3);
     } catch (Exception $e) {
         var_dump($e->getMessage());
     }
     $this->assertTrue(filesize($destinationPath) > 0);
 }
 function test_callableApiMethods_doNotFail()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     Piwik::createLogObject();
     Piwik::createAccessObject();
     Piwik::createDatabaseObject();
     Piwik::setUserIsSuperUser();
     Piwik_Translate::getInstance()->loadEnglishTranslation();
     $pluginsManager = Piwik_PluginsManager::getInstance();
     $pluginsManager->loadPlugins(Piwik_Config::getInstance()->Plugins['Plugins']);
     Piwik_SitesManager_API::getInstance()->addSite("name", "http://example.org");
     $apiGenerator = new Piwik_API_DocumentationGenerator_CallAllMethods();
     $requestUrls = $apiGenerator->getAllRequestsWithParameters();
     $this->assertTrue(count($requestUrls) > 20);
     foreach ($requestUrls as $url) {
         $call = new Piwik_API_Request($url);
         $output = $call->process();
         //			var_dump($url);
         //			var_dump($output);
         $this->assertTrue(!empty($output));
     }
     Piwik_Translate::getInstance()->unloadEnglishTranslation();
     $this->pass();
 }
 /**
  * Setup the database and create the base tables for all tests
  */
 public function setUp()
 {
     parent::setUp();
     try {
         Piwik::createConfigObject();
         Piwik_Config::getInstance()->setTestEnvironment();
         $dbConfig = Piwik_Config::getInstance()->database;
         $dbName = $dbConfig['dbname'];
         $dbConfig['dbname'] = null;
         Piwik::createDatabaseObject($dbConfig);
         Piwik::dropDatabase();
         Piwik::createDatabase($dbName);
         Piwik::disconnectDatabase();
         Piwik::createDatabaseObject();
         Piwik::createTables();
         Piwik::createLogObject();
         Piwik_PluginsManager::getInstance()->loadPlugins(array());
     } catch (Exception $e) {
         $this->fail("TEST INITIALIZATION FAILED: " . $e->getMessage());
     }
     include "DataFiles/SearchEngines.php";
     include "DataFiles/Languages.php";
     include "DataFiles/Countries.php";
     include "DataFiles/Currencies.php";
     include "DataFiles/LanguageToCountry.php";
 }
Example #9
0
 public function test_isAcceptableRemoteUrl()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $data = array('http://piwik.org/' => array(true), 'http://piwik.org' => array(true), 'http://qa.piwik.org/' => array(true), 'http://forum.piwik.org/' => array(true), 'http://dev.piwik.org/' => array(true), 'http://demo.piwik.org/' => array(true), 'http://www.piwik.org/' => array(false), 'https://piwik.org/' => array(false), 'http://example.org/' => array(false));
     foreach ($data as $url => $expected) {
         $this->assertEqual(Piwik_Proxy_Controller::isPiwikUrl($url), $expected[0], $url);
     }
 }
Example #10
0
 public function test_getAcceptableOrigins()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $tests = array('example.com' => array('http://example.com', 'https://example.com'), 'example.com:80' => array('http://example.com', 'https://example.com'), 'example.com:443' => array('http://example.com', 'https://example.com'), 'example.com:8080' => array('http://example.com', 'https://example.com', 'http://example.com:8080', 'https://example.com:8080'));
     foreach ($tests as $host => $expected) {
         $_SERVER['HTTP_HOST'] = $host;
         $this->assertEqual(Piwik_Nonce::getAcceptableOrigins(), $expected, $host);
     }
 }
Example #11
0
 function setUp()
 {
     parent::setUp();
     $pseudoMockAccess = new MockPiwik_Access();
     $pseudoMockAccess->setReturnValue('isSuperUser', true);
     Zend_Registry::set('access', $pseudoMockAccess);
     Piwik::createConfigObject();
     $user_agents = array('Mozilla/6.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4', 'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/18.6.872.0 Safari/535.2 UNTRUSTED/1.0 3gpp-gba UNTRUSTED/1.0', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1');
     $_SERVER['HTTP_USER_AGENT'] = $user_agents[mt_rand(0, count($user_agents) - 1)];
 }
Example #12
0
	static function update()
	{
		$config = Zend_Registry::get('config');
		$salt = Piwik_Common::generateUniqId();
		if(!isset($config->superuser->salt))
		{
			try {
				if(is_writable( Piwik_Config::getDefaultUserConfigPath() ))
				{
					$superuser_info = $config->superuser->toArray();
					$superuser_info['salt'] = $salt;
					$config->superuser = $superuser_info;

					$config->__destruct();
					Piwik::createConfigObject();
				}
				else
				{
					throw new Exception('mandatory update failed');
				}
			} catch(Exception $e) {
				throw new Piwik_Updater_UpdateErrorException("Please edit your config/config.ini.php file and add below <code>[superuser]</code> the following line: <br/><code>salt = $salt</code>");
			}
		}

		$config = Zend_Registry::get('config');
		$plugins = $config->Plugins->toArray();
		if(!in_array('MultiSites', $plugins))
		{
			try {
				if(is_writable( Piwik_Config::getDefaultUserConfigPath() ))
				{
					$plugins[] = 'MultiSites';
					$config->Plugins = $plugins;

					$config->__destruct();
					Piwik::createConfigObject();
				}
				else
				{
					throw new Exception('optional update failed');
				}
			} catch(Exception $e) {
				throw new Exception("You can now enable the new MultiSites plugin in the Plugins screen in the Piwik admin!");
			}
		}
		
		Piwik_Updater::updateDatabase(__FILE__, array(
			'ALTER TABLE `'. Piwik::prefixTable('log_action') .'` 
				CHANGE `name` `name` TEXT' => false,
		));
		
	}
Example #13
0
 public function setUp()
 {
     parent::setUp();
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     // setup the access layer (required in Segment contrustor testing if anonymous is allowed to use segments)
     $pseudoMockAccess = new FakeAccess();
     FakeAccess::$superUser = true;
     Zend_Registry::set('access', $pseudoMockAccess);
     // Load and install plugins
     $pluginsManager = Piwik_PluginsManager::getInstance();
     $pluginsManager->loadPlugins(Piwik_Config::getInstance()->Plugins['Plugins']);
 }
 function test_ajaxLibraryVersions()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $jqueryJs = file_get_contents(PIWIK_DOCUMENT_ROOT . '/libs/jquery/jquery.js', false, NULL, 0, 512);
     $this->assertTrue(preg_match('/jQuery (?:JavaScript Library )?v?([0-9.]+)/', $jqueryJs, $matches));
     $this->assertEqual($matches[1], Piwik_Config::getInstance()->General['jquery_version']);
     $jqueryuiJs = file_get_contents(PIWIK_DOCUMENT_ROOT . '/libs/jquery/jquery-ui.js', false, NULL, 0, 512);
     $this->assertTrue(preg_match('/jQuery UI (?:- v)?([0-9.]+)/', $jqueryuiJs, $matches));
     $this->assertEqual($matches[1], Piwik_Config::getInstance()->General['jqueryui_version']);
     $swfobjectJs = file_get_contents(PIWIK_DOCUMENT_ROOT . '/libs/swfobject/swfobject.js', false, NULL, 0, 512);
     $this->assertTrue(preg_match('/SWFObject v([0-9.]+)/', $swfobjectJs, $matches));
     $this->assertEqual($matches[1], Piwik_Config::getInstance()->General['swfobject_version']);
 }
Example #15
0
	static function update()
	{
		$config = Zend_Registry::get('config');
		try {
			if(is_writable( Piwik_Config::getDefaultUserConfigPath() )) {
				$plugins = $config->Plugins->toArray();
				$plugins[] = 'MultiSites';
				$config->Plugins = $plugins;
				$config->__destruct();
				Piwik::createConfigObject();
				return;
			}
		} catch(Exception $e) { }
		throw new Piwik_Updater_UpdateErrorException("You can now enable the new MultiSites plugin in the Plugins screen in the Piwik admin!");
	}
Example #16
0
 function __construct($title = '')
 {
     parent::__construct($title);
     print "The test class extends Test_Database: the test Piwik database is created once in the constructor, and all tables are truncated at the end of EACH unit test method.<br>";
     Piwik::createConfigObject();
     Piwik::createDatabaseObject();
     Zend_Registry::get('config')->setTestEnvironment();
     Zend_Registry::get('config')->disableSavingConfigurationFileUpdates();
     Piwik::createLogObject();
     Piwik::dropDatabase();
     Piwik::createDatabase();
     Piwik::disconnectDatabase();
     Piwik::createDatabaseObject();
     Piwik::createTables();
 }
Example #17
0
 public function test_getCurrentHost()
 {
     $GLOBALS['PIWIK_TRACKER_MODE'] = false;
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $saved = $this->saveGlobals(array('HTTP_HOST', 'HTTP_X_FORWARDED_HOST'));
     $tests = array('localhost IPv4' => array('127.0.0.1', null, null, null, '127.0.0.1'), 'localhost IPv6' => array('[::1]', null, null, null, '[::1]'), 'localhost name' => array('localhost', null, null, null, 'localhost'), 'IPv4 without proxy' => array('128.1.2.3', null, null, null, '128.1.2.3'), 'IPv6 without proxy' => array('[2001::b0b]', null, null, null, '[2001::b0b]'), 'name without proxy' => array('example.com', null, null, null, 'example.com'), 'IPv4 with one proxy' => array('127.0.0.1', '128.1.2.3', 'HTTP_X_FORWARDED_HOST', null, '128.1.2.3'), 'IPv6 with one proxy' => array('[::1]', '[2001::b0b]', 'HTTP_X_FORWARDED_HOST', null, '[2001::b0b]'), 'name with one IPv4 proxy' => array('192.168.1.10', 'example.com', 'HTTP_X_FORWARDED_HOST', null, 'example.com'), 'name with one IPv6 proxy' => array('[::10]', 'www.example.com', 'HTTP_X_FORWARDED_HOST', null, 'www.example.com'), 'name with one named proxy' => array('dmz.example.com', 'www.example.com', 'HTTP_X_FORWARDED_HOST', null, 'www.example.com'), 'IPv4 with multiple proxies' => array('127.0.0.1', '128.1.2.3, 192.168.1.10', 'HTTP_X_FORWARDED_HOST', '192.168.1.*', '128.1.2.3'), 'IPv6 with multiple proxies' => array('[::1]', '[2001::b0b], [::ffff:192.168.1.10]', 'HTTP_X_FORWARDED_HOST', '::ffff:192.168.1.0/124', '[2001::b0b]'), 'name with multiple proxies' => array('dmz.example.com', 'www.example.com, dmz.example.com', 'HTTP_X_FORWARDED_HOST', 'dmz.example.com', 'www.example.com'));
     foreach ($tests as $description => $test) {
         $_SERVER['HTTP_HOST'] = $test[0];
         $_SERVER['HTTP_X_FORWARDED_HOST'] = $test[1];
         Piwik_Config::getInstance()->General['proxy_host_headers'] = array($test[2]);
         Piwik_Config::getInstance()->General['proxy_ips'] = array($test[3]);
         $this->assertEqual(Piwik_Url::getCurrentHost(), $test[4], $description);
     }
     $this->restoreGlobals($saved);
 }
Example #18
0
 public static function setUpBeforeClass()
 {
     try {
         Piwik::createConfigObject();
         Piwik_Config::getInstance()->setTestEnvironment();
         $dbConfig = Piwik_Config::getInstance()->database;
         $dbName = $dbConfig['dbname'];
         $dbConfig['dbname'] = null;
         Piwik::createDatabaseObject($dbConfig);
         Piwik::dropDatabase();
         Piwik::createDatabase($dbName);
         Piwik::disconnectDatabase();
         Piwik::createDatabaseObject();
         Piwik::createTables();
         Piwik::createLogObject();
         Piwik_PluginsManager::getInstance()->loadPlugins(array());
     } catch (Exception $e) {
         self::fail("TEST INITIALIZATION FAILED: " . $e->getMessage());
     }
     include "DataFiles/SearchEngines.php";
     include "DataFiles/Languages.php";
     include "DataFiles/Countries.php";
     include "DataFiles/Currencies.php";
     include "DataFiles/LanguageToCountry.php";
     Piwik::createAccessObject();
     Piwik_PostEvent('FrontController.initAuthenticationObject');
     // We need to be SU to create websites for tests
     Piwik::setUserIsSuperUser();
     // Load and install plugins
     $pluginsManager = Piwik_PluginsManager::getInstance();
     $plugins = $pluginsManager->readPluginsDirectory();
     $pluginsManager->loadPlugins($plugins);
     $pluginsManager->installLoadedPlugins();
     $_GET = $_REQUEST = array();
     $_SERVER['HTTP_REFERER'] = '';
     // Make sure translations are loaded to check messages in English
     Piwik_Translate::getInstance()->loadEnglishTranslation();
     Piwik_LanguagesManager_API::getInstance()->setLanguageForUser('superUserLogin', 'en');
     // List of Modules, or Module.Method that should not be called as part of the XML output compare
     // Usually these modules either return random changing data, or are already tested in specific unit tests.
     self::setApiNotToCall(self::$defaultApiNotToCall);
     self::setApiToCall(array());
 }
Example #19
0
 function __construct($title = '')
 {
     parent::__construct($title);
     try {
         Piwik::createConfigObject();
         Piwik_Config::getInstance()->setTestEnvironment();
         Piwik::createDatabaseObject();
         Piwik::createLogObject();
         Piwik::dropDatabase();
         Piwik::createDatabase();
         Piwik::disconnectDatabase();
         Piwik::createDatabaseObject();
         Piwik::createTables();
         Piwik_PluginsManager::getInstance()->installLoadedPlugins();
     } catch (Exception $e) {
         echo $e->getMessage();
         echo "<br/><b>TEST INITIALIZATION FAILED!";
         throw $e;
     }
 }
 function test_callableApiMethods_doNotFail()
 {
     Piwik::createConfigObject();
     Piwik::createLogObject();
     Piwik::createAccessObject();
     Piwik::createDatabaseObject();
     Piwik::setUserIsSuperUser();
     $pluginsManager = Piwik_PluginsManager::getInstance();
     $pluginsManager->setPluginsToLoad(Zend_Registry::get('config')->Plugins->Plugins->toArray());
     $apiGenerator = new Piwik_API_DocumentationGenerator_CallAllMethods();
     $requestUrls = $apiGenerator->getAllRequestsWithParameters();
     $this->assertTrue(count($requestUrls) > 20);
     foreach ($requestUrls as $url) {
         $call = new Piwik_API_Request($url);
         $output = $call->process();
         //			var_dump($url);
         //			var_dump($output);
         $this->assertTrue(!empty($output));
     }
     $this->pass();
 }
Example #21
0
 public function test_checkValidLoginString()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $fail = array('', '   ', 'a', 'aa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'alpha/beta', 'alpha:beta', 'alpha;beta', 'alpha<beta', 'alpha=beta', 'alpha>beta', 'alpha?beta');
     foreach ($fail as $toTest) {
         try {
             Piwik::checkValidLoginString($toTest);
             $this->fail('Exception raised, expected fail: ' . $toTest);
         } catch (Exception $e) {
             $this->pass();
         }
     }
     $pass = array('aaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', '*****@*****.**');
     foreach ($pass as $toTest) {
         try {
             Piwik::checkValidLoginString($toTest);
             $this->pass();
         } catch (Exception $e) {
             $this->fail('Exception raised, expected pass: ' . $toTest);
         }
     }
 }
Example #22
0
 function oneShotTest_memoryUsageArrayIncreasingIndexOrJumps()
 {
     ini_set('memory_limit', '200M');
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     Piwik::createLogObject();
     //test array[0] array[1] array[2]
     //VS
     // test array[0] array[100] array[200]
     // same memory  usage? hash
     echo "start " . __FUNCTION__ . "<br>";
     echo Piwik::getMemoryUsage();
     $timer = new Piwik_Timer();
     $testId = 2;
     if ($testId == 1) {
         echo "start incrementing index<br>";
         $array = array();
         for ($i = 0; $i < 1000000; $i++) {
             $array[$i] = 1;
         }
     } elseif ($testId == 2) {
         echo "start indexing by strings<br>";
         $array = array();
         for ($i = 0; $i < 1000000; $i++) {
             $array[$i . "_" . $i] = 1;
         }
     } elseif ($testId == 3) {
         echo "start jumping index<br>";
         for ($i = 0; $i < 1000000; $i++) {
             $array[$i * 100] = 1;
         }
     }
     echo $timer . "<br>";
     echo "size serialized:" . Piwik::getPrettySizeFromBytes(strlen(serialize($array))) . "<br>";
     echo Piwik::getMemoryUsage();
     echo "end " . __FUNCTION__ . "<br>";
 }
 *  - Allows to overwrite the Visitor IP, and Server datetime 
 *  
 * @see Main.test.php
 * 
 */
// Wrapping the request inside ob_start() calls to ensure that the Test
// calling us waits for the full request to process before unblocking
ob_start();
define('PIWIK_INCLUDE_PATH', '../..');
define('PIWIK_USER_PATH', PIWIK_INCLUDE_PATH);
require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php';
require_once PIWIK_INCLUDE_PATH . '/core/Loader.php';
// Config files forced to use the test database
// Note that this also provides security for Piwik installs containing tests files:
// this proxy will not record any data in the production database.
Piwik::createConfigObject();
Piwik_Config::getInstance()->setTestEnvironment();
Piwik_Config::getInstance()->PluginsInstalled['PluginsInstalled'] = array();
// Do not run scheduled tasks during tests
Piwik_Config::getInstance()->Tracker['scheduled_tasks_min_interval'] = 0;
// Tests can force the use of 3rd party cookie for ID visitor
if (Piwik_Common::getRequestVar('forceUseThirdPartyCookie', false) == 1) {
    Piwik_Config::getInstance()->Tracker['use_third_party_id_cookie'] = 1;
}
// Tests can force the enabling of IP anonymization
$forceIpAnonymization = false;
if (Piwik_Common::getRequestVar('forceIpAnonymization', false) == 1) {
    Piwik_Config::getInstance()->Tracker['ip_address_mask_length'] = 2;
    $pluginsTracker = Piwik_Config::getInstance()->Plugins_Tracker['Plugins_Tracker'];
    $pluginsTracker[] = "AnonymizeIP";
    Piwik_Config::getInstance()->Plugins_Tracker['Plugins_Tracker'] = $pluginsTracker;
 /**
  * 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));
 }
	/**
	 * 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));
	}
Example #26
0
 /**
  * Overwrite the global GET/POST/COOKIE variables and set the fake ones @see setFakeRequest()
  * Reads the configuration file but disables write to this file
  * Creates the database object & enable profiling by default (@see disableProfiler())
  *
  */
 public function __construct()
 {
     $_COOKIE = $_GET = $_POST = array();
     // init GET and REQUEST to the empty array
     $this->setFakeRequest();
     Piwik::createConfigObject(PIWIK_INCLUDE_PATH . '/config/config.ini.php');
     Zend_Registry::get('config')->disableSavingConfigurationFileUpdates();
     // setup database
     Piwik::createDatabaseObject();
     Piwik_Tracker_Db::enableProfiling();
     $this->timestampToUse = time();
 }
Example #27
0
 function test_getNonProxyIpFromHeader()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $saved = $this->saveGlobals(array('REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR'));
     $ips = array('0.0.0.0', '72.14.204.99', '127.0.0.1', '169.254.0.1', '208.80.152.2', '224.0.0.1');
     // no proxies
     foreach ($ips as $ip) {
         $this->assertEqual(Piwik_IP::getNonProxyIpFromHeader($ip, array()), $ip, $ip);
     }
     // 1.1.1.1 is not a trusted proxy
     $_SERVER['REMOTE_ADDR'] = '1.1.1.1';
     foreach ($ips as $ip) {
         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
         $this->assertEqual(Piwik_IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR')), '1.1.1.1', $ip);
     }
     // 1.1.1.1 is a trusted proxy
     $_SERVER['REMOTE_ADDR'] = '1.1.1.1';
     foreach ($ips as $ip) {
         $_SERVER['HTTP_X_FORWARDED_FOR'] = $ip;
         $this->assertEqual(Piwik_IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR')), $ip, $ip);
         $_SERVER['HTTP_X_FORWARDED_FOR'] = '1.2.3.4, ' . $ip;
         $this->assertEqual(Piwik_IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR')), $ip, $ip);
         // misconfiguration
         $_SERVER['HTTP_X_FORWARDED_FOR'] = $ip . ', 1.1.1.1';
         $this->assertEqual(Piwik_IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR')), $ip, $ip);
     }
     $this->restoreGlobals($saved);
 }
 /**
  * Creates a config object for use w/ tests.
  */
 public static function createTestConfig()
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
 }
Example #29
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);
     }
 }
Example #30
0
 /**
  * @dataProvider getIpFromHeaderTestData
  * @group Core
  * @group IP
  */
 public function testGetIpFromHeader($description, $test)
 {
     Piwik::createConfigObject();
     Piwik_Config::getInstance()->setTestEnvironment();
     $_SERVER['REMOTE_ADDR'] = $test[0];
     $_SERVER['HTTP_X_FORWARDED_FOR'] = $test[1];
     Piwik_Config::getInstance()->General['proxy_client_headers'] = array($test[2]);
     Piwik_Config::getInstance()->General['proxy_ips'] = array($test[3]);
     $this->assertEquals($test[4], Piwik_IP::getIpFromHeader(), $description);
 }