This class reads and writes to the config/config.ini.php file. If config options are missing from that file, this class will look for their default values in config/global.ini.php. ### Examples **Getting a value:** read the minimum_memory_limit option under the [General] section $minValue = Config::getInstance()->General['minimum_memory_limit']; **Setting a value:** set the minimum_memory_limit option Config::getInstance()->General['minimum_memory_limit'] = 256; Config::getInstance()->forceSave(); **Setting an entire section:** Config::getInstance()->MySection = array('myoption' => 1); Config::getInstance()->forceSave();
Inheritance: extends piwik\Singleton
Exemple #1
0
 function __construct($processor)
 {
     parent::__construct($processor);
     $this->columnToSortByBeforeTruncation = Metrics::INDEX_NB_VISITS;
     $this->maximumRowsInDataTable = Config::getInstance()->General['datatable_archiving_maximum_rows_events'];
     $this->maximumRowsInSubDataTable = Config::getInstance()->General['datatable_archiving_maximum_rows_subtable_events'];
 }
Exemple #2
0
 public static function update()
 {
     $salt = Common::generateUniqId();
     $config = Config::getInstance();
     $superuser = $config->superuser;
     if (!isset($superuser['salt'])) {
         try {
             if (is_writable(Config::getLocalConfigPath())) {
                 $superuser['salt'] = $salt;
                 $config->superuser = $superuser;
                 $config->forceSave();
             } else {
                 throw new \Exception('mandatory update failed');
             }
         } catch (\Exception $e) {
             throw new \Piwik\UpdaterErrorException("Please edit your config/config.ini.php file and add below <code>[superuser]</code> the following line: <br /><code>salt = {$salt}</code>");
         }
     }
     $plugins = $config->Plugins;
     if (!in_array('MultiSites', $plugins)) {
         try {
             if (is_writable(Config::getLocalConfigPath())) {
                 $plugins[] = 'MultiSites';
                 $config->Plugins = $plugins;
                 $config->forceSave();
             } 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!");
         }
     }
     Updater::updateDatabase(__FILE__, self::getSql());
 }
 public static function sendNotificationToAdmin($args)
 {
     list($idsite, $idvisitor, $message) = $args;
     $visitorInfo = ChatPersonnalInformation::get($idvisitor);
     $subject = "New message on " . ChatSite::getSiteName($idsite);
     $mail = new Mail();
     $mail->setFrom(Config::getInstance()->General['noreply_email_address'], "Piwik Chat");
     $mail->setSubject($subject);
     $mail->setBodyHtml("Name : " . $visitorInfo['name'] . "<br />\n        Email : " . $visitorInfo['email'] . "<br />\n        Phone : " . $visitorInfo['phone'] . "<br />\n        Comments : " . $visitorInfo['comments'] . "<br />\n        <br /><br />\n        Message:<br />{$message}");
     foreach (ChatCommon::getUsersBySite($idsite) as $user) {
         if (empty($user['email'])) {
             continue;
         }
         if (ChatPiwikUser::isStaffOnline($user['login'])) {
             continue;
         }
         $mail->addTo($user['email']);
         try {
             $mail->send();
         } catch (Exception $e) {
             throw new Exception("An error occured while sending '{$subject}' " . " to " . implode(', ', $mail->getRecipients()) . ". Error was '" . $e->getMessage() . "'");
         }
         $mail->clearRecipients();
     }
 }
 public function setUp()
 {
     parent::setUp();
     Config::getInstance()->setTestEnvironment();
     Config::getInstance()->Plugins['Plugins'] = array();
     $this->unloadAllPlugins();
 }
 public function execute()
 {
     $isPiwikInstalling = !Config::getInstance()->existsLocalConfig();
     if ($isPiwikInstalling) {
         // Skip the diagnostic if Piwik is being installed
         return array();
     }
     $label = $this->translator->translate('Installation_DatabaseAbilities');
     $optionTable = Common::prefixTable('option');
     $testOptionNames = array('test_system_check1', 'test_system_check2');
     $loadDataInfile = false;
     $errorMessage = null;
     try {
         $loadDataInfile = Db\BatchInsert::tableInsertBatch($optionTable, array('option_name', 'option_value'), array(array($testOptionNames[0], '1'), array($testOptionNames[1], '2')), $throwException = true);
     } catch (\Exception $ex) {
         $errorMessage = str_replace("\n", "<br/>", $ex->getMessage());
     }
     // delete the temporary rows that were created
     Db::exec("DELETE FROM `{$optionTable}` WHERE option_name IN ('" . implode("','", $testOptionNames) . "')");
     if ($loadDataInfile) {
         return array(DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_OK, 'LOAD DATA INFILE'));
     }
     $comment = sprintf('LOAD DATA INFILE<br/>%s<br/>%s', $this->translator->translate('Installation_LoadDataInfileUnavailableHelp', array('LOAD DATA INFILE', 'FILE')), $this->translator->translate('Installation_LoadDataInfileRecommended'));
     if ($errorMessage) {
         $comment .= sprintf('<br/><strong>%s:</strong> %s<br/>%s', $this->translator->translate('General_Error'), $errorMessage, 'Troubleshooting: <a target="_blank" href="?module=Proxy&action=redirect&url=http://piwik.org/faq/troubleshooting/%23faq_194">FAQ on piwik.org</a>');
     }
     return array(DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_WARNING, $comment));
 }
 /**
  * Check for a newer version
  *
  * @param bool $force Force check
  * @param int $interval Interval used for update checks
  */
 public static function check($force = false, $interval = null)
 {
     if (!self::isAutoUpdateEnabled()) {
         return;
     }
     if ($interval === null) {
         $interval = self::CHECK_INTERVAL;
     }
     $lastTimeChecked = Option::get(self::LAST_TIME_CHECKED);
     if ($force || $lastTimeChecked === false || time() - $interval > $lastTimeChecked) {
         // set the time checked first, so that parallel Piwik requests don't all trigger the http requests
         Option::set(self::LAST_TIME_CHECKED, time(), $autoLoad = 1);
         $parameters = array('piwik_version' => Version::VERSION, 'php_version' => PHP_VERSION, 'url' => Url::getCurrentUrlWithoutQueryString(), 'trigger' => Common::getRequestVar('module', '', 'string'), 'timezone' => API::getInstance()->getDefaultTimezone());
         $url = Config::getInstance()->General['api_service_url'] . '/1.0/getLatestVersion/' . '?' . http_build_query($parameters, '', '&');
         $timeout = self::SOCKET_TIMEOUT;
         if (@Config::getInstance()->Debug['allow_upgrades_to_beta']) {
             $url = 'http://builds.piwik.org/LATEST_BETA';
         }
         try {
             $latestVersion = Http::sendHttpRequest($url, $timeout);
             if (!preg_match('~^[0-9][0-9a-zA-Z_.-]*$~D', $latestVersion)) {
                 $latestVersion = '';
             }
         } catch (Exception $e) {
             // e.g., disable_functions = fsockopen; allow_url_open = Off
             $latestVersion = '';
         }
         Option::set(self::LATEST_VERSION, $latestVersion);
     }
 }
