Beispiel #1
0
 public function hasKey($key)
 {
     if ($key === 'auth') {
         $key = 'Piwik\\Auth';
     }
     return StaticContainer::getContainer()->has($key);
 }
 public function initAuthenticationObject($activateCookieAuth = false)
 {
     $auth = new Auth();
     StaticContainer::getContainer()->set('Piwik\\Auth', $auth);
     $login = new Login();
     return $login->initAuthenticationFromCookie($auth, $activateCookieAuth);
 }
Beispiel #3
0
 /**
  * Constructor.
  *
  * @param string[] $options The string options applied to the generate:travis-yml command.
  */
 public function __construct($options)
 {
     $this->options = $options;
     if (class_exists('\\Piwik\\Container\\StaticContainer')) {
         $this->logger = \Piwik\Container\StaticContainer::getContainer()->get('Psr\\Log\\LoggerInterface');
     }
     $this->view = new TravisYmlView();
 }
 /**
  * @param array $widget
  *
  * @dataProvider availableWidgetsProvider
  */
 public function test_WidgetIsRenderable_ToPreventBreakingTheAPI($widget)
 {
     $params = $widget['parameters'];
     $parameters = array();
     $resolver = new ControllerResolver(StaticContainer::getContainer());
     $controller = $resolver->getController($params['module'], $params['action'], $parameters);
     $this->assertNotEmpty($controller, $widget['name'] . ' is not renderable with following params: ' . json_encode($params) . '. This breaks the API, please make sure to keep the URL working');
 }
Beispiel #5
0
 /**
  * @return MetricsProvider[]
  */
 private function getProviders()
 {
     $container = StaticContainer::getContainer();
     $providers = array($container->get('Piwik\\Plugins\\SEO\\Metric\\Google'), $container->get('Piwik\\Plugins\\SEO\\Metric\\Bing'), $container->get('Piwik\\Plugins\\SEO\\Metric\\Alexa'), $container->get('Piwik\\Plugins\\SEO\\Metric\\DomainAge'), $container->get('Piwik\\Plugins\\SEO\\Metric\\Dmoz'));
     /**
      * Use this event to register new SEO metrics providers.
      *
      * @param array $providers Contains an array of Piwik\Plugins\SEO\Metric\MetricsProvider instances.
      */
     Piwik::postEvent('SEO.getMetricsProviders', array(&$providers));
     return $providers;
 }
Beispiel #6
0
 /**
  * You can create your own Users Plugin to override this class.
  * Example of how you would overwrite the UsersManager_API with your own class:
  * Call the following in your plugin __construct() for example:
  *
  * StaticContainer::getContainer()->set('UsersManager_API', \Piwik\Plugins\MyCustomUsersManager\API::getInstance());
  *
  * @throws Exception
  * @return \Piwik\Plugins\UsersManager\API
  */
 public static function getInstance()
 {
     try {
         $instance = StaticContainer::get('UsersManager_API');
         if (!$instance instanceof API) {
             // Exception is caught below and corrected
             throw new Exception('UsersManager_API must inherit API');
         }
         self::$instance = $instance;
     } catch (Exception $e) {
         self::$instance = StaticContainer::get('Piwik\\Plugins\\UsersManager\\API');
         StaticContainer::getContainer()->set('UsersManager_API', self::$instance);
     }
     return self::$instance;
 }
Beispiel #7
0
 /**
  * Returns the singleton instance for the derived class. If the singleton instance
  * has not been created, this method will create it.
  *
  * @return static
  */
 public static function getInstance()
 {
     $class = get_called_class();
     if (!isset(self::$instances[$class])) {
         $container = StaticContainer::getContainer();
         $refl = new \ReflectionClass($class);
         if (!$refl->getConstructor() || $refl->getConstructor()->isPublic()) {
             self::$instances[$class] = $container->get($class);
         } else {
             /** @var LoggerInterface $logger */
             $logger = $container->get('Psr\\Log\\LoggerInterface');
             // BC with API defining a protected constructor
             $logger->notice('The API class {class} defines a protected constructor which is deprecated, make the constructor public instead', array('class' => $class));
             self::$instances[$class] = new $class();
         }
     }
     return self::$instances[$class];
 }
