public function __construct($username)
 {
     $this->username = $username;
     $this->title = 'Piwik - ' . Url::getCurrentHost();
     $this->description = Piwik::getCurrentUserLogin();
     $this->load();
 }
Пример #2
0
 public function configureTopMenu(MenuTop $menu)
 {
     $login = Piwik::getCurrentUserLogin();
     $user = APIUsersManager::getInstance()->getUser($login);
     if (!empty($user['alias'])) {
         $login = $user['alias'];
     }
     if (Plugin\Manager::getInstance()->isPluginActivated('Feedback')) {
         $menu->registerMenuIcon('General_Help', 'icon-help');
         $menu->addItem('General_Help', null, array('module' => 'Feedback', 'action' => 'index'), $order = 990, Piwik::translate('General_Help'));
     }
     $menu->registerMenuIcon($login, 'icon-user');
     if (Piwik::isUserIsAnonymous()) {
         if (Plugin\Manager::getInstance()->isPluginActivated('ScheduledReports')) {
             $menu->addItem($login, null, array('module' => 'ScheduledReports', 'action' => 'index'), 970, Piwik::translate('ScheduledReports_PersonalEmailReports'));
         } else {
             $menu->addItem($login, null, array('module' => 'API', 'action' => 'listAllAPI'), 970, Piwik::translate('API_ReportingApiReference'));
         }
     } else {
         $tooltip = sprintf('%s: %s', Piwik::translate('UsersManager_PersonalSettings'), $login);
         $menu->addItem($login, null, array('module' => 'UsersManager', 'action' => 'userSettings'), 970, $tooltip);
     }
     $module = $this->getLoginModule();
     if (Piwik::isUserIsAnonymous()) {
         $menu->registerMenuIcon('Login_LogIn', 'icon-sign-in');
         $menu->addItem('Login_LogIn', null, array('module' => $module, 'action' => false), 1000, Piwik::translate('Login_LogIn'));
     } else {
         $menu->registerMenuIcon('General_Logout', 'icon-sign-out');
         $menu->addItem('General_Logout', null, array('module' => $module, 'action' => 'logout', 'idSite' => null), 1000, Piwik::translate('General_Logout'));
     }
 }
 /**
  * Checks if the provided CURRENT password is correct and calls the parent
  * class function if so. Otherwise provides error message.
  *
  * @see the parent class function for parameters and return value
  */
 public function recordUserSettings()
 {
     try {
         $passwordCurrent = Common::getRequestvar('passwordCurrent', false);
         $passwordCurrent = Crypto::decrypt($passwordCurrent);
         // Note: Compare loosely, so both, "" (password input empty; forms send strings)
         //       and "password input not sent" are covered - see
         //       https://secure.php.net/manual/en/types.comparisons.php
         if ($passwordCurrent != "") {
             $userName = Piwik::getCurrentUserLogin();
             // gets username as string or "anonymous"
             // see Piwik\Plugins\Login\Auth for used password hash function
             // (in setPassword()) and access to hashed password (in getTokenAuthSecret())
             if ($userName != 'anonymous') {
                 $model = new Model();
                 $user = $model->getUser($userName);
                 if (UsersManagerEncrypted::getPasswordHash($passwordCurrent) === $user['password']) {
                     $toReturn = parent::recordUserSettings();
                 } else {
                     throw new Exception(Piwik::translate('UsersManagerEncrypted_CurrentPasswordIncorrect'));
                 }
             } else {
                 throw new Exception(Piwik::translate('UsersManagerEncrypted_UserNotAuthenticated'));
             }
         } else {
             throw new Exception(Piwik::translate('UsersManagerEncrypted_CurrentPasswordNotProvided'));
         }
     } catch (Exception $e) {
         $response = new ResponseBuilder(Common::getRequestVar('format'));
         $toReturn = $response->getResponseException($e);
     }
     return $toReturn;
 }
