Elgg  Version 1.11
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 
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 
312 function _elgg_notify_user($to, $from, $subject, $message, array $params = null, $methods_override = "") {
313 
314  $notify_service = _elgg_services()->notifications;
315 
316  // Sanitise
317  if (!is_array($to)) {
318  $to = array((int)$to);
319  }
320  $from = (int)$from;
321  //$subject = sanitise_string($subject);
322 
323  // Get notification methods
324  if (($methods_override) && (!is_array($methods_override))) {
325  $methods_override = array($methods_override);
326  }
327 
328  $result = array();
329 
330  foreach ($to as $guid) {
331  // Results for a user are...
332  $result[$guid] = array();
333 
334  if ($guid) { // Is the guid > 0?
335  // Are we overriding delivery?
336  $methods = $methods_override;
337  if (!$methods) {
338  $tmp = get_user_notification_settings($guid);
339  $methods = array();
340  // $tmp may be false. don't cast
341  if (is_object($tmp)) {
342  foreach ($tmp as $k => $v) {
343  // Add method if method is turned on for user!
344  if ($v) {
345  $methods[] = $k;
346  }
347  }
348  }
349  }
350 
351  if ($methods) {
352  // Deliver
353  foreach ($methods as $method) {
354 
355  $handler = $notify_service->getDeprecatedHandler($method);
356  /* @var callable $handler */
357  if (!$handler || !is_callable($handler)) {
358  elgg_log("No handler registered for the method $method", 'WARNING');
359  continue;
360  }
361 
362  elgg_log("Sending message to $guid using $method");
363 
364  // Trigger handler and retrieve result.
365  try {
366  $result[$guid][$method] = call_user_func($handler,
367  $from ? get_entity($from) : null,
368  get_entity($guid),
369  $subject,
370  $message,
371  $params
372  );
373  } catch (Exception $e) {
374  error_log($e->getMessage());
375  }
376  }
377  }
378  }
379  }
380 
381  return $result;
382 }
383 
384 
434 function notify_user($to, $from, $subject, $message, array $params = array(), $methods_override = "") {
435 
436  if (!is_array($to)) {
437  $to = array((int)$to);
438  }
439  $from = (int)$from;
440  $from = get_entity($from) ? $from : elgg_get_site_entity()->guid;
441  $sender = get_entity($from);
442  $summary = elgg_extract('summary', $params, '');
443 
444  // Get notification methods
445  if (($methods_override) && (!is_array($methods_override))) {
446  $methods_override = array($methods_override);
447  }
448 
449  $result = array();
450 
451  $available_methods = _elgg_services()->notifications->getMethods();
452  if (!$available_methods) {
453  // There are no notifications methods to use
454  return $result;
455  }
456 
457  // temporary backward compatibility for 1.8 and earlier notifications
458  $event = null;
459  if (isset($params['object']) && isset($params['action'])) {
460  $event = new \Elgg\Notifications\Event($params['object'], $params['action'], $sender);
461  }
462  $params['event'] = $event;
463 
464  foreach ($to as $guid) {
465  // Results for a user are...
466  $result[$guid] = array();
467 
468  if ($guid) { // Is the guid > 0?
469  // Are we overriding delivery?
470  $methods = $methods_override;
471  if (!$methods) {
472  $tmp = (array)get_user_notification_settings($guid);
473  $methods = array();
474  foreach ($tmp as $k => $v) {
475  // Add method if method is turned on for user!
476  if ($v) {
477  $methods[] = $k;
478  }
479  }
480  }
481 
482  if ($methods) {
483  // Deliver
484  foreach ($methods as $method) {
485  if (!in_array($method, $available_methods)) {
486  // This method was available the last time the user saved their
487  // notification settings. It's however currently disabled.
488  continue;
489  }
490 
491  if (_elgg_services()->hooks->hasHandler('send', "notification:$method")) {
492  // 1.9 style notification handler
493  $recipient = get_entity($guid);
494  if (!$recipient) {
495  continue;
496  }
497  $language = $recipient->language;
498  $notification = new \Elgg\Notifications\Notification($sender, $recipient, $language, $subject, $message, $summary, $params);
499  $params['notification'] = $notification;
500  $result[$guid][$method] = _elgg_services()->hooks->trigger('send', "notification:$method", $params, false);
501  } else {
502  $result[$guid][$method] = _elgg_notify_user($guid, $from, $subject, $message, $params, array($method));
503  }
504  }
505  }
506  }
507  }
508 
509  return $result;
510 }
511 
520  $user_guid = (int)$user_guid;
521 
522  if ($user_guid == 0) {
524  }
525 
526  // @todo: there should be a better way now that metadata is cached. E.g. just query for MD names, then
527  // query user object directly
528  $all_metadata = elgg_get_metadata(array(
529  'guid' => $user_guid,
530  'limit' => 0
531  ));
532  if ($all_metadata) {
533  $prefix = "notification:method:";
534  $return = new \stdClass;
535 
536  foreach ($all_metadata as $meta) {
537  $name = substr($meta->name, strlen($prefix));
538  $value = $meta->value;
539 
540  if (strpos($meta->name, $prefix) === 0) {
541  $return->$name = $value;
542  }
543  }
544 
545  return $return;
546  }
547 
548  return false;
549 }
550 
561  $user_guid = (int)$user_guid;
563 
565  if (!$user) {
567  }
568 
569  if (($user) && ($user instanceof \ElggUser)) {
570  $prefix = "notification:method:$method";
571  $user->$prefix = $value;
572  $user->save();
573 
574  return true;
575  }
576 
577  return false;
578 }
579 
593 function elgg_send_email($from, $to, $subject, $body, array $params = null) {
594  global $CONFIG;
595 
596  if (!$from) {
597  $msg = "Missing a required parameter, '" . 'from' . "'";
598  throw new \NotificationException($msg);
599  }
600 
601  if (!$to) {
602  $msg = "Missing a required parameter, '" . 'to' . "'";
603  throw new \NotificationException($msg);
604  }
605 
606  $headers = array(
607  "Content-Type" => "text/plain; charset=UTF-8; format=flowed",
608  "MIME-Version" => "1.0",
609  "Content-Transfer-Encoding" => "8bit",
610  );
611 
612  // return true/false to stop elgg_send_email() from sending
613  $mail_params = array(
614  'to' => $to,
615  'from' => $from,
616  'subject' => $subject,
617  'body' => $body,
618  'headers' => $headers,
619  'params' => $params,
620  );
621 
622  // $mail_params is passed as both params and return value. The former is for backwards
623  // compatibility. The latter is so handlers can now alter the contents/headers of
624  // the email by returning the array
625  $result = elgg_trigger_plugin_hook('email', 'system', $mail_params, $mail_params);
626  if (is_array($result)) {
627  foreach (array('to', 'from', 'subject', 'body', 'headers') as $key) {
628  if (isset($result[$key])) {
629  ${$key} = $result[$key];
630  }
631  }
632  } elseif ($result !== null) {
633  return $result;
634  }
635 
636  $header_eol = "\r\n";
637  if (isset($CONFIG->broken_mta) && $CONFIG->broken_mta) {
638  // Allow non-RFC 2822 mail headers to support some broken MTAs
639  $header_eol = "\n";
640  }
641 
642  // Windows is somewhat broken, so we use just address for to and from
643  if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
644  // strip name from to and from
645  if (strpos($to, '<')) {
646  preg_match('/<(.*)>/', $to, $matches);
647  $to = $matches[1];
648  }
649  if (strpos($from, '<')) {
650  preg_match('/<(.*)>/', $from, $matches);
651  $from = $matches[1];
652  }
653  }
654 
655  // make sure From is set
656  if (empty($headers['From'])) {
657  $headers['From'] = $from;
658  }
659 
660  // stringify headers
661  $headers_string = '';
662  foreach ($headers as $key => $value) {
663  $headers_string .= "$key: $value{$header_eol}";
664  }
665 
666  // Sanitise subject by stripping line endings
667  $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject);
668  // this is because Elgg encodes everything and matches what is done with body
669  $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8'); // Decode any html entities
670  if (is_callable('mb_encode_mimeheader')) {
671  $subject = mb_encode_mimeheader($subject, "UTF-8", "B");
672  }
673 
674  // Format message
675  $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8'); // Decode any html entities
676  $body = elgg_strip_tags($body); // Strip tags from message
677  $body = preg_replace("/(\r\n|\r)/", "\n", $body); // Convert to unix line endings in body
678  $body = preg_replace("/^From/", ">From", $body); // Change lines starting with From to >From
679  $body = wordwrap($body);
680 
681  return mail($to, $subject, $body, $headers_string);
682 }
683 
691  $method = get_input('method');
692 
693  $current_settings = get_user_notification_settings();
694 
695  $result = false;
696  foreach ($method as $k => $v) {
697  // check if setting has changed and skip if not
698  if ($current_settings->$k == ($v == 'yes')) {
699  continue;
700  }
701 
702  $result = set_user_notification_setting(elgg_get_logged_in_user_guid(), $k, ($v == 'yes') ? true : false);
703 
704  if (!$result) {
705  register_error(elgg_echo('notifications:usersettings:save:fail'));
706  }
707  }
708 
709  if ($result) {
710  system_message(elgg_echo('notifications:usersettings:save:ok'));
711  }
712 }
713 
717 function _elgg_notifications_test($hook, $type, $tests) {
718  global $CONFIG;
719  $tests[] = "{$CONFIG->path}engine/tests/ElggCoreDatabaseQueueTest.php";
720  return $tests;
721 }
722 
723 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
724  $events->registerHandler('init', 'system', '_elgg_notifications_init');
725 
726  $hooks->registerHandler('unit_test', 'system', '_elgg_notifications_test');
727 };
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:26
$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:1246
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Definition: elgglib.php:703
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.
if($entity) $container
Definition: access.php:62
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
_elgg_services()
Definition: autoloader.php:14
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)
Definition: elgglib.php:775
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)
Definition: elgglib.php:519
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:933
_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
$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.
$language
$vars[&#39;language&#39;]
Definition: languages.php:6
elgg_send_email($from, $to, $subject, $body, array $params=null)
Send an email to any email address.
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