Beispiel #8
0
 /**
  * @param array $reports
  * @param array $info
  * @return mixed
  */
 public function getReportMetadata(&$reports, $info)
 {
     $idSites = $info['idSites'];
     // If only one website is selected, we add the Graph URL
     if (count($idSites) != 1) {
         return;
     }
     $idSite = reset($idSites);
     // in case API.getReportMetadata was not called with date/period we use sane defaults
     if (empty($info['period'])) {
         $info['period'] = 'day';
     }
     if (empty($info['date'])) {
         $info['date'] = 'today';
     }
     // need two sets of period & date, one for single period graphs, one for multiple periods graphs
     if (Period::isMultiplePeriod($info['date'], $info['period'])) {
         $periodForMultiplePeriodGraph = $info['period'];
         $dateForMultiplePeriodGraph = $info['date'];
         $periodForSinglePeriodGraph = 'range';
         $dateForSinglePeriodGraph = $info['date'];
     } else {
         $periodForSinglePeriodGraph = $info['period'];
         $dateForSinglePeriodGraph = $info['date'];
         $piwikSite = new Site($idSite);
         if ($periodForSinglePeriodGraph == 'range') {
             // for period=range, show the configured sub-periods
             $periodForMultiplePeriodGraph = Config::getInstance()->General['graphs_default_period_to_plot_when_period_range'];
             $dateForMultiplePeriodGraph = $dateForSinglePeriodGraph;
         } else {
             if ($info['period'] == 'day' || !Config::getInstance()->General['graphs_show_evolution_within_selected_period']) {
                 // for period=day, always show the last n days
                 // if graphs_show_evolution_within_selected_period=false, show the last n periods
                 $periodForMultiplePeriodGraph = $periodForSinglePeriodGraph;
                 $dateForMultiplePeriodGraph = Range::getRelativeToEndDate($periodForSinglePeriodGraph, 'last' . self::GRAPH_EVOLUTION_LAST_PERIODS, $dateForSinglePeriodGraph, $piwikSite);
             } else {
                 // if graphs_show_evolution_within_selected_period=true, show the days within the period
                 // (except if the period is day, see above)
                 $periodForMultiplePeriodGraph = 'day';
                 $period = PeriodFactory::build($info['period'], $info['date']);
                 $start = $period->getDateStart()->toString();
                 $end = $period->getDateEnd()->toString();
                 $dateForMultiplePeriodGraph = $start . ',' . $end;
             }
         }
     }
     $token_auth = Common::getRequestVar('token_auth', false);
     $segment = Request::getRawSegmentFromRequest();
     /** @var Scheduler $scheduler */
     $scheduler = StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
     $isRunningTask = $scheduler->isRunningTask();
     // add the idSubtable if it exists
     $idSubtable = Common::getRequestVar('idSubtable', false);
     $urlPrefix = "index.php?";
     foreach ($reports as &$report) {
         $reportModule = $report['module'];
         $reportAction = $report['action'];
         $reportUniqueId = $reportModule . '_' . $reportAction;
         $parameters = array();
         $parameters['module'] = 'API';
         $parameters['method'] = 'ImageGraph.get';
         $parameters['idSite'] = $idSite;
         $parameters['apiModule'] = $reportModule;
         $parameters['apiAction'] = $reportAction;
         if (!empty($token_auth)) {
             $parameters['token_auth'] = $token_auth;
         }
         // Forward custom Report parameters to the graph URL
         if (!empty($report['parameters'])) {
             $parameters = array_merge($parameters, $report['parameters']);
         }
         if (empty($report['dimension'])) {
             $parameters['period'] = $periodForMultiplePeriodGraph;
             $parameters['date'] = $dateForMultiplePeriodGraph;
         } else {
             $parameters['period'] = $periodForSinglePeriodGraph;
             $parameters['date'] = $dateForSinglePeriodGraph;
         }
         if ($idSubtable !== false) {
             $parameters['idSubtable'] = $idSubtable;
         }
         if (!empty($_GET['_restrictSitesToLogin']) && $isRunningTask) {
             $parameters['_restrictSitesToLogin'] = $_GET['_restrictSitesToLogin'];
         }
         if (!empty($segment)) {
             $parameters['segment'] = $segment;
         }
         $report['imageGraphUrl'] = $urlPrefix . Url::getQueryStringFromParameters($parameters);
         // thanks to API.getRowEvolution, reports with dimensions can now be plotted using an evolution graph
         // however, most reports with a fixed set of dimension values are excluded
         // this is done so Piwik Mobile and Scheduled Reports do not display them
         $reportWithDimensionsSupportsEvolution = empty($report['constantRowsCount']) || in_array($reportUniqueId, self::$CONSTANT_ROW_COUNT_REPORT_EXCEPTIONS);
         $reportSupportsEvolution = !in_array($reportUniqueId, self::$REPORTS_DISABLED_EVOLUTION_GRAPH);
         if ($reportSupportsEvolution && $reportWithDimensionsSupportsEvolution) {
             $parameters['period'] = $periodForMultiplePeriodGraph;
             $parameters['date'] = $dateForMultiplePeriodGraph;
             $report['imageGraphEvolutionUrl'] = $urlPrefix . Url::getQueryStringFromParameters($parameters);
         }
     }
 }