Exemple #7
0
 private function getValueFromConfig()
 {
     $config = Config::getInstance()->{$this->pluginName};
     if (!empty($config) && array_key_exists($this->name, $config)) {
         return $config[$this->name];
     }
 }
Exemple #8
0
 protected function makeUpdate(InputInterface $input, OutputInterface $output, $doDryRun)
 {
     $this->checkAllRequiredOptionsAreNotEmpty($input);
     $updater = $this->makeUpdaterInstance($output);
     $componentsWithUpdateFile = $updater->getComponentUpdates();
     if (empty($componentsWithUpdateFile)) {
         throw new NoUpdatesFoundException("Everything is already up to date.");
     }
     $output->writeln(array("", "    *** " . Piwik::translate('CoreUpdater_UpdateTitle') . " ***"));
     // handle case of existing database with no tables
     if (!DbHelper::isInstalled()) {
         $this->handleCoreError($output, Piwik::translate('CoreUpdater_EmptyDatabaseError', Config::getInstance()->database['dbname']));
         return;
     }
     $output->writeln(array("", "    " . Piwik::translate('CoreUpdater_DatabaseUpgradeRequired'), "", "    " . Piwik::translate('CoreUpdater_YourDatabaseIsOutOfDate')));
     if ($this->isUpdatingCore($componentsWithUpdateFile)) {
         $currentVersion = $this->getCurrentVersionForCore($updater);
         $output->writeln(array("", "    " . Piwik::translate('CoreUpdater_PiwikWillBeUpgradedFromVersionXToVersionY', array($currentVersion, Version::VERSION))));
     }
     $pluginsToUpdate = $this->getPluginsToUpdate($componentsWithUpdateFile);
     if (!empty($pluginsToUpdate)) {
         $output->writeln(array("", "    " . Piwik::translate('CoreUpdater_TheFollowingPluginsWillBeUpgradedX', implode(', ', $pluginsToUpdate))));
     }
     $dimensionsToUpdate = $this->getDimensionsToUpdate($componentsWithUpdateFile);
     if (!empty($dimensionsToUpdate)) {
         $output->writeln(array("", "    " . Piwik::translate('CoreUpdater_TheFollowingDimensionsWillBeUpgradedX', implode(', ', $dimensionsToUpdate))));
     }
     $output->writeln("");
     if ($doDryRun) {
         $this->doDryRun($updater, $output);
     } else {
         $this->doRealUpdate($updater, $componentsWithUpdateFile, $output);
     }
 }
