3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\Plaintext;
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Renderer;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Item;
32 use Friendica\Model\Notification;
33 use Friendica\Model\Post;
34 use Friendica\Model\User;
35 use Friendica\Model\Verb;
36 use Friendica\Protocol\Activity;
39 * Creates a notification entry and possibly sends a mail
41 * @param array $params Array with the elements:
42 * type, event, otype, activity, verb, uid, cid, item, link,
43 * source_name, source_mail, source_nick, source_link, source_photo,
44 * show_in_notification_page
47 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
49 function notification($params)
51 /** @var string the common prefix of a notification subject */
52 $subjectPrefix = DI::l10n()->t('[Friendica:Notify]');
54 // Temporary logging for finding the origin
55 if (!isset($params['uid'])) {
56 Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
59 // Ensure that the important fields are set at any time
60 $fields = ['nickname', 'page-flags', 'notify-flags', 'language', 'username', 'email'];
61 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
63 if (!DBA::isResult($user)) {
64 Logger::error('Unknown user', ['uid' => $params['uid']]);
68 // There is no need to create notifications for forum accounts
69 if (in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
73 $params['notify_flags'] = $user['notify-flags'];
74 $params['language'] = $user['language'];
75 $params['to_name'] = $user['username'];
76 $params['to_email'] = $user['email'];
78 // from here on everything is in the recipients language
79 $l10n = DI::l10n()->withLang($params['language']);
81 if (!empty($params['cid'])) {
82 $contact = Contact::getById($params['cid'], ['url', 'name', 'photo']);
83 if (DBA::isResult($contact)) {
84 $params['source_link'] = $contact['url'];
85 $params['source_name'] = $contact['name'];
86 $params['source_photo'] = $contact['photo'];
90 $siteurl = DI::baseUrl()->get(true);
91 $sitename = DI::config()->get('config', 'sitename');
93 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
94 // the database, and an email is sent if applicable.
95 // default, if not specified: true
96 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
98 $title = $params['item']['title'] ?? '';
99 $body = $params['item']['body'] ?? '';
101 $parent_id = $params['item']['parent'] ?? 0;
102 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
112 switch ($params['type']) {
113 case Notification\Type::MAIL:
114 $itemlink = $params['link'];
116 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
118 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
119 $epreamble = $l10n->t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=' . $itemlink . ']' . $l10n->t('a private message').'[/url]');
121 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
122 $tsitelink = sprintf($sitelink, $itemlink);
123 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
125 // Mail notifications aren't using the "notify" table entry
126 $show_in_notification_page = false;
129 case Notification\Type::COMMENT:
130 if (Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
131 Logger::info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
135 $item = Post::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
140 $item_post_type = Item::postType($item, $l10n);
142 $content = Plaintext::getPost($item, 70);
143 if (!empty($content['text'])) {
144 $title = '"' . trim(str_replace("\n", " ", $content['text'])) . '"';
149 // First go for the general message
151 // "George Bull's post"
152 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
153 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
157 $message = $l10n->t('%1$s commented on your %2$s %3$s');
158 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
160 } elseif ($item['author-link'] == $params['source_link']) {
161 $message = $l10n->t('%1$s commented on their %2$s %3$s');
162 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
165 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
167 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
169 $epreamble = $dest_str;
171 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
172 $tsitelink = sprintf($sitelink, $siteurl);
173 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
174 $itemlink = $params['link'];
177 case Notification\Type::WALL:
178 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
180 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
181 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
182 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
186 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
187 $tsitelink = sprintf($sitelink, $siteurl);
188 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
189 $itemlink = $params['link'];
192 case Notification\Type::POKE:
193 $subject = $l10n->t('%1$s %2$s poked you', $subjectPrefix, $params['source_name']);
195 $preamble = $l10n->t('%1$s poked you at %2$s', $params['source_name'], $sitename);
196 $epreamble = $l10n->t('%1$s [url=%2$s]poked you[/url].',
197 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
201 $subject = str_replace('poked', $l10n->t($params['activity']), $subject);
202 $preamble = str_replace('poked', $l10n->t($params['activity']), $preamble);
203 $epreamble = str_replace('poked', $l10n->t($params['activity']), $epreamble);
205 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
206 $tsitelink = sprintf($sitelink, $siteurl);
207 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
208 $itemlink = $params['link'];
211 case Notification\Type::INTRO:
212 $itemlink = $params['link'];
213 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
215 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
216 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
218 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
221 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
223 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
224 $tsitelink = sprintf($sitelink, $siteurl);
225 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
227 switch ($params['verb']) {
228 case Activity::FRIEND:
229 // someone started to share with user (mostly OStatus)
230 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
232 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
233 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
234 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
238 case Activity::FOLLOW:
239 // someone started to follow the user (mostly OStatus)
240 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
242 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
243 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
244 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
249 // ACTIVITY_REQ_FRIEND is default activity for notifications
254 case Notification\Type::SUGGEST:
255 $itemlink = $params['link'];
256 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
258 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
259 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
261 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
262 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
265 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
266 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
267 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
269 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
270 $tsitelink = sprintf($sitelink, $siteurl);
271 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
274 case Notification\Type::CONFIRM:
275 if ($params['verb'] == Activity::FRIEND) { // mutual connection
276 $itemlink = $params['link'];
277 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
279 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
280 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
282 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
285 $body = $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
287 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
288 $tsitelink = sprintf($sitelink, $siteurl);
289 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
290 } else { // ACTIVITY_FOLLOW
291 $itemlink = $params['link'];
292 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
294 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
295 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
297 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
300 $body = $l10n->t('\'%1$s\' has chosen to accept you a fan, which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.', $params['source_name']);
302 $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
304 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
305 $tsitelink = sprintf($sitelink, $siteurl);
306 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
310 case Notification\Type::SYSTEM:
311 switch($params['event']) {
312 case "SYSTEM_REGISTER_REQUEST":
313 $itemlink = $params['link'];
314 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
316 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
317 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
319 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
322 $body = $l10n->t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
323 $params['source_name'],
324 $siteurl, $params['source_mail'],
325 $params['source_nick']
328 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
329 $tsitelink = sprintf($sitelink, $params['link']);
330 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
332 case "SYSTEM_DB_UPDATE_FAIL":
338 Logger::notice('Unhandled type', ['type' => $params['type']]);
342 return notification_store_and_send($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
345 function notification_store_and_send($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page)
347 $item_id = $params['item']['id'] ?? 0;
348 $uri_id = $params['item']['uri-id'] ?? 0;
349 $parent_id = $params['item']['parent'] ?? 0;
350 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
352 // Ensure that the important fields are set at any time
353 $fields = ['nickname'];
354 $user = User::getById($params['uid'], $fields);
356 $sitename = DI::config()->get('config', 'sitename');
358 $nickname = $user['nickname'];
360 $hostname = DI::baseUrl()->getHostname();
361 if (strpos($hostname, ':')) {
362 $hostname = substr($hostname, 0, strpos($hostname, ':'));
365 // Creates a new email builder for the notification email
366 $emailBuilder = DI::emailer()->newNotifyMail();
368 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
370 $subject .= " (".$nickname."@".$hostname.")";
374 'subject' => $subject,
375 'preamble' => $preamble,
376 'epreamble' => $epreamble,
378 'sitelink' => $sitelink,
379 'tsitelink' => $tsitelink,
380 'hsitelink' => $hsitelink,
381 'itemlink' => $itemlink
384 Hook::callAll('enotify', $h);
386 $subject = $h['subject'];
388 $preamble = $h['preamble'];
389 $epreamble = $h['epreamble'];
393 $tsitelink = $h['tsitelink'];
394 $hsitelink = $h['hsitelink'];
395 $itemlink = $h['itemlink'];
399 if ($show_in_notification_page) {
401 'name' => $params['source_name'] ?? '',
402 'name_cache' => substr(strip_tags(BBCode::convertForUriId($uri_id, $params['source_name'])), 0, 255),
403 'url' => $params['source_link'] ?? '',
404 'photo' => $params['source_photo'] ?? '',
405 'link' => $itemlink ?? '',
406 'uid' => $params['uid'] ?? 0,
407 'type' => $params['type'] ?? '',
408 'verb' => $params['verb'] ?? '',
409 'otype' => $params['otype'] ?? '',
411 if (!empty($item_id)) {
412 $fields['iid'] = $item_id;
414 if (!empty($uri_id)) {
415 $fields['uri-id'] = $uri_id;
417 if (!empty($parent_id)) {
418 $fields['parent'] = $parent_id;
420 if (!empty($parent_uri_id)) {
421 $fields['parent-uri-id'] = $parent_uri_id;
423 $notification = DI::notify()->insert($fields);
425 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
426 if (!$notification) {
430 $notification->msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $notification->link]);
432 DI::notify()->update($notification);
434 $itemlink = DI::baseUrl() . '/notification/' . $notification->id;
435 $notify_id = $notification->id;
438 // send email notification if notification preferences permit
439 if ((intval($params['notify_flags']) & intval($params['type']))
440 || $params['type'] == Notification\Type::SYSTEM) {
442 Logger::log('sending notification email');
444 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
445 $parent = Post::selectFirst(['guid'], ['id' => $params['parent']]);
446 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
448 // Is this the first email notification for this parent item and user?
449 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
450 Logger::log("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']), Logger::DEBUG);
452 $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
453 'receiver-uid' => $params['uid'], 'parent-item' => 0];
454 DBA::insert('notify-threads', $fields);
456 $emailBuilder->setHeader('Message-ID', $message_id);
457 $log_msg = "include/enotify: No previous notification found for this parent:\n" .
458 " parent: ${params['parent']}\n" . " uid : ${params['uid']}\n";
459 Logger::log($log_msg, Logger::DEBUG);
461 // If not, just "follow" the thread.
462 $emailBuilder->setHeader('References', $message_id);
463 $emailBuilder->setHeader('In-Reply-To', $message_id);
464 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
469 'preamble' => $preamble,
470 'type' => $params['type'],
471 'parent' => $parent_id,
472 'source_name' => $params['source_name'] ?? null,
473 'source_link' => $params['source_link'] ?? null,
474 'source_photo' => $params['source_photo'] ?? null,
475 'uid' => $params['uid'],
476 'hsitelink' => $hsitelink,
477 'tsitelink' => $tsitelink,
478 'itemlink' => $itemlink,
481 'subject' => $subject,
482 'headers' => $emailBuilder->getHeaders(),
485 Hook::callAll('enotify_mail', $datarray);
488 ->withHeaders($datarray['headers'])
489 ->withRecipient($params['to_email'])
491 'uid' => $datarray['uid'],
492 'language' => $params['language'],
494 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
495 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
496 ->withItemLink($datarray['itemlink']);
498 // If a photo is present, add it to the email
499 if (!empty($datarray['source_photo'])) {
500 $emailBuilder->withPhoto(
501 $datarray['source_photo'],
502 $datarray['source_link'] ?? $sitelink,
503 $datarray['source_name'] ?? $sitename);
506 $email = $emailBuilder->build();
508 // use the Emailer class to send the message
509 return DI::emailer()->send($email);
515 function notification_from_array(array $notification)
517 Logger::info('Start', ['uid' => $notification['uid'], 'id' => $notification['id'], 'type' => $notification['type']]);
519 if ($notification['type'] == Post\UserNotification::NOTIF_NONE) {
520 Logger::info('Not an item based notification, quitting', ['uid' => $notification['uid'], 'id' => $notification['id'], 'type' => $notification['type']]);
525 $params['verb'] = Verb::getByID($notification['vid']);
527 $params['uid'] = $notification['uid'];
528 $params['otype'] = Notification\ObjectType::ITEM;
530 $user = User::getById($notification['uid']);
532 $params['notify_flags'] = $user['notify-flags'];
533 $params['language'] = $user['language'];
534 $params['to_name'] = $user['username'];
535 $params['to_email'] = $user['email'];
537 // from here on everything is in the recipients language
538 $l10n = DI::l10n()->withLang($user['language']);
540 $contact = Contact::getById($notification['actor-id'], ['url', 'name', 'photo']);
541 if (DBA::isResult($contact)) {
542 $params['source_link'] = $contact['url'];
543 $params['source_name'] = $contact['name'];
544 $params['source_photo'] = $contact['photo'];
547 $item = Post::selectFirstForUser($notification['uid'], Item::ITEM_FIELDLIST,
548 ['uid' => [0, $notification['uid']], 'uri-id' => $notification['target-uri-id'], 'deleted' => false],
549 ['order' => ['uid' => true]]);
551 Logger::info('Item not found', ['uri-id' => $notification['target-uri-id'], 'type' => $notification['type']]);
555 $params['item'] = $item;
556 $params['parent'] = $item['parent'];
557 $params['link'] = DI::baseUrl() . '/display/' . urlencode($item['guid']);
559 $subjectPrefix = $l10n->t('[Friendica:Notify]');
561 if (Post\ThreadUser::getIgnored($notification['parent-uri-id'], $notification['uid'])) {
562 Logger::info('Thread is ignored', ['parent-uri-id' => $notification['parent-uri-id'], 'type' => $notification['type']]);
566 // Check to see if there was already a tag notify or comment notify for this post.
567 // If so don't create a second notification
568 $condition = ['type' => [Notification\Type::TAG_SELF, Notification\Type::COMMENT, Notification\Type::SHARE],
569 'link' => $params['link'], 'verb' => Activity::POST, 'uid' => $notification['uid']];
570 if (DBA::exists('notify', $condition)) {
571 Logger::info('Duplicate found, quitting', $condition);
575 $content = Plaintext::getPost($item, 70);
576 if (!empty($content['text'])) {
577 $title = '"' . trim(str_replace("\n", " ", $content['text'])) . '"';
579 $title = $item['title'];
582 // Some mail software relies on subject field for threading.
583 // So, we cannot have different subjects for notifications of the same thread.
584 // Before this we have the name of the replier on the subject rendering
585 // different subjects for messages on the same thread.
586 if ($notification['type'] == Post\UserNotification::NOTIF_EXPLICIT_TAGGED) {
587 $params['type'] = Notification\Type::TAG_SELF;
588 $subject = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
589 } elseif ($notification['type'] == Post\UserNotification::NOTIF_SHARED) {
590 $params['type'] = Notification\Type::SHARE;
591 $subject = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
593 $params['type'] = Notification\Type::COMMENT;
594 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
597 $msg = Notification::getMessage($notification);
599 Logger::info('No notification message, quitting', ['uid' => $notification['uid'], 'id' => $notification['id'], 'type' => $notification['type']]);
603 $preamble = $msg['plain'];
604 $epreamble = $msg['rich'];
606 $sitename = DI::config()->get('config', 'sitename');
607 $siteurl = DI::baseUrl()->get(true);
609 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
610 $tsitelink = sprintf($sitelink, $siteurl);
611 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
612 $itemlink = $params['link'];
614 Logger::info('Perform notification', ['uid' => $notification['uid'], 'id' => $notification['id'], 'type' => $notification['type']]);
616 return notification_store_and_send($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);