Пример #4
0
 public function configureTopMenu(MenuTop $menu)
 {
     $login = Piwik::getCurrentUserLogin();
     $user = APIUsersManager::getInstance()->getUser($login);
     if (!empty($user['alias'])) {
         $login = $user['alias'];
     }
     if (Plugin\Manager::getInstance()->isPluginActivated('Feedback')) {
         $menu->addItem('General_Help', null, array('module' => 'Feedback', 'action' => 'index'));
     }
     if (Piwik::isUserIsAnonymous()) {
         if (Plugin\Manager::getInstance()->isPluginActivated('Feedback')) {
             $menu->addItem($login, null, array('module' => 'Feedback', 'action' => 'index'), 998);
         } else {
             $menu->addItem($login, null, array('module' => 'API', 'action' => 'listAllAPI'), 998);
         }
     } else {
         $menu->addItem($login, null, array('module' => 'UsersManager', 'action' => 'userSettings'), 998);
     }
     $module = $this->getLoginModule();
     if (Piwik::isUserIsAnonymous()) {
         $menu->addItem('Login_LogIn', null, array('module' => $module, 'action' => false), 999);
     } else {
         $menu->addItem('General_Logout', null, array('module' => $module, 'action' => 'logout', 'idSite' => null), 999);
     }
 }
Пример #5
0
 /**
  * Creates a new user setting.
  *
  * Settings will be displayed in the UI depending on the order of `makeSetting` calls. This means you can define
  * the order of the displayed settings by calling makeSetting first for more important settings.
  *
  * @param string $name         The name of the setting that shall be created
  * @param mixed  $defaultValue The default value for this setting. Note the value will not be converted to the
  *                             specified type.
  * @param string $type         The PHP internal type the value of this setting should have.
  *                             Use one of FieldConfig::TYPE_* constancts
  * @param \Closure $fieldConfigCallback   A callback method to configure the field that shall be displayed in the
  *                             UI to define the value for this setting
  * @return UserSetting   Returns an instance of the created measurable setting.
  */
 protected function makeSetting($name, $defaultValue, $type, $configureCallback)
 {
     $userLogin = Piwik::getCurrentUserLogin();
     $setting = new UserSetting($name, $defaultValue, $type, $this->pluginName, $userLogin);
     $setting->setConfigureCallback($configureCallback);
     $this->addSetting($setting);
     return $setting;
 }
Пример #6
0
 /**
  * Get all dashboards which a user has created.
  * @return \array[]
  */
 private function getUserDashboards()
 {
     $userLogin = Piwik::getCurrentUserLogin();
     $userDashboards = $this->dashboard->getAllDashboards($userLogin);
     $dashboards = array();
     foreach ($userDashboards as $userDashboard) {
         $widgets = $this->getVisibleWidgetsWithinDashboard($userDashboard);
         $dashboards[] = $this->buildDashboard($userDashboard, $widgets);
     }
     return $dashboards;
 }
Пример #7
0
 /**
  * Get all dashboards which a user has created.
  *
  * @return array[]
  */
 private function getUserDashboards()
 {
     $userLogin = Piwik::getCurrentUserLogin();
     $userDashboards = $this->dashboard->getAllDashboards($userLogin);
     $dashboards = array();
     foreach ($userDashboards as $userDashboard) {
         if ($this->hasDashboardColumns($userDashboard)) {
             $widgets = $this->getExistingWidgetsWithinDashboard($userDashboard);
             $dashboards[] = $this->buildDashboard($userDashboard, $widgets);
         }
     }
     return $dashboards;
 }
Пример #8
0
 /**
  * Returns default period type for Piwik reports.
  *
  * @return string `'day'`, `'week'`, `'month'`, `'year'` or `'range'`
  * @api
  */
 public function getDefaultPeriod()
 {
     $userSettingsDate = APIUsersManager::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE);
     if ($userSettingsDate === false) {
         return Config::getInstance()->General['default_period'];
     }
     if (in_array($userSettingsDate, array('today', 'yesterday'))) {
         return 'day';
     }
     if (strpos($userSettingsDate, 'last') === 0 || strpos($userSettingsDate, 'previous') === 0) {
         return 'range';
     }
     return $userSettingsDate;
 }
Пример #9
0
 public function configureReportingMenu(MenuReporting $menu)
 {
     $menu->addItem('Dashboard_Dashboard', '', $this->urlForAction('embeddedIndex', array('idDashboard' => 1)), 5);
     if (!Piwik::isUserIsAnonymous()) {
         $login = Piwik::getCurrentUserLogin();
         $dashboard = new Dashboard();
         $dashboards = $dashboard->getAllDashboards($login);
         $pos = 0;
         foreach ($dashboards as $dashboard) {
             $menu->addItem('Dashboard_Dashboard', $dashboard['name'], $this->urlForAction('embeddedIndex', array('idDashboard' => $dashboard['iddashboard'])), $pos);
             $pos++;
         }
     }
 }