Exemple #9
0
 private function getActionCategoryDelimiter()
 {
     if (isset(Config::getInstance()->General['action_category_delimiter'])) {
         return Config::getInstance()->General['action_category_delimiter'];
     }
     return Config::getInstance()->General['action_url_category_delimiter'];
 }
 /**
  * @param $auth
  */
 public static function initAuthenticationFromCookie(\Piwik\Auth $auth, $activateCookieAuth)
 {
     if (self::isModuleIsAPI() && !$activateCookieAuth) {
         return;
     }
     $authCookieName = Config::getInstance()->General['login_cookie_name'];
     $authCookieExpiry = 0;
     $authCookiePath = Config::getInstance()->General['login_cookie_path'];
     $authCookie = new Cookie($authCookieName, $authCookieExpiry, $authCookiePath);
     $defaultLogin = '******';
     $defaultTokenAuth = 'anonymous';
     if ($authCookie->isCookieFound()) {
         $defaultLogin = $authCookie->get('login');
         $defaultTokenAuth = $authCookie->get('token_auth');
     }
     $auth->setLogin($defaultLogin);
     $auth->setTokenAuth($defaultTokenAuth);
     $storage = new Storage($defaultLogin);
     if (!$storage->isActive()) {
         return;
     }
     $secret = $storage->getSecret();
     $cookieSecret = $authCookie->get('auth_code');
     if ($cookieSecret == SessionInitializer::getHashTokenAuth($defaultLogin, $secret)) {
         $googleAuth = new PHPGangsta\GoogleAuthenticator();
         $auth->setAuthCode($googleAuth->getCode($secret));
         $auth->validateAuthCode();
     }
 }
Exemple #11
0
 /**
  * @link http://php-di.org/doc/container-configuration.html
  * @throws \Exception
  * @return Container
  */
 public function create()
 {
     $builder = new ContainerBuilder();
     $builder->useAnnotations(false);
     $builder->setDefinitionCache(new ArrayCache());
     // INI config
     $builder->addDefinitions(new IniConfigDefinitionSource(Config::getInstance()));
     // Global config
     $builder->addDefinitions(PIWIK_USER_PATH . '/config/global.php');
     // Plugin configs
     $this->addPluginConfigs($builder);
     // Development config
     if (Development::isEnabled()) {
         $builder->addDefinitions(PIWIK_USER_PATH . '/config/environment/dev.php');
     }
     // User config
     if (file_exists(PIWIK_USER_PATH . '/config/config.php')) {
         $builder->addDefinitions(PIWIK_USER_PATH . '/config/config.php');
     }
     // Environment config
     $this->addEnvironmentConfig($builder);
     if (!empty($this->definitions)) {
         $builder->addDefinitions($this->definitions);
     }
     return $builder->build();
 }
