public function index()
 {
     Piwik::checkUserIsNotAnonymous();
     $view = new View('@MobileMessaging/index');
     $view->isSuperUser = Piwik::isUserIsSuperUser();
     $mobileMessagingAPI = API::getInstance();
     $view->delegatedManagement = $mobileMessagingAPI->getDelegatedManagement();
     $view->credentialSupplied = $mobileMessagingAPI->areSMSAPICredentialProvided();
     $view->accountManagedByCurrentUser = $view->isSuperUser || $view->delegatedManagement;
     $view->strHelpAddPhone = Piwik::translate('MobileMessaging_Settings_PhoneNumbers_HelpAdd', array(Piwik::translate('General_Settings'), Piwik::translate('MobileMessaging_SettingsMenu')));
     if ($view->credentialSupplied && $view->accountManagedByCurrentUser) {
         $view->provider = $mobileMessagingAPI->getSMSProvider();
         $view->creditLeft = $mobileMessagingAPI->getCreditLeft();
     }
     $view->smsProviders = SMSProvider::$availableSMSProviders;
     // construct the list of countries from the lang files
     $countries = array();
     foreach (Common::getCountriesList() as $countryCode => $continentCode) {
         if (isset(CountryCallingCodes::$countryCallingCodes[$countryCode])) {
             $countries[$countryCode] = array('countryName' => \Piwik\Plugins\UserCountry\countryTranslate($countryCode), 'countryCallingCode' => CountryCallingCodes::$countryCallingCodes[$countryCode]);
         }
     }
     $view->countries = $countries;
     $view->defaultCountry = Common::getCountry(LanguagesManager::getLanguageCodeForCurrentUser(), true, IP::getIpFromHeader());
     $view->phoneNumbers = $mobileMessagingAPI->getPhoneNumbers();
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Example #2
0
 public function getDefaultLayout()
 {
     $defaultLayout = $this->getLayoutForUser('', 1);
     if (empty($defaultLayout)) {
         if (Piwik::isUserIsSuperUser()) {
             $topWidget = '{"uniqueId":"widgetCoreHomegetDonateForm",' . '"parameters":{"module":"CoreHome","action":"getDonateForm"}},';
         } else {
             $topWidget = '{"uniqueId":"widgetCoreHomegetPromoVideo",' . '"parameters":{"module":"CoreHome","action":"getPromoVideo"}},';
         }
         $defaultLayout = '[
             [
                 {"uniqueId":"widgetVisitsSummarygetEvolutionGraphcolumnsArray","parameters":{"module":"VisitsSummary","action":"getEvolutionGraph","columns":"nb_visits"}},
                 {"uniqueId":"widgetLivewidget","parameters":{"module":"Live","action":"widget"}},
                 {"uniqueId":"widgetVisitorInterestgetNumberOfVisitsPerVisitDuration","parameters":{"module":"VisitorInterest","action":"getNumberOfVisitsPerVisitDuration"}}
             ],
             [
                 ' . $topWidget . '
                 {"uniqueId":"widgetReferrersgetKeywords","parameters":{"module":"Referrers","action":"getKeywords"}},
                 {"uniqueId":"widgetReferrersgetWebsites","parameters":{"module":"Referrers","action":"getWebsites"}}
             ],
             [
                 {"uniqueId":"widgetUserCountryMapvisitorMap","parameters":{"module":"UserCountryMap","action":"visitorMap"}},
                 {"uniqueId":"widgetUserSettingsgetBrowser","parameters":{"module":"UserSettings","action":"getBrowser"}},
                 {"uniqueId":"widgetReferrersgetSearchEngines","parameters":{"module":"Referrers","action":"getSearchEngines"}},
                 {"uniqueId":"widgetVisitTimegetVisitInformationPerServerTime","parameters":{"module":"VisitTime","action":"getVisitInformationPerServerTime"}},
                 {"uniqueId":"widgetExampleRssWidgetrssPiwik","parameters":{"module":"ExampleRssWidget","action":"rssPiwik"}}
             ]
         ]';
     }
     $defaultLayout = $this->removeDisabledPluginFromLayout($defaultLayout);
     return $defaultLayout;
 }
Example #3
0
 protected function checkAutoArchive($autoArchive, $idSite)
 {
     $autoArchive = (int) $autoArchive;
     if ($autoArchive) {
         $exception = new Exception("To prevent abuse, autoArchive=1 requires Super User or ControllerAdmin access.");
         if (empty($idSite)) {
             if (!Piwik::isUserIsSuperUser()) {
                 throw $exception;
             }
         } else {
             if (!Piwik::isUserHasAdminAccess($idSite)) {
                 throw $exception;
             }
         }
     }
     return $autoArchive;
 }