Пример #10
0
 public function configureReportingMenu(MenuReporting $menu)
 {
     $menu->add('Dashboard_Dashboard', '', array('module' => 'Dashboard', 'action' => 'embeddedIndex', 'idDashboard' => 1), true, 5);
     if (!Piwik::isUserIsAnonymous()) {
         $login = Piwik::getCurrentUserLogin();
         $dashboard = new Dashboard();
         $dashboards = $dashboard->getAllDashboards($login);
         $pos = 0;
         foreach ($dashboards as $dashboard) {
             $menu->add('Dashboard_Dashboard', $dashboard['name'], array('module' => 'Dashboard', 'action' => 'embeddedIndex', 'idDashboard' => $dashboard['iddashboard']), true, $pos);
             $pos++;
         }
     }
 }
 private function createAlert($name, $period, $idSites, $metric, $report, $login = false)
 {
     if (false === $login) {
         $login = Piwik::getCurrentUserLogin();
     }
     $emails = array('*****@*****.**', '*****@*****.**');
     $phoneNumbers = array('0123456789');
     $reportMatched = '';
     if ('VisitsSummary_get' != $report) {
         $reportMatched = 'Piwik';
     }
     $model = new Model();
     $model->createAlert($name, $idSites, $login, $period, 0, $emails, $phoneNumbers, $metric, 'less_than', 5, $comparedTo = 1, $report, 'matches_exactly', $reportMatched);
 }
Пример #12
0
 function redirectToCoreHomeIndex()
 {
     $defaultReport = API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), API::PREFERENCE_DEFAULT_REPORT);
     $module = 'CoreHome';
     $action = 'index';
     // User preference: default report to load is the All Websites dashboard
     if ($defaultReport == 'MultiSites' && \Piwik\Plugin\Manager::getInstance()->isPluginActivated('MultiSites')) {
         $module = 'MultiSites';
     }
     if ($defaultReport == Piwik::getLoginPluginName()) {
         $module = Piwik::getLoginPluginName();
     }
     $idSite = Common::getRequestVar('idSite', false, 'int');
     parent::redirectToIndex($module, $action, $idSite);
 }
Пример #13
0
 private function buildUserSettingName($name, $userLogin = null)
 {
     if (empty($userLogin)) {
         $userLogin = Piwik::getCurrentUserLogin();
     }
     // the asterisk tag is indeed important here and better than an underscore. Imagine a plugin has the settings
     // "api_password" and "api". A user having the login "_password" could otherwise under circumstances change the
     // setting for "api" although he is not allowed to. It is not so important at the moment because only alNum is
     // currently allowed as a name this might change in the future.
     $appendix = '#' . $userLogin . '#';
     if (Common::stringEndsWith($name, $appendix)) {
         return $name;
     }
     return $name . $appendix;
 }
Пример #14
0
 /**
  * anonymous = in the session
  * authenticated user = in the session and in DB
  */
 public function saveLanguage()
 {
     $language = Common::getRequestVar('language');
     // Prevent CSRF only when piwik is not installed yet (During install user can change language)
     if (DbHelper::isInstalled()) {
         $this->checkTokenInUrl();
     }
     LanguagesManager::setLanguageForSession($language);
     if (\Piwik\Registry::isRegistered('access')) {
         $currentUser = Piwik::getCurrentUserLogin();
         if ($currentUser && $currentUser !== 'anonymous') {
             API::getInstance()->setLanguageForUser($currentUser, $language);
         }
     }
     Url::redirectToReferrer();
 }
 public function addPiwikClientTracking(&$out)
 {
     $settings = StaticContainer::get('Piwik\\Plugins\\AnonymousPiwikUsageMeasurement\\Settings');
     $config = array('targets' => array(), 'visitorCustomVariables' => array(), 'trackingDomain' => self::TRACKING_DOMAIN, 'exampleDomain' => self::EXAMPLE_DOMAIN, 'userId' => Piwik::getCurrentUserLogin());
     if (Piwik::isUserIsAnonymous() || !$settings->canUserOptOut->getValue() || !$settings->userTrackingEnabled->isReadableByCurrentUser() || $settings->userTrackingEnabled->getValue()) {
         // an anonymous user is currently always tracked, an anonymous user would not have permission to read
         // this user setting. The `isUserIsAnonymous()` check is not needed but there to improve performance
         // in case user is anonymous. Then we avoid checking whether user has access to any sites which can be slow
         // a user not having any view permission is also always tracked so far as such a user is not allowed to read
         // this setting
         $targets = StaticContainer::get('Piwik\\Plugins\\AnonymousPiwikUsageMeasurement\\Tracker\\Targets');
         $customVars = StaticContainer::get('Piwik\\Plugins\\AnonymousPiwikUsageMeasurement\\Tracker\\CustomVariables');
         $config['targets'] = $targets->getTargets();
         $config['visitorCustomVariables'] = $customVars->getClientVisitCustomVariables();
     }
     $out .= "\nvar piwikUsageTracking = " . json_encode($config) . ";\n";
 }