Exemple #12
0
 /**
  * Returns a non-proxy IP address from header.
  *
  * @param string $default Default value to return if there no matching proxy header.
  * @param array $proxyHeaders List of proxy headers.
  * @return string
  */
 public static function getNonProxyIpFromHeader($default, $proxyHeaders)
 {
     $proxyIps = array();
     $config = Config::getInstance()->General;
     if (isset($config['proxy_ips'])) {
         $proxyIps = $config['proxy_ips'];
     }
     if (!is_array($proxyIps)) {
         $proxyIps = array();
     }
     $proxyIps[] = $default;
     // examine proxy headers
     foreach ($proxyHeaders as $proxyHeader) {
         if (!empty($_SERVER[$proxyHeader])) {
             // this may be buggy if someone has proxy IPs and proxy host headers configured as
             // `$_SERVER[$proxyHeader]` could be eg $_SERVER['HTTP_X_FORWARDED_HOST'] and
             // include an actual host name, not an IP
             $proxyIp = self::getLastIpFromList($_SERVER[$proxyHeader], $proxyIps);
             if (strlen($proxyIp) && stripos($proxyIp, 'unknown') === false) {
                 return $proxyIp;
             }
         }
     }
     return $default;
 }
 function init()
 {
     $config = Config::getInstance();
     $config->log['log_only_when_debug_parameter'] = 0;
     $config->log['log_writers'] = array('screen');
     $config->log['log_level'] = 'VERBOSE';
 }
Exemple #14
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->recreateContainerWithWebEnvironment();
     $this->initHostAndQueryString($input);
     if ($this->isTestModeEnabled()) {
         require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/TestingEnvironment.php';
         Config::unsetInstance();
         StaticContainer::clearContainer();
         \Piwik_TestingEnvironment::addHooks();
         $indexFile = '/tests/PHPUnit/proxy/';
         $this->resetDatabase();
     } else {
         $indexFile = '/';
     }
     $indexFile .= 'index.php';
     if (!empty($_GET['pid'])) {
         $process = new Process($_GET['pid']);
         if ($process->hasFinished()) {
             return;
         }
         $process->startProcess();
     }
     require_once PIWIK_INCLUDE_PATH . $indexFile;
     if (!empty($process)) {
         $process->finishProcess();
     }
 }
Exemple #15
0
 /**
  * @dataProvider getTestActiveReleaseChannel
  */
 public function test_getActiveReleaseChannel_shouldReturnCorrectReleaseChannelForId($expectedId, $activeId)
 {
     $backupId = Config::getInstance()->General['release_channel'];
     $this->channels->setActiveReleaseChannelId($activeId);
     $this->assertSame($expectedId, $this->channels->getActiveReleaseChannel()->getId());
     $this->channels->setActiveReleaseChannelId($backupId);
 }
Exemple #16
0
 private static function migrateConfigSuperUserToDb()
 {
     $config = Config::getInstance();
     if (!$config->existsLocalConfig()) {
         return;
     }
     try {
         $superUser = $config->superuser;
     } catch (\Exception $e) {
         $superUser = null;
     }
     if (!empty($superUser['bridge']) || empty($superUser) || empty($superUser['login'])) {
         // there is a super user which is not from the config but from the bridge, that means we already have
         // a super user in the database
         return;
     }
     $userApi = UsersManagerApi::getInstance();
     try {
         Db::get()->insert(Common::prefixTable('user'), array('login' => $superUser['login'], 'password' => $superUser['password'], 'alias' => $superUser['login'], 'email' => $superUser['email'], 'token_auth' => $userApi->getTokenAuth($superUser['login'], $superUser['password']), 'date_registered' => Date::now()->getDatetime(), 'superuser_access' => 1));
     } catch (\Exception $e) {
         echo "There was an issue, but we proceed: " . $e->getMessage();
     }
     if (array_key_exists('salt', $superUser)) {
         $salt = $superUser['salt'];
     } else {
         $salt = Common::generateUniqId();
     }
     $config->General['salt'] = $salt;
     $config->superuser = array();
     $config->forceSave();
 }
 function __construct($processor)
 {
     parent::__construct($processor);
     $this->processor = $processor;
     $this->maximumRowsInDataTableLevelZero = Config::getInstance()->General['datatable_archiving_maximum_rows_custom_variables'];
     $this->maximumRowsInSubDataTable = Config::getInstance()->General['datatable_archiving_maximum_rows_subtable_custom_variables'];
 }
