Extension:Echo/Creating a new notification type

From mediawiki.org

The Notifications system allows logged in users to receive alerts and notices about their interactions with connected wikis. In Wikimedia projects, users receive cross-wiki notifications from almost all wikis in the cluster. However, the Notifications system can also be used by third-parties. Third parties can install it on a single wiki or on a series of connected wikis (using the cross-wiki notification system).

Video tutorial on how to create new notification types from the 2017 Wikimedia Developer Summit.

The system allows extension developers the ability to add new notification types that users can receive under certain circumstances. This document will outline the way to create such notifications, explain best practices and formulate the known pitfalls to avoid.

Introduction to how notifications work[edit]

Notifications are, very generally, made of two concepts - the Event and the PresentationModel. The event stores details of the triggered event and the presentation model defines the way it is presented in the user interface.


The EchoEvent class defines general events, collects information about the related page, user and wiki and inserts them into the database. Events are general, and one even may define multiple views. For example, mentioning 4 people will create a single event, that will then be referenced (and 'trigger' a notification) for the four mentioned users. All of their individual notifications, however, will reference the same event.


Every type of notification requires a presentation model, a way to define what the notification will display, where it will link to, and what secondary actions it will present. The front-end components of the notifications system (the notifications popup and the Special:Notifications page) read that information to produce a proper display of the notification.

The presentation of a notification type is always based on the base definition in EchoEventPresentationModel. That class defines the base behavior of all notifications, and each child notification must extend it, and then adjust the details to its needs.

How events work[edit]

