diff --git a/core/API/Proxy.php b/core/API/Proxy.php index 9e4d193b3b2..43faca7063d 100644 --- a/core/API/Proxy.php +++ b/core/API/Proxy.php @@ -168,27 +168,40 @@ public function call($className, $methodName, $parametersRequest) /** * Triggered before an API request is dispatched. * - * This event can be used to modify the input that is passed to every API method or just - * one. + * This event can be used to modify the arguments passed to one or more API methods. + * + * **Example** + * + * Piwik::addAction('API.Request.dispatch', function (&$parameters, $pluginName, $methodName) { + * if ($pluginName == 'Actions') { + * if ($methodName == 'getPageUrls') { + * // ... do something ... + * } else { + * // ... do something else ... + * } + * } + * }); * * @param array &$finalParameters List of parameters that will be passed to the API method. - * @param string $pluginName The name of the plugin being dispatched to. + * @param string $pluginName The name of the plugin the API method belongs to. * @param string $methodName The name of the API method that will be called. */ Piwik::postEvent('API.Request.dispatch', array(&$finalParameters, $pluginName, $methodName)); /** + * Triggered before an API request is dispatched. + * * This event exists for convenience and is triggered directly after the {@hook API.Request.dispatch} - * event is triggered. + * event is triggered. It can be used to modify the arguments passed to a **single** API method. * - * It can be used to modify the input that is passed to a single API method. This is also - * possible with the {@hook API.Request.dispatch} event, however that event requires event handlers - * check if the plugin name and method name are correct before modifying the parameters. + * _Note: This is can be accomplished with the {@hook API.Request.dispatch} event as well, however + * event handlers for that event will have to do more work._ * * **Example** * * Piwik::addAction('API.Actions.getPageUrls', function (&$parameters) { - * // ... + * // force use of a single website. for some reason. + * $parameters['idSite'] = 1; * }); * * @param array &$finalParameters List of parameters that will be passed to the API method. @@ -207,21 +220,36 @@ public function call($className, $methodName, $parametersRequest) ); /** + * Triggered directly after an API request is dispatched. + * * This event exists for convenience and is triggered immediately before the - * {@hook API.Request.dispatch.end} event. + * {@hook API.Request.dispatch.end} event. It can be used to modify the output of a **single** + * API method. * - * It can be used to modify the output of a single API method. This is also possible with - * the {@hook API.Request.dispatch.end} event, however that event requires event handlers - * check if the plugin name and method name are correct before modifying the output. + * _Note: This can be accomplished with the {@hook API.Request.dispatch.end} event as well, + * however event handlers for that event will have to do more work._ * - * @param mixed &$returnedValue The value returned from the API method. This will not be - * a rendered string, but an actual object. For example, it + * **Example** + * + * // append (0 hits) to the end of row labels whose row has 0 hits + * Piwik::addAction('API.Actions.getPageUrls', function (&$returnValue, $info)) { + * $returnValue->filter('ColumnCallbackReplace', 'label', function ($label, $hits) { + * if ($hits === 0) { + * return $label . " (0 hits)"; + * } else { + * return $label; + * } + * }, null, array('nb_hits')); + * } + * + * @param mixed &$returnedValue The API method's return value. Can be an object, such as a + * {@link Piwik\DataTable DataTable} instance. * could be a {@link Piwik\DataTable DataTable}. * @param array $extraInfo An array holding information regarding the API request. Will * contain the following data: * - * - **className**: The name of the namespace-d class name of the - * API instance that's being called. + * - **className**: The namespace-d class name of the API instance + * that's being called. * - **module**: The name of the plugin the API request was * dispatched to. * - **action**: The name of the API method that was executed. @@ -235,14 +263,33 @@ public function call($className, $methodName, $parametersRequest) * * This event can be used to modify the output of any API method. * - * @param mixed &$returnedValue The value returned from the API method. This will not be - * a rendered string, but an actual object. For example, it - * could be a {@link Piwik\DataTable}. + * **Example** + * + * // append (0 hits) to the end of row labels whose row has 0 hits for any report that has the 'nb_hits' metric + * Piwik::addAction('API.Actions.getPageUrls', function (&$returnValue, $info)) { + * // don't process non-DataTable reports and reports that don't have the nb_hits column + * if (!($returnValue instanceof DataTableInterface) + * || in_array('nb_hits', $returnValue->getColumns()) + * ) { + * return; + * } + * + * $returnValue->filter('ColumnCallbackReplace', 'label', function ($label, $hits) { + * if ($hits === 0) { + * return $label . " (0 hits)"; + * } else { + * return $label; + * } + * }, null, array('nb_hits')); + * } + * + * @param mixed &$returnedValue The API method's return value. Can be an object, such as a + * {@link Piwik\DataTable DataTable} instance. * @param array $extraInfo An array holding information regarding the API request. Will * contain the following data: * - * - **className**: The name of the namespace-d class name of the - * API instance that's being called. + * - **className**: The namespace-d class name of the API instance + * that's being called. * - **module**: The name of the plugin the API request was * dispatched to. * - **action**: The name of the API method that was executed. diff --git a/core/API/Request.php b/core/API/Request.php index 50f8d64ec38..76ee0791bea 100644 --- a/core/API/Request.php +++ b/core/API/Request.php @@ -238,11 +238,11 @@ static public function reloadAuthUsingTokenAuth($request = null) if ($token_auth) { /** - * Triggered when authenticating an API request. Only triggered if the **token_auth** + * Triggered when authenticating an API request, but only if the **token_auth** * query parameter is found in the request. * * Plugins that provide authentication capabilities should subscribe to this event - * and make sure the authentication object (the object returned by `Registry::get('auth')`) + * and make sure the global authentication object (the object returned by `Registry::get('auth')`) * is setup to use `$token_auth` when its `authenticate()` method is executed. * * @param string $token_auth The value of the **token_auth** query parameter. diff --git a/core/Access.php b/core/Access.php index 7dfb25bb517..86a4a04cf50 100644 --- a/core/Access.php +++ b/core/Access.php @@ -427,11 +427,12 @@ protected function getIdSites($idSites) } /** - * Exception thrown when a user doesn't have sufficient access. + * Exception thrown when a user doesn't have sufficient access to a resource. * * @package Piwik * @subpackage Access + * @api */ class NoAccessException extends \Exception { -} +} \ No newline at end of file diff --git a/core/ArchiveProcessor/Parameters.php b/core/ArchiveProcessor/Parameters.php index db8919228cb..7ac9129b3b4 100644 --- a/core/ArchiveProcessor/Parameters.php +++ b/core/ArchiveProcessor/Parameters.php @@ -101,7 +101,7 @@ public function getIdSites() $idSites = array($idSite); - Piwik::postEvent('ArchiveProcessor.Parameters.getIdSites', array( &$idSites, $this->getPeriod() ) ); + Piwik::postEvent('ArchiveProcessor.Parameters.getIdSites', array(&$idSites, $this->getPeriod())); return $idSites; } diff --git a/core/AssetManager.php b/core/AssetManager.php index 915bb5f07e9..ec850de0dbe 100644 --- a/core/AssetManager.php +++ b/core/AssetManager.php @@ -163,7 +163,7 @@ private static function prepareMergedCssFile() * * This event can be used to modify merged CSS. * - * @param string &$mergedContent The merged an minified CSS. + * @param string &$mergedContent The merged and minified CSS. */ Piwik::postEvent('AssetManager.filterMergedStylesheets', array(&$mergedContent)); @@ -295,12 +295,12 @@ private static function getStylesheetFiles() * Plugins that have stylesheets should use this event to make those stylesheets * load. * - * Stylesheets should be placed within a **stylesheets** subfolder in your plugin's + * Stylesheets should be placed within a **stylesheets** subdirectory in your plugin's * root directory. * - * Note: In case you are developing your plugin you may enable the config setting - * `[Debug] disable_merged_assets`. Otherwise your custom stylesheets won't be - * reloaded immediately after a change. + * _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** * @@ -382,7 +382,7 @@ private static function generateMergedJsFile() $mergedContent = str_replace("\n", "\r\n", $mergedContent); /** - * Triggered after all JavaScript files Piwik uses are minified and merged into a + * 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 @@ -431,19 +431,19 @@ private static function getJsFiles() * 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** subfolder in your + * JavaScript files should be placed within a **javascripts** subdirectory in your * plugin's root directory. * - * Note: In case you are developing your plugin you may enable the config setting - * `[Debug] disable_merged_assets`. Otherwise your JavaScript won't be reloaded - * immediately after a change. + * _Note: While you are developing your plugin you should enable the config setting + * `[Debug] disable_merged_assets` so JavaScript files will be reloaded immediately + * after every change._ * * **Example** * - * public function getJsFiles(&jsFiles) + * public function getJsFiles(&$jsFiles) * { - * jsFiles[] = "plugins/MyPlugin/javascripts/myfile.js"; - * jsFiles[] = "plugins/MyPlugin/javascripts/anotherone.js"; + * $jsFiles[] = "plugins/MyPlugin/javascripts/myfile.js"; + * $jsFiles[] = "plugins/MyPlugin/javascripts/anotherone.js"; * } * * @param string[] $jsFiles The JavaScript files to load. @@ -710,4 +710,4 @@ private static function getFirstLineOfMergedJs() { return "/* Piwik Javascript - cb=" . self::generateAssetsCacheBuster() . "*/\n"; } -} +} \ No newline at end of file diff --git a/core/Console.php b/core/Console.php index 15ecbc18bce..1547d6aec09 100644 --- a/core/Console.php +++ b/core/Console.php @@ -48,18 +48,17 @@ private function getAvailableCommands() $commands = array(); /** - * Triggered when gathering all available console commands. Plugins that want to expose new console commands + * 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'; - * } - * ``` + * + * public function addConsoleCommands(&$commands) + * { + * $commands[] = 'Piwik\Plugins\MyPlugin\Commands\MyCommand'; + * } * - * @param array &$commands An array containing a list of command classnames. + * @param array &$commands An array containing a list of command class names. */ Piwik::postEvent('Console.addCommands', array(&$commands)); diff --git a/core/CronArchive.php b/core/CronArchive.php index f3d74858001..9298a01f8df 100644 --- a/core/CronArchive.php +++ b/core/CronArchive.php @@ -795,8 +795,13 @@ private function filterWebsiteIds(&$websiteIds) $websiteIds = array_intersect($websiteIds, $this->allWebsites); /** - * When the cron to run archive.php is executed, it fetches the list of website IDs to process. - * Use this hook to add, remove, or change the order of websites IDs to pre-archive. + * Triggered by the **archive.php** cron script so plugins can modify the list of + * websites that the archiving process will be launched for. + * + * Plugins can use this hook to add websites to archive, remove websites to archive, or change + * the order in which websites will be archived. + * + * @param array $websiteIds The list of website IDs to launch the archiving process for. */ Piwik::postEvent('CronArchive.filterWebsiteIds', array(&$websiteIds)); } diff --git a/core/Db.php b/core/Db.php index f71b64742c2..a1ae66916dd 100644 --- a/core/Db.php +++ b/core/Db.php @@ -74,21 +74,21 @@ public static function createDatabaseObject($dbInfos = null) } /** - * Triggered before a connection to the database is established. + * Triggered before a database connection is established. * - * This event can be used to dynamically change the settings used to connect to the - * database. + * 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 + * @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'` + * - **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)); diff --git a/core/FrontController.php b/core/FrontController.php index dbd3bb86d40..e9fb8f6093b 100644 --- a/core/FrontController.php +++ b/core/FrontController.php @@ -91,7 +91,7 @@ public function dispatch($module = null, $action = null, $parameters = null) * Triggered directly before controller actions are dispatched. * * This event can be used to modify the parameters passed to one or more controller actions - * and can be used to change the plugin and action that is being dispatched to. + * and can be used to change the controller action being dispatched to. * * @param string &$module The name of the plugin being dispatched to. * @param string &$action The name of the controller method being dispatched to. @@ -102,6 +102,8 @@ public function dispatch($module = null, $action = null, $parameters = null) list($controller, $action) = $this->makeController($module, $action); /** + * Triggered directly before controller actions are dispatched. + * * This event exists for convenience and is triggered directly after the {@hook Request.dispatch} * event is triggered. * @@ -116,6 +118,8 @@ public function dispatch($module = null, $action = null, $parameters = null) $result = call_user_func_array(array($controller, $action), $parameters); /** + * Triggered after a controller action is successfully called. + * * This event exists for convenience and is triggered immediately before the {@hook Request.dispatch.end} * event is triggered. * @@ -131,10 +135,9 @@ public function dispatch($module = null, $action = null, $parameters = null) /** * Triggered after a controller action is successfully called. * - * This event can be used to modify controller action output (if there was any) before - * the output is returned. + * This event can be used to modify controller action output (if any) before the output is returned. * - * @param mixed &$result The result of the controller action. + * @param mixed &$result The controller action result. * @param array $parameters The arguments passed to the controller action. */ Piwik::postEvent('Request.dispatch.end', array(&$result, $parameters)); @@ -255,9 +258,10 @@ static public function createConfigObject() } catch (Exception $exception) { /** - * Triggered when the configuration file cannot be found or read. This usually - * means Piwik is not installed yet. This event can be used to start the - * installation process or to display a custom error message. + * Triggered when the configuration file cannot be found or read, which usually + * means Piwik is not installed yet. + * + * This event can be used to start the installation process or to display a custom error message. * * @param Exception $exception The exception that was thrown by `Config::getInstance()`. */ @@ -335,8 +339,9 @@ public function init() /** * Triggered if the INI config file has the incorrect format or if certain required configuration - * options are absent. This event can be used to start the installation process or to display a - * custom error message. + * options are absent. + * + * This event can be used to start the installation process or to display a custom error message. * * @param Exception $exception The exception thrown from creating and testing the database * connection. @@ -350,8 +355,10 @@ public function init() /** * Triggered just after the platform is initialized and plugins are loaded. - * This event can be used to do early initialization. Note: At this point the user - * is not authenticated yet. + * + * This event can be used to do early initialization. + * + * _Note: At this point the user is not authenticated yet._ */ Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen'); @@ -363,9 +370,17 @@ public function init() } /** - * Triggered before the user is authenticated. You can use it to create your own - * authentication object which implements the {@link Piwik\Auth} interface and overrides - * the default authentication logic. + * Triggered before the user is authenticated, when the global authentication object + * should be created. + * + * Plugins that provide their own authentication implementation should use this event + * to set the global authentication object (which must derive from {@link Piwik\Auth}). + * + * **Example** + * + * Piwik::addAction('Request.initAuthenticationObject', function() { + * Piwik\Registry::set('auth', new MyAuthImplementation()); + * }); */ Piwik::postEvent('Request.initAuthenticationObject'); try { @@ -390,7 +405,7 @@ public function init() /** * Triggered after the platform is initialized and after the user has been authenticated, but - * before the platform dispatched the request. + * before the platform has handled the request. * * Piwik uses this event to check for updates to Piwik. */ diff --git a/core/Log.php b/core/Log.php index bdf4ac23c7e..b2facc6cb65 100644 --- a/core/Log.php +++ b/core/Log.php @@ -302,17 +302,19 @@ private function getAvailableWriters() * This event is called when the Log instance is created. Plugins can use this event to * make new logging writers available. * - * A logging writer is a callback that takes the following arguments: - * int $level, string $tag, string $datetime, string $message + * A logging writer is a callback with the following signature: + * + * function (int $level, string $tag, string $datetime, string $message) * - * $level is the log level to use, $tag is the log tag used, $datetime is the date time - * of the logging call and $message is the formatted log message. + * `$level` is the log level to use, `$tag` is the log tag used, `$datetime` is the date time + * of the logging call and `$message` is the formatted log message. * - * Logging writers must be associated by name in the array passed to event handlers. + * Logging writers must be associated by name in the array passed to event handlers. The + * name specified can be used in Piwik's INI configuration. * - * ***Example** + * **Example** * - * function (&$writers) { + * public function getAvailableWriters(&$writers) { * $writers['myloggername'] = function ($level, $tag, $datetime, $message) { * // ... * }; @@ -320,7 +322,7 @@ private function getAvailableWriters() * * // 'myloggername' can now be used in the log_writers config option. * - * @param $ + * @param array $writers Array mapping writer names with logging writers. */ Piwik::postEvent(self::GET_AVAILABLE_WRITERS_EVENT, array(&$writers)); @@ -338,12 +340,20 @@ private function logToFile($level, $tag, $datetime, $message) $logger = $this; /** - * This event is called when trying to log an object to a file. Plugins can use + * Triggered when trying to log an object to a file. Plugins can use * this event to convert objects to strings before they are logged. * + * **Example** + * + * public function formatFileMessage(&$message, $level, $tag, $datetime, $logger) { + * if ($message instanceof MyCustomDebugInfo) { + * $message = $message->formatForFile(); + * } + * } + * * @param mixed &$message The object that is being logged. Event handlers should * check if the object is of a certain type and if it is, - * set $message to the string that should be logged. + * set `$message` to the string that should be logged. * @param int $level The log level used with this log entry. * @param string $tag The current plugin that started logging (or if no plugin, * the current class). @@ -387,15 +397,23 @@ private function logToScreen($level, $tag, $datetime, $message) $logger = $this; /** - * This event is called when trying to log an object to the screen. Plugins can use + * Triggered when trying to log an object to the screen. Plugins can use * this event to convert objects to strings before they are logged. * * The result of this callback can be HTML so no sanitization is done on the result. - * This means YOU MUST SANITIZE THE MESSAGE YOURSELF if you use this event. + * This means **YOU MUST SANITIZE THE MESSAGE YOURSELF** if you use this event. * + * **Example** + * + * public function formatScreenMessage(&$message, $level, $tag, $datetime, $logger) { + * if ($message instanceof MyCustomDebugInfo) { + * $message = Common::sanitizeInputValue($message->formatForScreen()); + * } + * } + * * @param mixed &$message The object that is being logged. Event handlers should * check if the object is of a certain type and if it is, - * set $message to the string that should be logged. + * set `$message` to the string that should be logged. * @param int $level The log level used with this log entry. * @param string $tag The current plugin that started logging (or if no plugin, * the current class). @@ -420,12 +438,20 @@ private function logToDatabase($level, $tag, $datetime, $message) $logger = $this; /** - * This event is called when trying to log an object to a database table. Plugins can use + * Triggered when trying to log an object to a database table. Plugins can use * this event to convert objects to strings before they are logged. * + * **Example** + * + * public function formatDatabaseMessage(&$message, $level, $tag, $datetime, $logger) { + * if ($message instanceof MyCustomDebugInfo) { + * $message = $message->formatForDatabase(); + * } + * } + * * @param mixed &$message The object that is being logged. Event handlers should * check if the object is of a certain type and if it is, - * set $message to the string that should be logged. + * set `$message` to the string that should be logged. * @param int $level The log level used with this log entry. * @param string $tag The current plugin that started logging (or if no plugin, * the current class). diff --git a/core/Menu/MenuTop.php b/core/Menu/MenuTop.php index 8e2caba4a54..e9d5dc6f52a 100644 --- a/core/Menu/MenuTop.php +++ b/core/Menu/MenuTop.php @@ -92,8 +92,9 @@ public function getMenu() /** * Triggered when collecting all available menu items that are be displayed on the very top of every - * page, next to the login/logout links. Subscribe to this event if you want to add one or more items - * to the top menu. + * page, next to the login/logout links. + * + * Subscribe to this event if you want to add one or more items to the top menu. * * Menu items should be added via the {@link addEntry()} method. * diff --git a/core/Plugin/ViewDataTable.php b/core/Plugin/ViewDataTable.php index 204c25a9faf..b3b64ac05a9 100644 --- a/core/Plugin/ViewDataTable.php +++ b/core/Plugin/ViewDataTable.php @@ -124,13 +124,14 @@ public function __construct($controllerAction, $apiMethodToRequestDataTable) /** * Triggered during {@link ViewDataTable} construction. Subscribers should customize - * the view based on the report that it is displaying. + * the view based on the report that is being displayed. * * Plugins that define their own reports must subscribe to this event in order to - * specify how the Piwik UI will display the report. + * specify how the Piwik UI should display the report. * * **Example** * + * // event handler * public function configureViewDataTable(ViewDataTable $view) * { * switch ($view->requestConfig->apiMethodToRequestDataTable) { diff --git a/core/SettingsPiwik.php b/core/SettingsPiwik.php index 941f9af9200..58ac848a9a5 100644 --- a/core/SettingsPiwik.php +++ b/core/SettingsPiwik.php @@ -65,23 +65,29 @@ public static function getKnownSegmentsToArchive() /** * Triggered during the cron archiving process to collect segments that * should be pre-processed for all websites. The archiving process will be launched - * for each of these segments when archiving data for each site. + * for each of these segments when archiving data. * - * This event can be used to add segments to be pre-processed. This can be provide - * enhanced performance if your plugin depends on data from a specific segment. + * This event can be used to add segments to be pre-processed. If your plugin depends + * on data from a specific segment, this event could be used to provide enhanced + * performance. * - * Note: If you just want to add a segment that is managed by the user, you should use the - * SegmentEditor API. + * _Note: If you just want to add a segment that is managed by the user, use the + * SegmentEditor API._ + * + * **Example** + * + * Piwik::addAction('Segments.getKnownSegmentsToArchiveAllSites', function (&$segments) { + * $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 process to this array in your event - * handler. + * + * array( + * 'browserCode=ff;resolution=800x600', + * 'country=jp;city=Tokyo' + * ) + * + * Add segments to this array in your event handler. */ Piwik::postEvent('Segments.getKnownSegmentsToArchiveAllSites', array(&$segmentsToProcess)); @@ -107,21 +113,25 @@ public static function getKnownSegmentsToArchiveForSite($idSite) * 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. This can be provide - * enhanced performance if your plugin depends on data from a specific segment. + * 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** * - * Note: If you just want to add a segment that is managed by the user, you should use the - * SegmentEditor API. + * 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 process to this array in your event - * handler. + * + * 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)); diff --git a/core/Site.php b/core/Site.php index 38b9c32410f..6e4e9c4753d 100644 --- a/core/Site.php +++ b/core/Site.php @@ -92,14 +92,21 @@ protected static function setSite($idSite, $infoSite) throw new Exception("Un unexpected website was found."); } - /** - * Piwik core APIs and plugins use the Site object to get information about websites. - * This event is called just before a Website information is stored in the memory cache. - * It can be used to modify the data for a website, such as decorate its name or change its created datetime. + * Triggered so plugins can modify website entities without modifying the database. + * + * This event should **not** be used to add data that is expensive to compute. If you + * need to make HTTP requests or query the database for more information, this is not + * the place to do it. * - * @param int $idSite Website ID - * @param array $infoSite Website information array + * **Example** + * + * Piwik::addAction('Site.setSite', function ($idSite, &$info) { + * $info['name'] .= " (original)"; + * }); + * + * @param int $idSite The ID of the website entity that will be modified. + * @param array $infoSite The website entity. [Learn more.](/guides/persistence-and-the-mysql-backend#websites-aka-sites) */ Piwik::postEvent('Site.setSite', array($idSite, &$infoSite)); diff --git a/core/TaskScheduler.php b/core/TaskScheduler.php index 5503f68340f..05bc56de3a7 100644 --- a/core/TaskScheduler.php +++ b/core/TaskScheduler.php @@ -79,26 +79,23 @@ static public function runTasks() $tasks = array(); /** - * Triggered when the TaskScheduler runs scheduled tasks. Collects all the tasks that - * will be run. + * Triggered during scheduled task execution. Collects all the tasks to run. * * Subscribe to this event to schedule code execution on an hourly, daily, weekly or monthly * basis. * * **Example** * - * ``` - * public function getScheduledTasks(&$tasks) - * { - * $tasks[] = new ScheduledTask( - * 'Piwik\Plugins\CorePluginsAdmin\MarketplaceApiClient', - * 'clearAllCacheEntries', - * null, - * ScheduledTime::factory('daily'), - * ScheduledTask::LOWEST_PRIORITY - * ); - * } - * ``` + * public function getScheduledTasks(&$tasks) + * { + * $tasks[] = new ScheduledTask( + * 'Piwik\Plugins\CorePluginsAdmin\MarketplaceApiClient', + * 'clearAllCacheEntries', + * null, + * ScheduledTime::factory('daily'), + * ScheduledTask::LOWEST_PRIORITY + * ); + * } * * @param ScheduledTask[] &$tasks List of tasks to run periodically. */ diff --git a/core/Tracker.php b/core/Tracker.php index 0e8b746b0fe..abf396cbfd9 100644 --- a/core/Tracker.php +++ b/core/Tracker.php @@ -523,13 +523,13 @@ public static function connectPiwikTrackerDb() } /** - * Triggered before a connection to the database is established in the Tracker. + * Triggered before a connection to the database is established by the Tracker. * - * This event can be used to dynamically change the settings used to connect to the - * database. + * This event can be used to change the database connection settings used by the Tracker. * * @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. @@ -588,13 +588,13 @@ protected function getNewVisitObject() $visit = null; /** - * Triggered before a new `{@link Piwik\Tracker\Visit}` object is created. Subscribers to this + * Triggered before a new **visit object** is created. Subscribers to this * event can force the use of a custom visit object that extends from * {@link Piwik\Tracker\VisitInterface}. * * @param \Piwik\Tracker\VisitInterface &$visit Initialized to null, but can be set to - * a created Visit object. If it isn't - * modified Piwik uses the default class. + * a new visit object. If it isn't modified + * Piwik uses the default class. */ Piwik::postEvent('Tracker.makeNewVisitObject', array(&$visit)); diff --git a/core/Tracker/Action.php b/core/Tracker/Action.php index 10c8514f058..71c090efd6d 100644 --- a/core/Tracker/Action.php +++ b/core/Tracker/Action.php @@ -264,7 +264,7 @@ public function record($idVisit, $visitorIdCookie, $idReferrerActionUrl, $idRefe ? (int)$this->getIdActionName() : null; - $insert = array( + $visitAction = array( 'idvisit' => $idVisit, 'idsite' => $this->request->getIdSite(), 'idvisitor' => $visitorIdCookie, @@ -277,12 +277,12 @@ public function record($idVisit, $visitorIdCookie, $idReferrerActionUrl, $idRefe ); foreach($this->actionIdsCached as $field => $idAction) { - $insert[$field] = $idAction; + $visitAction[$field] = $idAction; } $customValue = $this->getCustomFloatValue(); if (!empty($customValue)) { - $insert[self::DB_COLUMN_CUSTOM_FLOAT] = $customValue; + $visitAction[self::DB_COLUMN_CUSTOM_FLOAT] = $customValue; } $customVariables = $this->getCustomVariables(); @@ -291,47 +291,27 @@ public function record($idVisit, $visitorIdCookie, $idReferrerActionUrl, $idRefe Common::printDebug($customVariables); } - $insert = array_merge($insert, $customVariables); - $fields = implode(", ", array_keys($insert)); - $bind = array_values($insert); - $values = Common::getSqlStringFieldsArray($insert); + $visitAction = array_merge($visitAction, $customVariables); + $fields = implode(", ", array_keys($visitAction)); + $bind = array_values($visitAction); + $values = Common::getSqlStringFieldsArray($visitAction); $sql = "INSERT INTO " . Common::prefixTable('log_link_visit_action') . " ($fields) VALUES ($values)"; Tracker::getDatabase()->query($sql, $bind); $this->idLinkVisitAction = Tracker::getDatabase()->lastInsertId(); + $visitAction['idlink_va'] = $this->idLinkVisitAction; - $info = array( - 'idSite' => $this->request->getIdSite(), - 'idLinkVisitAction' => $this->idLinkVisitAction, - 'idVisit' => $idVisit, - 'idReferrerActionUrl' => $idReferrerActionUrl, - 'idReferrerActionName' => $idReferrerActionName, - 'timeSpentReferrerAction' => $timeSpentReferrerAction, - ); Common::printDebug("Inserted new action:"); - Common::printDebug($insert); + Common::printDebug($visitAction); /** - * Triggered after successfully logging an action for a visit. - * + * Triggered after successfully persisting a [visit action entity](/guides/persistence-and-the-mysql-backend#visit-actions). * * @param Action $tracker Action The Action tracker instance. - * @param array $info An array describing the current visit action. Includes the - * following information: - * - **idSite**: The ID of the site that we are tracking. - * - **idLinkVisitAction**: The ID of the row that was inserted into the - * log_link_visit_action table. - * - **idVisit**: The visit ID. - * - **idReferrerActionUrl**: The ID referencing the row in the log_action table - * that holds the URL of the visitor's last action. - * - **idReferrerActionName**: The ID referencing the row in the log_action table - * that holds the name of the visitor's last action. - * - **timeSpentReferrerAction**: The number of seconds since the visitor's last - * action. + * @param array $visitAction The visit action entity that was persisted. Read + * [this](/guides/persistence-and-the-mysql-backend#visit-actions) to see what it contains. */ - Piwik::postEvent('Tracker.recordAction', array($trackerAction = $this, $info)); + Piwik::postEvent('Tracker.recordAction', array($trackerAction = $this, $visitAction)); } - -} - +} \ No newline at end of file diff --git a/core/Tracker/Cache.php b/core/Tracker/Cache.php index 142c075eade..3b23d554423 100644 --- a/core/Tracker/Cache.php +++ b/core/Tracker/Cache.php @@ -70,8 +70,11 @@ static function getCacheWebsiteAttributes($idSite) $content = array(); /** - * This event is called to get the details of a site by its ID. It can be used to - * add custom attributes for the website to the Tracker cache. + * 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** * @@ -81,8 +84,8 @@ static function getCacheWebsiteAttributes($idSite) * $content['myplugin_site_data'] = Db::fetchOne($sql, array($idSite)); * } * - * @param array &$content List of attributes. - * @param int $idSite The site ID. + * @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)); @@ -129,13 +132,14 @@ static public function getCacheGeneral() ); /** - * Triggered before the general tracker cache is saved to disk. This event can be - * used to add extra content to the cace. + * Triggered before the [general tracker cache](/guides/all-about-tracking#the-tracker-cache) + * is saved to disk. This event can be used to add extra content to the cache. * * Data that is used during tracking but is expensive to compute/query should be - * cached so as not to slow the tracker down. One example of such data are options - * that are stored in the piwik_option table. Requesting data on each tracking - * request means an extra unnecessary database query on each visitor action. + * cached to keep tracking efficient. One example of such data are options + * that are stored in the piwik_option table. Querying data for each tracking + * request means an extra unnecessary database query for each visitor action. Using + * a cache solves this problem. * * **Example** * diff --git a/core/Tracker/GoalManager.php b/core/Tracker/GoalManager.php index b626485ca57..ca385fc59bf 100644 --- a/core/Tracker/GoalManager.php +++ b/core/Tracker/GoalManager.php @@ -352,33 +352,33 @@ protected function getRevenue($revenue) * Records an Ecommerce conversion in the DB. Deals with Items found in the request. * Will deal with 2 types of conversions: Ecommerce Order and Ecommerce Cart update (Add to cart, Update Cart etc). * - * @param array $goal - * @param array $visitorInformation + * @param array $conversion + * @param array $visitInformation */ - protected function recordEcommerceGoal($goal, $visitorInformation) + protected function recordEcommerceGoal($conversion, $visitInformation) { if ($this->isThereExistingCartInVisit) { Common::printDebug("There is an existing cart for this visit"); } if ($this->isGoalAnOrder) { - $goal['idgoal'] = self::IDGOAL_ORDER; - $goal['idorder'] = $this->orderId; - $goal['buster'] = Common::hashStringToInt($this->orderId); - $goal['revenue_subtotal'] = $this->getRevenue($this->request->getParam('ec_st')); - $goal['revenue_tax'] = $this->getRevenue($this->request->getParam('ec_tx')); - $goal['revenue_shipping'] = $this->getRevenue($this->request->getParam('ec_sh')); - $goal['revenue_discount'] = $this->getRevenue($this->request->getParam('ec_dt')); + $conversion['idgoal'] = self::IDGOAL_ORDER; + $conversion['idorder'] = $this->orderId; + $conversion['buster'] = Common::hashStringToInt($this->orderId); + $conversion['revenue_subtotal'] = $this->getRevenue($this->request->getParam('ec_st')); + $conversion['revenue_tax'] = $this->getRevenue($this->request->getParam('ec_tx')); + $conversion['revenue_shipping'] = $this->getRevenue($this->request->getParam('ec_sh')); + $conversion['revenue_discount'] = $this->getRevenue($this->request->getParam('ec_dt')); $debugMessage = 'The conversion is an Ecommerce order'; } // If Cart update, select current items in the previous Cart else { - $goal['buster'] = 0; - $goal['idgoal'] = self::IDGOAL_CART; + $conversion['buster'] = 0; + $conversion['idgoal'] = self::IDGOAL_CART; $debugMessage = 'The conversion is an Ecommerce Cart Update'; } - $goal['revenue'] = $this->getRevenue($this->request->getGoalRevenue($defaultRevenue = 0)); + $conversion['revenue'] = $this->getRevenue($this->request->getGoalRevenue($defaultRevenue = 0)); - Common::printDebug($debugMessage . ':' . var_export($goal, true)); + Common::printDebug($debugMessage . ':' . var_export($conversion, true)); // INSERT or Sync items in the Cart / Order for this visit & order $items = $this->getEcommerceItemsFromRequest(); @@ -390,29 +390,35 @@ protected function recordEcommerceGoal($goal, $visitorInformation) foreach ($items as $item) { $itemsCount += $item[self::INTERNAL_ITEM_QUANTITY]; } - $goal['items'] = $itemsCount; + $conversion['items'] = $itemsCount; if($this->isThereExistingCartInVisit) { $updateWhere = array( - 'idvisit' => $visitorInformation['idvisit'], + 'idvisit' => $visitInformation['idvisit'], 'idgoal' => self::IDGOAL_CART, 'buster' => 0, ); - $recorded = $this->updateExistingConversion($goal, $updateWhere); + $recorded = $this->updateExistingConversion($conversion, $updateWhere); } else { - $recorded = $this->insertNewConversion($goal, $visitorInformation); + $recorded = $this->insertNewConversion($conversion, $visitInformation); } if ($recorded) { - $this->recordEcommerceItems($goal, $items, $visitorInformation); + $this->recordEcommerceItems($conversion, $items, $visitInformation); } /** - * This hook is called after recording an ecommerce goal. You can use it for instance to sync the recorded goal - * with third party systems. `$goal` contains all available information like `items` and `revenue`. - * `$visitor` contains the current known visit information. + * Triggered after successfully persisting an ecommerce conversion. + * + * _Note: Subscribers should be wary of doing any expensive computation here as it may slow + * the tracker down._ + * + * @param array $conversion The conversion entity that was just persisted. See what information + * it contains [here](/guides/persistence-and-the-mysql-backend#conversions). + * @param array $visitInformation The visit entity that we are tracking a conversion for. See what + * information it contains [here](/guides/persistence-and-the-mysql-backend#visits). */ - Piwik::postEvent('Tracker.recordEcommerceGoal', array($goal, $visitorInformation)); + Piwik::postEvent('Tracker.recordEcommerceGoal', array($conversion, $visitInformation)); } /** @@ -756,59 +762,67 @@ protected function recordStandardGoals($goal, $action, $visitorInformation) { foreach ($this->convertedGoals as $convertedGoal) { Common::printDebug("- Goal " . $convertedGoal['idgoal'] . " matched. Recording..."); - $newGoal = $goal; - $newGoal['idgoal'] = $convertedGoal['idgoal']; - $newGoal['url'] = $convertedGoal['url']; - $newGoal['revenue'] = $this->getRevenue($convertedGoal['revenue']); + $conversion = $goal; + $conversion['idgoal'] = $convertedGoal['idgoal']; + $conversion['url'] = $convertedGoal['url']; + $conversion['revenue'] = $this->getRevenue($convertedGoal['revenue']); if (!is_null($action)) { - $newGoal['idaction_url'] = $action->getIdActionUrl(); - $newGoal['idlink_va'] = $action->getIdLinkVisitAction(); + $conversion['idaction_url'] = $action->getIdActionUrl(); + $conversion['idlink_va'] = $action->getIdLinkVisitAction(); } // If multiple Goal conversions per visit, set a cache buster - $newGoal['buster'] = $convertedGoal['allow_multiple'] == 0 + $conversion['buster'] = $convertedGoal['allow_multiple'] == 0 ? '0' : $visitorInformation['visit_last_action_time']; - $this->insertNewConversion($newGoal, $visitorInformation); + $this->insertNewConversion($conversion, $visitorInformation); /** - * This hook is called after recording a standard goal. You can use it for instance to sync the recorded - * goal with third party systems. `$goal` contains all available information like `url` and `revenue`. + * Triggered after successfully recording a non-ecommerce conversion. + * + * _Note: Subscribers should be wary of doing any expensive computation here as it may slow + * the tracker down._ + * + * @param array $conversion The conversion entity that was just persisted. See what information + * it contains [here](/guides/persistence-and-the-mysql-backend#conversions). */ - Piwik::postEvent('Tracker.recordStandardGoals', array($newGoal)); + Piwik::postEvent('Tracker.recordStandardGoals', array($conversion)); } } /** * Helper function used by other record* methods which will INSERT or UPDATE the conversion in the DB * - * @param array $newGoal - * @param array $visitorInformation + * @param array $conversion + * @param array $visitInformation * @return bool */ - protected function insertNewConversion($newGoal, $visitorInformation) + protected function insertNewConversion($conversion, $visitInformation) { /** - * This hook is called before inserting a new Goal Conversion.. You can use it to update the Goal - * attributes before they are saved in the log_conversion table. - * `$visitor` contains the current known visit information. - * @param array $goal Array of SQL fields value for this conversion, will be inserted in the log_conversion table - * @param array $visitorInformation Array of log_visit field values for this visitor - * @param \Piwik\Tracker\Request $request + * Triggered before persisting a new [conversion entity](/guides/persistence-and-the-mysql-backend#conversions). + * + * This event can be used to modify conversion information or to add new information to be persisted. + * + * @param array $conversion The conversion entity. Read [this](/guides/persistence-and-the-mysql-backend#conversions) + * to see what it contains. + * @param array $visitInformation The visit entity that we are tracking a conversion for. See what + * information it contains [here](/guides/persistence-and-the-mysql-backend#visits). + * @param \Piwik\Tracker\Request $request An object describing the tracking request being processed. */ - Piwik::postEvent('Tracker.newConversionInformation', array( &$newGoal, $visitorInformation, $this->request)); + Piwik::postEvent('Tracker.newConversionInformation', array(&$conversion, $visitInformation, $this->request)); - $newGoalDebug = $newGoal; + $newGoalDebug = $conversion; $newGoalDebug['idvisitor'] = bin2hex($newGoalDebug['idvisitor']); Common::printDebug($newGoalDebug); - $fields = implode(", ", array_keys($newGoal)); - $bindFields = Common::getSqlStringFieldsArray($newGoal); + $fields = implode(", ", array_keys($conversion)); + $bindFields = Common::getSqlStringFieldsArray($conversion); $sql = 'INSERT IGNORE INTO ' . Common::prefixTable('log_conversion') . " ($fields) VALUES ($bindFields) "; - $bind = array_values($newGoal); + $bind = array_values($conversion); $result = Tracker::getDatabase()->query($sql, $bind); // If a record was inserted, we return true diff --git a/core/Tracker/Referrer.php b/core/Tracker/Referrer.php index 983c9695355..402f85d222f 100644 --- a/core/Tracker/Referrer.php +++ b/core/Tracker/Referrer.php @@ -135,10 +135,10 @@ protected function detectReferrerSearchEngine() * - **name**: The search engine name. * - **keywords**: The search keywords used. * - * This parameter will be defaulted to the results + * This parameter is initialized to the results * of Piwik's default search engine detection * logic. - * @param string referrerUrl The referrer URL. + * @param string referrerUrl The referrer URL from the tracking request. */ Piwik::postEvent('Tracker.detectReferrerSearchEngine', array(&$searchEngineInformation, $this->referrerUrl)); if ($searchEngineInformation === false) { diff --git a/core/Tracker/Request.php b/core/Tracker/Request.php index 13f81eab985..c8453dd8658 100644 --- a/core/Tracker/Request.php +++ b/core/Tracker/Request.php @@ -304,15 +304,15 @@ public function getIdSite() $idSite = Common::getRequestVar('idsite', 0, 'int', $this->params); /** - * Triggered when obtaining the ID of the site that is currently being tracked. + * Triggered when obtaining the ID of the site we are tracking a visit for. * - * This event can be used to modify the site ID from what is specified by the **idsite** - * query parameter. + * This event can be used to change the site ID so data is tracked for a different + * website. * * @param int &$idSite Initialized to the value of the **idsite** query parameter. If a * subscriber sets this variable, the value it uses must be greater * than 0. - * @param array $params The entire array of request parameters passed with this tracking + * @param array $params The entire array of request parameters in the current tracking * request. */ Piwik::postEvent('Tracker.Request.getIdSite', array(&$idSite, $this->params)); diff --git a/core/Tracker/Visit.php b/core/Tracker/Visit.php index e5071be6be5..962eeb772f3 100644 --- a/core/Tracker/Visit.php +++ b/core/Tracker/Visit.php @@ -91,7 +91,12 @@ public function handle() } /** - * This event can be used for instance to anonymize the IP (after testing for IP exclusion). + * Triggered after visits are tested for exclusion so plugins can modify the IP address + * persisted with a visit. + * + * This event is primarily used by the **AnonymizeIP** plugin to anonymize IP addresses. + * + * @param string &$ip The visitor's IP address. */ Piwik::postEvent('Tracker.setVisitorIp', array(&$this->visitorInfo['location_ip'])); @@ -238,8 +243,15 @@ protected function handleExistingVisit($action, $visitIsConverted) } /** - * This event is triggered before updating an existing visit's row. Use it to change any visitor information before - * the visitor is saved, or register information about an existing visitor. + * Triggered before a [visit entity](/guides/persistence-and-the-mysql-backend#visits) is updated when + * tracking an action for an existing visit. + * + * This event can be used to modify the visit properties that will be updated before the changes + * are persisted. + * + * @param array &$valuesToUpdate Visit entity properties that will be updated. + * @param array $visit The entire visit entity. Read [this](/guides/persistence-and-the-mysql-backend#visits) + * to see what it contains. */ Piwik::postEvent('Tracker.existingVisitInformation', array(&$valuesToUpdate, $this->visitorInfo)); @@ -286,14 +298,14 @@ protected function handleNewVisit($action, $visitIsConverted) $this->visitorInfo['config_resolution'] = substr($this->visitorInfo['config_resolution'], 0, 9); /** - * This event can be used to determine and set new visit information before the visit is - * logged. The UserCountry plugin, for example, uses this event to inject location information - * into the visit log table. + * Triggered before a new [visit entity](/guides/persistence-and-the-mysql-backend#visits) is persisted. + * + * This event can be used to modify the visit entity or add new information to it before it is persisted. + * The UserCountry plugin, for example, uses this event to add location information for each visit. * - * @param array $visitInfo Information regarding the visit. This is information that - * persisted to the database. - * @param \Piwik\Tracker\Request $request Request object, contains many useful methods - * such as getUserAgent() or getIp() to get the original IP. + * @param array &$visit The visit entity. Read [this](/guides/persistence-and-the-mysql-backend#visits) to see + * what information it contains. + * @param \Piwik\Tracker\Request $request An object describing the tracking request being processed. */ Piwik::postEvent('Tracker.newVisitorInformation', array(&$this->visitorInfo, $this->request)); @@ -967,14 +979,25 @@ public static function getVisitFieldsPersist() ); /** - * Use this event to load additional fields from the log_visit table into the visitor array for later use. + * Triggered when checking if the current action being tracked belongs to an existing visit. + * + * This event collects a list of [visit entity]() properties that should be loaded when reading + * the existing visit. Properties that appear in this list will be available in other tracking + * events such as {@hook Tracker.newConversionInformation} and {@hook Tracker.newVisitorInformation}. + * + * Plugins can use this event to load additional visit entity properties for later use during tracking. * When you add fields to this $fields array, they will be later available in Tracker.newConversionInformation - * or Tracker.newVisitorInformation. + * + * **Example** + * + * Piwik::addAction('Tracker.getVisitFieldsToPersist', function (&$fields) { + * $fields[] = 'custom_visit_property'; + * }); + * + * @param array &$fields The list of visit properties to load. */ - Piwik::postEvent('Tracker.getVisitFieldsToPersist', array( &$fields )); + Piwik::postEvent('Tracker.getVisitFieldsToPersist', array(&$fields)); return $fields; - } - -} +} \ No newline at end of file diff --git a/core/Tracker/VisitExcluded.php b/core/Tracker/VisitExcluded.php index b9506bc46d0..d52c4f65617 100644 --- a/core/Tracker/VisitExcluded.php +++ b/core/Tracker/VisitExcluded.php @@ -73,13 +73,13 @@ public function isExcluded() } /** - * Triggered on every pageview of a visitor. + * Triggered on every tracking request. * - * This event can be used to tell the Tracker not to record this particular pageview. + * This event can be used to tell the Tracker not to record this particular action or visit. * - * @param bool &$excluded Whether the pageview should be excluded or not. Initialized + * @param bool &$excluded Whether the request should be excluded or not. Initialized * to `false`. Event subscribers should set it to `true` in - * order to exclude the pageview. + * order to exclude the request. */ Piwik::postEvent('Tracker.isExcludedVisit', array(&$excluded)); diff --git a/core/Translate.php b/core/Translate.php index d66e18a6338..27570fb1cc3 100644 --- a/core/Translate.php +++ b/core/Translate.php @@ -118,7 +118,7 @@ public static function getLanguageToLoad() * } * } * - * @param string &$lang The language that should be used for the user. Will be + * @param string &$lang The language that should be used for the current user. Will be * initialized to the value of the **language** query parameter. */ Piwik::postEvent('User.getLanguage', array(&$lang)); @@ -177,8 +177,10 @@ private static function getClientSideTranslationKeys() /** * Triggered before generating the JavaScript code that allows i18n strings to be used - * in the browser. Plugins should subscribe to this event to specify which translations - * should be available in JavaScript code. + * in the browser. + * + * Plugins should subscribe to this event to specify which translations + * should be available to JavaScript. * * Event handlers should add whole translation keys, ie, keys that include the plugin name. * diff --git a/core/View/ReportsByDimension.php b/core/View/ReportsByDimension.php index 24f21104759..c3a298f588c 100644 --- a/core/View/ReportsByDimension.php +++ b/core/View/ReportsByDimension.php @@ -91,9 +91,12 @@ public function getId() public function render() { /** - * Use this hook to configure the "Report by dimension" UI controller. This controller is displayed for example - * in the Referrers>Overview and the Goals>Overview report. It displays a list of repotrs on the left, and when click - * loads the report on the right column. This hook can be used to filter this list of report. @see ReportsByDimension class for more info. + * Triggered before rendering {@link ReportsByDimension} views. + * + * Plugins can use this event to configure {@link ReportsByDimension} instances by + * adding or removing reports to display. + * + * @param ReportsByDimension $this The view instance. */ Piwik::postEvent('View.ReportsByDimension.render', array($this)); @@ -125,4 +128,4 @@ public function render() return parent::render(); } -} +} \ No newline at end of file diff --git a/core/ViewDataTable/Factory.php b/core/ViewDataTable/Factory.php index 44b601478f0..0a9510372a7 100644 --- a/core/ViewDataTable/Factory.php +++ b/core/ViewDataTable/Factory.php @@ -151,18 +151,22 @@ private static function getDefaultTypeViewDataTable() if (null === self::$defaultViewTypes) { self::$defaultViewTypes = array(); /** - * Triggered when gathering the default view types for all available reports. By default the HtmlTable - * visualization is used. If you define your own report, you may want to subscribe to this event to - * make sure another Visualization is used (for example, a pie graph, bar graph, or something else). + * Triggered when gathering the default view types for all available reports. + * + * If you define your own report, you may want to subscribe to this event to + * make sure the correct default Visualization is used (for example, a pie graph, + * bar graph, or something else). * + * If there is no default type associated with a report, the **table** visualization + * used. + * * **Example** - * ``` - * public function getDefaultTypeViewDataTable(&$defaultViewTypes) - * { - * $defaultViewTypes['Referrers.getSocials'] = HtmlTable::ID; - * $defaultViewTypes['Referrers.getUrlsForSocial'] = Pie::ID; - * } - * ``` + * + * public function getDefaultTypeViewDataTable(&$defaultViewTypes) + * { + * $defaultViewTypes['Referrers.getSocials'] = HtmlTable::ID; + * $defaultViewTypes['Referrers.getUrlsForSocial'] = Pie::ID; + * } * * @param array &$defaultViewTypes The array mapping report IDs with visualization IDs. */ diff --git a/core/WidgetsList.php b/core/WidgetsList.php index 26b4086d837..a3b1098940c 100644 --- a/core/WidgetsList.php +++ b/core/WidgetsList.php @@ -74,7 +74,7 @@ private static function addWidgets() self::$hookCalled = true; /** - * Triggered once when the widget list is first requested. Collects all available widgets. + * Used to collect all available dashboard widgets. * * Subscribe to this event to make your plugin's reports or other controller actions available * as dashboard widgets. Event handlers should call the {@link WidgetsList::add()} method for each @@ -82,12 +82,10 @@ private static function addWidgets() * * **Example** * - * ``` - * public function addWidgets() - * { - * WidgetsList::add('General_Actions', 'General_Pages', 'Actions', 'getPageUrls'); - * } - * ``` + * public function addWidgets() + * { + * WidgetsList::add('General_Actions', 'General_Pages', 'Actions', 'getPageUrls'); + * } */ Piwik::postEvent('WidgetsList.addWidgets'); } diff --git a/plugins/API/API.php b/plugins/API/API.php index 34364dd184a..4fdc53f0bb3 100644 --- a/plugins/API/API.php +++ b/plugins/API/API.php @@ -85,9 +85,9 @@ public function getSegmentsMetadata($idSites = array(), $_hideImplementationData $segments = array(); /** - * Triggered when gathering all available segments. + * Triggered when gathering all available segment dimensions. * - * This event can be used to make new segments available. + * This event can be used to make new segment dimensions available. * * **Example** * @@ -95,7 +95,7 @@ public function getSegmentsMetadata($idSites = array(), $_hideImplementationData * { * $segments[] = array( * 'type' => 'dimension', - * 'category' => Piwik::translate('General_Visit'), + * 'category' => Piwik::translate('General_Visit'), * 'name' => 'General_VisitorIP', * 'segment' => 'visitIp', * 'acceptedValues' => '13.54.122.1, etc.', @@ -105,27 +105,27 @@ public function getSegmentsMetadata($idSites = array(), $_hideImplementationData * ); * } * - * @param array &$segments The list of available segments. Append to this list to add - * new segments. Each element in this list must contain the - * following information: + * @param array &$dimensions The list of available segment dimensions. Append to this list to add + * new segments. Each element in this list must contain the + * following information: * - * - **type**: Either `'metric'` or `'dimension'`. `'metric'` means - * the value is a numeric and `'dimension'` means it is - * a string. Also, `'metric'` values will be displayed - * **Visit (metrics)** in the Segment Editor. - * - **category**: The segment category name. This can be an existing - * segment category visible in the segment editor. - * - **name**: The pretty name of the segment. - * - **segment**: The segment name, eg, `'visitIp'` or `'searches'`. - * - **acceptedValues**: A string describing one or two exacmple values, eg - * `'13.54.122.1, etc.'`. - * - **sqlSegment**: The table column this segment will segment by. - * For example, `'log_visit.location_ip'` for the - * **visitIp** segment. - * - **sqlFilter**: A PHP callback to apply to segment values before - * they are used in SQL. - * - **permission**: True if the current user has view access to this - * segment, false if otherwise. + * - **type**: Either `'metric'` or `'dimension'`. `'metric'` means + * the value is a numeric and `'dimension'` means it is + * a string. Also, `'metric'` values will be displayed + * under **Visit (metrics)** in the Segment Editor. + * - **category**: The segment category name. This can be an existing + * segment category visible in the segment editor. + * - **name**: The pretty name of the segment. Can be a translation token. + * - **segment**: The segment name, eg, `'visitIp'` or `'searches'`. + * - **acceptedValues**: A string describing one or two exacmple values, eg + * `'13.54.122.1, etc.'`. + * - **sqlSegment**: The table column this segment will segment by. + * For example, `'log_visit.location_ip'` for the + * **visitIp** segment. + * - **sqlFilter**: A PHP callback to apply to segment values before + * they are used in SQL. + * - **permission**: True if the current user has view access to this + * segment, false if otherwise. * @param array $idSites The list of site IDs we're getting the available segments * for. Some segments (such as Goal segments) depend on the * site. diff --git a/plugins/API/ProcessedReport.php b/plugins/API/ProcessedReport.php index 79fca329c0a..910623a8589 100644 --- a/plugins/API/ProcessedReport.php +++ b/plugins/API/ProcessedReport.php @@ -87,27 +87,49 @@ public function getReportMetadata($idSites, $period = false, $date = false, $hid $availableReports = array(); /** - * Triggered when gathering the metadata for all available reports. + * 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. * - * TODO: list all information that is required in $availableReports. - * * @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 report depend on this data. + * getting reports for. Some reports depend on this data. * For example, Goals reports depend on the site IDs being - * request. Contains the following information: + * 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 */ Piwik::postEvent('API.getReportMetadata', array(&$availableReports, $parameters)); foreach ($availableReports as &$availableReport) { @@ -134,7 +156,8 @@ public function getReportMetadata($idSites, $period = false, $date = false, $hid * 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. + * @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 diff --git a/plugins/Goals/Goals.php b/plugins/Goals/Goals.php index 9f63cd39dcb..5a5de35886e 100644 --- a/plugins/Goals/Goals.php +++ b/plugins/Goals/Goals.php @@ -364,14 +364,31 @@ static private function getAllReportsWithGoalMetrics() /** * Triggered when gathering all reports that contain Goal metrics. The list of reports - * will be displayed on the left column of the bottom of the Goals Overview page and - * each individual Goal page. + * will be displayed on the left column of the bottom of every _Goals_ page. * - * If plugins define reports that contain Goal metrics (such as conversions or revenue), - * they can use this event to make sure their reports can be loaded on the relevant - * Goals pages. + * If plugins define reports that contain goal metrics (such as **conversions** or **revenue**), + * they can use this event to make sure their reports can be viewed on Goals pages. * - * @param array &$reportsWithGoals The list of reports that have Goal metrics. + * **Example** + * + * public function getReportsWithGoalMetrics(&$reports) + * { + * $reports[] = array( + * 'category' => Piwik::translate('MyPlugin_myReportCategory'), + * 'name' => Piwik::translate('MyPlugin_myReportDimension'), + * 'module' => 'MyPlugin', + * 'action' => 'getMyReport' + * ); + * } + * + * @param array &$reportsWithGoals The list of arrays describing reports that have Goal metrics. + * Each element of this array must be an array with the following + * properties: + * + * - **category**: The report category. This should be a translated string. + * - **name**: The report's translated name. + * - **module**: The plugin the report is in, eg, `'UserCountry'`. + * - **action**: The API method of the report, eg, `'getCountry'`. */ Piwik::postEvent('Goals.getReportsWithGoalMetrics', array(&$reportsWithGoals)); diff --git a/plugins/Live/API.php b/plugins/Live/API.php index 5d0c685fb30..e80145b5637 100644 --- a/plugins/Live/API.php +++ b/plugins/Live/API.php @@ -380,7 +380,7 @@ public function getVisitorProfile($idSite, $visitorId = false, $segment = false, * - **visitorAvatar**: A URL to an image to display in the top left corner of the popup. * - **visitorDescription**: Text to be used as the tooltip of the avatar image. * - * @param array &$visitorProfile The normal visitor profile info. + * @param array &$visitorProfile The unaugmented visitor profile info. */ Piwik::postEvent('Live.getExtraVisitorDetails', array(&$result)); diff --git a/plugins/Overlay/API.php b/plugins/Overlay/API.php index 8fd8f26a0b7..cd6e4f67543 100644 --- a/plugins/Overlay/API.php +++ b/plugins/Overlay/API.php @@ -107,7 +107,7 @@ public function getFollowingPages($url, $idSite, $period, $date, $segment = fals private function authenticate($idSite) { /** - * Triggered shortly before the user is authenticated. + * Triggered immediately before the user is authenticated. * * This event can be used by plugins that provide their own authentication mechanism * to make that mechanism available. Subscribers should set the `'auth'` object in @@ -122,7 +122,7 @@ private function authenticate($idSite) * Registry::set('auth', new LDAPAuth($allowCookieAuthentication)); * } * - * @param bool $allowCookieAuthentication Whether authentication based on $_COOKIE values should + * @param bool $allowCookieAuthentication Whether authentication based on `$_COOKIE` values should * be allowed. */ Piwik::postEvent('Request.initAuthenticationObject', array($allowCookieAuthentication = true)); diff --git a/plugins/Provider/Provider.php b/plugins/Provider/Provider.php index 52cfd4105fc..cab62213433 100644 --- a/plugins/Provider/Provider.php +++ b/plugins/Provider/Provider.php @@ -166,21 +166,23 @@ private function getCleanHostname($hostname) $cleanHostname = null; /** - * Triggered when prettifying a hostname string. depending on a given hostname. + * Triggered when prettifying a hostname string. * * This event can be used to customize the way a hostname is displayed in the * Providers report. * * **Example** * - * ``` - * public function getCleanHostname(&$cleanHostname, $hostname) - * { - * if ('fvae.VARG.ceaga.site.co.jp' == $hostname) { - * $cleanHostname = 'site.co.jp'; + * public function getCleanHostname(&$cleanHostname, $hostname) + * { + * if ('fvae.VARG.ceaga.site.co.jp' == $hostname) { + * $cleanHostname = 'site.co.jp'; + * } * } - * } - * ``` + * + * @param string &$cleanHostname The hostname string to display. Set by the event + * handler. + * @param string $hostname The full hostname. */ Piwik::postEvent('Provider.getCleanHostname', array(&$cleanHostname, $hostname)); if ($cleanHostname !== null) { diff --git a/plugins/ScheduledReports/API.php b/plugins/ScheduledReports/API.php index bb4bcd9b797..4970c0593a2 100644 --- a/plugins/ScheduledReports/API.php +++ b/plugins/ScheduledReports/API.php @@ -386,16 +386,15 @@ public function generateReport($idReport, $date, $language = false, $outputType /** * Triggered when generating the content of scheduled reports. * - * This event can be used to modify the content of processed report data or - * metadata, either for one specific report/report type/output format or all - * of them. + * This event can be used to modify the report data or report metadata of one or more reports + * in a scheduled report, before the scheduled report is rendered and delivered. * * TODO: list data available in $report or make it a new class that can be documented (same for * all other events that use a $report) * * @param array &$processedReports The list of processed reports in the scheduled - * report. Includes report data and metadata. - * @param string $reportType A string ID describing how the report is sent, eg, + * report. Entries includes report data and metadata for each report. + * @param string $reportType A string ID describing how the scheduled report will be sent, eg, * `'sms'` or `'email'`. * @param string $outputType The output format of the report, eg, `'html'`, `'pdf'`, etc. * @param array $report An array describing the scheduled report that is being @@ -409,10 +408,10 @@ public function generateReport($idReport, $date, $language = false, $outputType $reportRenderer = null; /** - * Triggered when obtaining a renderer instance based on the scheduled report type. + * Triggered when obtaining a renderer instance based on the scheduled report output format. * - * Plugins that provide new scheduled report backends should use this event to - * handle their new report types. + * Plugins that provide new scheduled report output formats should use this event to + * handle their new report formats. * * @param ReportRenderer &$reportRenderer This variable should be set to an instance that * extends {@link Piwik\ReportRenderer} by one of the event @@ -523,8 +522,8 @@ public function sendReport($idReport, $period = false, $date = false) /** * Triggered when sending scheduled reports. * - * Plugins that provide new scheduled report backends should use this event to - * send the scheduled report uses their backend. + * Plugins that provide new scheduled report transport mediums should use this event to + * send the scheduled report. * * @param string $reportType A string ID describing how the report is sent, eg, * `'sms'` or `'email'`. @@ -538,7 +537,7 @@ public function sendReport($idReport, $period = false, $date = false) * scheduled report. * @param string $reportSubject A string describing what's in the scheduled * report. - * @param string $reportTitle The scheduled report's given title. + * @param string $reportTitle The scheduled report's given title (given by a Piwik user). * @param array $additionalFiles The list of additional files that should be * sent with this report. */ @@ -591,8 +590,8 @@ private static function validateReportParameters($reportType, $parameters) /** * Triggered when gathering the available parameters for a scheduled report type. * - * Plugins that provide their own scheduled reports backend should use this - * event to list the available report parameters for their backend. + * Plugins that provide their own scheduled report transport mediums should use this + * event to list the available report parameters for their transport medium. * * @param array $availableParameters The list of available parameters for this report type. * This is an array that maps paramater IDs with a boolean @@ -733,13 +732,15 @@ static public function getReportMetadata($idSite, $reportType) $availableReportMetadata = array(); /** + * TODO: change this event so it returns a list of API methods instead of report metadata arrays. * Triggered when gathering the list of Piwik reports that can be used with a certain - * scheduled reports backend. + * transport medium. * - * Plugins that provide their own scheduled reports backend should use this + * Plugins that provide their own transport mediums should use this * event to list the Piwik reports that their backend supports. * - * @param array &$availableReportMetadata + * @param array &$availableReportMetadata An array containg report metadata for each supported + * report. * @param string $reportType A string ID describing how the report is sent, eg, * `'sms'` or `'email'`. * @param int $idSite The ID of the site we're getting available reports for. @@ -760,10 +761,10 @@ static public function allowMultipleReports($reportType) $allowMultipleReports = null; /** - * Triggered when we're determining if a scheduled report backend can + * Triggered when we're determining if a scheduled report transport medium can * handle sending multiple Piwik reports in one scheduled report or not. * - * Plugins that provide their own scheduled reports backend should use this + * Plugins that provide their own transport mediums should use this * event to specify whether their backend can send more than one Piwik report * at a time. * @@ -787,14 +788,13 @@ static public function getReportTypes() $reportTypes = array(); /** - * Triggered when gathering all available scheduled report backend types. + * Triggered when gathering all available transport mediums. * - * Plugins that provide their own scheduled reports backend should use this - * event to make their backend available. + * Plugins that provide their own transport mediums should use this + * event to make their medium available. * - * @param array &$reportTypes An array mapping string IDs for each available - * scheduled report backend with icon paths for those - * backends. Add your new backend's ID to this array. + * @param array &$reportTypes An array mapping transport medium IDs with the paths to those + * mediums' icons. Add your new backend's ID to this array. */ Piwik::postEvent(self::GET_REPORT_TYPES_EVENT, array(&$reportTypes)); @@ -817,6 +817,8 @@ static public function getReportFormats($reportType) * @param array &$reportFormats An array mapping string IDs for each available * scheduled report format with icon paths for those * formats. Add your new format's ID to this array. + * @param string $reportType A string ID describing how the report is sent, eg, + * `'sms'` or `'email'`. */ Piwik::postEvent( self::GET_REPORT_FORMATS_EVENT, @@ -836,8 +838,8 @@ static public function getReportRecipients($report) /** * Triggered when getting the list of recipients of a scheduled report. * - * Plugins that provide their own scheduled report backend should use this event - * so the list of recipients can be extracted from their backend's specific report + * Plugins that provide their own scheduled report transport medium should use this event + * to extract the list of recipients their backend's specific scheduled report * format. * * @param array &$recipients An array of strings describing each of the scheduled @@ -936,4 +938,4 @@ private function createAttachment($report, $processedReport, $prettyDate) return $additionalFile; } -} +} \ No newline at end of file diff --git a/plugins/UsersManager/API.php b/plugins/UsersManager/API.php index a1beb26f0bb..2d713b225d5 100644 --- a/plugins/UsersManager/API.php +++ b/plugins/UsersManager/API.php @@ -653,8 +653,8 @@ private function deleteUserOnly($userLogin) /** * Triggered after a user has been deleted. * - * This event should be used to clean up any data that is related to the user that was - * deleted. For example, the Dashboard plugin uses this event to remove the user's dashboards. + * This event should be used to clean up any data that is related to the now deleted user. + * The **Dashboard** plugin, for example, uses this event to remove the user's dashboards. * * @param string $userLogin The login handle of the deleted user. */ diff --git a/tests/PHPUnit/UI b/tests/PHPUnit/UI index 4df88a1f66a..673d21c6a75 160000 --- a/tests/PHPUnit/UI +++ b/tests/PHPUnit/UI @@ -1 +1 @@ -Subproject commit 4df88a1f66a102521cf5ec459b90be780f2c3514 +Subproject commit 673d21c6a750d8280f4e9ab9d203072dd8d844d2