Beispiel #9
0
 protected function getDeleteDataInfo()
 {
     Piwik::checkUserHasSuperUserAccess();
     $deleteDataInfos = array();
     $deleteDataInfos["config"] = PrivacyManager::getPurgeDataSettings();
     $deleteDataInfos["deleteTables"] = "<br/>" . implode(", ", LogDataPurger::getDeleteTableLogTables());
     /** @var Scheduler $scheduler */
     $scheduler = StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
     $scheduleTimetable = $scheduler->getScheduledTimeForMethod("PrivacyManager", "deleteLogTables");
     $optionTable = Option::get(self::OPTION_LAST_DELETE_PIWIK_LOGS);
     //If task was already rescheduled, read time from taskTimetable. Else, calculate next possible runtime.
     if (!empty($scheduleTimetable) && $scheduleTimetable - time() > 0) {
         $nextPossibleSchedule = (int) $scheduleTimetable;
     } else {
         $date = Date::factory("today");
         $nextPossibleSchedule = $date->addDay(1)->getTimestamp();
     }
     //deletion schedule did not run before
     if (empty($optionTable)) {
         $deleteDataInfos["lastRun"] = false;
         //next run ASAP (with next schedule run)
         $date = Date::factory("today");
         $deleteDataInfos["nextScheduleTime"] = $nextPossibleSchedule;
     } else {
         $deleteDataInfos["lastRun"] = $optionTable;
         $deleteDataInfos["lastRunPretty"] = Date::factory((int) $optionTable)->getLocalized(Date::DATE_FORMAT_SHORT);
         //Calculate next run based on last run + interval
         $nextScheduleRun = (int) ($deleteDataInfos["lastRun"] + $deleteDataInfos["config"]["delete_logs_schedule_lowest_interval"] * 24 * 60 * 60);
         //is the calculated next run in the past? (e.g. plugin was disabled in the meantime or something) -> run ASAP
         if ($nextScheduleRun - time() <= 0) {
             $deleteDataInfos["nextScheduleTime"] = $nextPossibleSchedule;
         } else {
             $deleteDataInfos["nextScheduleTime"] = $nextScheduleRun;
         }
     }
     $formatter = new Formatter();
     $deleteDataInfos["nextRunPretty"] = $formatter->getPrettyTimeFromSeconds($deleteDataInfos["nextScheduleTime"] - time());
     return $deleteDataInfos;
 }
Beispiel #10
0
 /**
  * Initializes the authentication object.
  * Listens to Request.initAuthenticationObject hook.
  */
 function initAuthenticationObject($activateCookieAuth = false)
 {
     $this->initAuthenticationFromCookie(StaticContainer::getContainer()->get('Piwik\\Auth'), $activateCookieAuth);
 }
 /**
  * @return Scheduler
  */
 private static function getInstance()
 {
     return StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
 }
