public function setGeneralSettings()
 {
     Piwik::checkUserIsSuperUser();
     $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format'));
     try {
         $this->checkTokenInUrl();
         $enableBrowserTriggerArchiving = Piwik_Common::getRequestVar('enableBrowserTriggerArchiving');
         $todayArchiveTimeToLive = Piwik_Common::getRequestVar('todayArchiveTimeToLive');
         Piwik_ArchiveProcessing::setBrowserTriggerArchiving((bool) $enableBrowserTriggerArchiving);
         Piwik_ArchiveProcessing::setTodayArchiveTimeToLive($todayArchiveTimeToLive);
         // Update email settings
         $mail = array();
         $mail['transport'] = Piwik_Common::getRequestVar('mailUseSmtp') == '1' ? 'smtp' : '';
         $mail['port'] = Piwik_Common::getRequestVar('mailPort', '');
         $mail['host'] = Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('mailHost', ''));
         $mail['type'] = Piwik_Common::getRequestVar('mailType', '');
         $mail['username'] = Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('mailUsername', ''));
         $mail['password'] = Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('mailPassword', ''));
         $mail['encryption'] = Piwik_Common::getRequestVar('mailEncryption', '');
         Piwik_Config::getInstance()->mail = $mail;
         // update branding settings
         Piwik_Config::getInstance()->branding['use_custom_logo'] = Piwik_Common::getRequestVar('useCustomLogo', '0');
         $toReturn = $response->getResponse();
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     echo $toReturn;
 }
