public function test_isUsedInAtLeastOneSite_shouldCache() { $key = '1.month.' . $this->date; $cache = Cache::getTransientCache(); $this->assertFalse($cache->contains($key)); $this->userId->isUsedInAtLeastOneSite($idSites = array(1), 'day', $this->date); $this->assertTrue($cache->contains($key)); $this->assertFalse($cache->fetch($key)); }
private function isUsedInSiteCached($idSite, $period, $date) { $cache = Cache::getTransientCache(); $key = sprintf('%d.%s.%s', $idSite, $period, $date); if (!$cache->contains($key)) { $result = $this->isUsedInSite($idSite, $period, $date); $cache->save($key, $result); } return $cache->fetch($key); }
/** * Returns all language codes the transifex project is available for * * @return array * @throws AuthenticationFailedException * @throws Exception */ public function getAvailableLanguageCodes() { $cache = Cache::getTransientCache(); $cacheId = 'transifex_languagescodes_' . $this->projectSlug; $languageCodes = $cache->fetch($cacheId); if (empty($languageCodes)) { $apiData = $this->getApiResults('project/' . $this->projectSlug . '/languages'); foreach ($apiData as $languageData) { $languageCodes[] = $languageData->language_code; } $cache->save($cacheId, $languageCodes); } return $languageCodes; }
/** * Returns a list of all available reports. Even not enabled reports will be returned. They will be already sorted * depending on the order and category of the report. * @return \Piwik\Plugin\Report[] * @api */ public function getAllReports() { $reports = $this->getAllReportClasses(); $cacheId = CacheId::languageAware('Reports' . md5(implode('', $reports))); $cache = PiwikCache::getTransientCache(); if (!$cache->contains($cacheId)) { $instances = array(); /** * Triggered to add new reports that cannot be picked up automatically by the platform. * This is useful if the plugin allows a user to create reports / dimensions dynamically. For example * CustomDimensions or CustomVariables. There are a variable number of dimensions in this case and it * wouldn't be really possible to create a report file for one of these dimensions as it is not known * how many Custom Dimensions will exist. * * **Example** * * public function addReport(&$reports) * { * $reports[] = new MyCustomReport(); * } * * @param Report[] $reports An array of reports */ Piwik::postEvent('Report.addReports', array(&$instances)); foreach ($reports as $report) { $instances[] = new $report(); } /** * Triggered to filter / restrict reports. * * **Example** * * public function filterReports(&$reports) * { * foreach ($reports as $index => $report) { * if ($report->getCategory() === 'Actions') {} * unset($reports[$index]); // remove all reports having this action * } * } * } * * @param Report[] $reports An array of reports */ Piwik::postEvent('Report.filterReports', array(&$instances)); usort($instances, array($this, 'sort')); $cache->save($cacheId, $instances); } return $cache->fetch($cacheId); }
/** * Setup the database and create the base tables for all tests */ public function setUp() { parent::setUp(); static::$fixture->extraDefinitions = array_merge(static::provideContainerConfigBeforeClass(), $this->provideContainerConfig()); static::$fixture->createEnvironmentInstance(); Db::createDatabaseObject(); Fixture::loadAllPlugins(new TestingEnvironmentVariables(), get_class($this), self::$fixture->extraPluginsToLoad); Access::getInstance()->setSuperUserAccess(true); if (!empty(self::$tableData)) { self::restoreDbTables(self::$tableData); } PiwikCache::getEagerCache()->flushAll(); PiwikCache::getTransientCache()->flushAll(); MenuAbstract::clearMenus(); }
public function test_flushAll_shouldActuallyFlushAllCaches() { $cache1 = Cache::getTransientCache(); $cache2 = Cache::getLazyCache(); $cache3 = Cache::getEagerCache(); $cache1->save('test1', 'content'); $cache2->save('test2', 'content'); $cache3->save('test3', 'content'); $this->assertTrue($cache1->contains('test1')); $this->assertTrue($cache2->contains('test2')); $this->assertTrue($cache3->contains('test3')); Cache::flushAll(); $this->assertFalse($cache1->contains('test1')); $this->assertFalse($cache2->contains('test2')); $this->assertFalse($cache3->contains('test3')); }
/** * Returns all registered visualization classes. Uses the 'Visualization.getAvailable' * event to retrieve visualizations. * * @return array Array mapping visualization IDs with their associated visualization classes. * @throws \Exception If a visualization class does not exist or if a duplicate visualization ID * is found. * @return array */ public static function getAvailableViewDataTables() { $cache = Cache::getTransientCache(); $cacheId = 'ViewDataTable.getAvailableViewDataTables'; $dataTables = $cache->fetch($cacheId); if (!empty($dataTables)) { return $dataTables; } $klassToExtend = '\\Piwik\\Plugin\\ViewDataTable'; /** @var string[] $visualizations */ $visualizations = PluginManager::getInstance()->findMultipleComponents('Visualizations', $klassToExtend); /** * Triggered when gathering all available DataTable visualizations. * * Plugins that want to expose new DataTable visualizations should subscribe to * this event and add visualization class names to the incoming array. * * **Example** * * public function addViewDataTable(&$visualizations) * { * $visualizations[] = 'Piwik\\Plugins\\MyPlugin\\MyVisualization'; * } * * @param array &$visualizations The array of all available visualizations. * @ignore * @deprecated since 2.5.0 Place visualization in a "Visualizations" directory instead. */ Piwik::postEvent('ViewDataTable.addViewDataTable', array(&$visualizations)); $result = array(); foreach ($visualizations as $viz) { if (!class_exists($viz)) { throw new \Exception("Invalid visualization class '{$viz}' found in Visualization.getAvailableVisualizations."); } if (!is_subclass_of($viz, $klassToExtend)) { throw new \Exception("ViewDataTable class '{$viz}' does not extend Plugin/ViewDataTable"); } $vizId = $viz::getViewDataTableId(); if (isset($result[$vizId])) { throw new \Exception("ViewDataTable ID '{$vizId}' is already in use!"); } $result[$vizId] = $viz; } $cache->save($cacheId, $result); return $result; }
/** * Returns all registered visualization classes. Uses the 'Visualization.getAvailable' * event to retrieve visualizations. * * @return array Array mapping visualization IDs with their associated visualization classes. * @throws \Exception If a visualization class does not exist or if a duplicate visualization ID * is found. * @return array */ public static function getAvailableViewDataTables() { $cache = Cache::getTransientCache(); $cacheId = 'ViewDataTable.getAvailableViewDataTables'; $dataTables = $cache->fetch($cacheId); if (!empty($dataTables)) { return $dataTables; } $klassToExtend = '\\Piwik\\Plugin\\ViewDataTable'; /** @var string[] $visualizations */ $visualizations = PluginManager::getInstance()->findMultipleComponents('Visualizations', $klassToExtend); $result = array(); foreach ($visualizations as $viz) { if (!class_exists($viz)) { throw new \Exception("Invalid visualization class '{$viz}' found in Visualization.getAvailableVisualizations."); } if (!is_subclass_of($viz, $klassToExtend)) { throw new \Exception("ViewDataTable class '{$viz}' does not extend Plugin/ViewDataTable"); } $vizId = $viz::getViewDataTableId(); if (isset($result[$vizId])) { throw new \Exception("ViewDataTable ID '{$vizId}' is already in use!"); } $result[$vizId] = $viz; } /** * Triggered to filter available DataTable visualizations. * * Plugins that want to disable certain visualizations should subscribe to * this event and remove visualizations from the incoming array. * * **Example** * * public function filterViewDataTable(&$visualizations) * { * unset($visualizations[HtmlTable::ID]); * } * * @param array &$visualizations An array of all available visualizations indexed by visualization ID. * @since Piwik 3.0.0 */ Piwik::postEvent('ViewDataTable.filterViewDataTable', array(&$result)); $cache->save($cacheId, $result); return $result; }
public function test_getIdSitesToArchiveWhenNoVisits_CanBeUsedToTriggerArchiving_EvenIfSiteHasNoVisits() { // add our mock archiver instance // TODO: should use a dummy plugin that is activated for this test explicitly, but that can be tricky, especially in the future PluginsArchiver::$archivers['VisitsSummary'] = 'Piwik\\Tests\\Integration\\ArchiveWithNoVisitsTest_MockArchiver'; // initiate archiving w/o adding the event and make sure no methods are called VisitsSummaryAPI::getInstance()->get($idSite = 1, 'week', '2012-01-01'); $this->assertEmpty(ArchiveWithNoVisitsTest_MockArchiver::$methodsCalled); // mark our only site as should archive when no visits $eventDispatcher = $this->getEventDispatcher(); $eventDispatcher->addObserver('Archiving.getIdSitesToArchiveWhenNoVisits', function (&$idSites) { $idSites[] = 1; }); Cache::getTransientCache()->flushAll(); // initiate archiving and make sure both aggregate methods are called correctly VisitsSummaryAPI::getInstance()->get($idSite = 1, 'week', '2012-01-10'); $expectedMethodCalls = array('aggregateDayReport', 'aggregateDayReport', 'aggregateDayReport', 'aggregateDayReport', 'aggregateDayReport', 'aggregateDayReport', 'aggregateDayReport', 'aggregateMultipleReports'); $this->assertEquals($expectedMethodCalls, ArchiveWithNoVisitsTest_MockArchiver::$methodsCalled); }
public function setUp() { Cache::getTransientCache()->flushAll(); parent::setUp(); }
public static function getDefaultMetricsDocumentation() { $cacheId = CacheId::pluginAware('DefaultMetricsDocumentation'); $cache = PiwikCache::getTransientCache(); if ($cache->contains($cacheId)) { return $cache->fetch($cacheId); } $translations = array('nb_visits' => 'General_ColumnNbVisitsDocumentation', 'nb_uniq_visitors' => 'General_ColumnNbUniqVisitorsDocumentation', 'nb_actions' => 'General_ColumnNbActionsDocumentation', 'nb_users' => 'General_ColumnNbUsersDocumentation', 'nb_actions_per_visit' => 'General_ColumnActionsPerVisitDocumentation', 'avg_time_on_site' => 'General_ColumnAvgTimeOnSiteDocumentation', 'bounce_rate' => 'General_ColumnBounceRateDocumentation', 'conversion_rate' => 'General_ColumnConversionRateDocumentation', 'avg_time_on_page' => 'General_ColumnAverageTimeOnPageDocumentation', 'nb_hits' => 'General_ColumnPageviewsDocumentation', 'exit_rate' => 'General_ColumnExitRateDocumentation'); /** * Use this event to register translations for metrics documentation processed by your plugin. * * @param string[] $translations The array mapping of column_name => Plugin_TranslationForColumnDocumentation */ Piwik::postEvent('Metrics.getDefaultMetricDocumentationTranslations', array(&$translations)); $translations = array_map(array('\\Piwik\\Piwik', 'translate'), $translations); $cache->save($cacheId, $translations); return $translations; }
/** * Triggers a hook to ask plugins for available Reports. * Returns metadata information about each report (category, name, dimension, metrics, etc.) * * @param string $idSites Comma separated list of website Ids * @param bool|string $period * @param bool|Date $date * @param bool $hideMetricsDoc * @param bool $showSubtableReports * @return array */ public function getReportMetadata($idSites, $period = false, $date = false, $hideMetricsDoc = false, $showSubtableReports = false) { $idSites = Site::getIdSitesFromIdSitesString($idSites); if (!empty($idSites)) { Piwik::checkUserHasViewAccess($idSites); } // as they cache key contains a lot of information there would be an even better cache result by caching parts of // this huge method separately but that makes it also more complicated. leaving it like this for now. $key = $this->buildReportMetadataCacheKey($idSites, $period, $date, $hideMetricsDoc, $showSubtableReports); $key = CacheId::pluginAware($key); $cache = PiwikCache::getTransientCache(); if ($cache->contains($key)) { return $cache->fetch($key); } $parameters = array('idSites' => $idSites, 'period' => $period, 'date' => $date); $availableReports = array(); foreach (Report::getAllReports() as $report) { $report->configureReportMetadata($availableReports, $parameters); } /** * Triggered when gathering metadata for all available reports. * * Plugins that define new reports should use this event to make them available in via * the metadata API. By doing so, the report will become available in scheduled reports * as well as in the Piwik Mobile App. In fact, any third party app that uses the metadata * API will automatically have access to the new report. * * @param string &$availableReports The list of available reports. Append to this list * to make a report available. * * Every element of this array must contain the following * information: * * - **category**: A translated string describing the report's category. * - **name**: The translated display title of the report. * - **module**: The plugin of the report. * - **action**: The API method that serves the report. * * The following information is optional: * * - **dimension**: The report's [dimension](/guides/all-about-analytics-data#dimensions) if any. * - **metrics**: An array mapping metric names with their display names. * - **metricsDocumentation**: An array mapping metric names with their * translated documentation. * - **processedMetrics**: The array of metrics in the report that are * calculated using existing metrics. Can be set to * `false` if the report contains no processed * metrics. * - **order**: The order of the report in the list of reports * with the same category. * * @param array $parameters Contains the values of the sites and period we are * getting reports for. Some reports depend on this data. * For example, Goals reports depend on the site IDs being * requested. Contains the following information: * * - **idSites**: The array of site IDs we are getting reports for. * - **period**: The period type, eg, `'day'`, `'week'`, `'month'`, * `'year'`, `'range'`. * - **date**: A string date within the period or a date range, eg, * `'2013-01-01'` or `'2012-01-01,2013-01-01'`. * * TODO: put dimensions section in all about analytics data * @deprecated since 2.5.0 Use Report Classes instead. * @ignore */ Piwik::postEvent('API.getReportMetadata', array(&$availableReports, $parameters)); // TODO we can remove this one once we remove API.getReportMetadata event (except hideMetricsDoc) foreach ($availableReports as &$availableReport) { // can be removed once we remove hook API.getReportMetadata if (!isset($availableReport['metrics'])) { $availableReport['metrics'] = Metrics::getDefaultMetrics(); } // can be removed once we remove hook API.getReportMetadata if (!isset($availableReport['processedMetrics'])) { $availableReport['processedMetrics'] = Metrics::getDefaultProcessedMetrics(); } if ($hideMetricsDoc) { unset($availableReport['metricsDocumentation']); } else { if (!isset($availableReport['metricsDocumentation'])) { // set metric documentation to default if it's not set // can be removed once we remove hook API.getReportMetadata $availableReport['metricsDocumentation'] = Metrics::getDefaultMetricsDocumentation(); } } } /** * Triggered after all available reports are collected. * * This event can be used to modify the report metadata of reports in other plugins. You * could, for example, add custom metrics to every report or remove reports from the list * of available reports. * * @param array &$availableReports List of all report metadata. Read the {@hook API.getReportMetadata} * docs to see what this array contains. * @param array $parameters Contains the values of the sites and period we are * getting reports for. Some report depend on this data. * For example, Goals reports depend on the site IDs being * request. Contains the following information: * * - **idSites**: The array of site IDs we are getting reports for. * - **period**: The period type, eg, `'day'`, `'week'`, `'month'`, * `'year'`, `'range'`. * - **date**: A string date within the period or a date range, eg, * `'2013-01-01'` or `'2012-01-01,2013-01-01'`. */ Piwik::postEvent('API.getReportMetadata.end', array(&$availableReports, $parameters)); // Sort results to ensure consistent order usort($availableReports, array('self', 'sortReports')); $knownMetrics = array_merge(Metrics::getDefaultMetrics(), Metrics::getDefaultProcessedMetrics()); $columnsToKeep = $this->getColumnsToKeep(); $columnsToRemove = $this->getColumnsToRemove(); foreach ($availableReports as &$availableReport) { // Ensure all metrics have a translation $metrics = $availableReport['metrics']; $cleanedMetrics = array(); // TODO we can remove this once we remove the getReportMetadata event, leaving it here for backwards compatibility foreach ($metrics as $metricId => $metricTranslation) { // When simply the column name was given, ie 'metric' => array( 'nb_visits' ) // $metricTranslation is in this case nb_visits. We look for a known translation. if (is_numeric($metricId) && isset($knownMetrics[$metricTranslation])) { $metricId = $metricTranslation; $metricTranslation = $knownMetrics[$metricTranslation]; } $cleanedMetrics[$metricId] = $metricTranslation; } $availableReport['metrics'] = $cleanedMetrics; // if hide/show columns specified, hide/show metrics & docs $availableReport['metrics'] = $this->hideShowMetricsWithParams($availableReport['metrics'], $columnsToRemove, $columnsToKeep); if (isset($availableReport['processedMetrics'])) { $availableReport['processedMetrics'] = $this->hideShowMetricsWithParams($availableReport['processedMetrics'], $columnsToRemove, $columnsToKeep); } if (isset($availableReport['metricsDocumentation'])) { $availableReport['metricsDocumentation'] = $this->hideShowMetricsWithParams($availableReport['metricsDocumentation'], $columnsToRemove, $columnsToKeep); } // Remove array elements that are false (to clean up API output) foreach ($availableReport as $attributeName => $attributeValue) { if (empty($attributeValue)) { unset($availableReport[$attributeName]); } } // when there are per goal metrics, don't display conversion_rate since it can differ from per goal sum // TODO we should remove this once we remove the getReportMetadata event, leaving it here for backwards compatibility if (isset($availableReport['metricsGoal'])) { unset($availableReport['processedMetrics']['conversion_rate']); unset($availableReport['metricsGoal']['conversion_rate']); } // Processing a uniqueId for each report, // can be used by UIs as a key to match a given report $uniqueId = $availableReport['module'] . '_' . $availableReport['action']; if (!empty($availableReport['parameters'])) { foreach ($availableReport['parameters'] as $key => $value) { $uniqueId .= '_' . $key . '--' . $value; } } $availableReport['uniqueId'] = $uniqueId; // Order is used to order reports internally, but not meant to be used outside unset($availableReport['order']); } // remove subtable reports if (!$showSubtableReports) { foreach ($availableReports as $idx => $report) { if (isset($report['isSubtableReport']) && $report['isSubtableReport']) { unset($availableReports[$idx]); } } } $actualReports = array_values($availableReports); $cache->save($key, $actualReports); return $actualReports; // make sure array has contiguous key values }
/** * Returns a list of all available reports. Even not enabled reports will be returned. They will be already sorted * depending on the order and category of the report. * @return \Piwik\Plugin\Report[] * @api */ public static function getAllReports() { $reports = self::getAllReportClasses(); $cacheId = CacheId::languageAware('Reports' . md5(implode('', $reports))); $cache = PiwikCache::getTransientCache(); if (!$cache->contains($cacheId)) { $instances = array(); foreach ($reports as $report) { $instances[] = new $report(); } usort($instances, array('self', 'sort')); $cache->save($cacheId, $instances); } return $cache->fetch($cacheId); }
/** * Returns list of social networks by URL * * @see core/DataFiles/Socials.php * * @return array Array of ( URL => Social Network Name ) */ public static function getSocialUrls() { $cacheId = 'Common.getSocialUrls'; $cache = Cache::getTransientCache(); $socialUrls = $cache->fetch($cacheId); if (empty($socialUrls)) { require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; $socialUrls = $GLOBALS['Piwik_socialUrl']; Piwik::postEvent('Referrer.addSocialUrls', array(&$socialUrls)); $cache->save($cacheId, $socialUrls); } return $socialUrls; }
private function isIpInRange() { $cache = PiwikCache::getTransientCache(); $ip = IP::fromBinaryIP($this->ip); $key = 'VisitExcludedIsIpInRange' . $ip->toString(); if ($cache->contains($key)) { $isInRanges = $cache->fetch($key); } else { if ($this->isChromeDataSaverUsed($ip)) { $isInRanges = false; } else { $isInRanges = $ip->isInRanges($this->getBotIpRanges()); } $cache->save($key, $isInRanges); } return $isInRanges; }
/** * Returns list of search engines by name * * @return array Array of ( searchEngineName => URL ) */ public function getNames() { $cacheId = 'SearchEngine.getSearchEngineNames'; $cache = Cache::getTransientCache(); $nameToUrl = $cache->fetch($cacheId); if (empty($nameToUrl)) { $searchEngines = $this->getDefinitions(); $nameToUrl = array(); foreach ($searchEngines as $url => $info) { if (!isset($nameToUrl[$info['name']])) { $nameToUrl[$info['name']] = $url; } } $cache->save($cacheId, $nameToUrl); } return $nameToUrl; }
private function getSiteIdsThatAreRequestedInThisArchiveButWereNotInvalidatedYet() { if (is_null(self::$cache)) { self::$cache = Cache::getTransientCache(); } $id = 'Archive.SiteIdsOfRememberedReportsInvalidated'; if (!self::$cache->contains($id)) { self::$cache->save($id, array()); } $siteIdsAlreadyHandled = self::$cache->fetch($id); $siteIdsRequested = $this->params->getIdSites(); foreach ($siteIdsRequested as $index => $siteIdRequested) { $siteIdRequested = (int) $siteIdRequested; if (in_array($siteIdRequested, $siteIdsAlreadyHandled)) { unset($siteIdsRequested[$index]); // was already handled previously, do not do it again } else { $siteIdsAlreadyHandled[] = $siteIdRequested; // we will handle this id this time } } self::$cache->save($id, $siteIdsAlreadyHandled); return $siteIdsRequested; }
public function test_Archive_getNumeric_shouldInvalidateRememberedReportsOncePerRequestIfNeeded() { $this->markTestSkippedOnPhp53(); // Tests that getting a visits summary metric (nb_visits) & a Goal's metric (Goal_revenue) // at the same time works. $dateTimeRange = '2010-01-03,2010-01-06'; $columns = array('nb_visits', 'Goal_nb_conversions', 'nb_actions'); $idSite1 = self::$fixture->idSite1; $archive = Archive::build($idSite1, 'range', $dateTimeRange); $result = $archive->getNumeric($columns); $this->assertEquals(array('nb_visits' => 5, 'Goal_nb_conversions' => 6, 'nb_actions' => 13), $result); $cache = Cache::getTransientCache(); $this->assertEquals(array(self::$fixture->idSite1, self::$fixture->idSite2), $cache->fetch('Archive.SiteIdsOfRememberedReportsInvalidated')); $invalidator = StaticContainer::get('Piwik\\Archive\\ArchiveInvalidator'); self::$fixture->trackVisits(); // trackVisits should remember to invalidate archived reports $this->assertNotEmpty($invalidator->getRememberedArchivedReportsThatShouldBeInvalidated()); // although there were new tracked visists it doesn'T change as the report invalidation is cached and was // already invalidated in previous Archive::get(); $archive = Archive::build($idSite1, 'range', $dateTimeRange); $result = $archive->getNumeric($columns); $this->assertEquals(array('nb_visits' => 5, 'Goal_nb_conversions' => 6, 'nb_actions' => 13), $result); // make sure the caching in archive::get() worked and they are still to be invalidated $this->assertCount(10, $invalidator->getRememberedArchivedReportsThatShouldBeInvalidated()); // now we force to actually invalidate archived reports again and then archive will be rebuilt for requsted siteId = 1 $cache->delete('Archive.SiteIdsOfRememberedReportsInvalidated'); $archive = Archive::build($idSite1, 'range', $dateTimeRange); $result = $archive->getNumeric($columns); // archive::get() should have invalidated siteId 1 and siteId 2 should be still to be done $expectedArchiveReportsLeft = array('2010-01-04' => array(2)); $this->assertEquals($expectedArchiveReportsLeft, $invalidator->getRememberedArchivedReportsThatShouldBeInvalidated()); $this->assertEquals(array('nb_visits' => 6, 'Goal_nb_conversions' => 7, 'nb_actions' => 26), $result); }
/** * Get all conversion dimensions that are defined by all activated plugins. * @ignore */ public static function getAllDimensions() { $cacheId = CacheId::pluginAware('ConversionDimensions'); $cache = PiwikCache::getTransientCache(); if (!$cache->contains($cacheId)) { $plugins = PluginManager::getInstance()->getPluginsLoadedAndActivated(); $instances = array(); foreach ($plugins as $plugin) { foreach (self::getDimensions($plugin) as $instance) { $instances[] = $instance; } } $cache->save($cacheId, $instances); } return $cache->fetch($cacheId); }
/** * Returns all available user settings. A plugin has to specify a file named `UserSettings.php` containing a class * named `UserSettings` that extends `Piwik\Settings\Plugin\UserSettings` in order to be considered as a plugin * setting. Otherwise the settings for a plugin won't be available. * * @return UserSettings[] An array containing array([pluginName] => [setting instance]). */ public function getAllUserSettings() { $cacheId = CacheId::languageAware('AllUserSettings'); $cache = PiwikCache::getTransientCache(); if (!$cache->contains($cacheId)) { $pluginNames = $this->pluginManager->getActivatedPlugins(); $byPluginName = array(); foreach ($pluginNames as $plugin) { $component = $this->getUserSettings($plugin); if (!empty($component)) { $byPluginName[$plugin] = $component; } } $cache->save($cacheId, $byPluginName); } return $cache->fetch($cacheId); }
private static function getCacheForCompleteList() { return PiwikCache::getTransientCache(); }
/** * This method allows to set custom IP + server time + visitor ID, when using Tracking API. * These two attributes can be only set by the Super User (passing token_auth). */ protected function authenticateTrackingApi($tokenAuth) { $shouldAuthenticate = TrackerConfig::getConfigValue('tracking_requests_require_authentication'); if ($shouldAuthenticate) { try { $idSite = $this->getIdSite(); } catch (Exception $e) { $this->isAuthenticated = false; return; } if (empty($tokenAuth)) { $tokenAuth = Common::getRequestVar('token_auth', false, 'string', $this->params); } $cache = PiwikCache::getTransientCache(); $cacheKey = 'tracker_request_authentication_' . $idSite . '_' . $tokenAuth; if ($cache->contains($cacheKey)) { Common::printDebug("token_auth is authenticated in cache!"); $this->isAuthenticated = $cache->fetch($cacheKey); return; } try { $this->isAuthenticated = self::authenticateSuperUserOrAdmin($tokenAuth, $idSite); $cache->save($cacheKey, $this->isAuthenticated); } catch (Exception $e) { Common::printDebug("could not authenticate, caught exception: " . $e->getMessage()); $this->isAuthenticated = false; } if ($this->isAuthenticated) { Common::printDebug("token_auth is authenticated!"); } } else { $this->isAuthenticated = true; Common::printDebug("token_auth authentication not required"); } }
private function getIdSitesToArchiveWhenNoVisits() { $cache = Cache::getTransientCache(); $cacheKey = 'Archiving.getIdSitesToArchiveWhenNoVisits'; if (!$cache->contains($cacheKey)) { $idSites = array(); // leaving undocumented unless decided otherwise Piwik::postEvent('Archiving.getIdSitesToArchiveWhenNoVisits', array(&$idSites)); $cache->save($cacheKey, $idSites); } return $cache->fetch($cacheKey); }
private function trackVisits($visitorCount, $setIp = false, $useLocal = true, $doBulk = false) { static $calledCounter = 0; $calledCounter++; $dateTime = $this->dateTime; $idSite = $this->idSite; if ($useLocal) { Cache::getTransientCache()->flushAll(); // make sure dimension cache is empty between local tracking runs Visit::$dimensions = null; } // use local tracker so mock location provider can be used $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useLocal); if ($doBulk) { $t->enableBulkTracking(); } $t->setTokenAuth(self::getTokenAuth()); for ($i = 0; $i != $visitorCount; ++$i) { $t->setVisitorId(substr(md5($i + $calledCounter * 1000), 0, $t::LENGTH_VISITOR_ID)); if ($setIp) { $t->setIp(current($this->ips)); next($this->ips); } else { $t->setIp("1.2.4.{$i}"); } // first visit $date = Date::factory($dateTime)->addDay($i); $t->setForceVisitDateTime($date->getDatetime()); $t->setUrl("http://piwik.net/grue/lair"); $t->setCustomVariable(1, 'Cvar 1 name', 'Cvar1 value is ' . $i, 'visit'); $t->setCustomVariable(5, 'Cvar 5 name', 'Cvar5 value is ' . $i, 'visit'); $t->setCustomVariable(2, 'Cvar 2 PAGE name', 'Cvar2 PAGE value is ' . $i, 'page'); $t->setCustomVariable(5, 'Cvar 5 PAGE name', 'Cvar5 PAGE value is ' . $i, 'page'); $r = $t->doTrackPageView('It\'s <script> pitch black...'); if (!$doBulk) { self::checkResponse($r); } // second visit $date = $date->addHour(1); $t->setForceVisitDateTime($date->getDatetime()); $t->setUrl("http://piwik.net/space/quest/iv"); // Manually record some data $t->setDebugStringAppend('&_idts=' . $date->subDay(100)->getTimestampUTC() . '&_ects=' . $date->subDay(50)->getTimestampUTC() . '&_viewts=' . $date->subDay(10)->getTimestampUTC() . '&_idvc=5'); $r = $t->doTrackPageView("Space Quest XII"); if (!$doBulk) { self::checkResponse($r); } // Track site search (for AutoSuggestAPI test) // Only for half visitors so they don't all have a "site search" as last action and some of them have a standard page view as last action $date = $date->addHour(0.1); $t->setForceVisitDateTime($date->getDatetime()); if ($i % 2 == 0) { $r = $t->doTrackSiteSearch('Bring on the party', 'CAT'); } if (!$doBulk) { self::checkResponse($r); } $date = $date->addHour(0.2); $t->setForceVisitDateTime($date->getDatetime()); $r = $t->doTrackGoal($this->idGoal2); if (!$doBulk) { self::checkResponse($r); } $date = $date->addHour(0.05); $t->setForceVisitDateTime($date->getDatetime()); $t->doTrackAction('http://example.org/path/file' . $i . '.zip', "download"); if (!$doBulk) { self::checkResponse($r); } $date = $date->addHour(0.05); $t->setForceVisitDateTime($date->getDatetime()); $r = $t->doTrackAction('http://example-outlink.org/' . $i . '.html', "link"); if (!$doBulk) { self::checkResponse($r); } $date = $date->addHour(0.05); $t->setForceVisitDateTime($date->getDatetime()); $r = $t->doTrackEvent('Cat' . $i, 'Action' . $i, 'Name' . $i, 345.678 + $i); if (!$doBulk) { self::checkResponse($r); } } if ($doBulk) { self::checkBulkTrackingResponse($t->doBulkTrack()); } }
public function clearInMemoryCaches() { Archive::clearStaticCache(); DataTableManager::getInstance()->deleteAll(); Option::clearCache(); Site::clearCache(); Cache::deleteTrackerCache(); PiwikCache::getTransientCache()->flushAll(); PiwikCache::getEagerCache()->flushAll(); PiwikCache::getLazyCache()->flushAll(); ArchiveTableCreator::clear(); \Piwik\Plugins\ScheduledReports\API::$cache = array(); Singleton::clearAll(); PluginsArchiver::$archivers = array(); $_GET = $_REQUEST = array(); Translate::reset(); self::getConfig()->Plugins; // make sure Plugins exists in a config object for next tests that use Plugin\Manager // since Plugin\Manager uses getFromGlobalConfig which doesn't init the config object }
private function getCache() { return Cache::getTransientCache(); }
/** * Returns a URL query string as an array. * * @param string $urlQuery The query string, eg, `'?param1=value1¶m2=value2'`. * @return array eg, `array('param1' => 'value1', 'param2' => 'value2')` * @api */ public static function getArrayFromQueryString($urlQuery) { if (strlen($urlQuery) == 0) { return array(); } // TODO: this method should not use a cache. callers should instead have their own cache, configured through DI. // one undesirable side effect of using a cache here, is that this method can now init the StaticContainer, which makes setting // test environment for RequestCommand more complicated. $cache = Cache::getTransientCache(); $cacheKey = 'arrayFromQuery' . $urlQuery; if ($cache->contains($cacheKey)) { return $cache->fetch($cacheKey); } if ($urlQuery[0] == '?') { $urlQuery = substr($urlQuery, 1); } $separator = '&'; $urlQuery = $separator . $urlQuery; // $urlQuery = str_replace(array('%20'), ' ', $urlQuery); $referrerQuery = trim($urlQuery); $values = explode($separator, $referrerQuery); $nameToValue = array(); foreach ($values as $value) { $pos = strpos($value, '='); if ($pos !== false) { $name = substr($value, 0, $pos); $value = substr($value, $pos + 1); if ($value === false) { $value = ''; } } else { $name = $value; $value = false; } if (!empty($name)) { $name = Common::sanitizeInputValue($name); } if (!empty($value)) { $value = Common::sanitizeInputValue($value); } // if array without indexes $count = 0; $tmp = preg_replace('/(\\[|%5b)(]|%5d)$/i', '', $name, -1, $count); if (!empty($tmp) && $count) { $name = $tmp; if (isset($nameToValue[$name]) == false || is_array($nameToValue[$name]) == false) { $nameToValue[$name] = array(); } array_push($nameToValue[$name], $value); } elseif (!empty($name)) { $nameToValue[$name] = $value; } } $cache->save($cacheKey, $nameToValue); return $nameToValue; }
private function getGoalsInfoStaticCache() { return PiwikCache::getTransientCache(); }
/** * Returns the list of stored segments to pre-process for an individual site when executing * cron archiving. * * @param int $idSite The ID of the site to get stored segments for. * @return string[] The list of stored segments that apply to the requested site. */ public static function getKnownSegmentsToArchiveForSite($idSite) { $cacheId = 'KnownSegmentsToArchiveForSite' . $idSite; $cache = PiwikCache::getTransientCache(); if ($cache->contains($cacheId)) { return $cache->fetch($cacheId); } $segments = array(); /** * Triggered during the cron archiving process to collect segments that * should be pre-processed for one specific site. The archiving process will be launched * for each of these segments when archiving data for that one site. * * This event can be used to add segments to be pre-processed for one site. * * _Note: If you just want to add a segment that is managed by the user, you should use the * SegmentEditor API._ * * **Example** * * Piwik::addAction('Segments.getKnownSegmentsToArchiveForSite', function (&$segments, $idSite) { * $segments[] = 'country=jp;city=Tokyo'; * }); * * @param array &$segmentsToProcess List of segment definitions, eg, * * array( * 'browserCode=ff;resolution=800x600', * 'country=JP;city=Tokyo' * ) * * Add segments to this array in your event handler. * @param int $idSite The ID of the site to get segments for. */ Piwik::postEvent('Segments.getKnownSegmentsToArchiveForSite', array(&$segments, $idSite)); $segments = array_unique($segments); $cache->save($cacheId, $segments); return $segments; }
/** * Gets an instance of all available visit, action and conversion dimension. * @return Dimension[] */ public static function getAllDimensions() { $cacheId = CacheId::pluginAware('AllDimensions'); $cache = PiwikCache::getTransientCache(); if (!$cache->contains($cacheId)) { $plugins = PluginManager::getInstance()->getPluginsLoadedAndActivated(); $instances = array(); /** * Triggered to add new dimensions that cannot be picked up automatically by the platform. * This is useful if the plugin allows a user to create reports / dimensions dynamically. For example * CustomDimensions or CustomVariables. There are a variable number of dimensions in this case and it * wouldn't be really possible to create a report file for one of these dimensions as it is not known * how many Custom Dimensions will exist. * * **Example** * * public function addDimension(&$dimensions) * { * $dimensions[] = new MyCustomDimension(); * } * * @param Dimension[] $reports An array of dimensions */ Piwik::postEvent('Dimension.addDimensions', array(&$instances)); foreach ($plugins as $plugin) { foreach (self::getDimensions($plugin) as $instance) { $instances[] = $instance; } } /** * Triggered to filter / restrict dimensions. * * **Example** * * public function filterDimensions(&$dimensions) * { * foreach ($dimensions as $index => $dimension) { * if ($dimension->getName() === 'Page URL') {} * unset($dimensions[$index]); // remove this dimension * } * } * } * * @param Dimension[] $dimensions An array of dimensions */ Piwik::postEvent('Dimension.filterDimensions', array(&$instances)); $cache->save($cacheId, $instances); } return $cache->fetch($cacheId); }