Elgg  Version 2.3
notification.php
Go to the documentation of this file.
1 <?php
2 
5 
65 function elgg_register_notification_event($object_type, $object_subtype, array $actions = array()) {
66  _elgg_services()->notifications->registerEvent($object_type, $object_subtype, $actions);
67 }
68 
77 function elgg_unregister_notification_event($object_type, $object_subtype) {
78  return _elgg_services()->notifications->unregisterEvent($object_type, $object_subtype);
79 }
80 
94  _elgg_services()->notifications->registerMethod($name);
95 }
96 
110  return _elgg_services()->notifications->getMethods();
111 }
112 
122  return _elgg_services()->notifications->unregisterMethod($name);
123 }
124 
134 function elgg_add_subscription($user_guid, $method, $target_guid) {
135  $methods = _elgg_services()->notifications->getMethods();
136  $db = _elgg_services()->db;
137  $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
138  return $subs->addSubscription($user_guid, $method, $target_guid);
139 }
140 
150 function elgg_remove_subscription($user_guid, $method, $target_guid) {
151  $methods = _elgg_services()->notifications->getMethods();
152  $db = _elgg_services()->db;
153  $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
154  return $subs->removeSubscription($user_guid, $method, $target_guid);
155 }
156 
172  $methods = _elgg_services()->notifications->getMethods();
173  $db = _elgg_services()->db;
174  $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
175  return $subs->getSubscriptionsForContainer($container_guid);
176 }
177 
194  _elgg_services()->notifications->enqueueEvent($action, $type, $object);
195 }
196 
201  // calculate when we should stop
202  // @todo make configurable?
203  $stop_time = time() + 45;
204  _elgg_services()->notifications->processQueue($stop_time);
205 }
206 
218 
219  if ($result === true) {
220  // assume someone else already sent the message
221  return;
222  }
223 
224  /* @var \Elgg\Notifications\Notification $message */
225  $message = $params['notification'];
226 
227  $sender = $message->getSender();
228  $recipient = $message->getRecipient();
229 
230  if (!$sender) {
231  return false;
232  }
233 
234  if (!$recipient || !$recipient->email) {
235  return false;
236  }
237 
238  $to = $recipient->email;
239 
241  // If there's an email address, use it - but only if it's not from a user.
242  if (!($sender instanceof \ElggUser) && $sender->email) {
243  $from = $sender->email;
244  } else if ($site->email) {
245  $from = $site->email;
246  } else {
247  // If all else fails, use the domain of the site.
248  $token = _elgg_services()->crypto->getRandomBytes(24);
249  $from = "noreply-{$token}@{$site->getDomain()}";
250  }
251 
252  return elgg_send_email($from, $to, $message->subject, $message->body, $params);
253 }
254 
270 
271  if (!is_array($returnvalue) || !is_array($returnvalue['params'])) {
272  // another hook handler returned a non-array, let's not override it
273  return;
274  }
275 
276  $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
277  $url_path = parse_url(elgg_get_site_url(), PHP_URL_PATH);
278 
279  $mt = microtime(true);
280 
281  $returnvalue['headers']['Message-ID'] = "{$url_path}.default.{$mt}@{$hostname}";
282 
283  return $returnvalue;
284 }
296 function _elgg_notifications_smtp_thread_headers($hook, $type, $returnvalue, $params) {
297 
298  if (!is_array($returnvalue) || !is_array($returnvalue['params'])) {
299  // another hook handler returned a non-array, let's not override it
300  return;
301  }
302 
303  $notificationParams = elgg_extract('params', $returnvalue, array());
305  $notification = elgg_extract('notification', $notificationParams);
306 
307  if (!($notification instanceof \Elgg\Notifications\Notification)) {
308  return $returnvalue;
309  }
310 
311  $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
312  $urlPath = parse_url(elgg_get_site_url(), PHP_URL_PATH);
313 
314  $object = elgg_extract('object', $notification->params);
316  $event = elgg_extract('event', $notification->params);
317 
318  if (($object instanceof \ElggEntity) && ($event instanceof \Elgg\Notifications\NotificationEvent)) {
319  if ($event->getAction() === 'create') {
320  // create event happens once per entity and we need to guarantee message id uniqueness
321  // and at the same time have thread message id that we don't need to store
322  $messageId = "{$urlPath}.entity.{$object->guid}@{$hostname}";
323  } else {
324  $mt = microtime(true);
325  $messageId = "{$urlPath}.entity.{$object->guid}.$mt@{$hostname}";
326  }
327  $returnvalue['headers']["Message-ID"] = $messageId;
328  $container = $object->getContainerEntity();
329 
330  // let's just thread comments by default
331  if (($container instanceof \ElggEntity) && ($object instanceof \ElggComment)) {
332 
333  $threadMessageId = "<{$urlPath}.entity.{$container->guid}@{$hostname}>";
334  $returnvalue['headers']['In-Reply-To'] = $threadMessageId;
335  $returnvalue['headers']['References'] = $threadMessageId;
336  }
337  }
338 
339  return $returnvalue;
340 }
341 
346  elgg_register_plugin_hook_handler('cron', 'minute', '_elgg_notifications_cron', 100);
347  elgg_register_event_handler('all', 'all', '_elgg_enqueue_notification_event', 700);
348 
349  // add email notifications
351  elgg_register_plugin_hook_handler('send', 'notification:email', '_elgg_send_email_notification');
352  elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_default_message_id_header', 1);
353  elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_thread_headers');
354 
355  // add ability to set personal notification method
356  elgg_extend_view('forms/account/settings', 'core/settings/account/notifications');
357  elgg_register_plugin_hook_handler('usersettings:save', 'user', '_elgg_save_notification_user_settings');
358 }
359 
375 function _elgg_notify_user($to, $from, $subject, $message, array $params = null, $methods_override = "") {
376 
377  $notify_service = _elgg_services()->notifications;
378 
379  // Sanitise
380  if (!is_array($to)) {
381  $to = array((int) $to);
382  }
383  $from = (int) $from;
384  //$subject = sanitise_string($subject);
385  // Get notification methods
386  if (($methods_override) && (!is_array($methods_override))) {
387  $methods_override = array($methods_override);
388  }
389 
390  $result = array();
391 
392  foreach ($to as $guid) {
393  // Results for a user are...
394  $result[$guid] = array();
395 
396  if ($guid) { // Is the guid > 0?
397  // Are we overriding delivery?
398  $methods = $methods_override;
399  if (!$methods) {
400  $tmp = get_user_notification_settings($guid);
401  $methods = array();
402  // $tmp may be false. don't cast
403  if (is_object($tmp)) {
404  foreach ($tmp as $k => $v) {
405  // Add method if method is turned on for user!
406  if ($v) {
407  $methods[] = $k;
408  }
409  }
410  }
411  }
412 
413  if ($methods) {
414  // Deliver
415  foreach ($methods as $method) {
416 
417  $handler = $notify_service->getDeprecatedHandler($method);
418  /* @var callable $handler */
419  if (!$handler || !is_callable($handler)) {
420  elgg_log("No handler registered for the method $method", 'WARNING');
421  continue;
422  }
423 
424  elgg_log("Sending message to $guid using $method");
425 
426  // Trigger handler and retrieve result.
427  try {
428  $result[$guid][$method] = call_user_func(
429  $handler,
430  $from ? get_entity($from) : null,
431  get_entity($guid),
432  $subject,
433  $message,
434  $params
435  );
436  } catch (Exception $e) {
437  error_log($e->getMessage());
438  }
439  }
440  }
441  }
442  }
443 
444  return $result;
445 }
446 
495 function notify_user($to, $from = 0, $subject = '', $message = '', array $params = array(), $methods_override = null) {
496 
497  $params['subject'] = $subject;
498  $params['body'] = $message;
499  $params['methods_override'] = $methods_override;
500 
501  if ($from) {
502  $sender = get_entity($from);
503  } else {
504  $sender = elgg_get_site_entity();
505  }
506  if (!$sender) {
507  return [];
508  }
509 
510  $recipients = [];
511  $to = (array) $to;
512  foreach ($to as $guid) {
513  $recipient = get_entity($guid);
514  if (!$recipient) {
515  continue;
516  }
517  $recipients[] = $recipient;
518  }
519 
520  return _elgg_services()->notifications->sendInstantNotifications($sender, $recipients, $params);
521 }
522 
532 
533  elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::getNotificationSettings()', '2.3');
534 
535  if ((int) $user_guid == 0) {
537  }
538 
540  if (!$user instanceof \ElggUser) {
541  return false;
542  }
543 
544  return (object) $user->getNotificationSettings();
545 }
546 
558  elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::setNotificationSetting()', '2.3');
559 
560  if (!$user_guid) {
562  }
564  if (!$user instanceof \ElggUser) {
565  return false;
566  }
567 
568  if (is_string($value)) {
569  $value = strtolower($value);
570  }
571  if ($value == 'yes' || $value == 'on' || $value == 'enabled') {
572  $value = true;
573  } else if ($value == 'no' || $value == 'off' || $value == 'disabled') {
574  $value = false;
575  }
576 
577  return $user->setNotificationSetting($method, (bool) $value);
578 }
579 
593 function elgg_send_email($from, $to, $subject, $body, array $params = null) {
594  if (!$from) {
595  $msg = "Missing a required parameter, '" . 'from' . "'";
596  throw new \NotificationException($msg);
597  }
598 
599  if (!$to) {
600  $msg = "Missing a required parameter, '" . 'to' . "'";
601  throw new \NotificationException($msg);
602  }
603 
604  $headers = array(
605  "Content-Type" => "text/plain; charset=UTF-8; format=flowed",
606  "MIME-Version" => "1.0",
607  "Content-Transfer-Encoding" => "8bit",
608  );
609 
610  // return true/false to stop elgg_send_email() from sending
611  $mail_params = array(
612  'to' => $to,
613  'from' => $from,
614  'subject' => $subject,
615  'body' => $body,
616  'headers' => $headers,
617  'params' => $params,
618  );
619 
620  // $mail_params is passed as both params and return value. The former is for backwards
621  // compatibility. The latter is so handlers can now alter the contents/headers of
622  // the email by returning the array
623  $result = _elgg_services()->hooks->trigger('email', 'system', $mail_params, $mail_params);
624  if (!is_array($result)) {
625  // don't need null check: Handlers can't set a hook value to null!
626  return (bool) $result;
627  }
628 
629  // strip name from to and from
630 
631  $to_address = Address::fromString($result['to']);
632  $from_address = Address::fromString($result['from']);
633 
634 
635  $subject = elgg_strip_tags($result['subject']);
636  $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');
637  // Sanitise subject by stripping line endings
638  $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject);
639  $subject = trim($subject);
640 
641  $body = elgg_strip_tags($result['body']);
642  $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
643  $body = wordwrap($body);
644 
645  $message = new Message();
646  $message->setEncoding('UTF-8');
647  $message->addFrom($from_address);
648  $message->addTo($to_address);
649  $message->setSubject($subject);
650  $message->setBody($body);
651 
652  foreach ($result['headers'] as $headerName => $headerValue) {
653  // Create a headerline in the format 'name: value'
654  // This is done to force correct class detection for each header type
655  // which influences the output of the header in the message
656  $message->getHeaders()->addHeaderLine("{$headerName}: {$headerValue}");
657  }
658 
659  try {
660  _elgg_services()->mailer->send($message);
661  } catch (\Zend\Mail\Exception\RuntimeException $e) {
662  _elgg_services()->logger->error($e->getMessage());
663  return false;
664  }
665 
666  return true;
667 }
668 
676 
678  if (!$user) {
679  return;
680  }
681 
682  $method = get_input('method');
683 
684  $current_settings = $user->getNotificationSettings();
685 
686  $result = false;
687  foreach ($method as $k => $v) {
688  // check if setting has changed and skip if not
689  if ($current_settings[$k] == ($v == 'yes')) {
690  continue;
691  }
692 
693  $result = $user->setNotificationSetting($k, ($v == 'yes'));
694  if (!$result) {
695  register_error(elgg_echo('notifications:usersettings:save:fail'));
696  }
697  }
698 
699  if ($result) {
700  system_message(elgg_echo('notifications:usersettings:save:ok'));
701  }
702 }
703 
707 function _elgg_notifications_test($hook, $type, $tests) {
708  global $CONFIG;
709  $tests[] = "{$CONFIG->path}engine/tests/ElggCoreDatabaseQueueTest.php";
710  return $tests;
711 }
712 
713 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
714  $events->registerHandler('init', 'system', '_elgg_notifications_init');
715 
716  $hooks->registerHandler('unit_test', 'system', '_elgg_notifications_test');
717 };
$object
These two snippets demonstrates triggering an event and how to register for that event.
Definition: trigger.php:7
elgg_get_site_entity($site_guid=0)
Get an entity (default is current site)
Definition: sites.php:18
$action
Definition: full.php:133
elgg_register_notification_method($name)
Register a delivery method for notifications.
$subject
Definition: exceptions.php:25
if($guid==elgg_get_logged_in_user_guid()) $name
Definition: delete.php:21
elgg_echo($message_key, $args=array(), $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
$method
Definition: form.php:25
$e
Definition: metadata.php:12
elgg_strip_tags($string, $allowable_tags=null)
Strip tags and offer plugins the chance.
Definition: output.php:477
_elgg_notifications_cron()
private
$headers
Definition: default.php:14
elgg_unregister_notification_event($object_type, $object_subtype)
Unregister a notification event.
_elgg_enqueue_notification_event($action, $type, $object)
Queue a notification event for later handling.
$value
Definition: longtext.php:42
$guid
Removes an admin notice.
elgg parse_url
Parse a URL into its parts.
Definition: elgglib.js:450
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Definition: elgglib.php:740
elgg_remove_subscription($user_guid, $method, $target_guid)
Unsubscribe a user to notifications about a target entity.
$actions
Definition: user_hover.php:12
$params
Definition: login.php:72
elgg_get_subscriptions_for_container($container_guid)
Get the subscriptions for the content created inside this container.
_elgg_notifications_init()
private
_elgg_save_notification_user_settings()
Save personal notification settings - input comes from request.
elgg_unregister_notification_method($name)
Unregister a delivery method for notifications.
Save menu items.
$container
Definition: delete.php:29
get_input($variable, $default=null, $filter_result=true)
Get some input from variables passed submitted through GET or POST.
Definition: input.php:27
global $CONFIG
$user
Definition: ban.php:13
notify_user($to, $from=0, $subject= '', $message= '', array $params=array(), $methods_override=null)
Notify a user via their preferences.
_elgg_notifications_smtp_default_message_id_header($hook, $type, $returnvalue, $params)
Adds default Message-ID header to all e-mails.
set_user_notification_setting($user_guid, $method, $value)
Set a user notification pref.
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1098
elgg global
Pointer to the global context.
Definition: elgglib.js:12
elgg_get_site_url($site_guid=0)
Get the URL for the current (or specified) site.
elgg_extend_view($view, $view_extension, $priority=501)
Extends a view with another view.
Definition: views.php:380
_elgg_services(\Elgg\Di\ServiceProvider $services=null)
Get the global service provider.
Definition: autoloader.php:17
$token
elgg_extract($key, $array, $default=null, $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:1375
elgg system_message
Wrapper function for system_messages.
Definition: elgglib.js:390
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Definition: elgglib.php:550
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:1028
_elgg_send_email_notification($hook, $type, $result, $params)
Send an email notification.
_elgg_notifications_test($hook, $type, $tests)
private
elgg_add_subscription($user_guid, $method, $target_guid)
Subscribe a user to notifications about a target entity.
elgg subtext time
elgg_register_notification_event($object_type, $object_subtype, array $actions=array())
Register a notification event.
elgg register_error
Wrapper function for system_messages.
Definition: elgglib.js:399
elgg_get_logged_in_user_entity()
Return the current logged in user, or null if no user is logged in.
Definition: sessions.php:32
elgg_get_notification_methods()
Returns registered delivery methods for notifications [ &#39;email&#39; => &#39;email&#39;, &#39;sms&#39; => &#39;sms&#39;...
$container_guid
$handler
Definition: add.php:10
$user_guid
Avatar remove action.
Definition: remove.php:6
get_user_notification_settings($user_guid=0)
Get the notification settings for a given user.
elgg_send_email($from, $to, $subject, $body, array $params=null)
Send an email to any email address.
http free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:5
elgg_get_logged_in_user_guid()
Return the current logged in user by guid.
Definition: sessions.php:42
_elgg_notify_user($to, $from, $subject, $message, array $params=null, $methods_override="")
Notify a user via their preferences.
get_entity($guid)
Loads and returns an entity object from a guid.
Definition: entities.php:204
if(!$display_name) $type
Definition: delete.php:27