Example #4
0
 /**
  * Returns array containing data about the website: goals, URLs, etc.
  *
  * @param int $idSite
  * @return array
  */
 static function getCacheWebsiteAttributes($idSite)
 {
     if ($idSite == 'all') {
         return array();
     }
     $idSite = (int) $idSite;
     if ($idSite <= 0) {
         return array();
     }
     $cache = self::getInstance();
     if (($cacheContent = $cache->get($idSite)) !== false) {
         return $cacheContent;
     }
     Tracker::initCorePiwikInTrackerMode();
     // save current user privilege and temporarily assume super user privilege
     $isSuperUser = Piwik::isUserIsSuperUser();
     Piwik::setUserIsSuperUser();
     $content = array();
     /**
      * Triggered to get the attributes of a site entity that might be used by the
      * Tracker.
      * 
      * Plugins add new site attributes for use in other tracking events must
      * use this event to put those attributes in the Tracker Cache.
      * 
      * **Example**
      * 
      *     public function getSiteAttributes($content, $idSite)
      *     {
      *         $sql = "SELECT info FROM " . Common::prefixTable('myplugin_extra_site_info') . " WHERE idsite = ?";
      *         $content['myplugin_site_data'] = Db::fetchOne($sql, array($idSite));
      *     }
      * 
      * @param array &$content Array mapping of site attribute names with values.
      * @param int $idSite The site ID to get attributes for.
      */
     Piwik::postEvent('Tracker.Cache.getSiteAttributes', array(&$content, $idSite));
     // restore original user privilege
     Piwik::setUserIsSuperUser($isSuperUser);
     // 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($idSite, $content);
     }
     return $content;
 }
 /**
  * Main view showing listing of websites and settings
  */
 public function index()
 {
     $view = new View('@SitesManager/index');
     Site::clearCache();
     if (Piwik::isUserIsSuperUser()) {
         $sitesRaw = API::getInstance()->getAllSites();
     } else {
         $sitesRaw = API::getInstance()->getSitesWithAdminAccess();
     }
     // Gets sites after Site.setSite hook was called
     $sites = array_values(Site::getSites());
     if (count($sites) != count($sitesRaw)) {
         throw new Exception("One or more website are missing or invalid.");
     }
     foreach ($sites as &$site) {
         $site['alias_urls'] = API::getInstance()->getSiteUrlsFromId($site['idsite']);
         $site['excluded_ips'] = explode(',', $site['excluded_ips']);
         $site['excluded_parameters'] = explode(',', $site['excluded_parameters']);
         $site['excluded_user_agents'] = explode(',', $site['excluded_user_agents']);
     }
     $view->adminSites = $sites;
     $view->adminSitesCount = count($sites);
     $timezones = API::getInstance()->getTimezonesList();
     $view->timezoneSupported = SettingsServer::isTimezoneSupportEnabled();
     $view->timezones = Common::json_encode($timezones);
     $view->defaultTimezone = API::getInstance()->getDefaultTimezone();
     $view->currencies = Common::json_encode(API::getInstance()->getCurrencyList());
     $view->defaultCurrency = API::getInstance()->getDefaultCurrency();
     $view->utcTime = Date::now()->getDatetime();
     $excludedIpsGlobal = API::getInstance()->getExcludedIpsGlobal();
     $view->globalExcludedIps = str_replace(',', "\n", $excludedIpsGlobal);
     $excludedQueryParametersGlobal = API::getInstance()->getExcludedQueryParametersGlobal();
     $view->globalExcludedQueryParameters = str_replace(',', "\n", $excludedQueryParametersGlobal);
     $globalExcludedUserAgents = API::getInstance()->getExcludedUserAgentsGlobal();
     $view->globalExcludedUserAgents = str_replace(',', "\n", $globalExcludedUserAgents);
     $view->globalSearchKeywordParameters = API::getInstance()->getSearchKeywordParametersGlobal();
     $view->globalSearchCategoryParameters = API::getInstance()->getSearchCategoryParametersGlobal();
     $view->isSearchCategoryTrackingEnabled = \Piwik\Plugin\Manager::getInstance()->isPluginActivated('CustomVariables');
     $view->allowSiteSpecificUserAgentExclude = API::getInstance()->isSiteSpecificUserAgentExcludeEnabled();
     $view->globalKeepURLFragments = API::getInstance()->getKeepURLFragmentsGlobal();
     $view->currentIpAddress = IP::getIpFromHeader();
     $view->showAddSite = (bool) Common::getRequestVar('showaddsite', false);
     $this->setBasicVariablesView($view);
     return $view->render();
 }
 function addMenu()
 {
     $pluginsUpdateMessage = '';
     $themesUpdateMessage = '';
     if (Piwik::isUserIsSuperUser() && static::isMarketplaceEnabled()) {
         $marketplace = new Marketplace();
         $pluginsHavingUpdate = $marketplace->getPluginsHavingUpdate($themesOnly = false);
         $themesHavingUpdate = $marketplace->getPluginsHavingUpdate($themesOnly = true);
         if (!empty($pluginsHavingUpdate)) {
             $pluginsUpdateMessage = sprintf(' (%d)', count($pluginsHavingUpdate));
         }
         if (!empty($themesHavingUpdate)) {
             $themesUpdateMessage = sprintf(' (%d)', count($themesHavingUpdate));
         }
     }
     MenuAdmin::getInstance()->add('CorePluginsAdmin_MenuPlatform', null, "", !Piwik::isUserIsAnonymous(), $order = 7);
     MenuAdmin::getInstance()->add('CorePluginsAdmin_MenuPlatform', Piwik::translate('General_Plugins') . $pluginsUpdateMessage, array('module' => 'CorePluginsAdmin', 'action' => 'plugins', 'activated' => ''), Piwik::isUserIsSuperUser(), $order = 1);
     MenuAdmin::getInstance()->add('CorePluginsAdmin_MenuPlatform', Piwik::translate('CorePluginsAdmin_Themes') . $themesUpdateMessage, array('module' => 'CorePluginsAdmin', 'action' => 'themes', 'activated' => ''), Piwik::isUserIsSuperUser(), $order = 3);
     if (static::isMarketplaceEnabled()) {
         MenuAdmin::getInstance()->add('CorePluginsAdmin_MenuPlatform', 'CorePluginsAdmin_Marketplace', array('module' => 'CorePluginsAdmin', 'action' => 'extend', 'activated' => ''), !Piwik::isUserIsAnonymous(), $order = 5);
     }
 }
 public function generalSettings()
 {
     Piwik::checkUserHasSomeAdminAccess();
     $view = new View('@CoreAdminHome/generalSettings');
     if (Piwik::isUserIsSuperUser()) {
         $this->handleGeneralSettingsAdmin($view);
         $trustedHosts = array();
         if (isset(Config::getInstance()->General['trusted_hosts'])) {
             $trustedHosts = Config::getInstance()->General['trusted_hosts'];
         }
         $view->trustedHosts = $trustedHosts;
         $view->branding = Config::getInstance()->branding;
         $logo = new CustomLogo();
         $view->logosWriteable = $logo->isCustomLogoWritable();
         $view->pathUserLogo = CustomLogo::getPathUserLogo();
         $view->pathUserLogoSmall = CustomLogo::getPathUserLogoSmall();
         $view->pathUserLogoSVG = CustomLogo::getPathUserSvgLogo();
         $view->pathUserLogoDirectory = dirname($view->pathUserLogo) . '/';
     }
     $view->language = LanguagesManager::getLanguageCodeForCurrentUser();
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Example #8
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);
 }