Beispiel #12
0
 /**
  * Returns the list of websites ID with the 'view' or 'admin' access for the current user.
  * For the superUser it returns all the websites in the database.
  *
  * @param bool $_restrictSitesToLogin
  * @return array list of websites ID
  */
 public function getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin = false)
 {
     /** @var Scheduler $scheduler */
     $scheduler = StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
     if (Piwik::hasUserSuperUserAccess() && !$scheduler->isRunningTask()) {
         return Access::getInstance()->getSitesIdWithAtLeastViewAccess();
     }
     if (!empty($_restrictSitesToLogin) && (Piwik::hasUserSuperUserAccessOrIsTheUser($_restrictSitesToLogin) || $scheduler->isRunningTask())) {
         if (Piwik::hasTheUserSuperUserAccess($_restrictSitesToLogin)) {
             return Access::getInstance()->getSitesIdWithAtLeastViewAccess();
         }
         $accessRaw = Access::getInstance()->getRawSitesWithSomeViewAccess($_restrictSitesToLogin);
         $sitesId = array();
         foreach ($accessRaw as $access) {
             $sitesId[] = $access['idsite'];
         }
         return $sitesId;
     } else {
         return Access::getInstance()->getSitesIdWithAtLeastViewAccess();
     }
 }
Beispiel #13
0
 /**
  * Initializes the authentication object.
  * Listens to Request.initAuthenticationObject hook.
  */
 function initAuthenticationObject($activateCookieAuth = false)
 {
     $auth = new Auth();
     StaticContainer::getContainer()->set('Piwik\\Auth', $auth);
     $this->initAuthenticationFromCookie($auth, $activateCookieAuth);
 }
Beispiel #14
0
 /**
  * @api
  *
  * Get measurable settings for a specific plugin.
  *
  * @param string $pluginName    The name of a plugin.
  * @param int $idSite           The ID of a site. If a site is about to be created pass idSite = 0.
  * @param string|null $idType   If null, idType will be detected automatically if the site already exists. Only
  *                              needed to set a value when idSite = 0 (this is the case when a site is about)
  *                              to be created.
  *
  * @return MeasurableSettings|null  Returns null if no MeasurableSettings implemented by this plugin or when plugin
  *                                  is not loaded and activated. Returns an instance of the settings otherwise.
  */
 public function getMeasurableSettings($pluginName, $idSite, $idType = null)
 {
     $plugin = $this->getLoadedAndActivated($pluginName);
     if ($plugin) {
         $component = $plugin->findComponent('MeasurableSettings', 'Piwik\\Settings\\Measurable\\MeasurableSettings');
         if ($component) {
             return StaticContainer::getContainer()->make($component, array('idSite' => $idSite, 'idMeasurableType' => $idType));
         }
     }
 }
Beispiel #15
0
 /**
  * Initializes the authentication object.
  * Listens to Request.initAuthenticationObject hook.
  */
 function initAuthenticationObject($activateCookieAuth = false)
 {
     $auth = AuthBase::factory();
     StaticContainer::getContainer()->set('Piwik\\Auth', $auth);
     Login::initAuthenticationFromCookie($auth, $activateCookieAuth);
 }
 private function makePluginSettings()
 {
     $settings = new Settings();
     StaticContainer::getContainer()->set('Piwik\\Plugins\\AnonymousPiwikUsageMeasurement\\Settings', $settings);
     return $settings;
 }