Exemple #2
0
 public function setGeneralSettings()
 {
     Piwik::checkUserIsSuperUser();
     $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format'));
     try {
         $this->checkTokenInUrl();
         $enableBrowserTriggerArchiving = Piwik_Common::getRequestVar('enableBrowserTriggerArchiving');
         $todayArchiveTimeToLive = Piwik_Common::getRequestVar('todayArchiveTimeToLive');
         Piwik_ArchiveProcessing::setBrowserTriggerArchiving((bool) $enableBrowserTriggerArchiving);
         Piwik_ArchiveProcessing::setTodayArchiveTimeToLive($todayArchiveTimeToLive);
         // Update email settings
         $mail = Zend_Registry::get('config')->mail;
         $mail->transport = Piwik_Common::getRequestVar('mailUseSmtp') == '1' ? 'smtp' : '';
         $mail->port = Piwik_Common::getRequestVar('mailPort', '');
         $mail->host = Piwik_Common::getRequestVar('mailHost', '');
         $mail->type = Piwik_Common::getRequestVar('mailType', '');
         $mail->username = Piwik_Common::getRequestVar('mailUsername', '');
         $mail->password = Piwik_Common::getRequestVar('mailPassword', '');
         $mail->encryption = Piwik_Common::getRequestVar('mailEncryption', '');
         Zend_Registry::get('config')->mail = $mail->toArray();
         $toReturn = $response->getResponse();
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     echo $toReturn;
 }
Exemple #3
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)
 {
     $event = parent::formatEvent($event);
     $errstr = $event['message'];
     $outputFormat = strtolower(Piwik_Common::getRequestVar('format', 'html', 'string'));
     $response = new Piwik_API_ResponseBuilder($outputFormat);
     $message = $response->getResponseException(new Exception($errstr));
     return parent::format($message);
 }
 /**
  * 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)
 {
     $event = parent::formatEvent($event);
     $errno = $event['errno'];
     $errstr = $event['message'];
     $errfile = $event['errfile'];
     $errline = $event['errline'];
     $backtrace = $event['backtrace'];
     require_once "API/ResponseBuilder.php";
     $outputFormat = strtolower(Piwik_Common::getRequestVar('format', 'html', 'string'));
     $response = new Piwik_API_ResponseBuilder(null, $outputFormat);
     $message = $response->getResponseException(new Exception($errstr));
     return parent::format($message);
 }
Exemple #5
0
 /**
  * Handles the request to the API.
  * It first checks that the method called (parameter 'method') is available in the module (it means that the method exists and is public)
  * It then reads the parameters from the request string and throws an exception if there are missing parameters.
  * It then calls the API Proxy which will call the requested method.
  * 
  * @return mixed The data resulting from the API call  
  */
 public function process()
 {
     // read the format requested for the output data
     $outputFormat = strtolower(Piwik_Common::getRequestVar('format', 'xml', 'string', $this->request));
     // create the response
     $response = new Piwik_API_ResponseBuilder($this->request, $outputFormat);
     try {
         // read parameters
         $moduleMethod = Piwik_Common::getRequestVar('method', null, null, $this->request);
         list($module, $method) = $this->extractModuleAndMethod($moduleMethod);
         if (!Piwik_PluginsManager::getInstance()->isPluginActivated($module)) {
             throw new Piwik_FrontController_PluginDeactivatedException($module);
         }
         $module = "Piwik_" . $module . "_API";
         // if a token_auth is specified in the API request, we load the right permissions
         $token_auth = Piwik_Common::getRequestVar('token_auth', '', 'string', $this->request);
         if ($token_auth) {
             Piwik_PostEvent('API.Request.authenticate', $token_auth);
             Zend_Registry::get('access')->reloadAccess();
         }
         // call the method
         $returnedValue = Piwik_API_Proxy::getInstance()->call($module, $method, $this->request);
         $toReturn = $response->getResponse($returnedValue);
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     return $toReturn;
 }
 public function setSettings()
 {
     $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format'));
     try {
         Piwik::checkUserIsSuperUser();
         $this->checkTokenInUrl();
         $mode = Piwik_Common::getRequestVar('TeraWurflMode');
         $url = Piwik_Common::getRequestVar('TeraWurflURL');
         $path = Piwik_Common::getRequestVar('TeraWurflPath');
         switch ($mode) {
             case 'TeraWurfl':
             case 'TeraWurflEnterprise':
                 if (!(file_exists($path) && (require_once $path))) {
                     echo $response->getResponseException(new Exception("Could not save settings: The file " . htmlentities($path) . " does not exist"));
                     return;
                 } elseif (!class_exists($mode)) {
                     echo $response->getResponseException(new Exception("Could not save settings: The file " . htmlentities($path) . " exists but does not contain the required class " . htmlentities($mode)));
                     return;
                 } else {
                     Piwik_MobileAnalytics::saveSetting('TeraWurflMode', $mode);
                     Piwik_MobileAnalytics::saveSetting('TeraWurflPath', $path);
                 }
                 break;
             case 'TeraWurflRemoteClient':
                 require_once PIWIK_INCLUDE_PATH . '/plugins/MobileAnalytics/TeraWurflRemoteClient.php';
                 try {
                     $this->wurflObj = new TeraWurflRemoteClient($url);
                     @$this->wurflObj->getCapabilitiesFromAgent(null, Piwik_MobileAnalytics::$requiredCapabilities);
                 } catch (Exception $e) {
                     echo $response->getResponseException(new Exception("Could not save settings: A request to the Tera-WURFL web service (" . htmlentities($url) . ") failed."));
                     return;
                 }
                 Piwik_MobileAnalytics::saveSetting('TeraWurflURL', $url);
                 Piwik_MobileAnalytics::saveSetting('TeraWurflMode', $mode);
                 break;
             default:
             case 'disabled':
                 Piwik_MobileAnalytics::saveSetting('TeraWurflMode', 'disabled');
                 break;
         }
         echo $response->getResponse();
     } catch (Exception $e) {
         echo $response->getResponseException($e);
     }
 }
Exemple #7
0
 function setGlobalSettings()
 {
     $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format'));
     try {
         $this->checkTokenInUrl();
         $timezone = Piwik_Common::getRequestVar('timezone', false);
         $excludedIps = Piwik_Common::getRequestVar('excludedIps', false);
         $excludedQueryParameters = Piwik_Common::getRequestVar('excludedQueryParameters', false);
         $currency = Piwik_Common::getRequestVar('currency', false);
         Piwik_SitesManager_API::getInstance()->setDefaultTimezone($timezone);
         Piwik_SitesManager_API::getInstance()->setDefaultCurrency($currency);
         Piwik_SitesManager_API::getInstance()->setGlobalExcludedQueryParameters($excludedQueryParameters);
         Piwik_SitesManager_API::getInstance()->setGlobalExcludedIps($excludedIps);
         $toReturn = $response->getResponse();
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     echo $toReturn;
 }
Exemple #8
0
	protected function getLabelsFromTable($table)
	{
		$request = $_GET;
		$request['serialize'] = 0;
		
		// Apply generic filters
		$response = new Piwik_API_ResponseBuilder($format = 'original', $request);
		$table = $response->getResponse($table);
		
		// If period=lastX we only keep the first resultset as we want to return a plain list
		if($table instanceof Piwik_DataTable_Array)
		{
			$tables = $table->getArray();
			$table = current($tables);
		}
		// Keep the response simple, only include keywords
		$keywords = $table->getColumn('label');
		return $keywords;
	}
 function test_convertMultiDimensionalArrayToJson()
 {
     // Two dimensions standard array
     $input = array("firstElement", array("firstElement", "secondElement"), "thirdElement");
     $this->assertEqual(Piwik_API_ResponseBuilder::convertMultiDimensionalArrayToJson($input), json_encode($input));
     // Two dimensions associative array
     $input = array("firstElement" => "isFirst", "secondElement" => array("firstElement" => "isFirst", "secondElement" => "isSecond"), "thirdElement" => "isThird");
     $this->assertEqual(Piwik_API_ResponseBuilder::convertMultiDimensionalArrayToJson($input), json_encode($input));
     // Two dimensions mixed array
     $input = array("firstElement" => "isFirst", array("firstElement", "secondElement"), "thirdElement" => array("firstElement" => "isFirst", "secondElement" => "isSecond"));
     $this->assertEqual(Piwik_API_ResponseBuilder::convertMultiDimensionalArrayToJson($input), json_encode($input));
 }
Exemple #10
0
 /**
  * Handles the request to the API.
  * It first checks that the method called (parameter 'method') is available in the module (it means that the method exists and is public)
  * It then reads the parameters from the request string and throws an exception if there are missing parameters.
  * It then calls the API Proxy which will call the requested method.
  * 
  * @return mixed The data resulting from the API call  
  */
 public function process()
 {
     // read the format requested for the output data
     $outputFormat = strtolower(Piwik_Common::getRequestVar('format', 'xml', 'string', $this->request));
     // create the response
     $response = new Piwik_API_ResponseBuilder($this->request, $outputFormat);
     try {
         // read parameters
         $moduleMethod = Piwik_Common::getRequestVar('method', null, null, $this->request);
         list($module, $method) = $this->extractModuleAndMethod($moduleMethod);
         if (!Piwik_PluginsManager::getInstance()->isPluginActivated($module)) {
             throw new Piwik_FrontController_PluginDeactivatedException($module);
         }
         $module = "Piwik_" . $module . "_API";
         // call the method
         $returnedValue = Piwik_API_Proxy::getInstance()->call($module, $method, $this->request);
         $toReturn = $response->getResponse($returnedValue);
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     return $toReturn;
 }
 /**
  * Two dimensions mixed array
  *
  * @group Core
  * @group API
  * @group API_ResponseBuilder
  */
 public function testConvertMultiDimensionalMixedArrayToXML()
 {
     $input = array("firstElement" => "isFirst", array("firstElement", "secondElement"), "thirdElement" => array("firstElement" => "isFirst", "secondElement" => "isSecond"));
     $expected = '<firstElement>isFirst</firstElement><row><row>firstElement</row><row>secondElement</row></row><thirdElement><firstElement>isFirst</firstElement><secondElement>isSecond</secondElement></thirdElement>';
     $actual = preg_replace("/[\t\n]+/", '', Piwik_API_ResponseBuilder::convertMultiDimensionalArrayToXml($input));
     $this->assertEquals($expected, $actual);
 }
 /**
  * Method for the recursive descend
  * @return Piwik_DataTable_Row | false
  */
 protected function doFilterRecursiveDescend($labelParts, $dataTable, $date = false)
 {
     if (!$dataTable instanceof Piwik_DataTable) {
         throw new Exception("Using the label filter is not supported for DataTable " . get_class($dataTable));
     }
     // search for the first part of the tree search
     $labelPart = array_shift($labelParts);
     foreach ($this->getLabelVariations($labelPart) as $labelPart) {
         $row = $dataTable->getRowFromLabel($labelPart);
         if ($row !== false) {
             break;
         }
     }
     if ($row === false) {
         // not found
         return false;
     }
     // end of tree search reached
     if (count($labelParts) == 0) {
         return $row;
     }
     // match found on this level and more levels remaining: go deeper
     $request = $this->request;
     // this is why the filter does not work with expanded=1:
     // if the entire table is loaded, the id of sub-datatable has a different semantic.
     $idSubTable = $row->getIdSubDataTable();
     $request['idSubtable'] = $idSubTable;
     if ($date) {
         $request['date'] = $date;
     }
     $class = 'Piwik_' . $this->apiModule . '_API';
     $method = $this->getApiMethodForSubtable();
     // Clean up request for Piwik_API_ResponseBuilder to behave correctly
     unset($request['label']);
     $request['serialize'] = 0;
     $dataTable = Piwik_API_Proxy::getInstance()->call($class, $method, $request);
     $response = new Piwik_API_ResponseBuilder($format = 'original', $request);
     $dataTable = $response->getResponse($dataTable);
     return $this->doFilterRecursiveDescend($labelParts, $dataTable, $date);
 }
	/**
	 * Records settings from the "User Settings" page
	 */
	public function recordUserSettings()
	{
		$response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format'));
		try {
			$this->checkTokenInUrl();
			$alias = Piwik_Common::getRequestVar('alias');
			$email = Piwik_Common::getRequestVar('email');
			$defaultReport = Piwik_Common::getRequestVar('defaultReport');
			$defaultDate = Piwik_Common::getRequestVar('defaultDate');

			$newPassword = false;
			$password = Piwik_Common::getRequestvar('password', false);
			$passwordBis = Piwik_Common::getRequestvar('passwordBis', false);
			if(!empty($password)
				|| !empty($passwordBis))
			{
				if($password != $passwordBis)
				{
					throw new Exception(Piwik_Translate('Login_PasswordsDoNotMatch'));
				}
				$newPassword = $password;
			}
			
			$userLogin = Piwik::getCurrentUserLogin();
			if(Piwik::isUserIsSuperUser())
			{
				$superUser = Zend_Registry::get('config')->superuser;
				$updatedSuperUser = false;

				if($newPassword !== false)
				{
					$newPassword = Piwik_Common::unsanitizeInputValue($newPassword);
					$md5PasswordSuperUser = md5($newPassword);
					$superUser->password = $md5PasswordSuperUser;
					$updatedSuperUser = true;
				}
	 			if($superUser->email != $email)
				{
					$superUser->email = $email;
	 				$updatedSuperUser = true;
				}
				if($updatedSuperUser)
				{
					Zend_Registry::get('config')->superuser = $superUser->toArray();
				}
			}
			else
			{
				Piwik_UsersManager_API::getInstance()->updateUser($userLogin, $newPassword, $email, $alias);
				if($newPassword !== false)
				{
					$newPassword = Piwik_Common::unsanitizeInputValue($newPassword);
				}
			}

			// logs the user in with the new password
			if($newPassword !== false)
			{
				$info = array(
					'login' => $userLogin, 
					'md5Password' => md5($newPassword),
					'rememberMe' => false,
				);
				Piwik_PostEvent('Login.initSession', $info);
			}

			Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, 
																Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, 
																$defaultReport);
			Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, 
																Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE, 
																$defaultDate);
			$toReturn = $response->getResponse();
		} catch(Exception $e ) {
			$toReturn = $response->getResponseException( $e );
		}
		echo $toReturn;
	}
 /**
  * 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));
 }
 /**
  * Load the subtable for a row.
  * Returns null if none is found.
  *
  * @param Piwik_Datatable_Row  $row
  * @param bool|string          $date
  * @throws Exception
  * @return Piwik_DataTable
  */
 protected function loadSubtable($row, $date = false)
 {
     if (!($this->apiModule && $this->apiMethod && count($this->request))) {
         return null;
     }
     $request = $this->request;
     // loading subtables doesn't work if expanded=1 because when the entire table is loaded,
     // the ids of sub-datatables have a different semantic.
     if (Piwik_Common::getRequestVar('expanded', false, 'int', $this->request)) {
         throw new Exception('Cannot load subtable if expanded=1 is set.');
     }
     $idSubTable = $row->getIdSubDataTable();
     if ($idSubTable === null) {
         return null;
     }
     $request['idSubtable'] = $idSubTable;
     if ($date) {
         $request['date'] = $date;
     }
     $class = 'Piwik_' . $this->apiModule . '_API';
     $method = $this->getApiMethodForSubtable();
     $this->manipulateSubtableRequest($request);
     $request['serialize'] = 0;
     $dataTable = Piwik_API_Proxy::getInstance()->call($class, $method, $request);
     $response = new Piwik_API_ResponseBuilder($format = 'original', $request);
     $dataTable = $response->getResponse($dataTable);
     if (method_exists($dataTable, 'applyQueuedFilters')) {
         $dataTable->applyQueuedFilters();
     }
     return $dataTable;
 }
 protected function handleMaintenanceMode()
 {
     if (Piwik_Config::getInstance()->General['maintenance_mode'] == 1 && !Piwik_Common::isPhpCliMode()) {
         $format = Piwik_Common::getRequestVar('format', '');
         $message = "Piwik is in scheduled maintenance. Please come back later." . " The administrator can disable maintenance by editing the file piwik/config/config.ini.php and removing the following: " . " maintenance_mode=1 ";
         if (Piwik_Config::getInstance()->Tracker['record_statistics'] == 0) {
             $message .= ' and record_statistics=0';
         }
         $exception = new Exception($message);
         // extend explain how to re-enable
         // show error message when record stats = 0
         if (empty($format)) {
             throw $exception;
         }
         $response = new Piwik_API_ResponseBuilder($format);
         echo $response->getResponseException($exception);
         exit;
     }
 }