If you are creating a new notification type, you should first create an event. The logical process is:

  1. When relevant, your code creates the event using EchoEvent::create()
    1. As part of the definition of the event you should detail which users receive a notification from this event. This is defined by the parameter 'user-locators' => array( ... ) (For an example of this, see Flow's 'user-locators' method used to locate users who are following a title)
    2. The event is stored in the database, and as notifications for the relevant users
    3. When users request their notification list from the API, the system looks for the relevant presentation model and creates the data - title, primary link, secondary links, relevant user, etc.
    4. The front-end uses the structured data to present the notification.
This is a slight generalization of the process for the sake of clarity. Explaining how things work in practice with database table rows (per user, wiki, cross-wiki, etc) is outside the scope of this tutorial.


Event definition[edit]

Event definitions happen in the method that responds to the BeforeCreateEchoEvent hook. That hook includes three variables: $notifications, $notificationCategories, $icons.

Defining the event category[edit]

Users are generally allowed to check/uncheck the option of receiving notifications in web or email in the preferences. The preference category has a tooltip, and should be defined with $notificationCategories. The category name is used as the key, and is what the event definition then refers to in the "category" parameter. You also need to define a message with the name echo-category-title-my-category, replacing my-category with the actual category name. This is used in Special:Preferences under the Notifications tab.

Defining the notification icon[edit]

Notifications appear with icons. If an icon is not set up, a default icon will appear. If the icon is a new one, it must be loaded and defined using $icons.

Define the icon using the full url of the icon: $icons[ 'iconName' ]['url'] = '//example.org/icon.svg";

Alternatively, you can use a file path that is relative to relative to $wgExtensionAssetsPath : $icons[ 'iconName' ]['path'] = 'extensionPath/to/icon.svg";

Defining the event information[edit]

Parameter Required Description
category yes The category this event belongs to.

This is important for displaying in the Special:Preferences page

section yes Defines the section this notification belongs to.

There are two types, Alerts and Notices. Alerts are for urgent notifications that should be dealt with promptly, e.g. a post on the user's talk page. Notices are for notifications that do not have to be dealt with promptly, e.g. a thank. For Alerts, put 'alert'. For Notices, put 'message'

presentation-model yes Class for the presentation model for this event display
user-locators yes Defines functions that produce the list of users to notify
group no Group this with similar notifications.

Known groups in Echo core are: 'positive', 'negative', 'interactive', 'neutral'. If one is not specified, 'neutral' is used.

user-filters[Pitfalls 1] no Defines functions that produce the list of users to not notify.
immediate no Whether to use the job queue or not.

Boolean, default is to use the job queue (i.e. false)

Event creation details[edit]

When we create and trigger the event, we need to supply details as well:

Parameter Required Description
type yes The name of the event, the key we used to define the event by adding it to &$notifications in the BeforeCreateEchoEvent hook
title no The related title, if relevant.
extra no An array of extra definitions for Echo and the presentation model to use
agent no The user that originated this notification (note: This is not the user that is being notified!)

Presentation model definition[edit]

Presentation models are meant to be very flexible, so as to allow the creation of notification types with specific displays. Unlike event definition and creation, the presentation model is a class on its own, and requires extending it and making the methods specific to the notification case. These are the definitions of the base EchoEventPresentationModel class:

Method Default value Description
canRender[Pitfalls 2] true Defines the conditions under which this notification can be rendered.

For example, you can check if a page has been deleted, and if so, don't show the notification. A common use is if the notification uses $this->title of the page anywhere (for header message or for links) the canRender() must check whether $this->title is set.

getIconType Must be overridden Defines the symbolic name of the icon for this notification (as defined in $wgEchoNotificationIcons)
getHeaderMessage A message based on default key notification-header-{$this->type} Defines the i18n message for the header
getCompactHeaderMessage If not defined, uses getHeaderMessage() Defines the i18n message for the header in cases where the notification is "compact" (for example, inside a bundle or a cross-wiki group.)
getSubjectMessage If not defined, uses getHeaderMessage() Defines the i18n message for notification email subject line
getBodyMessage false Defines the i18n message for the notification body.


getPrimaryLink Must be overridden Defines the primary link for this notification.

For a primary link definition, use the structure ['url' => (string) url, 'label' => (string) link text (non-escaped)] (the 'label' is used for no-JavaScript versions)

If there is no primary link, return false.

getSecondaryLinks[Pitfalls 3] array(); Defines secondary actions

Structure of secondary links[edit]

The secondary links information allows notifications to specify sub-links to actions that are extending the main primary link for the notification. For example, a notification about some revision edit can have its primary link point to the revision diff page, but also have secondary links pointing for the user page of the user who made the change, or a link to view the page that was changed.

Secondary links also allow API-directed actions ('dynamic' actions) for actions like 'stop watching a page' or others that require the front-end to request an AJAX request to the API directly from the notification. Further details about dynamic actions are outside the scope of this tutorial.

The general structure of secondary links:

public function getSecondaryLinks() {
    return [
            'url' => (string) url,
            'label' => (string) link text (non-escaped),
            'description' => (string) descriptive text (optional, non-escaped),
            'icon' => (bool|string) symbolic ooui icon name (or false if there is none),

Walkthrough: Creating a new notification type[edit]

Let's say we have an extension that keeps a list of users who are interested in new titles created with specific words in them. The extension allows users to add and remove themselves from a watch-list for a certain list of words in a title, and listens to the hook for creating new pages on the wiki to identify relevant pages. When a relevant page is created, the extension code will create an event with the relevant details, and notify the users that are on the list for that combination of words.

This section will demonstrate how to create this new notification type.

Defining the event[edit]

We need to make sure our event is defined in the system. This is done by listening to the hook BeforeCreateEchoEvent and defining the event definition:

class MyExtHooks {

    public static function onBeforeCreateEchoEvent(
		&$notifications, &$notificationCategories, &$icons
	) {
	    // Define the category this event belongs to
	    // (this will appear in Special:Preferences)
	    $notificationCategories['my-ext-topic-word-follow'] = [
			'priority' => 3,
			'tooltip' => 'echo-pref-tooltip-my-ext-topic-word-follow',

	    // Define the event
        $notifications['my-ext-topic-word'] = [
    		'category' => 'my-ext-topic-word-follow',
    		'group' => 'positive',
    		'section' => 'alert',
    		'presentation-model' => EchoMyExtTopicWordPresentationModel::class,
    		'bundle' => [
    			'web' => true,
    			'expandable' => true,
            'user-locators' => [ 'MyExtensionClass::locateUsersInList' ],
            // We might want to add a filter to remove mentioned users here, because
            // a page may have been created with mentions - and we don't want the
            // mentioned user to be notified twice. (This is an implementation choice
            // of course - 'user-filters' is not mandatory)
            'user-filters' => [ 'MyExtensionClass::locateMentionedUsers' ]

        // Define the icon to use for this notification
        // You can use existing icons in Echo, but if the icon is
        // new, you must define it
		$icons['my-ext-topic-word'] = [
			// You can provide a url that will not be qualified
			'url' => 'http://example.org/icon.svg'
			// If a url is not given, then a Echo will look for a path
			'path' => 'MyExt/icons/TopicWordNotification.svg',
			// If neither a url or path is given then a placeholder will be used

You can see another example of this in the Thanks extension.

Identify relevant users to notify[edit]

The Notifications system will try to notify relevant users, but it can't guess who those are. The code that creates the event needs to supply that information. To do that, we should create a function that is then inserted into the definition of the new event.

In this case, we will want to go over the list of users and add them all:

class MyExtensionClass {

     * @param EchoEvent $event
     * @return array
    public function locateUsersInList( EchoEvent $event ) {
        // Get the list of users
        $userIds = $this->getList( $event )->getUsers();
        return array_map( function ( $userId ) {
            return User::newFromId( $userId );
        }, $userIds );


Adding code to trigger the event[edit]

Now that we have a way to identify who we want to notify, we need to actually trigger this event. Our hypothetical extension listens to page creation hook and then checks to see if the new title has words that fit the list. However the extension code does this, once it identifies a title that fits a list, it will create an event and notify the relevant users.

The code below skips the actual operation of listening to new page creation and checking the words, and jumps straight into defining the new event:

// ...
// Some code to listen to new page creation, check words
// and find the relevant list
// ...

// Creating the event
EchoEvent::create( [
	'type' => 'my-ext-topic-word',
	'title' => $title,
	'extra' => [
		'revid' => $revision->getId(),
		'source' => $source,
		'excerpt' => EchoDiscussionParser::getEditExcerpt( $revision, $this->getLanguage() ),
	'agent' => $user,
] );

You can see an example of filtering out mentioned users in Flow's event for flow-new-topic.

Creating a presentation model[edit]

Now that everything is set up, we can create our presentation model. We will have to extend EchoEventPresentationModel and implement our methods. You can see a few examples of these type of models in several extensions like Flow [1][2][3][4], Thanks and inside Echo [5][6][7] itself.

Here's an example of a presentation model for our hypothetical extension:

class EchoMyExtTopicWordPresentationModel extends EchoEventPresentationModel {
	public function canRender() {
	    // Define that we have to have the page this is
	    // refering to as a condition to display this
	    // notification
		return (bool)$this->event->getTitle();
	public function getIconType() {
	    // You can use existing icons in Echo icon folder
	    // or define your own through the $icons variable
	    // when you define your event in BeforeCreateEchoEvent
		return 'someIcon';
	public function getHeaderMessage() {
		if ( $this->isBundled() ) {
		    // This is the header message for the bundle that contains
		    // several notifications of this type
			$msg = $this->msg( 'notification-bundle-myext-topic-word' );
			$msg->params( $this->getBundleCount() );
			$msg->params( $this->getTruncatedTitleText( $this->event->getTitle(), true ) );
			$msg->params( $this->getViewingUserForGender() );
			return $msg;
		} else {
		    // This is the header message for individual non-bundle message
			$msg = $this->getMessageWithAgent( 'notification-myext-topic-word' );
			$msg->params( $this->getTruncatedTitleText( $this->event->getTitle(), true ) );
			$msg->params( $this->getViewingUserForGender() );
			return $msg;
	public function getCompactHeaderMessage() {
	    // This is the header message for individual notifications
	    // *inside* the bundle
		$msg = parent::getCompactHeaderMessage();
		$msg->params( $this->getViewingUserForGender() );
		return $msg;
	public function getBodyMessage() {
	    // This is the body message.
        // We will retrieve the edit summary that we added earlier with EchoEvent::create().
		$comment = $this->event->getExtraParam( 'excerpt', false );
		if ( $comment ) {
			// Create a dummy message to contain the excerpt.
			$msg = new RawMessage( '$1' );
			$msg->plaintextParams( $comment );
			return $msg;
	public function getPrimaryLink() {
	    // This is the link to the new page
	    $link = $this->getPageLink( $this->event->getTitle(), '', true );
        return $link;

	public function getSecondaryLinks() {
		if ( $this->isBundled() ) {
		    // For the bundle, we don't need secondary actions
			return [];
		} else {
		    // For individual items, display a link to the user
		    // that created this page
			return [ $this->getAgentLink() ];

And that's it! Our new notification is now active and will be displayed to the relevant users with the header and body messages and the primary and secondary links we defined.

How to bundle notifications[edit]

  • Make sure your bundle config is set to true in the echo event definition:
    $notifications['my-ext-topic-word'] = [
    		'bundle' => [
    			'web' => true,        // Bundle when rendering on the web?
    			'email' => true,      // Bundle in emails?
    			'expandable' => true, // Make bundles expandable?
            // More stuff here
  • Add a hook for bundling rules:
public static function onEchoGetBundleRules( $event, &$bundleString ) {
    switch ( $event->getType() ) {
        case 'my-ext-topic-word':            // Your notification type. This
                                             // is the key you set for the
                                             // first parameter in your
                                             // BeforeCreateEchoEvent hook.
            $bundleString = 'my-ext-topic';  // Which messages go into which
                                             // bundle. For the same bundle,
                                             // return the same $bundleString.
    return true;
  • Hook up the function in extension.json:
    "Hooks": {
        "BeforeCreateEchoEvent": [
        "EchoGetBundleRules": [
        // More stuff here
  • You can use $this->isBundled() in your presentation model code to check if you're in a bundled notification, and vary the header and body messages accordingly:
public function getHeaderMessage() {
    if ( $this->isBundled() ) {
        $msg = $this->msg( 'something' );
        return $msg;
    } else {
  • When an expandable bundle is expanded, each sub-notification is rendered individually. By default getHeaderMessage() is displayed, but it is recommended that you supply a shorter message in your presentation model code for this case using getCompactHeaderMessage():
public function getCompactHeaderMessage() {
    return $this->msg( 'somethingshort' );

And you're done! Don't forget to add your messages. Also note that bundles may or may not be expandable.

Pitfalls and warnings[edit]

  1. The role of user-locators and user-filters is important to make sure we don't produce double-notification from a single event to users. For example, if a new topic is created in Flow, we want to notify all those who follow the board - but we want to ignore users who were mentioned, because 'mention' will produce its own event.
    When you create new events, try to make sure you filter out potential colliding events for your notified users, otherwise, they will receive two notifications for the same event.
  2. Note that canRender is an incredibly important method. On top of affecting whether the notification is displayed, it is also part of the test the Notifications system uses to moderate notifications. For example, if a notification was created about a new mention for a user, but the revision that triggered this was then deleted or suppressed, the notification should vanish as well. The system will check if the notification can be displayed (using, among other things, 'canRender') - if canRender in this case checks that the revision exists, it will return 'false' (because the revision was deleted) which will make sure the notification is flagged for deletion. Not defining canRender correctly can result in errors, as the notification will try to call for details on a missing title or revision, so please take care to define it if it is needed.
  3. getSecondaryLinks must return an array. If your notification only has secondary links in certain cases, please make sure that all other cases return an array and not 'false' or 'null'; unlike getPrimaryLink that returns false for empty value, getSecondaryLinks must return an array.

Notes and references[edit]