Пример #16
0
 /**
  * Saves the current time for a user as an option if the current request is for something
  * in the reporting UI, the current user is not anonymous and the time hasn't been saved
  * in the last 5 minutes.
  */
 public function logCurrentUserLastSeenTime()
 {
     $module = Common::getRequestVar('module', false);
     $currentUserLogin = Piwik::getCurrentUserLogin();
     // only log time for non-anonymous visits to the reporting UI
     if ($module == 'API' || $module == 'Proxy' || $currentUserLogin == 'anonymous') {
         return;
     }
     // get the last known time
     $optionName = self::OPTION_PREFIX . $currentUserLogin;
     $lastSeen = Option::get($optionName);
     // do not log if last known time is less than N minutes from now (so we don't make too many
     // queries)
     if (time() - $lastSeen <= self::LAST_TIME_SAVE_DELTA) {
         return;
     }
     // log last seen time (Note: autoload is important so the Option::get above does not result in
     // a separate query)
     Option::set($optionName, time(), $autoload = 1);
 }
Пример #17
0
 /**
  * Constructor.
  */
 public function __construct($idSite = false)
 {
     parent::__construct();
     $this->jsClass = "SegmentSelectorControl";
     $this->cssIdentifier = "segmentEditorPanel";
     $this->cssClass = "piwikTopControl borderedControl piwikSelector";
     $this->idSite = $idSite ?: Common::getRequestVar('idSite', false, 'int');
     $this->selectedSegment = Common::getRequestVar('segment', false, 'string');
     $formatter = StaticContainer::get('Piwik\\Plugins\\SegmentEditor\\SegmentFormatter');
     $this->segmentDescription = $formatter->getHumanReadable(Request::getRawSegmentFromRequest(), $this->idSite);
     $this->isAddingSegmentsForAllWebsitesEnabled = SegmentEditor::isAddingSegmentsForAllWebsitesEnabled();
     $segments = APIMetadata::getInstance()->getSegmentsMetadata($this->idSite);
     $visitTitle = Piwik::translate('General_Visit');
     $segmentsByCategory = array();
     foreach ($segments as $segment) {
         if ($segment['category'] == $visitTitle && ($segment['type'] == 'metric' && $segment['segment'] != 'visitIp')) {
             $metricsLabel = Piwik::translate('General_Metrics');
             $metricsLabel[0] = Common::mb_strtolower($metricsLabel[0]);
             $segment['category'] .= ' (' . $metricsLabel . ')';
         }
         $segmentsByCategory[$segment['category']][] = $segment;
     }
     $this->createRealTimeSegmentsIsEnabled = Config::getInstance()->General['enable_create_realtime_segments'];
     $this->segmentsByCategory = $segmentsByCategory;
     $this->nameOfCurrentSegment = '';
     $this->isSegmentNotAppliedBecauseBrowserArchivingIsDisabled = 0;
     $this->availableSegments = API::getInstance()->getAll($this->idSite);
     foreach ($this->availableSegments as &$savedSegment) {
         $savedSegment['name'] = Common::sanitizeInputValue($savedSegment['name']);
         if (!empty($this->selectedSegment) && $this->selectedSegment == $savedSegment['definition']) {
             $this->nameOfCurrentSegment = $savedSegment['name'];
             $this->isSegmentNotAppliedBecauseBrowserArchivingIsDisabled = $this->wouldApplySegment($savedSegment) ? 0 : 1;
         }
     }
     $this->authorizedToCreateSegments = SegmentEditorAPI::getInstance()->isUserCanAddNewSegment($this->idSite);
     $this->isUserAnonymous = Piwik::isUserIsAnonymous();
     $this->segmentTranslations = $this->getTranslations();
     $this->segmentProcessedOnRequest = Rules::isBrowserArchivingAvailableForSegments();
     $this->hideSegmentDefinitionChangeMessage = UsersManagerAPI::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), 'hideSegmentDefinitionChangeMessage');
 }