Exemple #18
0
 /**
  * @param bool $standalone When set to true, the Top controls will be hidden to provide better full screen view
  * @param bool $fetch
  * @param bool|string $segmentOverride
  *
  * @return string
  */
 public function realtimeMap($standalone = false, $fetch = false, $segmentOverride = false)
 {
     $this->checkUserCountryPluginEnabled();
     $idSite = Common::getRequestVar('idSite', 1, 'int');
     Piwik::checkUserHasViewAccess($idSite);
     $token_auth = Piwik::getCurrentUserTokenAuth();
     $view = new View('@UserCountryMap/realtimeMap');
     $view->mapIsStandaloneNotWidget = $standalone;
     $view->metrics = $this->getMetrics($idSite, 'range', self::REAL_TIME_WINDOW, $token_auth);
     $view->defaultMetric = 'nb_visits';
     $liveRefreshAfterMs = (int) Config::getInstance()->General['live_widget_refresh_after_seconds'] * 1000;
     $goals = APIGoals::getInstance()->getGoals($idSite);
     $site = new Site($idSite);
     $hasGoals = !empty($goals) || $site->isEcommerceEnabled();
     // maximum number of visits to be displayed in the map
     $maxVisits = Common::getRequestVar('filter_limit', 100, 'int');
     // some translations
     $locale = array('nb_actions' => Piwik::translate('VisitsSummary_NbActionsDescription'), 'local_time' => Piwik::translate('VisitTime_ColumnLocalTime'), 'from' => Piwik::translate('General_FromReferrer'), 'seconds' => Piwik::translate('UserCountryMap_Seconds'), 'seconds_ago' => Piwik::translate('UserCountryMap_SecondsAgo'), 'minutes' => Piwik::translate('UserCountryMap_Minutes'), 'minutes_ago' => Piwik::translate('UserCountryMap_MinutesAgo'), 'hours' => Piwik::translate('UserCountryMap_Hours'), 'hours_ago' => Piwik::translate('UserCountryMap_HoursAgo'), 'days_ago' => Piwik::translate('UserCountryMap_DaysAgo'), 'actions' => Piwik::translate('VisitsSummary_NbPageviewsDescription'), 'searches' => Piwik::translate('UserCountryMap_Searches'), 'goal_conversions' => Piwik::translate('UserCountryMap_GoalConversions'));
     $segment = $segmentOverride ?: Request::getRawSegmentFromRequest() ?: '';
     $params = array('period' => 'range', 'idSite' => $idSite, 'segment' => $segment, 'token_auth' => $token_auth);
     $realtimeWindow = Common::getRequestVar('realtimeWindow', self::REAL_TIME_WINDOW, 'string');
     if ($realtimeWindow != 'false') {
         // handle special value
         $params['date'] = $realtimeWindow;
     }
     $reqParams = $this->getEnrichedRequest($params, $encode = false);
     $view->config = array('metrics' => array(), 'svgBasePath' => $view->piwikUrl . 'plugins/UserCountryMap/svg/', 'liveRefreshAfterMs' => $liveRefreshAfterMs, '_' => $locale, 'reqParams' => $reqParams, 'siteHasGoals' => $hasGoals, 'maxVisits' => $maxVisits, 'changeVisitAlpha' => Common::getRequestVar('changeVisitAlpha', true, 'int'), 'removeOldVisits' => Common::getRequestVar('removeOldVisits', true, 'int'), 'showFooterMessage' => Common::getRequestVar('showFooterMessage', true, 'int'), 'showDateTime' => Common::getRequestVar('showDateTime', true, 'int'), 'doNotRefreshVisits' => Common::getRequestVar('doNotRefreshVisits', false, 'int'), 'enableAnimation' => Common::getRequestVar('enableAnimation', true, 'int'), 'forceNowValue' => Common::getRequestVar('forceNowValue', false, 'int'));
     return $view->render();
 }