Example #9
0
 /**
  * Records one host, or an array of hosts in the config file,
  * if user is super user
  *
  * @static
  * @param $host string|array
  * @return bool
  */
 public static function saveTrustedHostnameInConfig($host)
 {
     if (Piwik::isUserIsSuperUser() && file_exists(Config::getLocalConfigPath())) {
         $general = Config::getInstance()->General;
         if (!is_array($host)) {
             $host = array($host);
         }
         $host = array_filter($host);
         if (empty($host)) {
             return false;
         }
         $general['trusted_hosts'] = $host;
         Config::getInstance()->General = $general;
         Config::getInstance()->forceSave();
         return true;
     }
     return false;
 }
Example #10
0
 protected static function isRequestAuthorizedToArchive()
 {
     return !self::$archivingDisabledByTests && (Rules::isBrowserTriggerEnabled() || Common::isPhpCliMode() || Piwik::isUserIsSuperUser() && SettingsServer::isArchivePhpTriggered());
 }
 /**
  * Adds the 'System Check' admin page if the user is the super user.
  */
 public function addMenu()
 {
     MenuAdmin::addEntry('Installation_SystemCheck', array('module' => 'Installation', 'action' => 'systemCheckPage'), Piwik::isUserIsSuperUser(), $order = 15);
 }
Example #12
0
 /**
  * Saves the layout as default
  */
 public function saveLayoutAsDefault()
 {
     $this->checkTokenInUrl();
     if (Piwik::isUserIsSuperUser()) {
         $layout = Common::unsanitizeInputValue(Common::getRequestVar('layout'));
         $paramsBind = array('', '1', $layout, $layout);
         $query = sprintf('INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', Common::prefixTable('user_dashboard'));
         Db::query($query, $paramsBind);
     }
 }