Beispiel #17
0
 /**
  * Update Piwik codebase by downloading and installing the latest version.
  *
  * @param bool $https Whether to use HTTPS if supported of not. If false, will use HTTP.
  * @return string[] Return an array of messages for the user.
  * @throws ArchiveDownloadException
  * @throws UpdaterException
  * @throws Exception
  */
 public function updatePiwik($https = true)
 {
     if (!$this->isNewVersionAvailable()) {
         throw new Exception($this->translator->translate('CoreUpdater_ExceptionAlreadyLatestVersion', Version::VERSION));
     }
     SettingsServer::setMaxExecutionTime(0);
     $newVersion = $this->getLatestVersion();
     $url = $this->getArchiveUrl($newVersion, $https);
     $messages = array();
     try {
         $archiveFile = $this->downloadArchive($newVersion, $url);
         $messages[] = $this->translator->translate('CoreUpdater_DownloadingUpdateFromX', $url);
         $extractedArchiveDirectory = $this->decompressArchive($archiveFile);
         $messages[] = $this->translator->translate('CoreUpdater_UnpackingTheUpdate');
         $this->verifyDecompressedArchive($extractedArchiveDirectory);
         $messages[] = $this->translator->translate('CoreUpdater_VerifyingUnpackedFiles');
         if (Marketplace::isMarketplaceEnabled()) {
             // we need to load the marketplace already here, otherwise it will use the new, updated file in Piwik 3
             // we also need to make sure to create a new instance here as otherwise we would change the "global"
             // environment, but we only want to change piwik version temporarily for this task here
             $environment = StaticContainer::getContainer()->make('Piwik\\Plugins\\Marketplace\\Environment');
             $environment->setPiwikVersion($newVersion);
             /** @var \Piwik\Plugins\Marketplace\Api\Client $marketplaceClient */
             $marketplaceClient = StaticContainer::getContainer()->make('Piwik\\Plugins\\Marketplace\\Api\\Client', array('environment' => $environment));
             require_once PIWIK_DOCUMENT_ROOT . '/plugins/CorePluginsAdmin/PluginInstaller.php';
             require_once PIWIK_DOCUMENT_ROOT . '/plugins/Marketplace/Api/Exception.php';
         }
         $this->installNewFiles($extractedArchiveDirectory);
         $messages[] = $this->translator->translate('CoreUpdater_InstallingTheLatestVersion');
     } catch (ArchiveDownloadException $e) {
         throw $e;
     } catch (Exception $e) {
         throw new UpdaterException($e, $messages);
     }
     try {
         if (Marketplace::isMarketplaceEnabled() && !empty($marketplaceClient)) {
             $messages[] = $this->translator->translate('CoreUpdater_CheckingForPluginUpdates');
             $pluginManager = PluginManager::getInstance();
             $pluginManager->loadAllPluginsAndGetTheirInfo();
             $loadedPlugins = $pluginManager->getLoadedPlugins();
             $marketplaceClient->clearAllCacheEntries();
             $pluginsWithUpdate = $marketplaceClient->checkUpdates($loadedPlugins);
             foreach ($pluginsWithUpdate as $pluginWithUpdate) {
                 $pluginName = $pluginWithUpdate['name'];
                 $messages[] = $this->translator->translate('CoreUpdater_UpdatingPluginXToVersionY', array($pluginName, $pluginWithUpdate['version']));
                 $pluginInstaller = new PluginInstaller($marketplaceClient);
                 $pluginInstaller->installOrUpdatePluginFromMarketplace($pluginName);
             }
         }
     } catch (MarketplaceApi\Exception $e) {
         // there is a problem with the connection to the server, ignore for now
     } catch (Exception $e) {
         throw new UpdaterException($e, $messages);
     }
     try {
         $disabledPluginNames = $this->disableIncompatiblePlugins($newVersion);
         if (!empty($disabledPluginNames)) {
             $messages[] = $this->translator->translate('CoreUpdater_DisablingIncompatiblePlugins', implode(', ', $disabledPluginNames));
         }
     } catch (Exception $e) {
         throw new UpdaterException($e, $messages);
     }
     return $messages;
 }