Пример #18
0
 public function getAllActive($idSite, $period, $idReport, $ifSuperUserReturnOnlySuperUserReports)
 {
     $where = array();
     $params = array();
     if (!Piwik::isUserIsSuperUser() || $ifSuperUserReturnOnlySuperUserReports) {
         $where[] = ' login = ? ';
         $params[] = Piwik::getCurrentUserLogin();
     }
     if (!empty($period)) {
         $where[] = ' period = ? ';
         $params[] = $period;
     }
     if (!empty($idSite)) {
         // Joining with the site table to work around pre-1.3 where reports could still be linked to a deleted site
         $where[] = Common::prefixTable('site') . '.idsite = ? ';
         $params[] = $idSite;
     }
     if (!empty($idReport)) {
         $where[] = ' idreport = ? ';
         $params[] = $idReport;
     }
     $sql = 'SELECT * FROM ' . $this->table . ' ' . 'INNER JOIN ' . Common::prefixTable('site') . ' ' . '    USING (idsite) ' . 'WHERE deleted = 0 AND ' . implode(' AND ', $where);
     return $this->db->fetchAll($sql, $params);
 }
Пример #19
0
 /**
  * Records settings from the "User Settings" page
  * @throws Exception
  */
 public function recordUserSettings()
 {
     $response = new ResponseBuilder(Common::getRequestVar('format'));
     try {
         $this->checkTokenInUrl();
         $defaultReport = Common::getRequestVar('defaultReport');
         $defaultDate = Common::getRequestVar('defaultDate');
         $language = Common::getRequestVar('language');
         $userLogin = Piwik::getCurrentUserLogin();
         $this->processPasswordChange($userLogin);
         LanguagesManager::setLanguageForSession($language);
         APILanguagesManager::getInstance()->setLanguageForUser($userLogin, $language);
         APIUsersManager::getInstance()->setUserPreference($userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT, $defaultReport);
         APIUsersManager::getInstance()->setUserPreference($userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE, $defaultDate);
         $toReturn = $response->getResponse();
     } catch (Exception $e) {
         $toReturn = $response->getResponseException($e);
     }
     return $toReturn;
 }
Пример #20
0
 /**
  * Get the dashboard layout for the current user (anonymous or logged user)
  *
  * @param int $idDashboard
  *
  * @return string $layout
  */
 protected function getLayout($idDashboard)
 {
     if (Piwik::isUserIsAnonymous()) {
         $session = new SessionNamespace("Dashboard");
         if (!isset($session->dashboardLayout)) {
             return $this->dashboard->getDefaultLayout();
         }
         $layout = $session->dashboardLayout;
     } else {
         $layout = $this->dashboard->getLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard);
     }
     if (!empty($layout)) {
         $layout = $this->dashboard->removeDisabledPluginFromLayout($layout);
     }
     if (empty($layout)) {
         $layout = $this->dashboard->getDefaultLayout();
     }
     return $layout;
 }