Example #13
0
 /**
  * Renders and echo's the in-app donate form w/ slider.
  */
 public function getDonateForm()
 {
     $view = new View('@CoreHome/getDonateForm');
     if (Common::getRequestVar('widget', false) && Piwik::isUserIsSuperUser()) {
         $view->footerMessage = Piwik::translate('CoreHome_OnlyForAdmin');
     }
     return $view->render();
 }
 /**
  * Constructor.
  * 
  * @param string $name The persisted name of the setting.
  * @param string $title The display name of the setting.
  */
 public function __construct($name, $title)
 {
     parent::__construct($name, $title);
     $this->displayedForCurrentUser = Piwik::isUserIsSuperUser();
 }
Example #15
0
 private function buildDataTable($idSitesOrIdSite, $period, $date, $segment, $_restrictSitesToLogin, $enhanced, $multipleWebsitesRequested)
 {
     $allWebsitesRequested = $idSitesOrIdSite == 'all';
     if ($allWebsitesRequested) {
         // First clear cache
         Site::clearCache();
         // Then, warm the cache with only the data we should have access to
         if (Piwik::isUserIsSuperUser() && !TaskScheduler::isTaskBeingExecuted()) {
             $sites = APISitesManager::getInstance()->getAllSites();
         } else {
             $sites = APISitesManager::getInstance()->getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin);
         }
         // Both calls above have called Site::setSitesFromArray. We now get these sites:
         $sitesToProblablyAdd = Site::getSites();
     } else {
         $sitesToProblablyAdd = array(APISitesManager::getInstance()->getSiteFromId($idSitesOrIdSite));
     }
     // build the archive type used to query archive data
     $archive = Archive::build($idSitesOrIdSite, $period, $date, $segment, $_restrictSitesToLogin);
     // determine what data will be displayed
     $fieldsToGet = array();
     $columnNameRewrites = array();
     $apiECommerceMetrics = array();
     $apiMetrics = API::getApiMetrics($enhanced);
     foreach ($apiMetrics as $metricName => $metricSettings) {
         $fieldsToGet[] = $metricSettings[self::METRIC_RECORD_NAME_KEY];
         $columnNameRewrites[$metricSettings[self::METRIC_RECORD_NAME_KEY]] = $metricName;
         if ($metricSettings[self::METRIC_IS_ECOMMERCE_KEY]) {
             $apiECommerceMetrics[$metricName] = $metricSettings;
         }
     }
     // get the data
     // $dataTable instanceOf Set
     $dataTable = $archive->getDataTableFromNumeric($fieldsToGet);
     $dataTable = $this->mergeDataTableMapAndPopulateLabel($idSitesOrIdSite, $multipleWebsitesRequested, $dataTable);
     if ($dataTable instanceof DataTable\Map) {
         foreach ($dataTable->getDataTables() as $table) {
             $this->addMissingWebsites($table, $fieldsToGet, $sitesToProblablyAdd);
         }
     } else {
         $this->addMissingWebsites($dataTable, $fieldsToGet, $sitesToProblablyAdd);
     }
     // calculate total visits/actions/revenue
     $this->setMetricsTotalsMetadata($dataTable, $apiMetrics);
     // if the period isn't a range & a lastN/previousN date isn't used, we get the same
     // data for the last period to show the evolution of visits/actions/revenue
     list($strLastDate, $lastPeriod) = Range::getLastDate($date, $period);
     if ($strLastDate !== false) {
         if ($lastPeriod !== false) {
             // NOTE: no easy way to set last period date metadata when range of dates is requested.
             //       will be easier if DataTable\Map::metadata is removed, and metadata that is
             //       put there is put directly in DataTable::metadata.
             $dataTable->setMetadata(self::getLastPeriodMetadataName('date'), $lastPeriod);
         }
         $pastArchive = Archive::build($idSitesOrIdSite, $period, $strLastDate, $segment, $_restrictSitesToLogin);
         $pastData = $pastArchive->getDataTableFromNumeric($fieldsToGet);
         $pastData = $this->mergeDataTableMapAndPopulateLabel($idSitesOrIdSite, $multipleWebsitesRequested, $pastData);
         // use past data to calculate evolution percentages
         $this->calculateEvolutionPercentages($dataTable, $pastData, $apiMetrics);
         $this->setPastDataMetadata($dataTable, $pastData, $apiMetrics);
     }
     // remove eCommerce related metrics on non eCommerce Piwik sites
     // note: this is not optimal in terms of performance: those metrics should not be retrieved in the first place
     if ($enhanced) {
         if ($dataTable instanceof DataTable\Map) {
             foreach ($dataTable->getDataTables() as $table) {
                 $this->removeEcommerceRelatedMetricsOnNonEcommercePiwikSites($table, $apiECommerceMetrics);
             }
         } else {
             $this->removeEcommerceRelatedMetricsOnNonEcommercePiwikSites($dataTable, $apiECommerceMetrics);
         }
     }
     // move the site id to a metadata column
     $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'idsite'));
     // set the label of each row to the site name
     if ($multipleWebsitesRequested) {
         $dataTable->filter('ColumnCallbackReplace', array('label', '\\Piwik\\Site::getNameFor'));
     } else {
         $dataTable->filter('ColumnDelete', array('label'));
     }
     // replace record names with user friendly metric names
     $dataTable->filter('ReplaceColumnNames', array($columnNameRewrites));
     // Ensures data set sorted, for Metadata output
     $dataTable->filter('Sort', array(self::NB_VISITS_METRIC, 'desc', $naturalSort = false));
     // filter rows without visits
     // note: if only one website is queried and there are no visits, we can not remove the row otherwise
     // ResponseBuilder throws 'Call to a member function getColumns() on a non-object'
     if ($multipleWebsitesRequested && !$enhanced) {
         $dataTable->filter('ColumnCallbackDeleteRow', array(self::NB_VISITS_METRIC, function ($value) {
             return $value == 0;
         }));
     }
     return $dataTable;
 }
 /**
  * Event handler. Adds menu items to the MenuAdmin menu.
  */
 public function addAdminMenu()
 {
     if ($this->isGeoLocationAdminEnabled()) {
         MenuAdmin::getInstance()->add('General_Settings', 'UserCountry_Geolocation', array('module' => 'UserCountry', 'action' => 'adminIndex'), Piwik::isUserIsSuperUser(), $order = 8);
     }
 }
