Notifications
- Il existe deux manières d’envoyer des notifications dans Elgg :
Notifications instantanées
Les notifications basées sur les événements sont envoyées à l’aide d’une file d’attente de notifications
Contenu
Notifications instantanées
La méthode générique pour envoyer une notification à un utilisateur utilise la fonction notify_user(). Celle-ci devrait être principalement utilisée lorsque nous voulons notifier un seul utilisateur. Une notification comme celle-ci peut, par exemple, informer que quelqu’un a aimé ou commenté la publication de l’utilisateur.
La fonction est habituellement appelée dans un fichier d”action.
Exemple :
Dans cet exemple, un utilisateur ($user
) déclenche une action pour noter une publication créée par un autre utilisateur ($owner
). Après avoir enregistré la note (ElggAnnotation $rating
) dans la base de données, nous pourrions utiliser le code suivant pour envoyer une notification concernant cette nouvelle note au propriétaire.
// Subject of the notification
$subject = elgg_echo('ratings:notification:subject', array(), $owner->language);
// Summary of the notification
$summary = elgg_echo('ratings:notification:summary', array($user->getDisplayName()), $owner->language);
// Body of the notification message
$body = elgg_echo('ratings:notification:body', array(
$user->getDisplayName(),
$owner->getDisplayName(),
$rating->getValue() // A value between 1-5
), $owner->language);
$params = array(
'object' => $rating,
'action' => 'create',
'summary' => $summary
);
// Send the notification
notify_user($owner->guid, $user->guid, $subject, $body, $params);
Note
La langue utilisée par le destinataire n’est pas nécessairement la même que celle de la personne qui déclenche la notification. Par conséquent, vous devez toujours penser à transmettre la langue du destinataire en tant que troisième paramètre à elgg_echo()
.
Note
Le paramètre 'summary'
est destiné aux plugins de notification qui ne souhaitent afficher qu’un message court au lieu du sujet et du corps de message. Par conséquent, le résumé doit être laconique, mais toujours contenir toutes les informations nécessaires.
Notifications en file d’attente
Sur les grands sites, il peut y avoir de nombreux utilisateurs qui se sont abonnés pour recevoir des notifications lors d’un événement particulier. L’envoi immédiat de notifications lorsqu’un utilisateur déclenche un tel événement peut ralentir considérablement la vitesse de chargement des pages. C’est pourquoi l’envoi de ces notifications devrait être mis dans la file d’attente de notification de Elgg.
De nouveaux événements de notification peuvent être enregistrés avec la fonction elgg_register_notification_event()
ou dans la configuration de elgg-plugin. Des notifications sur les événements enregistrés seront envoyées automatiquement à tous les utilisateurs abonnés.
Voici le workflow du système de notifications :
- Quelqu’un effectue une action qui déclenche un événement au sein de Elgg
L’action peut être
create
,update
oudelete
La cible de l’action peut être n’importe quelle instance de la classe
ElggEntity
(par exemple un article de blog)Le système de notifications enregistre cet événement dans une file d’attente de notifications dans la base de données
When the event handler for the one-minute interval gets triggered, the event is taken from the queue and it gets processed
- Les abonnements sont récupérés pour l’utilisateur qui a déclenché l’événement
Par défaut, ceci comprend tous les utilisateurs qui ont activé au moins une méthode de notification pour les utilisateurs via
www.site.com/notifications/personal/<username>
Plugins are allowed to alter the subscriptions using the
[get, subscriptions]
eventPlugins are allowed to terminate notifications queue processing with the
[send:before, notifications]
eventPlugins are allowed to alter the notification parameters with the
[prepare, notification]
eventPlugins are allowed to alter the notification subject/message/summary with the
[prepare, notification:<action>:<type>:<subtype>]
eventPlugins are allowed to format notification subject/message/summary for individual delivery methods with
[format, notification:<method>]
event
- Les notifications sont envoyées à chaque abonné en utilisant les méthodes qu’il a choisies
Plugins can take over or prevent sending of each individual notification with the
[send, notification:<method>]
eventThe
[send:after, notifications]
event is triggered for the event after all notifications have been sent
Exemple d’enregistrement d’un événement de notification
Indiquez à Elgg d’envoyer des notifications lorsqu’un nouvel objet de sous-type photo
est créé :
/**
* Initialize the photos plugin
*/
function photos_init() {
elgg_register_notification_event('object', 'photo', array('create'));
}
Ou dans elgg-plugin.php
'notifications' => [
'object' => [
'photo' => [
'create' => true,
],
],
],
Note
Pour envoyer les notifications lors des événements, vous devez configurer l’intervalle CRON d’une minute.
Contents of the notification message can be defined with the
'prepare', 'notification:[action]:[type]:[subtype]'
event.
Exemple d’enregistrement d’un événement de notification personnalisé
Indiquer à Elgg d’envoyer des notifications lorsqu’un nouvel objet de sous-type album
est créé :
// in the elgg-plugin.php
'notifications' => [
'object' => [
'photo' => [
'create' => PhotoAlbumCreateNotificationHandler::class, // this needs to be an extension of the \Elgg\Notifications\NotificationEventHandler class
],
],
],
//PhotoAlbumCreateNotificationHandler.php
class PhotoAlbumCreateNotificationHandler extends \Elgg\Notifications\NotificationEventHandler {
/**
* Overrule this function if you wish to modify the subscribers of this notification
*
* This will influence which subscribers are available in the 'get', 'subscribers' event
*/
public function getSubscriptions(): array {
}
/**
* Overrule this function if you wish to modify the subject of the notification
*
* A magic language key is checked for a default notification:
* 'notification:<action>:<type>:<subtype>:subject'
*/
protected function getNotificationSubject(\ElggUser $recipient, string $method): string {
}
/**
* Overrule this function if you wish to modify the body of the notification
*
* A magic language key is checked for a default notification:
* 'notification:<action>:<type>:<subtype>:body'
*/
protected function getNotificationBody(\ElggUser $recipient, string $method): string {
}
/**
* Overrule this function if you wish to modify the summary of the notification
*
* default: ''
*/
protected function getNotificationSummary(\ElggUser $recipient, string $method): string {
}
/**
* Overrule this function if you wish to modify the target url of the notification
*
* default: $event->object->getURL()
*/
protected function getNotificationURL(\ElggUser $recipient, string $method): string {
}
/**
* Overrule this function if you don't wish to allow the notification event to be configurable on the user notification settings page
*
* default: true
*/
public static function isConfigurableByUser(): bool {
}
}
Note
Assurez-vous que la notification sera dans la bonne langue en passant la langue du destinataire à la fonction elgg_echo()
.
Exemple de contenu de notification personnalisé
Indique à Elgg d’utiliser la fonction photos_prepare_notification()
pour formater le contenu de la notification quand un nouvel objet de sous-type “photo” est créé :
/**
* Initialize the photos plugin
*/
function photos_init() {
elgg_register_notification_event('object', 'photo', array('create'));
elgg_register_event_handler('prepare', 'notification:create:object:photo', 'photos_prepare_notification');
}
/**
* Prepare a notification message about a new photo
*
* @param \Elgg\Event $event 'prepare', 'notification:create:object:photo'
* @return \Elgg\Notification\Notification
*/
function photos_prepare_notification(\Elgg\Event $event) {
$notification_event = $event->getParam('event');
$entity = $notification_event->getObject();
$owner = $notification_event->getActor();
$recipient = $event->getParam('recipient');
$language = $event->getParam('language');
$method = $event->getParam('method');
/* @var $notification \Elgg\Notification\Notification */
$notification = $event->getValue();
// Title for the notification
$notification->subject = elgg_echo('photos:notify:subject', [$entity->getDisplayName()], $language);
// Message body for the notification
$notification->body = elgg_echo('photos:notify:body', array(
$owner->getDisplayName(),
$entity->getDisplayName(),
$entity->getExcerpt(),
$entity->getURL()
), $language);
// Short summary about the notification
$notification->summary = elgg_echo('photos:notify:summary', [$entity->getDisplayName()], $language);
return $notification;
}
Note
Make sure the notification will be in the correct language by passing
the recipient’s language into the elgg_echo()
function.
Salutation et signature de la notification
Elgg will by default prepend a salutation to all outgoing notification body text. Also a sign-off will be appended.
This means you will not need to add text like Hi Admin,
or Kind regards, your friendly site administrator
to your notifications body.
If for some reason you do not need this magic to happen, you can prevent it by setting the notification parameter add_salutation
to false
.
You can do this as part of the parameters in notify_user()
or in the prepare, notifications
event.
You can change the salutation and sign-off texts in the translations.
Vous pouvez également personnaliser la salutation en remplaçant la vue notifications/elements/salutation
. La signature peut être personnalisée en remplaçant la vue notifications/elements/sign-off
.
Méthodes de notification
Par défaut, Elgg propose trois méthodes de notification : email, delayed_email et le plugin site_notifications fourni avec Elgg.
E-mail
Enverra une notification par e-mail au destinataire.
E-mail différé
Enregistre les notifications pour les envoyer dans un e-mail groupé à l’intervalle configuré par le destinataire (quotidien ou hebdomadaire).
La disponibilité de cette méthode d’envoi peut être configurée par l’administrateur du site dans la section Paramètres du site.
La mise en page de l’e-mail groupé peut être personnalisée en remplaçant la vue email/delayed_email/plain_text
pour la partie en texte brut de l’e-mail et email/delayed_email/html
pour la partie HTML de l’e-mail.
Notification sur le site
Affichera la notification sur le site.
Enregistrement d’une nouvelle méthode de notification
Vous pouvez enregistrer une nouvelle méthode de notification avec la fonction elgg_register_notification_method()
.
Exemple :
Enregistrez un gestionnaire qui enverra les notifications par SMS.
/**
* Initialize the plugin
*/
function sms_notifications_init() {
elgg_register_notification_method('sms');
}
Après avoir enregistré la nouvelle méthode, celle-ci apparaîtra sur la page des paramètres de notification à l’adresse www.example.com/notifications/personal/[username]
.
Envoyer des notifications avec votre propre méthode
Besides registering the notification method, you also need to register
a handler that takes care of actually sending the SMS notifications.
This happens with the 'send', 'notification:[method]'
event.
Exemple :
/**
* Initialize the plugin
*/
function sms_notifications_init () {
elgg_register_notification_method('sms');
elgg_register_event_handler('send', 'notification:sms', 'sms_notifications_send');
}
/**
* Send an SMS notification
*
* @param \Elgg\Event $event 'send', 'notification:sms'
*
* @return bool
* @internal
*/
function sms_notifications_send(\Elgg\Event $event) {
/* @var \Elgg\Notifications\Notification $message */
$message = $event->getParam('notification');
$recipient = $message->getRecipient();
if (!$recipient || !$recipient->mobile) {
return false;
}
// (A pseudo SMS API class)
$sms = new SmsApi();
return $sms->send($recipient->mobile, $message->body);
}
Abonnements
Dans la plupart des cas, le noyau de Elgg s’occupe de la gestion des abonnements, de sorte que les plugins de notification n’ont généralement pas besoin de les modifier.
- Les abonnements peuvent toutefois être :
Ajoutés à l’aide de la fonction
\ElggEntity::addSubscription()
Supprimés à l’aide de la fonction
\ElggEntity::removeSubscription()
It’s possible to modify the recipients of a notification dynamically with the 'get', 'subscriptions'
event.
Exemple :
/**
* Initialize the plugin
*/
function discussion_init() {
elgg_register_event_handler('get', 'subscriptions', 'discussion_get_subscriptions');
}
/**
* Get subscriptions for group notifications
*
* @param \Elgg\Event $event 'get', 'subscriptions'
*
* @return void|array
*/
function discussion_get_subscriptions(\Elgg\Event $event) {
$reply = $event->getParam('event')->getObject();
if (!$reply instanceof \ElggDiscussionReply) {
return;
}
$subscriptions = $event->getValue();
$group_guid = $reply->getContainerEntity()->container_guid;
$group_subscribers = elgg_get_subscriptions_for_container($group_guid);
return ($subscriptions + $group_subscribers);
}
Notifications en sourdine
Les notifications peuvent être désactivées afin de ne plus recevoir de notifications, par exemple pour ne plus recevoir de notifications concernant de nouveaux commentaires sur une discussion.
Afin de désactiver les notifications, appelez \ElggEntity::muteNotifications($user_guid)
le $user_guid
est par défaut l’utilisateur actuellement connecté. Cela entraînera la suppression de tous les abonnements sur l’entité et un indicateur spécial sera défini pour savoir que les notifications sont désactivées.
Les règles de désactivation sont appliquées après que les abonnés d’un événement de notification ont été demandées et appliquées pour les entités suivantes de l’événement de notification : - l’acteur de l’événement \Elgg\Notifications\NotificationEvent::getActor()
- l’entité objet de l’événement \Elgg\Notifications\NotificationEvent::getObject()
- l’entité conteneur de l’objet de l’événement \Elgg\Notifications\NotificationEvent::getObject()::getContainerEntity()
- l’entité propriétaire de l’objet de l’événement \ Elgg\Notifications\NotificationEvent::getObject()::getOwnerEntity()
Pour réactiver les notifications, appelez \ElggEntity::unmuteNotifications($user_guid)
le $user_guid
est par défaut l’utilisateur actuellement connecté.
Pour vérifier si un utilisateur a les notifications désactivées, appelez \ElggEntity::hasMutedNotifications($user_guid)
le $user_guid
est par défaut l’utilisateur actuellement connecté.
Page d’aide
Une page d’aide a été ajoutée qui peut être liée (par exemple dans un pied de page d’e-mail) pour gérer la désactivation d’une notification particulière.
La page doit être obligatoirement signée et utiliser la route notifications:mute
qui nécessite : - entity_guid
l’entité sur laquelle porte la notification - recipient_guid
le destinataire de la notification
Désactiver temporairement les notifications
Les utilisateurs peuvent désactiver temporairement toutes les notifications en accédant aux paramètres de notification et en définissant une date de début et de fin pour la période pour laquelle ils ne souhaitent pas recevoir de notifications.
Paramètres de notification
Vous pouvez stocker et récupérer les paramètres de notification des utilisateurs avec \ElggUser::setNotificationSetting()
et \ElggUser::getNotificationSettings()
.
// Setting a notification preference
// notification method: mail
// notification is enabled
// for the purpose 'group_join' (when omitted this is 'default')
$user->setNotificationSetting('mail', true, 'group_join');
// retrieving the preference
$settings = $user->getNotificationSettings('group_join');
// this wil result in an array with all the current notification methods and their state like:
// [
// 'mail' => true,
// 'site' => false,
// 'sms' => false,
// ]
Lorsqu’un utilisateur n’a pas encore de paramètre distinct de celui par défaut, le système revient au paramètre de notification “default”.
Gestion des notifications
A generic menu event handler is provided to manage notification subscription and muting. If you wish to make it easy for users to subscribe to
your entities register a menu event on register
menu:<menu name>:<entity type>:<entity subtype>
with the callback
Elgg\Notifications\RegisterSubscriptionMenuItemsHandler
make sure an \ElggEntity
in $params['entity']
is provided.
This will work for most elgg_view_menu()
calls.