Пример #21
0
    /**
     * Returns the list of websites ID associated with a URL.
     *
     * @param string $url
     * @return array list of websites ID
     */
    public function getSitesIdFromSiteUrl($url)
    {
        $url = $this->removeTrailingSlash($url);
        list($url, $urlBis) = $this->getNormalizedUrls($url);
        if (Piwik::hasUserSuperUserAccess()) {
            $ids = Db::get()->fetchAll('SELECT idsite
                FROM ' . Common::prefixTable('site') . '
					WHERE (main_url = ? OR main_url = ?) ' . 'UNION
                SELECT idsite
                FROM ' . Common::prefixTable('site_url') . '
					WHERE (url = ? OR url = ?) ', array($url, $urlBis, $url, $urlBis));
        } else {
            $login = Piwik::getCurrentUserLogin();
            $ids = Db::get()->fetchAll('SELECT idsite
                FROM ' . Common::prefixTable('site') . '
					WHERE (main_url = ? OR main_url = ?)' . 'AND idsite IN (' . Access::getSqlAccessSite('idsite') . ') ' . 'UNION
                SELECT idsite
                FROM ' . Common::prefixTable('site_url') . '
					WHERE (url = ? OR url = ?)' . 'AND idsite IN (' . Access::getSqlAccessSite('idsite') . ')', array($url, $urlBis, $login, $url, $urlBis, $login));
        }
        return $ids;
    }
Пример #22
0
 /**
  * @return string|false if language preference could not be loaded
  */
 protected static function getLanguageFromPreferences()
 {
     if (($language = self::getLanguageForSession()) != null) {
         return $language;
     }
     try {
         $currentUser = Piwik::getCurrentUserLogin();
         return API::getInstance()->getLanguageForUser($currentUser);
     } catch (Exception $e) {
         return false;
     }
 }
Пример #23
0
 /**
  * Constructor.
  *
  * @param string $templateFile The template file to load. Must be in the following format:
  *                             `"@MyPlugin/templateFileName"`. Note the absence of .twig
  *                             from the end of the name.
  */
 public function __construct($templateFile)
 {
     $templateExt = '.twig';
     if (substr($templateFile, -strlen($templateExt)) !== $templateExt) {
         $templateFile .= $templateExt;
     }
     $this->template = $templateFile;
     $this->initializeTwig();
     $this->piwik_version = Version::VERSION;
     $this->userLogin = Piwik::getCurrentUserLogin();
     $this->isSuperUser = Access::getInstance()->hasSuperUserAccess();
     try {
         $this->piwikUrl = SettingsPiwik::getPiwikUrl();
     } catch (Exception $ex) {
         // pass (occurs when DB cannot be connected to, perhaps piwik URL cache should be stored in config file...)
     }
 }
Пример #24
0
 /**
  * Creates a {@link Piwik\Plugin\ViewDataTable} instance by ID. If the **viewDataTable** query parameter is set,
  * this parameter's value is used as the ID.
  *
  * See {@link Piwik\Plugin\ViewDataTable} to read about the visualizations that are packaged with Piwik.
  *
  * @param string|null $defaultType A ViewDataTable ID representing the default ViewDataTable type to use. If
  *                                 the **viewDataTable** query parameter is not found, this value is used as
  *                                 the ID of the ViewDataTable to create.
  *
  *                                 If a visualization type is configured for the report being displayed, it
  *                                 is used instead of the default type. (See {@hook ViewDataTable.getDefaultType}).
  *                                 If nothing is configured for the report and `null` is supplied for this
  *                                 argument, **table** is used.
  * @param bool|false|string $apiAction The API method for the report that will be displayed, eg,
  *                               `'DevicesDetection.getBrowsers'`.
  * @param bool|false|string $controllerAction The controller name and action dedicated to displaying the report. This
  *                                       action is used when reloading reports or changing the report visualization.
  *                                       Defaulted to `$apiAction` if `false` is supplied.
  * @param bool $forceDefault If true, then the visualization type that was configured for the report will be
  *                           ignored and `$defaultType` will be used as the default.
  * @param bool $loadViewDataTableParametersForUser Whether the per-user parameters for this user, this ViewDataTable and this Api action
  *                                          should be loaded from the user preferences and override the default params values.
  * @throws \Exception
  * @return \Piwik\Plugin\ViewDataTable
  */
 public static function build($defaultType = null, $apiAction = false, $controllerAction = false, $forceDefault = false, $loadViewDataTableParametersForUser = null)
 {
     if (false === $controllerAction) {
         $controllerAction = $apiAction;
     }
     $report = self::getReport($apiAction);
     $defaultViewType = self::getDefaultViewTypeForReport($report, $apiAction);
     $params = array();
     if (is_null($loadViewDataTableParametersForUser)) {
         $loadViewDataTableParametersForUser = '******' == Common::getRequestVar('widget', '0', 'string');
     }
     if ($loadViewDataTableParametersForUser) {
         $login = Piwik::getCurrentUserLogin();
         $params = Manager::getViewDataTableParameters($login, $controllerAction);
     }
     if (!self::isDefaultViewTypeForReportFixed($report)) {
         $savedViewDataTable = false;
         if (!empty($params['viewDataTable'])) {
             $savedViewDataTable = $params['viewDataTable'];
         }
         // order of default viewDataTables' priority is: function specified default, saved default, configured default for report
         //   function specified default is preferred
         // -> force default == true : defaultType ?: saved ?: defaultView
         // -> force default == false : saved ?: defaultType ?: defaultView
         if ($forceDefault) {
             $defaultType = $defaultType ?: $savedViewDataTable ?: $defaultViewType;
         } else {
             $defaultType = $savedViewDataTable ?: $defaultType ?: $defaultViewType;
         }
         $type = Common::getRequestVar('viewDataTable', $defaultType, 'string');
         // Common::getRequestVar removes backslashes from the defaultValue in case magic quotes are enabled.
         // therefore do not pass this as a default value to getRequestVar()
         if ('' === $type) {
             $type = $defaultType ?: HtmlTable::ID;
         }
     } else {
         $type = $defaultViewType;
     }
     $params['viewDataTable'] = $type;
     $visualizations = Manager::getAvailableViewDataTables();
     if (array_key_exists($type, $visualizations)) {
         return self::createViewDataTableInstance($visualizations[$type], $controllerAction, $apiAction, $params);
     }
     if (array_key_exists($defaultType, $visualizations)) {
         return self::createViewDataTableInstance($visualizations[$defaultType], $controllerAction, $apiAction, $params);
     }
     if (array_key_exists(HtmlTable::ID, $visualizations)) {
         return self::createViewDataTableInstance($visualizations[HtmlTable::ID], $controllerAction, $apiAction, $params);
     }
     throw new \Exception('No visualization found to render ViewDataTable');
 }
Пример #25
0
 private function getCurrentUserSettings()
 {
     return $this->getUserSettings(Piwik::getCurrentUserLogin());
 }
Пример #26
0
 public function segmentUpdated($idSegment, $updatedSegment)
 {
     $reportsUsingSegment = API::getInstance()->getReports(false, false, false, false, $idSegment);
     $reportsNeedSegment = array();
     if (!$updatedSegment['enable_all_users']) {
         // which reports would become invisible to other users?
         foreach ($reportsUsingSegment as $report) {
             if ($report['login'] == Piwik::getCurrentUserLogin()) {
                 continue;
             }
             $reportsNeedSegment[] = $report;
         }
     }
     if ($updatedSegment['enable_only_idsite']) {
         // which reports from other websites are set to use this segment restricted to one website?
         foreach ($reportsUsingSegment as $report) {
             if ($report['idsite'] == $updatedSegment['enable_only_idsite']) {
                 continue;
             }
             $reportsNeedSegment[] = $report;
         }
     }
     if (empty($reportsNeedSegment)) {
         return;
     }
     $this->throwExceptionReportsAreUsingSegment($reportsNeedSegment);
 }
Пример #27
0
 /**
  * Helper method used to redirect the current HTTP request to another module/action.
  * 
  * This function will exit immediately after executing.
  *
  * @param string $moduleToRedirect The plugin to redirect to, eg. `"MultiSites"`.
  * @param string $actionToRedirect Action, eg. `"index"`.
  * @param int|null $websiteId The new idSite query parameter, eg, `1`.
  * @param string|null $defaultPeriod The new period query parameter, eg, `'day'`.
  * @param string|null $defaultDate The new date query parameter, eg, `'today'`.
  * @param array $parameters Other query parameters to append to the URL.
  * @api
  */
 public function redirectToIndex($moduleToRedirect, $actionToRedirect, $websiteId = null, $defaultPeriod = null, $defaultDate = null, $parameters = array())
 {
     $userPreferences = new UserPreferences();
     if (empty($websiteId)) {
         $websiteId = $userPreferences->getDefaultWebsiteId();
     }
     if (empty($defaultDate)) {
         $defaultDate = $userPreferences->getDefaultDate();
     }
     if (empty($defaultPeriod)) {
         $defaultPeriod = $userPreferences->getDefaultPeriod();
     }
     $parametersString = '';
     if (!empty($parameters)) {
         $parametersString = '&' . Url::getQueryStringFromParameters($parameters);
     }
     if ($websiteId) {
         $url = "index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite=" . $websiteId . "&period=" . $defaultPeriod . "&date=" . $defaultDate . $parametersString;
         Url::redirectToUrl($url);
         exit;
     }
     if (Piwik::hasUserSuperUserAccess()) {
         Piwik_ExitWithMessage("Error: no website was found in this Piwik installation.\n\t\t\t<br />Check the table '" . Common::prefixTable('site') . "' in your database, it should contain your Piwik websites.", false, true);
     }
     $currentLogin = Piwik::getCurrentUserLogin();
     if (!empty($currentLogin) && $currentLogin != 'anonymous') {
         $emails = implode(',', Piwik::getAllSuperUserAccessEmailAddresses());
         $errorMessage = sprintf(Piwik::translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:" . $emails . "?subject=Access to Piwik for user {$currentLogin}'>", "</a>");
         $errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='index.php?module=" . Registry::get('auth')->getName() . "&amp;action=logout'>&rsaquo; " . Piwik::translate('General_Logout') . "</a></b><br />";
         Piwik_ExitWithMessage($errorMessage, false, true);
     }
     echo FrontController::getInstance()->dispatch(Piwik::getLoginPluginName(), false);
     exit;
 }
 /**
  * Action to generate a new Google Authenticator secret for the current user
  *
  * @return string
  * @throws \Exception
  * @throws \Piwik\NoAccessException
  */
 public function regenerate()
 {
     Piwik::checkUserIsNotAnonymous();
     $view = new View('@GoogleAuthenticator/regenerate');
     $this->setGeneralVariablesView($view);
     $googleAuth = new PHPGangsta\GoogleAuthenticator();
     $storage = new Storage(Piwik::getCurrentUserLogin());
     $secret = Common::getRequestVar('gasecret', '', 'string');
     $authCode = Common::getRequestVar('gaauthcode', '', 'string');
     $authCodeNonce = Common::getRequestVar('authCodeNonce', '', 'string');
     $title = Common::getRequestVar('gatitle', $storage->getTitle(), 'string');
     $description = Common::getRequestVar('gadescription', $storage->getDescription(), 'string');
     if (!empty($secret) && !empty($authCode) && Nonce::verifyNonce(self::AUTH_CODE_NONCE, $authCodeNonce) && $googleAuth->verifyCode($secret, $authCode, 2)) {
         $storage->setSecret($secret);
         $storage->setDescription($description);
         $storage->setTitle($title);
         $this->auth->setAuthCode($authCode);
         $this->auth->validateAuthCode();
         Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified(array('action' => 'settings', 'activate' => '1')));
     }
     if (empty($secret)) {
         $secret = $googleAuth->createSecret(32);
     }
     $view->title = $title;
     $view->description = $description;
     $view->authCodeNonce = Nonce::getNonce(self::AUTH_CODE_NONCE);
     $view->newSecret = $secret;
     $view->googleAuthImage = $googleAuth->getQRCodeGoogleUrl($description, $secret, $title);
     return $view->render();
 }
Пример #29
0
 /**
  * @group Plugins
  */
 public function test_UpdateSegment()
 {
     $name = 'name"';
     $definition = 'searches>1,visitIp!=127.0.0.1';
     $nameSegment1 = 'hello';
     $idSegment1 = API::getInstance()->add($nameSegment1, 'searches==0', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1);
     $idSegment2 = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1);
     $updatedSegment = array('idsegment' => $idSegment2, 'name' => 'NEW name', 'definition' => 'searches==0', 'enable_only_idsite' => '0', 'enable_all_users' => '0', 'auto_archive' => '0', 'ts_last_edit' => Date::now()->getDatetime(), 'ts_created' => Date::now()->getDatetime(), 'login' => Piwik::getCurrentUserLogin(), 'deleted' => '0');
     API::getInstance()->update($idSegment2, $updatedSegment['name'], $updatedSegment['definition'], $updatedSegment['enable_only_idsite'], $updatedSegment['auto_archive'], $updatedSegment['enable_all_users']);
     $newSegment = API::getInstance()->get($idSegment2);
     // avoid test failures for when ts_created/ts_last_edit are different by between 1/2 secs
     $this->removeSecondsFromSegmentInfo($updatedSegment);
     $this->removeSecondsFromSegmentInfo($newSegment);
     $this->assertEquals($newSegment, $updatedSegment);
     // Check the other segmenet was not updated
     $newSegment = API::getInstance()->get($idSegment1);
     $this->assertEquals($newSegment['name'], $nameSegment1);
 }
Пример #30
0
 /**
  * Returns true if the current user is the special **anonymous** user or not.
  *
  * @return bool
  * @api
  */
 public static function isUserIsAnonymous()
 {
     $currentUserLogin = Piwik::getCurrentUserLogin();
     return $currentUserLogin == 'anonymous';
 }