Example #17
0
 /**
  * Update an existing website.
  * If only one URL is specified then only the main url will be updated.
  * If several URLs are specified, both the main URL and the alias URLs will be updated.
  *
  * @param int $idSite website ID defining the website to edit
  * @param string $siteName website name
  * @param string|array $urls the website URLs
  * @param int $ecommerce Whether Ecommerce is enabled, 0 or 1
  * @param null|int $siteSearch Whether site search is enabled, 0 or 1
  * @param string $searchKeywordParameters Comma separated list of search keyword parameter names
  * @param string $searchCategoryParameters Comma separated list of search category parameter names
  * @param string $excludedIps Comma separated list of IPs to exclude from being tracked (allows wildcards)
  * @param null|string $excludedQueryParameters
  * @param string $timezone Timezone
  * @param string $currency Currency code
  * @param string $group Group name where this website belongs
  * @param string $startDate Date at which the statistics for this website will start. Defaults to today's date in YYYY-MM-DD format
  * @param null|string $excludedUserAgents
  * @param int|null $keepURLFragments If 1, URL fragments will be kept when tracking. If 2, they
  *                                   will be removed. If 0, the default global behavior will be used.
  * @param string $type The Website type, default value is "website"
  * @throws Exception
  * @see getKeepURLFragmentsGlobal. If null, the existing value will
  *                                   not be modified.
  *
  * @return bool true on success
  */
 public function updateSite($idSite, $siteName, $urls = null, $ecommerce = null, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = null, $type = null)
 {
     Piwik::checkUserHasAdminAccess($idSite);
     $idSites = API::getInstance()->getSitesId();
     if (!in_array($idSite, $idSites)) {
         throw new Exception("website id = {$idSite} not found");
     }
     $this->checkName($siteName);
     // Build the SQL UPDATE based on specified updates to perform
     $bind = array();
     if (!is_null($urls)) {
         $urls = $this->cleanParameterUrls($urls);
         $this->checkUrls($urls);
         $this->checkAtLeastOneUrl($urls);
         $url = $urls[0];
         $bind['main_url'] = $url;
     }
     if (!is_null($currency)) {
         $currency = trim($currency);
         $this->checkValidCurrency($currency);
         $bind['currency'] = $currency;
     }
     if (!is_null($timezone)) {
         $timezone = trim($timezone);
         $this->checkValidTimezone($timezone);
         $bind['timezone'] = $timezone;
     }
     if (!is_null($group) && Piwik::isUserIsSuperUser()) {
         $bind['group'] = trim($group);
     }
     if (!is_null($ecommerce)) {
         $bind['ecommerce'] = (int) (bool) $ecommerce;
     }
     if (!is_null($startDate)) {
         $bind['ts_created'] = Date::factory($startDate)->getDatetime();
     }
     $bind['excluded_ips'] = $this->checkAndReturnExcludedIps($excludedIps);
     $bind['excluded_parameters'] = $this->checkAndReturnCommaSeparatedStringList($excludedQueryParameters);
     $bind['excluded_user_agents'] = $this->checkAndReturnCommaSeparatedStringList($excludedUserAgents);
     if (!is_null($keepURLFragments)) {
         $keepURLFragments = (int) $keepURLFragments;
         self::checkKeepURLFragmentsValue($keepURLFragments);
         $bind['keep_url_fragment'] = $keepURLFragments;
     }
     $bind['sitesearch'] = $this->checkSiteSearch($siteSearch);
     list($searchKeywordParameters, $searchCategoryParameters) = $this->checkSiteSearchParameters($searchKeywordParameters, $searchCategoryParameters);
     $bind['sitesearch_keyword_parameters'] = $searchKeywordParameters;
     $bind['sitesearch_category_parameters'] = $searchCategoryParameters;
     $bind['type'] = $this->checkAndReturnType($type);
     $bind['name'] = $siteName;
     $db = Db::get();
     $db->update(Common::prefixTable("site"), $bind, "idsite = {$idSite}");
     // we now update the main + alias URLs
     $this->deleteSiteAliasUrls($idSite);
     if (count($urls) > 1) {
         $this->addSiteAliasUrls($idSite, array_slice($urls, 1));
     }
     $this->postUpdateWebsite($idSite);
 }