Exemple #19
0
 /**
  * @dataProvider getAcceptableOriginsTestData
  * @group Core
  */
 public function test_getAcceptableOrigins($host, $expected)
 {
     Config::getInstance()->General['enable_trusted_host_check'] = 0;
     $_SERVER['HTTP_HOST'] = $host;
     Config::getInstance()->General['trusted_hosts'] = array('example.com');
     $this->assertEquals($expected, Nonce::getAcceptableOrigins(), $host);
 }
Exemple #20
0
 public static function setUpBeforeClass()
 {
     $dbName = false;
     if (!empty($GLOBALS['PIWIK_BENCHMARK_DATABASE'])) {
         $dbName = $GLOBALS['PIWIK_BENCHMARK_DATABASE'];
     }
     // connect to database
     self::createTestConfig();
     self::connectWithoutDatabase();
     // create specified fixture (global var not set, use default no-data fixture (see end of this file))
     if (empty($GLOBALS['PIWIK_BENCHMARK_FIXTURE'])) {
         $fixtureName = 'Piwik_Test_Fixture_EmptyOneSite';
     } else {
         $fixtureName = 'Piwik_Test_Fixture_' . $GLOBALS['PIWIK_BENCHMARK_FIXTURE'];
     }
     self::$fixture = new $fixtureName();
     // figure out if the desired fixture has already been setup, and if not empty the database
     $installedFixture = false;
     try {
         if (isset(self::$fixture->tablesPrefix)) {
             Config::getInstance()->database['tables_prefix'] = self::$fixture->tablesPrefix;
         }
         Db::query("USE " . $dbName);
         $installedFixture = \Piwik\Option::get('benchmark_fixture_name');
     } catch (Exception $ex) {
         // ignore
     }
     $createEmptyDatabase = $fixtureName != $installedFixture;
     parent::_setUpBeforeClass($dbName, $createEmptyDatabase);
     // if we created an empty database, setup the fixture
     if ($createEmptyDatabase) {
         self::$fixture->setUp();
         \Piwik\Option::set('benchmark_fixture_name', $fixtureName);
     }
 }
Exemple #21
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $commandName = $input->getFirstArgument();
     $enable = false !== strpos($commandName, 'enable');
     $full = $input->getOption('full');
     $config = Config::getInstance();
     $development = $config->Development;
     if ($enable) {
         $development['enabled'] = 1;
         if ($full) {
             $development['disable_merged_assets'] = 1;
         }
         $message = 'Development mode enabled';
     } else {
         $development['enabled'] = 0;
         if ($full) {
             $development['disable_merged_assets'] = 0;
         }
         $message = 'Development mode disabled';
     }
     $config->Development = $development;
     $config->forceSave();
     Filesystem::deleteAllCacheOnUpdate();
     $this->writeSuccessMessage($output, array($message));
 }
 /**
  * Returns `true` if development mode is enabled and `false` otherwise.
  *
  * @return bool
  */
 public static function isEnabled()
 {
     if (is_null(self::$isEnabled)) {
         self::$isEnabled = (bool) Config::getInstance()->Development['enabled'];
     }
     return self::$isEnabled;
 }
Exemple #23
0
 /**
  * Load schema
  */
 private function loadSchema()
 {
     $config = Config::getInstance();
     $dbInfos = $config->database;
     $schemaName = trim($dbInfos['schema']);
     $className = self::getSchemaClassName($schemaName);
     $this->schema = new $className();
 }
 private function wouldApplySegment($savedSegment)
 {
     $isBrowserArchivingDisabled = Config::getInstance()->General['browser_archiving_disabled_enforce'];
     if (!$isBrowserArchivingDisabled) {
         return true;
     }
     return (bool) $savedSegment['auto_archive'];
 }
