protected function retrieveFileLocations() { /** * Triggered when gathering the list of all stylesheets (CSS and LESS) needed by * Piwik and its plugins. * * Plugins that have stylesheets should use this event to make those stylesheets * load. * * Stylesheets should be placed within a **stylesheets** subdirectory in your plugin's * root directory. * * **Example** * * public function getStylesheetFiles(&$stylesheets) * { * $stylesheets[] = "plugins/MyPlugin/stylesheets/myfile.less"; * $stylesheets[] = "plugins/MyPlugin/stylesheets/myotherfile.css"; * } * * @param string[] &$stylesheets The list of stylesheet paths. */ Piwik::postEvent('AssetManager.getStylesheetFiles', array(&$this->fileLocations)); $this->addThemeFiles(); }
/** * Connects to the database. * * Shouldn't be called directly, use {@link get()} instead. * * @param array|null $dbInfos Connection parameters in an array. Defaults to the `[database]` * INI config section. */ public static function createDatabaseObject($dbInfos = null) { $config = Config::getInstance(); if (is_null($dbInfos)) { $dbInfos = $config->database; } /** * Triggered before a database connection is established. * * This event can be used to change the settings used to establish a connection. * * @param array *$dbInfos Reference to an array containing database connection info, * including: * * - **host**: The host name or IP address to the MySQL database. * - **username**: The username to use when connecting to the * database. * - **password**: The password to use when connecting to the * database. * - **dbname**: The name of the Piwik MySQL database. * - **port**: The MySQL database port to use. * - **adapter**: either `'PDO_MYSQL'` or `'MYSQLI'` */ Piwik::postEvent('Reporting.getDatabaseConfig', array(&$dbInfos)); $dbInfos['profiler'] = $config->Debug['enable_sql_profiler']; $adapter = $dbInfos['adapter']; $db = @Adapter::factory($adapter, $dbInfos); self::$connection = $db; }
private static function getErrorResponse(Exception $ex) { $debugTrace = $ex->getTraceAsString(); $message = $ex->getMessage(); if (!method_exists($ex, 'isHtmlMessage') || !$ex->isHtmlMessage()) { $message = Common::sanitizeInputValue($message); } $logo = new CustomLogo(); $logoHeaderUrl = false; $logoFaviconUrl = false; try { $logoHeaderUrl = $logo->getHeaderLogoUrl(); $logoFaviconUrl = $logo->getPathUserFavicon(); } catch (Exception $ex) { Log::debug($ex); } $result = Piwik_GetErrorMessagePage($message, $debugTrace, true, true, $logoHeaderUrl, $logoFaviconUrl); /** * Triggered before a Piwik error page is displayed to the user. * * This event can be used to modify the content of the error page that is displayed when * an exception is caught. * * @param string &$result The HTML of the error page. * @param Exception $ex The Exception displayed in the error page. */ Piwik::postEvent('FrontController.modifyErrorPage', array(&$result, $ex)); return $result; }
public static function getDatabaseConfig($dbConfig = null) { $config = Config::getInstance(); if (is_null($dbConfig)) { $dbConfig = $config->database; } /** * Triggered before a database connection is established. * * This event can be used to change the settings used to establish a connection. * * @param array *$dbInfos Reference to an array containing database connection info, * including: * * - **host**: The host name or IP address to the MySQL database. * - **username**: The username to use when connecting to the * database. * - **password**: The password to use when connecting to the * database. * - **dbname**: The name of the Piwik MySQL database. * - **port**: The MySQL database port to use. * - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'` * - **type**: The MySQL engine to use, for instance 'InnoDB' */ Piwik::postEvent('Db.getDatabaseConfig', array(&$dbConfig)); $dbConfig['profiler'] = @$config->Debug['enable_sql_profiler']; return $dbConfig; }
/** * Return array of available languages * * @return array Arry of strings, each containing its ISO language code */ public function getAvailableLanguages() { if (!is_null($this->languageNames)) { return $this->languageNames; } $path = PIWIK_INCLUDE_PATH . "/lang/"; $languagesPath = _glob($path . "*.json"); $pathLength = strlen($path); $languages = array(); if ($languagesPath) { foreach ($languagesPath as $language) { $languages[] = substr($language, $pathLength, -strlen('.json')); } } /** * Hook called after loading available language files. * * Use this hook to customise the list of languagesPath available in Piwik. * * @param array */ Piwik::postEvent('LanguageManager.getAvailableLanguages', array(&$languages)); $this->languageNames = $languages; return $languages; }
/** * Returns a list of available command classnames. * * @return string[] */ private function getAvailableCommands() { $commands = $this->getDefaultPiwikCommands(); $detected = PluginManager::getInstance()->findMultipleComponents('Commands', 'Piwik\\Plugin\\ConsoleCommand'); $commands = array_merge($commands, $detected); /** * Triggered to filter / restrict console commands. Plugins that want to restrict commands * should subscribe to this event and remove commands from the existing list. * * **Example** * * public function filterConsoleCommands(&$commands) * { * $key = array_search('Piwik\Plugins\MyPlugin\Commands\MyCommand', $commands); * if (false !== $key) { * unset($commands[$key]); * } * } * * @param array &$commands An array containing a list of command class names. */ Piwik::postEvent('Console.filterCommands', array(&$commands)); $commands = array_values(array_unique($commands)); return $commands; }
protected function retrieveFileLocations() { /** * Triggered when gathering the list of all stylesheets (CSS and LESS) needed by * Piwik and its plugins. * * Plugins that have stylesheets should use this event to make those stylesheets * load. * * Stylesheets should be placed within a **stylesheets** subdirectory in your plugin's * root directory. * * _Note: While you are developing your plugin you should enable the config setting * `[Debug] disable_merged_assets` so your stylesheets will be reloaded immediately * after a change._ * * **Example** * * public function getStylesheetFiles(&$stylesheets) * { * $stylesheets[] = "plugins/MyPlugin/stylesheets/myfile.less"; * $stylesheets[] = "plugins/MyPlugin/stylesheets/myotherfile.css"; * } * * @param string[] &$stylesheets The list of stylesheet paths. */ Piwik::postEvent('AssetManager.getStylesheetFiles', array(&$this->fileLocations)); $this->addThemeFiles(); }
protected function retrieveFileLocations() { if (!empty($this->plugins)) { /** * Triggered when gathering the list of all JavaScript files needed by Piwik * and its plugins. * * Plugins that have their own JavaScript should use this event to make those * files load in the browser. * * JavaScript files should be placed within a **javascripts** subdirectory in your * plugin's root directory. * * _Note: While you are developing your plugin you should enable the config setting * `[Development] disable_merged_assets` so JavaScript files will be reloaded immediately * after every change._ * * **Example** * * public function getJsFiles(&$jsFiles) * { * $jsFiles[] = "plugins/MyPlugin/javascripts/myfile.js"; * $jsFiles[] = "plugins/MyPlugin/javascripts/anotherone.js"; * } * * @param string[] $jsFiles The JavaScript files to load. */ Piwik::postEvent('AssetManager.getJavaScriptFiles', array(&$this->fileLocations), null, $this->plugins); } $this->addThemeFiles(); }
/** * Get all existing widget configs. * * @return WidgetConfig[] */ public function getWidgetConfigs() { $widgetClasses = $this->getAllWidgetClassNames(); $configs = array(); /** * Triggered to add custom widget configs. To filder widgets have a look at the {@hook Widget.filterWidgets} * event. * * **Example** * * public function addWidgetConfigs(&$configs) * { * $config = new WidgetConfig(); * $config->setModule('PluginName'); * $config->setAction('renderDashboard'); * $config->setCategoryId('Dashboard_Dashboard'); * $config->setSubcategoryId('dashboardId'); * $configs[] = $config; * } * * @param array &$configs An array containing a list of widget config entries. */ Piwik::postEvent('Widget.addWidgetConfigs', array(&$configs)); foreach ($widgetClasses as $widgetClass) { $configs[] = $this->getWidgetConfigForClassName($widgetClass); } return $configs; }
/** * Triggers the Menu.MenuAdmin.addItems hook and returns the admin menu. * * @return Array */ public function getMenu() { if (!$this->menu) { /** * Triggered when collecting all available admin menu items. Subscribe to this event if you want * to add one or more items to the Piwik admin menu. * * Menu items should be added via the {@link add()} method. * * **Example** * * use Piwik\Menu\MenuAdmin; * * public function addMenuItems() * { * MenuAdmin::getInstance()->add( * 'MenuName', * 'SubmenuName', * array('module' => 'MyPlugin', 'action' => 'index'), * $showOnlyIf = Piwik::isUserIsSuperUser(), * $order = 6 * ); * } */ Piwik::postEvent('Menu.Admin.addItems'); } return parent::getMenu(); }
/** * Gets the singleton instance. Creates it if necessary. */ public static function getInstance() { if (self::$instance == null) { self::$instance = new self(); Piwik::postEvent('Access.createAccessSingleton', array(&self::$instance)); } return self::$instance; }
private function collectTasksRegisteredViaEvent() { $tasks = array(); /** * @ignore */ Piwik::postEvent(self::GET_TASKS_EVENT, array(&$tasks)); return $tasks; }
private function makeSureTestRunsInContextOfAnonymousUser() { Piwik::postEvent('Request.initAuthenticationObject'); $access = Access::getInstance(); $this->hasSuperUserAccess = $access->hasSuperUserAccess(); $access->setSuperUserAccess(false); $access->reloadAccess(StaticContainer::get('Piwik\\Auth')); Request::reloadAuthUsingTokenAuth(array('token_auth' => 'anonymous')); }
/** * Initializes the kernel globals and DI container. */ public function init() { $this->invokeBeforeContainerCreatedHook(); $this->container = $this->createContainer(); StaticContainer::push($this->container); $this->validateEnvironment(); $this->invokeEnvironmentBootstrappedHook(); Piwik::postEvent('Environment.bootstrapped'); // this event should be removed eventually }
public function test_ScheduledReports_shouldRemoveOnlyReportsForGivenSitesAndLogin_IfEventIsTriggered() { Piwik::postEvent('UsersManager.removeSiteAccess', array('userLogin', array(1, 2))); $this->assertHasNotReport('userlogin', 1); $this->assertHasNotReport('userlogin', 2); $this->assertHasReport('userlogin', 3); $this->assertHasReport('userlogin', 4); $this->assertHasReport('otherUser', 1); $this->assertHasReport('anotherUser', 2); }
public function test_shouldAddTrackingCallsWithoutTargetsAndCustomVariables_IfOptOutIsDisabled() { $settings = $this->makePluginSettings(); $settings->canUserOptOut->setValue(false); $settings->save(); // we need to save it first and create new settings instance since the setting will be missing afterwards. $this->makePluginSettings(); $out = ''; Piwik::postEvent('Template.jsGlobalVariables', array(&$out)); $this->assertContains('var piwikUsageTracking = {"targets":[{"url":"http:\\/\\/demo-anonymous.piwik.org\\/piwik.php","idSite":1,"useAnonymization":true}],"visitorCustomVariables":[{"id":1,"name":"Access","value":"superuser"}],"trackingDomain":"http:\\/\\/demo-anonymous.piwik.org","exampleDomain":"http:\\/\\/example.com","userId":"superUserLogin"}', $out); }
/** * @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; }
protected function postEvent(&$mergedContent) { /** * Triggered after all less stylesheets are compiled to CSS, minified and merged into * one file, but before the generated CSS is written to disk. * * This event can be used to modify merged CSS. * * @param string $mergedContent The merged and minified CSS. */ Piwik::postEvent('AssetManager.filterMergedStylesheets', array(&$mergedContent)); }
public function test_AvailableWidgetListIsUpToDate() { $namesOfWidgetsThatAreAPI = $this->getWidgetNames($this->getWidgetsThatAreAPI()); Piwik::postEvent('Platform.initialized'); // userCountryMap defines it's Widgets via this event currently $currentWidgetNames = array(); foreach (WidgetsList::get() as $widgets) { $currentWidgetNames = array_merge($this->getWidgetNames($widgets), $currentWidgetNames); } $allWidgetNames = array_merge($namesOfWidgetsThatAreAPI, $currentWidgetNames); $regressedWidgetNames = array_diff($allWidgetNames, $currentWidgetNames); $this->assertEmpty($regressedWidgetNames, 'The widgets list is no longer up to date. If you added, removed or renamed a widget please update `getAvailableWidgets()` otherwise you will need to fix it. Different names: ' . var_export($regressedWidgetNames, 1)); }
/** * Triggers the Menu.MenuAdmin.addItems hook and returns the admin menu. * * @return Array */ public function getMenu() { if (!$this->menu) { /** * @ignore */ Piwik::postEvent('Menu.Admin.addItems', array()); foreach ($this->getAvailableMenus() as $menu) { $menu->configureAdminMenu($this); } } return parent::getMenu(); }
public function test_getEagerCache_shouldPersistOnceEventWasTriggered() { $storageId = 'eagercache-test-ui'; $cache = Cache::getEagerCache(); $cache->save('test', 'mycontent'); // make sure something was changed, otherwise it won't save anything /** @var Cache\Backend $backend */ $backend = StaticContainer::get('Piwik\\Cache\\Backend'); $this->assertFalse($backend->doContains($storageId)); Piwik::postEvent('Request.dispatch.end'); // should trigger save $this->assertTrue($backend->doContains($storageId)); }
public function getSegmentsMetadata($idSites = array(), $_hideImplementationData = true, $isAuthenticatedWithViewAccess) { $segments = array(); /** * Triggered to add custom segment definitions. * * **Example** * * public function addSegments(&$segments) * { * $segment = new Segment(); * $segment->setSegment('my_segment_name'); * $segment->setType(Segment::TYPE_DIMENSION); * $segment->setName('My Segment Name'); * $segment->setSqlSegment('log_table.my_segment_name'); * $segments[] = $segment; * } * * @param array &$segments An array containing a list of segment entries. */ Piwik::postEvent('Segment.addSegments', array(&$segments)); foreach (Dimension::getAllDimensions() as $dimension) { foreach ($dimension->getSegments() as $segment) { $segments[] = $segment; } } /** @var Segment[] $dimensionSegments */ $dimensionSegments = $segments; $segments = array(); foreach ($dimensionSegments as $segment) { if ($segment->isRequiresAtLeastViewAccess()) { $segment->setPermission($isAuthenticatedWithViewAccess); } $segments[] = $segment->toArray(); } foreach ($segments as &$segment) { $segment['name'] = Piwik::translate($segment['name']); $segment['category'] = Piwik::translate($segment['category']); if ($_hideImplementationData) { unset($segment['sqlFilter']); unset($segment['sqlFilterValue']); unset($segment['sqlSegment']); if (isset($segment['suggestedValuesCallback']) && !is_string($segment['suggestedValuesCallback'])) { unset($segment['suggestedValuesCallback']); } } } usort($segments, array($this, 'sortSegments')); return $segments; }
/** * Triggers the Menu.Reporting.addItems hook and returns the menu. * * @return Array */ public function getMenu() { if (!$this->menu) { /** * @ignore * @deprecated */ Piwik::postEvent('Menu.Reporting.addItems', array()); foreach ($this->getAvailableMenus() as $menu) { $menu->configureReportingMenu($this); } } return parent::getMenu(); }
protected function postEvent(&$mergedContent) { $plugins = $this->getPlugins(); if (!empty($plugins)) { /** * Triggered after all the JavaScript files Piwik uses are minified and merged into a * single file, but before the merged JavaScript is written to disk. * * Plugins can use this event to modify merged JavaScript or do something else * with it. * * @param string $mergedContent The minified and merged JavaScript. */ Piwik::postEvent('AssetManager.filterMergedJavaScripts', array(&$mergedContent), null, $plugins); } }
protected function execute(InputInterface $input, OutputInterface $output) { $systemCheck = new SystemCheck(); $systemCheck->checkRedisIsInstalled(); $trackerEnvironment = new Environment('tracker'); $trackerEnvironment->init(); Log::unsetInstance(); $trackerEnvironment->getContainer()->get('Piwik\\Access')->setSuperUserAccess(false); $trackerEnvironment->getContainer()->get('Piwik\\Plugin\\Manager')->setTrackerPluginsNotToLoad(array('Provider')); Tracker::loadTrackerEnvironment(); if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) { $GLOBALS['PIWIK_TRACKER_DEBUG'] = true; } $backend = Queue\Factory::makeBackend(); $queueManager = Queue\Factory::makeQueueManager($backend); if (!$queueManager->canAcquireMoreLocks()) { $trackerEnvironment->destroy(); $this->writeSuccessMessage($output, array("Nothing to proccess. Already max number of workers in process.")); return; } $shouldProcess = false; foreach ($queueManager->getAllQueues() as $queue) { if ($queue->shouldProcess()) { $shouldProcess = true; break; } } if (!$shouldProcess) { $trackerEnvironment->destroy(); $this->writeSuccessMessage($output, array("No queue currently needs processing")); return; } $output->writeln("<info>Starting to process request sets, this can take a while</info>"); register_shutdown_function(function () use($queueManager) { $queueManager->unlock(); }); $startTime = microtime(true); $processor = new Processor($queueManager); $processor->setNumberOfMaxBatchesToProcess(1000); $tracker = $processor->process(); $neededTime = microtime(true) - $startTime; $numRequestsTracked = $tracker->getCountOfLoggedRequests(); $requestsPerSecond = $this->getNumberOfRequestsPerSecond($numRequestsTracked, $neededTime); Piwik::postEvent('Tracker.end'); $trackerEnvironment->destroy(); $this->writeSuccessMessage($output, array(sprintf('This worker finished queue processing with %sreq/s (%s requests in %02.2f seconds)', $requestsPerSecond, $numRequestsTracked, $neededTime))); }
private static function addWidgets() { if (!self::$hookCalled) { self::$hookCalled = true; /** * @ignore * @deprecated */ Piwik::postEvent('WidgetsList.addWidgets'); /** @var \Piwik\Plugin\Widgets[] $widgets */ $widgets = PluginManager::getInstance()->findComponents('Widgets', 'Piwik\\Plugin\\Widgets'); $widgetsList = self::getInstance(); foreach ($widgets as $widget) { $widget->configure($widgetsList); } } }
/** * Executed when the session was successfully authenticated. * * @param AuthResult $authResult The successful authentication result. * @param bool $rememberMe Whether the authenticated session should be remembered after * the browser is closed or not. */ protected function processSuccessfulSession(AuthResult $authResult, $rememberMe) { $storage = new Storage($authResult->getIdentity()); /** * @deprecated Create a custom SessionInitializer instead. */ Piwik::postEvent('Login.authenticate.successful', array($authResult->getIdentity(), $authResult->getTokenAuth())); $cookie = $this->getAuthCookie($rememberMe); $cookie->set('login', $authResult->getIdentity()); $cookie->set('token_auth', $this->getHashTokenAuth($authResult->getIdentity(), $authResult->getTokenAuth())); if ($storage->isActive()) { $cookie->set('auth_code', $this->getHashTokenAuth($authResult->getIdentity(), $storage->getSecret())); } $cookie->setSecure(ProxyHttp::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); }
private function loadDefinitions() { if ($this->definitionList === null) { // Read first from the auto-updated list in database $list = Option::get(self::OPTION_STORAGE_NAME); if ($list) { $this->definitionList = unserialize(base64_decode($list)); } else { // Fallback to reading the bundled list $yml = file_get_contents(PIWIK_INCLUDE_PATH . self::DEFINITION_FILE); $this->definitionList = $this->loadYmlData($yml); Option::set(self::OPTION_STORAGE_NAME, base64_encode(serialize($this->definitionList))); } } Piwik::postEvent('Referrer.addSocialUrls', array(&$this->definitionList)); return $this->definitionList; }
/** * Returns a list of available command classnames. * * @return string[] */ private function getAvailableCommands() { $commands = array(); /** * Triggered to gather all available console commands. Plugins that want to expose new console commands * should subscribe to this event and add commands to the incoming array. * * **Example** * * public function addConsoleCommands(&$commands) * { * $commands[] = 'Piwik\Plugins\MyPlugin\Commands\MyCommand'; * } * * @param array &$commands An array containing a list of command class names. */ Piwik::postEvent('Console.addCommands', array(&$commands)); return $commands; }
/** * Saves (persists) the current setting values in the database. * * Will trigger an event to notify plugins that a value has been changed. */ public function save() { parent::save(); /** * Triggered after user settings have been updated. * * **Example** * * Piwik::addAction('UserSettings.updated', function (UserSettings $settings) { * if ($settings->getPluginName() === 'PluginName') { * $value = $settings->someSetting->getValue(); * // Do something with the new setting value * } * }); * * @param Settings $settings The plugin settings object. */ Piwik::postEvent('UserSettings.updated', array($this)); }