Beispiel #18
0
 /**
  * Fetches the list of sites which names match the string pattern
  *
  * @param string $pattern
  * @param bool   $_restrictSitesToLogin
  * @return array|string
  */
 private function getSitesIdFromPattern($pattern, $_restrictSitesToLogin)
 {
     // First clear cache
     Site::clearCache();
     if (empty($pattern)) {
         /** @var Scheduler $scheduler */
         $scheduler = StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
         // Then, warm the cache with only the data we should have access to
         if (Piwik::hasUserSuperUserAccess() && !$scheduler->isRunningTask()) {
             APISitesManager::getInstance()->getAllSites();
         } else {
             APISitesManager::getInstance()->getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin);
         }
     } else {
         $sites = Request::processRequest('SitesManager.getPatternMatchSites', array('pattern' => $pattern, 'showColumns' => '', 'hideColumns' => '', 'serialize' => 0, 'format' => 'original'));
         if (!empty($sites)) {
             $idSites = array();
             foreach ($sites as $site) {
                 $idSites[] = $site['idsite'];
             }
             $model = new ModelSitesManager();
             $sites = $model->getSitesFromIds($idSites);
             // getPatternMatchSites does not return all sites information...
             Site::setSitesFromArray($sites);
         }
     }
     // Both calls above have called Site::setSitesFromArray. We now get these sites:
     $sitesToProblablyAdd = Site::getSites();
     return $sitesToProblablyAdd;
 }
Beispiel #19
0
 private function executeSingleUpdateClass($className)
 {
     $update = StaticContainer::getContainer()->make($className);
     try {
         call_user_func(array($update, 'doUpdate'), $this);
     } catch (\Exception $e) {
         // if an Update file executes PHP statements directly, DB exceptions be handled by executeSingleMigrationQuery, so
         // make sure to check for them here
         if ($e instanceof Zend_Db_Exception) {
             throw new UpdaterErrorException($e->getMessage(), $e->getCode(), $e);
         } else {
             if ($e instanceof MissingFilePermissionException) {
                 throw new UpdaterErrorException($e->getMessage(), $e->getCode(), $e);
             }
         }
         throw $e;
     }
 }
 /**
  * init the authentification object
  *
  * @return	void
  */
 function initAuthenticationObject()
 {
     $config = \Piwik\Config::getInstance();
     $auth = new \Piwik\Plugins\TYPO3Login\Auth();
     StaticContainer::getContainer()->set('Piwik\\Auth', $auth);
     $action = \Piwik\Piwik::getAction();
     if (\Piwik\Piwik::getModule() === 'API' && (empty($action) || $action == 'index')) {
         return;
     }
     $authCookieName = $config->General['login_cookie_name'];
     $authCookieExpiry = time() + $config->General['login_cookie_expire'];
     $authCookie = new \Piwik\Cookie($authCookieName, $authCookieExpiry);
     $defaultLogin = '******';
     $defaultTokenAuth = 'anonymous';
     if ($authCookie->isCookieFound()) {
         $defaultLogin = $authCookie->get('login');
         $defaultTokenAuth = $authCookie->get('token_auth');
     }
     $auth->setLogin($defaultLogin);
     $auth->setTokenAuth($defaultTokenAuth);
 }
 /**
  * Sets the options used by this class based on the elements in $options.
  *
  * The following elements of $options are used:
  *   'loc' - URL for location database.
  *   'isp' - URL for ISP database.
  *   'org' - URL for Organization database.
  *   'period' - 'weekly' or 'monthly'. When to run the updates.
  *
  * @param array $options
  * @throws Exception
  */
 public static function setUpdaterOptions($options)
 {
     // set url options
     foreach (self::$urlOptions as $optionKey => $optionName) {
         if (!isset($options[$optionKey])) {
             continue;
         }
         $url = $options[$optionKey];
         $url = self::removeDateFromUrl($url);
         Option::set($optionName, $url);
     }
     // set period option
     if (!empty($options['period'])) {
         $period = $options['period'];
         if ($period != self::SCHEDULE_PERIOD_MONTHLY && $period != self::SCHEDULE_PERIOD_WEEKLY) {
             throw new Exception(Piwik::translate('UserCountry_InvalidGeoIPUpdatePeriod', array("'{$period}'", "'" . self::SCHEDULE_PERIOD_MONTHLY . "', '" . self::SCHEDULE_PERIOD_WEEKLY . "'")));
         }
         Option::set(self::SCHEDULE_PERIOD_OPTION_NAME, $period);
         /** @var Scheduler $scheduler */
         $scheduler = StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
         $scheduler->rescheduleTask(new GeoIPAutoUpdater());
     }
 }
Beispiel #22
0
 /**
  * @ignore
  */
 public function __construct()
 {
     $this->container = StaticContainer::getContainer();
 }