Exemple #25
0
    static function getSql()
    {
        return array('ALTER DATABASE `' . Config::getInstance()->database['dbname'] . '` DEFAULT CHARACTER SET utf8' => false, 'ALTER TABLE `' . Common::prefixTable('log_visit') . '`
				DROP INDEX index_idsite_datetime_config,
				DROP INDEX index_idsite_idvisit,
				ADD INDEX index_idsite_config_datetime (idsite, config_id, visit_last_action_time),
				ADD INDEX index_idsite_datetime (idsite, visit_last_action_time)' => false);
    }
 /**
  * @param string $filename
  */
 private function setUpConfig($filename)
 {
     $userFile = PIWIK_INCLUDE_PATH . '/' . self::ASSET_MANAGER_TEST_DIR . 'configs/' . $filename;
     $globalFile = PIWIK_INCLUDE_PATH . '/' . self::ASSET_MANAGER_TEST_DIR . 'configs/plugins.ini.php';
     $config = Config::getInstance();
     $config->setTestEnvironment($userFile, $globalFile);
     $config->init();
 }
 static function update()
 {
     // when updating from pre-3.0 versions, set use_ldap_for_authentication to 0 and make sure
     // a warning displays in the UI to not set it to 1
     \Piwik\Config::getInstance()->LoginLdap['use_ldap_for_authentication'] = 0;
     \Piwik\Config::getInstance()->forceSave();
     Option::set('LoginLdap_updatedFromPre3_0', 1);
 }
Exemple #28
0
 /**
  * Check PostgreSQL version
  *
  * @throws Exception
  */
 public function checkServerVersion()
 {
     $databaseVersion = $this->getServerVersion();
     $requiredVersion = Config::getInstance()->General['minimum_pgsql_version'];
     if (version_compare($databaseVersion, $requiredVersion) === -1) {
         throw new Exception(Piwik::translate('General_ExceptionDatabaseVersion', array('PostgreSQL', $databaseVersion, $requiredVersion)));
     }
 }
 public function test_makeConfigured_CreatesCorrectlyConfiguredInstance_WhenAllConfigSupplied()
 {
     Config::getInstance()->LoginLdap = array('ldap_view_access_field' => 'viewaccessfield', 'ldap_admin_access_field' => 'adminaccessfield', 'ldap_superuser_access_field' => 'superuseraccessfield');
     $userAccessMapper = UserAccessMapper::makeConfigured();
     $this->assertEquals('viewaccessfield', $userAccessMapper->getViewAttributeName());
     $this->assertEquals('adminaccessfield', $userAccessMapper->getAdminAttributeName());
     $this->assertEquals('superuseraccessfield', $userAccessMapper->getSuperuserAttributeName());
 }
 /**
  * send email to Piwik team and display nice thanks
  * @throws Exception
  */
 function sendFeedback()
 {
     $email = Common::getRequestVar('email', '', 'string');
     $body = Common::getRequestVar('body', '', 'string');
     $category = Common::getRequestVar('category', '', 'string');
     $nonce = Common::getRequestVar('nonce', '', 'string');
     $view = new View('@Feedback/sendFeedback');
     $view->feedbackEmailAddress = Config::getInstance()->General['feedback_email_address'];
     try {
         $minimumBodyLength = 40;
         if (strlen($body) < $minimumBodyLength || strpos($email, 'probe@') !== false || strpos($body, '&lt;probe') !== false) {
             throw new Exception(Piwik::translate('Feedback_ExceptionBodyLength', array($minimumBodyLength)));
         }
         if (!Piwik::isValidEmailString($email)) {
             throw new Exception(Piwik::translate('UsersManager_ExceptionInvalidEmail'));
         }
         if (preg_match('/https?:/i', $body)) {
             throw new Exception(Piwik::translate('Feedback_ExceptionNoUrls'));
         }
         if (!Nonce::verifyNonce('Feedback.sendFeedback', $nonce)) {
             throw new Exception(Piwik::translate('General_ExceptionNonceMismatch'));
         }
         Nonce::discardNonce('Feedback.sendFeedback');
         $mail = new Mail();
         $mail->setFrom(Common::unsanitizeInputValue($email));
         $mail->addTo($view->feedbackEmailAddress, 'Piwik Team');
         $mail->setSubject('[ Feedback form - Piwik ] ' . $category);
         $mail->setBodyText(Common::unsanitizeInputValue($body) . "\n" . 'Piwik ' . Version::VERSION . "\n" . 'IP: ' . IP::getIpFromHeader() . "\n" . 'URL: ' . Url::getReferrer() . "\n");
         @$mail->send();
     } catch (Exception $e) {
         $view->errorString = $e->getMessage();
         $view->message = $body;
     }
     return $view->render();
 }