Elgg  Version 1.10
notification.php
Go to the documentation of this file.
1 <?php
61 function elgg_register_notification_event($object_type, $object_subtype, array $actions = array()) {
62  _elgg_services()->notifications->registerEvent($object_type, $object_subtype, $actions);
63 }
64 
73 function elgg_unregister_notification_event($object_type, $object_subtype) {
74  return _elgg_services()->notifications->unregisterEvent($object_type, $object_subtype);
75 }
76 
90  _elgg_services()->notifications->registerMethod($name);
91 }
92 
102  return _elgg_services()->notifications->unregisterMethod($name);
103 }
104 
114 function elgg_add_subscription($user_guid, $method, $target_guid) {
115  $methods = _elgg_services()->notifications->getMethods();
116  $db = _elgg_services()->db;
117  $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
118  return $subs->addSubscription($user_guid, $method, $target_guid);
119 }
120 
130 function elgg_remove_subscription($user_guid, $method, $target_guid) {
131  $methods = _elgg_services()->notifications->getMethods();
132  $db = _elgg_services()->db;
133  $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
134  return $subs->removeSubscription($user_guid, $method, $target_guid);
135 }
136 
151 function elgg_get_subscriptions_for_container($container_guid) {
152  $methods = _elgg_services()->notifications->getMethods();
153  $db = _elgg_services()->db;
154  $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
155  return $subs->getSubscriptionsForContainer($container_guid);
156 }
157 
174  _elgg_services()->notifications->enqueueEvent($action, $type, $object);
175 }
176 
181  // calculate when we should stop
182  // @todo make configurable?
183  $stop_time = time() + 45;
184  _elgg_services()->notifications->processQueue($stop_time);
185 }
186 
198  /* @var \Elgg\Notifications\Notification $message */
199  $message = $params['notification'];
200 
201  $sender = $message->getSender();
202  $recipient = $message->getRecipient();
203 
204  if (!$sender) {
205  return false;
206  }
207 
208  if (!$recipient || !$recipient->email) {
209  return false;
210  }
211 
212  $to = $recipient->email;
213 
215  // If there's an email address, use it - but only if it's not from a user.
216  if (!($sender instanceof \ElggUser) && $sender->email) {
217  $from = $sender->email;
218  } else if ($site->email) {
219  $from = $site->email;
220  } else {
221  // If all else fails, use the domain of the site.
222  $from = 'noreply@' . $site->getDomain();
223  }
224 
225  return elgg_send_email($from, $to, $message->subject, $message->body, $params);
226 }
227 
239 function _elgg_notifications_smtp_thread_headers($hook, $type, $returnvalue, $params) {
240 
241  $notificationParams = elgg_extract('params', $returnvalue, array());
243  $notification = elgg_extract('notification', $notificationParams);
244 
245  if (!($notification instanceof \Elgg\Notifications\Notification)) {
246  return $returnvalue;
247  }
248 
249  $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
250  $urlPath = parse_url(elgg_get_site_url(), PHP_URL_PATH);
251 
252  $object = elgg_extract('object', $notification->params);
254  $event = elgg_extract('event', $notification->params);
255 
256  if (($object instanceof \ElggEntity) && ($event instanceof \Elgg\Notifications\Event)) {
257  if ($event->getAction() === 'create') {
258  // create event happens once per entity and we need to guarantee message id uniqueness
259  // and at the same time have thread message id that we don't need to store
260  $messageId = "<{$urlPath}.entity.{$object->guid}@{$hostname}>";
261  } else {
262  $mt = microtime(true);
263  $messageId = "<{$urlPath}.entity.{$object->guid}.$mt@{$hostname}>";
264  }
265  $returnvalue['headers']["Message-ID"] = $messageId;
266  $container = $object->getContainerEntity();
267 
268  // let's just thread comments by default
269  if (($container instanceof \ElggEntity) && ($object instanceof \ElggComment)) {
270 
271  $threadMessageId = "<{$urlPath}.entity.{$container->guid}@{$hostname}>";
272  $returnvalue['headers']['In-Reply-To'] = $threadMessageId;
273  $returnvalue['headers']['References'] = $threadMessageId;
274  }
275  }
276 
277  return $returnvalue;
278 }
279 
284  elgg_register_plugin_hook_handler('cron', 'minute', '_elgg_notifications_cron', 100);
285  elgg_register_event_handler('all', 'all', '_elgg_enqueue_notification_event');
286 
287  // add email notifications
289  elgg_register_plugin_hook_handler('send', 'notification:email', '_elgg_send_email_notification');
290  elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_thread_headers');
291 
292  // add ability to set personal notification method
293  elgg_extend_view('forms/account/settings', 'core/settings/account/notifications');
294  elgg_register_plugin_hook_handler('usersettings:save', 'user', '_elgg_save_notification_user_settings');
295 }
296 
297 elgg_register_event_handler('init', 'system', '_elgg_notifications_init');
298 
299 
300 
316 function _elgg_notify_user($to, $from, $subject, $message, array $params = null, $methods_override = "") {
317 
318  $notify_service = _elgg_services()->notifications;
319 
320  // Sanitise
321  if (!is_array($to)) {
322  $to = array((int)$to);
323  }
324  $from = (int)$from;
325  //$subject = sanitise_string($subject);
326 
327  // Get notification methods
328  if (($methods_override) && (!is_array($methods_override))) {
329  $methods_override = array($methods_override);
330  }
331 
332  $result = array();
333 
334  foreach ($to as $guid) {
335  // Results for a user are...
336  $result[$guid] = array();
337 
338  if ($guid) { // Is the guid > 0?
339  // Are we overriding delivery?
340  $methods = $methods_override;
341  if (!$methods) {
342  $tmp = get_user_notification_settings($guid);
343  $methods = array();
344  // $tmp may be false. don't cast
345  if (is_object($tmp)) {
346  foreach ($tmp as $k => $v) {
347  // Add method if method is turned on for user!
348  if ($v) {
349  $methods[] = $k;
350  }
351  }
352  }
353  }
354 
355  if ($methods) {
356  // Deliver
357  foreach ($methods as $method) {
358 
359  $handler = $notify_service->getDeprecatedHandler($method);
360  /* @var callable $handler */
361  if (!$handler || !is_callable($handler)) {
362  elgg_log("No handler registered for the method $method", 'WARNING');
363  continue;
364  }
365 
366  elgg_log("Sending message to $guid using $method");
367 
368  // Trigger handler and retrieve result.
369  try {
370  $result[$guid][$method] = call_user_func($handler,
371  $from ? get_entity($from) : null,
372  get_entity($guid),
373  $subject,
374  $message,
375  $params
376  );
377  } catch (Exception $e) {
378  error_log($e->getMessage());
379  }
380  }
381  }
382  }
383  }
384 
385  return $result;
386 }
387 
388 
438 function notify_user($to, $from, $subject, $message, array $params = array(), $methods_override = "") {
439 
440  if (!is_array($to)) {
441  $to = array((int)$to);
442  }
443  $from = (int)$from;
444  $from = get_entity($from) ? $from : elgg_get_site_entity()->guid;
445  $sender = get_entity($from);
446  $summary = elgg_extract('summary', $params, '');
447 
448  // Get notification methods
449  if (($methods_override) && (!is_array($methods_override))) {
450  $methods_override = array($methods_override);
451  }
452 
453  $result = array();
454 
455  $available_methods = _elgg_services()->notifications->getMethods();
456  if (!$available_methods) {
457  // There are no notifications methods to use
458  return $result;
459  }
460 
461  // temporary backward compatibility for 1.8 and earlier notifications
462  $event = null;
463  if (isset($params['object']) && isset($params['action'])) {
464  $event = new \Elgg\Notifications\Event($params['object'], $params['action'], $sender);
465  }
466  $params['event'] = $event;
467 
468  foreach ($to as $guid) {
469  // Results for a user are...
470  $result[$guid] = array();
471 
472  if ($guid) { // Is the guid > 0?
473  // Are we overriding delivery?
474  $methods = $methods_override;
475  if (!$methods) {
476  $tmp = (array)get_user_notification_settings($guid);
477  $methods = array();
478  foreach ($tmp as $k => $v) {
479  // Add method if method is turned on for user!
480  if ($v) {
481  $methods[] = $k;
482  }
483  }
484  }
485 
486  if ($methods) {
487  // Deliver
488  foreach ($methods as $method) {
489  if (!in_array($method, $available_methods)) {
490  // This method was available the last time the user saved their
491  // notification settings. It's however currently disabled.
492  continue;
493  }
494 
495  if (_elgg_services()->hooks->hasHandler('send', "notification:$method")) {
496  // 1.9 style notification handler
497  $recipient = get_entity($guid);
498  if (!$recipient) {
499  continue;
500  }
501  $language = $recipient->language;
502  $notification = new \Elgg\Notifications\Notification($sender, $recipient, $language, $subject, $message, $summary, $params);
503  $params['notification'] = $notification;
504  $result[$guid][$method] = _elgg_services()->hooks->trigger('send', "notification:$method", $params, false);
505  } else {
506  $result[$guid][$method] = _elgg_notify_user($guid, $from, $subject, $message, $params, array($method));
507  }
508  }
509  }
510  }
511  }
512 
513  return $result;
514 }
515 
524  $user_guid = (int)$user_guid;
525 
526  if ($user_guid == 0) {
528  }
529 
530  // @todo: there should be a better way now that metadata is cached. E.g. just query for MD names, then
531  // query user object directly
532  $all_metadata = elgg_get_metadata(array(
533  'guid' => $user_guid,
534  'limit' => 0
535  ));
536  if ($all_metadata) {
537  $prefix = "notification:method:";
538  $return = new \stdClass;
539 
540  foreach ($all_metadata as $meta) {
541  $name = substr($meta->name, strlen($prefix));
542  $value = $meta->value;
543 
544  if (strpos($meta->name, $prefix) === 0) {
545  $return->$name = $value;
546  }
547  }
548 
549  return $return;
550  }
551 
552  return false;
553 }
554 
565  $user_guid = (int)$user_guid;
567 
569  if (!$user) {
571  }
572 
573  if (($user) && ($user instanceof \ElggUser)) {
574  $prefix = "notification:method:$method";
575  $user->$prefix = $value;
576  $user->save();
577 
578  return true;
579  }
580 
581  return false;
582 }
583 
597 function elgg_send_email($from, $to, $subject, $body, array $params = null) {
598  global $CONFIG;
599 
600  if (!$from) {
601  $msg = "Missing a required parameter, '" . 'from' . "'";
602  throw new \NotificationException($msg);
603  }
604 
605  if (!$to) {
606  $msg = "Missing a required parameter, '" . 'to' . "'";
607  throw new \NotificationException($msg);
608  }
609 
610  $headers = array(
611  "Content-Type" => "text/plain; charset=UTF-8; format=flowed",
612  "MIME-Version" => "1.0",
613  "Content-Transfer-Encoding" => "8bit",
614  );
615 
616  // return true/false to stop elgg_send_email() from sending
617  $mail_params = array(
618  'to' => $to,
619  'from' => $from,
620  'subject' => $subject,
621  'body' => $body,
622  'headers' => $headers,
623  'params' => $params,
624  );
625 
626  // $mail_params is passed as both params and return value. The former is for backwards
627  // compatibility. The latter is so handlers can now alter the contents/headers of
628  // the email by returning the array
629  $result = elgg_trigger_plugin_hook('email', 'system', $mail_params, $mail_params);
630  if (is_array($result)) {
631  foreach (array('to', 'from', 'subject', 'body', 'headers') as $key) {
632  if (isset($result[$key])) {
633  ${$key} = $result[$key];
634  }
635  }
636  } elseif ($result !== null) {
637  return $result;
638  }
639 
640  $header_eol = "\r\n";
641  if (isset($CONFIG->broken_mta) && $CONFIG->broken_mta) {
642  // Allow non-RFC 2822 mail headers to support some broken MTAs
643  $header_eol = "\n";
644  }
645 
646  // Windows is somewhat broken, so we use just address for to and from
647  if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
648  // strip name from to and from
649  if (strpos($to, '<')) {
650  preg_match('/<(.*)>/', $to, $matches);
651  $to = $matches[1];
652  }
653  if (strpos($from, '<')) {
654  preg_match('/<(.*)>/', $from, $matches);
655  $from = $matches[1];
656  }
657  }
658 
659  // make sure From is set
660  if (empty($headers['From'])) {
661  $headers['From'] = $from;
662  }
663 
664  // stringify headers
665  $headers_string = '';
666  foreach ($headers as $key => $value) {
667  $headers_string .= "$key: $value{$header_eol}";
668  }
669 
670  // Sanitise subject by stripping line endings
671  $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject);
672  // this is because Elgg encodes everything and matches what is done with body
673  $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8'); // Decode any html entities
674  if (is_callable('mb_encode_mimeheader')) {
675  $subject = mb_encode_mimeheader($subject, "UTF-8", "B");
676  }
677 
678  // Format message
679  $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8'); // Decode any html entities
680  $body = elgg_strip_tags($body); // Strip tags from message
681  $body = preg_replace("/(\r\n|\r)/", "\n", $body); // Convert to unix line endings in body
682  $body = preg_replace("/^From/", ">From", $body); // Change lines starting with From to >From
683  $body = wordwrap($body);
684 
685  return mail($to, $subject, $body, $headers_string);
686 }
687 
695  $method = get_input('method');
696 
697  $current_settings = get_user_notification_settings();
698 
699  $result = false;
700  foreach ($method as $k => $v) {
701  // check if setting has changed and skip if not
702  if ($current_settings->$k == ($v == 'yes')) {
703  continue;
704  }
705 
706  $result = set_user_notification_setting(elgg_get_logged_in_user_guid(), $k, ($v == 'yes') ? true : false);
707 
708  if (!$result) {
709  register_error(elgg_echo('notifications:usersettings:save:fail'));
710  }
711  }
712 
713  if ($result) {
714  system_message(elgg_echo('notifications:usersettings:save:ok'));
715  }
716 }
717 
721 function _elgg_notifications_test($hook, $type, $tests) {
722  global $CONFIG;
723  $tests[] = "{$CONFIG->path}engine/tests/ElggCoreDatabaseQueueTest.php";
724  return $tests;
725 }
726 
727 elgg_register_plugin_hook_handler('unit_test', 'system', '_elgg_notifications_test');
elgg_get_site_entity($site_guid=0)
Get an entity (default is current site)
Definition: sites.php:18
get_input($variable, $default=null, $filter_result=true)
Get some input from variables passed submitted through GET or POST.
Definition: input.php:27
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
$method
Definition: form.php:25
$e
Definition: metadata.php:12
$object
Definition: upgrade.php:12
elgg_strip_tags($string, $allowable_tags=null)
Strip tags and offer plugins the chance.
Definition: output.php:499
_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:29
if(!$autoload_available) _elgg_services()
Definition: autoloader.php:20
$return
Definition: opendd.php:15
$guid
Removes an admin notice.
elgg parse_url
Parse a URL into its parts.
Definition: elgglib.js:432
elgg_extract($key, array $array, $default=null, $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:1349
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Register a callback as a plugin hook handler.
Definition: elgglib.php:737
elgg_remove_subscription($user_guid, $method, $target_guid)
Unsubscribe a user to notifications about a target entity.
$action
$actions
Definition: user_hover.php:12
$summary
Definition: full.php:21
$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.
elgg_echo($message_key, $args=array(), $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
$key
Definition: summary.php:34
global $CONFIG
sanitise_string($string)
Wrapper function for alternate English spelling (.
Definition: database.php:150
elgg_extend_view($view, $view_extension, $priority=501, $viewtype= '')
Extends a view with another view.
Definition: views.php:401
$user
Definition: ban.php:13
set_user_notification_setting($user_guid, $method, $value)
Set a user notification pref.
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Trigger a Plugin Hook and run all handler callbacks registered to that hook:type. ...
Definition: elgglib.php:809
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.
$type
Definition: add.php:8
elgg system_message
Wrapper function for system_messages.
Definition: elgglib.js:374
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Register a callback as an Elgg event handler.
Definition: elgglib.php:553
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:967
_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_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:383
elgg_get_metadata(array $options=array())
Returns metadata.
Definition: metadata.php:143
notify_user($to, $from, $subject, $message, array $params=array(), $methods_override="")
Notify a user via their preferences.
elgg_get_logged_in_user_entity()
Return the current logged in user, or null if no user is logged in.
Definition: sessions.php:32
$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.
$language
$vars[&#39;language&#39;] $vars[&#39;lc&#39;] if present, client will be sent long expires headers ...
Definition: languages.php:7
elgg_send_email($from, $to, $subject, $body, array $params=null)
Send an email to any email address.
$container
Definition: access.php:30
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:382