Example #18
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())
 {
     if (empty($websiteId)) {
         $websiteId = $this->getDefaultWebsiteId();
     }
     if (empty($defaultDate)) {
         $defaultDate = $this->getDefaultDate();
     }
     if (empty($defaultPeriod)) {
         $defaultPeriod = $this->getDefaultPeriod();
     }
     $parametersString = '';
     if (!empty($parameters)) {
         $parametersString = '&' . Url::getQueryStringFromParameters($parameters);
     }
     if ($websiteId) {
         $url = "Location: index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite=" . $websiteId . "&period=" . $defaultPeriod . "&date=" . $defaultDate . $parametersString;
         header($url);
         exit;
     }
     if (Piwik::isUserIsSuperUser()) {
         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') {
         $errorMessage = sprintf(Piwik::translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:" . Piwik::getSuperUserEmail() . "?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;
 }
Example #19
0
 function addMenu()
 {
     MenuAdmin::getInstance()->add('CoreAdminHome_MenuDiagnostic', 'DBStats_DatabaseUsage', array('module' => 'DBStats', 'action' => 'index'), Piwik::isUserIsSuperUser(), $order = 6);
 }
Example #20
0
 public function privacySettings()
 {
     Piwik::checkUserHasSomeAdminAccess();
     $view = new View('@PrivacyManager/privacySettings');
     if (Piwik::isUserIsSuperUser()) {
         $view->deleteData = $this->getDeleteDataInfo();
         $view->anonymizeIP = $this->getAnonymizeIPInfo();
         $view->dntSupport = DoNotTrackHeaderChecker::isActive();
         $view->canDeleteLogActions = Db::isLockPrivilegeGranted();
         $view->dbUser = Config::getInstance()->database['username'];
         $view->deactivateNonce = Nonce::getNonce(self::DEACTIVATE_DNT_NONCE);
         $view->activateNonce = Nonce::getNonce(self::ACTIVATE_DNT_NONCE);
     }
     $view->language = LanguagesManager::getLanguageCodeForCurrentUser();
     $this->displayWarningIfConfigFileNotWritable();
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Example #21
0
 /**
  * Renders the current view. Also sends the stored 'Content-Type' HTML header.
  * See {@link setContentType()}.
  *
  * @return string Generated template.
  */
 public function render()
 {
     try {
         $this->currentModule = Piwik::getModule();
         $this->currentAction = Piwik::getAction();
         $userLogin = Piwik::getCurrentUserLogin();
         $this->userLogin = $userLogin;
         $count = SettingsPiwik::getWebsitesCountToDisplay();
         $sites = APISitesManager::getInstance()->getSitesWithAtLeastViewAccess($count);
         usort($sites, function ($site1, $site2) {
             return strcasecmp($site1["name"], $site2["name"]);
         });
         $this->sites = $sites;
         $this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
         $this->token_auth = Piwik::getCurrentUserTokenAuth();
         $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
         $this->userIsSuperUser = Piwik::isUserIsSuperUser();
         $this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
         $this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
         $this->isWidget = Common::getRequestVar('widget', 0, 'int');
         if (Config::getInstance()->General['autocomplete_min_sites'] <= count($sites)) {
             $this->show_autocompleter = true;
         } else {
             $this->show_autocompleter = false;
         }
         $this->loginModule = Piwik::getLoginPluginName();
         $user = APIUsersManager::getInstance()->getUser($userLogin);
         $this->userAlias = $user['alias'];
     } catch (Exception $e) {
         // can fail, for example at installation (no plugin loaded yet)
     }
     try {
         $this->totalTimeGeneration = Registry::get('timer')->getTime();
         $this->totalNumberOfQueries = Profiler::getQueryCount();
     } catch (Exception $e) {
         $this->totalNumberOfQueries = 0;
     }
     ProxyHttp::overrideCacheControlHeaders('no-store');
     @header('Content-Type: ' . $this->contentType);
     // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail)
     @header('X-Frame-Options: ' . (string) $this->xFrameOptions);
     return $this->renderTwigTemplate();
 }
Example #22
0
 public function safemode($lastError = array())
 {
     if (empty($lastError)) {
         $lastError = array('message' => Common::getRequestVar('error_message', null, 'string'), 'file' => Common::getRequestVar('error_file', null, 'string'), 'line' => Common::getRequestVar('error_line', null, 'integer'));
     }
     $outputFormat = Common::getRequestVar('format', 'html', 'string');
     $outputFormat = strtolower($outputFormat);
     if (!empty($outputFormat) && 'html' !== $outputFormat) {
         $errorMessage = $lastError['message'];
         if (Piwik::isUserIsAnonymous()) {
             $errorMessage = 'A fatal error occurred.';
         }
         $response = new \Piwik\API\ResponseBuilder($outputFormat);
         $message = $response->getResponseException(new Exception($errorMessage));
         return $message;
     }
     $view = new View('@CorePluginsAdmin/safemode');
     $view->lastError = $lastError;
     $view->isSuperUser = Piwik::isUserIsSuperUser();
     $view->isAnonymousUser = Piwik::isUserIsAnonymous();
     $view->plugins = Plugin\Manager::getInstance()->returnLoadedPluginsInfo();
     $view->deactivateNonce = Nonce::getNonce(static::DEACTIVATE_NONCE);
     $view->uninstallNonce = Nonce::getNonce(static::UNINSTALL_NONCE);
     $view->emailSuperUser = Piwik::getSuperUserEmail();
     $view->piwikVersion = Version::VERSION;
     $view->showVersion = !Common::getRequestVar('tests_hide_piwik_version', 0);
     $view->pluginCausesIssue = '';
     if (!empty($lastError['file'])) {
         preg_match('/piwik\\/plugins\\/(.*)\\//', $lastError['file'], $matches);
         if (!empty($matches[1])) {
             $view->pluginCausesIssue = $matches[1];
         }
     }
     return $view->render();
 }
Example #23
0
 private function processPasswordChange($userLogin)
 {
     $alias = Common::getRequestVar('alias');
     $email = Common::getRequestVar('email');
     $newPassword = false;
     $password = Common::getRequestvar('password', false);
     $passwordBis = Common::getRequestvar('passwordBis', false);
     if (!empty($password) || !empty($passwordBis)) {
         if ($password != $passwordBis) {
             throw new Exception(Piwik::translate('Login_PasswordsDoNotMatch'));
         }
         $newPassword = $password;
     }
     // UI disables password change on invalid host, but check here anyway
     if (!Url::isValidHost() && $newPassword !== false) {
         throw new Exception("Cannot change password with untrusted hostname!");
     }
     if (Piwik::isUserIsSuperUser()) {
         $superUser = Config::getInstance()->superuser;
         $updatedSuperUser = false;
         if ($newPassword !== false) {
             $newPassword = Common::unsanitizeInputValue($newPassword);
             $md5PasswordSuperUser = md5($newPassword);
             $superUser['password'] = $md5PasswordSuperUser;
             $updatedSuperUser = true;
         }
         if ($superUser['email'] != $email) {
             $superUser['email'] = $email;
             $updatedSuperUser = true;
         }
         if ($updatedSuperUser) {
             Config::getInstance()->superuser = $superUser;
             Config::getInstance()->forceSave();
         }
     } else {
         APIUsersManager::getInstance()->updateUser($userLogin, $newPassword, $email, $alias);
         if ($newPassword !== false) {
             $newPassword = Common::unsanitizeInputValue($newPassword);
         }
     }
     // logs the user in with the new password
     if ($newPassword !== false) {
         \Piwik\Registry::get('auth')->initSession($userLogin, md5($newPassword), $rememberMe = false);
     }
 }
Example #24
0
 /**
  * Returns the list of all the users
  *
  * @param string $userLogins Comma separated list of users to select. If not specified, will return all users
  * @return array the list of all the users
  */
 public function getUsers($userLogins = '')
 {
     Piwik::checkUserHasSomeAdminAccess();
     $where = '';
     $bind = array();
     if (!empty($userLogins)) {
         $userLogins = explode(',', $userLogins);
         $where = 'WHERE login IN (' . Common::getSqlStringFieldsArray($userLogins) . ')';
         $bind = $userLogins;
     }
     $db = Db::get();
     $users = $db->fetchAll("SELECT *\n\t\t\t\t\t\t\t\tFROM " . Common::prefixTable("user") . "\n\t\t\t\t\t\t\t\t{$where}\n\t\t\t\t\t\t\t\tORDER BY login ASC", $bind);
     // Non Super user can only access login & alias
     if (!Piwik::isUserIsSuperUser()) {
         foreach ($users as &$user) {
             $user = array('login' => $user['login'], 'alias' => $user['alias']);
         }
     }
     return $users;
 }
Example #25
0
 /**
  * Tracker requests will automatically trigger the Scheduled tasks.
  * This is useful for users who don't setup the cron,
  * but still want daily/weekly/monthly PDF reports emailed automatically.
  *
  * This is similar to calling the API CoreAdminHome.runScheduledTasks (see misc/cron/archive.php)
  */
 protected static function runScheduledTasks()
 {
     $now = time();
     // Currently, there are no hourly tasks. When there are some,
     // this could be too aggressive minimum interval (some hours would be skipped in case of low traffic)
     $minimumInterval = Config::getInstance()->Tracker['scheduled_tasks_min_interval'];
     // If the user disabled browser archiving, he has already setup a cron
     // To avoid parallel requests triggering the Scheduled Tasks,
     // Get last time tasks started executing
     $cache = Cache::getCacheGeneral();
     if ($minimumInterval <= 0 || empty($cache['isBrowserTriggerArchivingEnabled'])) {
         Common::printDebug("-> Scheduled tasks not running in Tracker: Browser archiving is disabled.");
         return;
     }
     $nextRunTime = $cache['lastTrackerCronRun'] + $minimumInterval;
     if (isset($GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS']) && $GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS'] || $cache['lastTrackerCronRun'] === false || $nextRunTime < $now) {
         $cache['lastTrackerCronRun'] = $now;
         Cache::setCacheGeneral($cache);
         self::initCorePiwikInTrackerMode();
         Option::set('lastTrackerCronRun', $cache['lastTrackerCronRun']);
         Common::printDebug('-> Scheduled Tasks: Starting...');
         // save current user privilege and temporarily assume super user privilege
         $isSuperUser = Piwik::isUserIsSuperUser();
         // Scheduled tasks assume Super User is running
         Piwik::setUserIsSuperUser();
         // While each plugins should ensure that necessary languages are loaded,
         // we ensure English translations at least are loaded
         Translate::loadEnglishTranslation();
         $resultTasks = TaskScheduler::runTasks();
         // restore original user privilege
         Piwik::setUserIsSuperUser($isSuperUser);
         Common::printDebug($resultTasks);
         Common::printDebug('Finished Scheduled Tasks.');
     } else {
         Common::printDebug("-> Scheduled tasks not triggered.");
     }
     Common::printDebug("Next run will be from: " . date('Y-m-d H:i:s', $nextRunTime) . ' UTC');
 }
 /**
  * Assigns view properties that would be useful to views that render admin pages.
  *
  * Assigns the following variables:
  *
  * - **statisticsNotRecorded** - Set to true if the `[Tracker] record_statistics` INI
  *                               config is `0`. If not `0`, this variable will not be defined.
  * - **topMenu** - The result of `MenuTop::getInstance()->getMenu()`.
  * - **currentAdminMenuName** - The currently selected admin menu name.
  * - **enableFrames** - The value of the `[General] enable_framed_pages` INI config option. If
  *                    true, {@link Piwik\View::setXFrameOptions()} is called on the view.
  * - **isSuperUser** - Whether the current user is a superuser or not.
  * - **usingOldGeoIPPlugin** - Whether this Piwik install is currently using the old GeoIP
  *                             plugin or not.
  * - **invalidPluginsWarning** - Set if some of the plugins to load (determined by INI configuration)
  *                               are invalid or missing.
  * - **phpVersion** - The current PHP version.
  * - **phpIsNewEnough** - Whether the current PHP version is new enough to run Piwik.
  * - **adminMenu** - The result of `MenuAdmin::getInstance()->getMenu()`.
  *
  * @param View $view
  * @api
  */
 public static function setBasicVariablesAdminView(View $view)
 {
     self::notifyWhenTrackingStatisticsDisabled();
     $view->topMenu = MenuTop::getInstance()->getMenu();
     $view->currentAdminMenuName = MenuAdmin::getInstance()->getCurrentAdminMenuName();
     $view->isDataPurgeSettingsEnabled = self::isDataPurgeSettingsEnabled();
     $view->enableFrames = PiwikConfig::getInstance()->General['enable_framed_settings'];
     if (!$view->enableFrames) {
         $view->setXFrameOptions('sameorigin');
     }
     $view->isSuperUser = Piwik::isUserIsSuperUser();
     self::notifyAnyInvalidPlugin();
     self::checkPhpVersion($view);
     $adminMenu = MenuAdmin::getInstance()->getMenu();
     $view->adminMenu = $adminMenu;
     $view->notifications = NotificationManager::getAllNotificationsToDisplay();
     NotificationManager::cancelAllNonPersistent();
 }
Example #27
0
 /**
  * Returns the current user's email address.
  *
  * @return string
  * @api
  */
 public static function getCurrentUserEmail()
 {
     if (!Piwik::isUserIsSuperUser()) {
         $user = API::getInstance()->getUser(Piwik::getCurrentUserLogin());
         return $user['email'];
     }
     return self::getSuperUserEmail();
 }