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\Plaintext;
23 use Friendica\Core\Hook;
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Item;
30 use Friendica\Model\Notification;
31 use Friendica\Model\Post;
32 use Friendica\Model\User;
33 use Friendica\Navigation\Notifications;
34 use Friendica\Protocol\Activity;
37 * Creates a notification entry and possibly sends a mail
39 * @param array $params Array with the elements:
40 * type, event, otype, activity, verb, uid, cid, item, link,
41 * source_name, source_mail, source_nick, source_link, source_photo,
42 * show_in_notification_page
45 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
47 function notification($params)
49 /** @var string the common prefix of a notification subject */
50 $subjectPrefix = DI::l10n()->t('[Friendica:Notify]');
52 // Temporary logging for finding the origin
53 if (!isset($params['uid'])) {
54 Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
57 // Ensure that the important fields are set at any time
58 $fields = ['nickname', 'page-flags', 'notify-flags', 'language', 'username', 'email'];
59 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
61 if (!DBA::isResult($user)) {
62 Logger::error('Unknown user', ['uid' => $params['uid']]);
66 // There is no need to create notifications for forum accounts
67 if (in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
71 $params['notify_flags'] = $user['notify-flags'];
72 $params['language'] = $user['language'];
73 $params['to_name'] = $user['username'];
74 $params['to_email'] = $user['email'];
76 // from here on everything is in the recipients language
77 $l10n = DI::l10n()->withLang($params['language']);
79 if (!empty($params['cid'])) {
80 $contact = Contact::getById($params['cid'], ['url', 'name', 'photo']);
81 if (DBA::isResult($contact)) {
82 $params['source_link'] = $contact['url'];
83 $params['source_name'] = $contact['name'];
84 $params['source_photo'] = $contact['photo'];
88 $siteurl = DI::baseUrl()->get(true);
89 $sitename = DI::config()->get('config', 'sitename');
91 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
92 // the database, and an email is sent if applicable.
93 // default, if not specified: true
94 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
96 $title = $params['item']['title'] ?? '';
97 $body = $params['item']['body'] ?? '';
99 $parent_id = $params['item']['parent'] ?? 0;
100 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
110 switch ($params['type']) {
111 case Notification\Type::MAIL:
112 $itemlink = $params['link'];
114 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
116 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
117 $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]');
119 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
120 $tsitelink = sprintf($sitelink, $itemlink);
121 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
123 // Mail notifications aren't using the "notify" table entry
124 $show_in_notification_page = false;
127 case Notification\Type::COMMENT:
128 if (Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
129 Logger::info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
133 $item = Post::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
138 $item_post_type = Item::postType($item, $l10n);
140 $content = Plaintext::getPost($item, 70);
141 if (!empty($content['text'])) {
142 $title = '"' . trim(str_replace("\n", " ", $content['text'])) . '"';
147 // First go for the general message
149 // "George Bull's post"
150 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
151 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
155 $message = $l10n->t('%1$s commented on your %2$s %3$s');
156 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
158 } elseif ($item['author-link'] == $params['source_link']) {
159 $message = $l10n->t('%1$s commented on their %2$s %3$s');
160 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
163 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
165 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
167 $epreamble = $dest_str;
169 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
170 $tsitelink = sprintf($sitelink, $siteurl);
171 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
172 $itemlink = $params['link'];
175 case Notification\Type::WALL:
176 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
178 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
179 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
180 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
184 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
185 $tsitelink = sprintf($sitelink, $siteurl);
186 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
187 $itemlink = $params['link'];
190 case Notification\Type::POKE:
191 $subject = $l10n->t('%1$s %2$s poked you', $subjectPrefix, $params['source_name']);
193 $preamble = $l10n->t('%1$s poked you at %2$s', $params['source_name'], $sitename);
194 $epreamble = $l10n->t('%1$s [url=%2$s]poked you[/url].',
195 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
199 $subject = str_replace('poked', $l10n->t($params['activity']), $subject);
200 $preamble = str_replace('poked', $l10n->t($params['activity']), $preamble);
201 $epreamble = str_replace('poked', $l10n->t($params['activity']), $epreamble);
203 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
204 $tsitelink = sprintf($sitelink, $siteurl);
205 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
206 $itemlink = $params['link'];
209 case Notification\Type::INTRO:
210 $itemlink = $params['link'];
211 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
213 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
214 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
216 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
219 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
221 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
222 $tsitelink = sprintf($sitelink, $siteurl);
223 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
225 switch ($params['verb']) {
226 case Activity::FRIEND:
227 // someone started to share with user (mostly OStatus)
228 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
230 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
231 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
232 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
236 case Activity::FOLLOW:
237 // someone started to follow the user (mostly OStatus)
238 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
240 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
241 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
242 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
247 // ACTIVITY_REQ_FRIEND is default activity for notifications
252 case Notification\Type::SUGGEST:
253 $itemlink = $params['link'];
254 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
256 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
257 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
259 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
260 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
263 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
264 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
265 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
267 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
268 $tsitelink = sprintf($sitelink, $siteurl);
269 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
272 case Notification\Type::CONFIRM:
273 if ($params['verb'] == Activity::FRIEND) { // mutual connection
274 $itemlink = $params['link'];
275 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
277 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
278 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
280 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
283 $body = $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
285 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
286 $tsitelink = sprintf($sitelink, $siteurl);
287 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
288 } else { // ACTIVITY_FOLLOW
289 $itemlink = $params['link'];
290 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
292 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
293 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
295 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
298 $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']);
300 $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
302 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
303 $tsitelink = sprintf($sitelink, $siteurl);
304 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
308 case Notification\Type::SYSTEM:
309 switch($params['event']) {
310 case "SYSTEM_REGISTER_REQUEST":
311 $itemlink = $params['link'];
312 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
314 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
315 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
317 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
320 $body = $l10n->t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
321 $params['source_name'],
322 $siteurl, $params['source_mail'],
323 $params['source_nick']
326 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
327 $tsitelink = sprintf($sitelink, $params['link']);
328 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
330 case "SYSTEM_DB_UPDATE_FAIL":
336 Logger::notice('Unhandled type', ['type' => $params['type']]);
340 return notification_store_and_send($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
343 function notification_store_and_send($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page)
345 $item_id = $params['item']['id'] ?? 0;
346 $uri_id = $params['item']['uri-id'] ?? 0;
347 $parent_id = $params['item']['parent'] ?? 0;
348 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
350 // Ensure that the important fields are set at any time
351 $fields = ['nickname'];
352 $user = User::getById($params['uid'], $fields);
354 $sitename = DI::config()->get('config', 'sitename');
356 $nickname = $user['nickname'];
358 $hostname = DI::baseUrl()->getHostname();
359 if (strpos($hostname, ':')) {
360 $hostname = substr($hostname, 0, strpos($hostname, ':'));
363 // Creates a new email builder for the notification email
364 $emailBuilder = DI::emailer()->newNotifyMail();
366 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
368 $subject .= " (".$nickname."@".$hostname.")";
372 'subject' => $subject,
373 'preamble' => $preamble,
374 'epreamble' => $epreamble,
376 'sitelink' => $sitelink,
377 'tsitelink' => $tsitelink,
378 'hsitelink' => $hsitelink,
379 'itemlink' => $itemlink
382 Hook::callAll('enotify', $h);
384 $subject = $h['subject'];
386 $preamble = $h['preamble'];
387 $epreamble = $h['epreamble'];
391 $tsitelink = $h['tsitelink'];
392 $hsitelink = $h['hsitelink'];
393 $itemlink = $h['itemlink'];
397 if ($show_in_notification_page) {
398 $Notify = DI::notifyFactory()->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
400 $Notify = DI::notify()->save($Notify);
401 } catch (Notifications\Exception\NotificationCreationInterceptedException $e) {
402 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
406 $Notify->updateMsgFromPreamble($epreamble);
407 $Notify = DI::notify()->save($Notify);
409 $itemlink = DI::baseUrl() . '/notification/' . $Notify->id;
410 $notify_id = $Notify->id;
413 // send email notification if notification preferences permit
414 if ((intval($params['notify_flags']) & intval($params['type']))
415 || $params['type'] == Notification\Type::SYSTEM) {
417 Logger::log('sending notification email');
419 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
420 $parent = Post::selectFirst(['guid'], ['id' => $params['parent']]);
421 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
423 // Is this the first email notification for this parent item and user?
424 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
425 Logger::log("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']), Logger::DEBUG);
427 $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
428 'receiver-uid' => $params['uid'], 'parent-item' => 0];
429 DBA::insert('notify-threads', $fields);
431 $emailBuilder->setHeader('Message-ID', $message_id);
432 $log_msg = "include/enotify: No previous notification found for this parent:\n" .
433 " parent: ${params['parent']}\n" . " uid : ${params['uid']}\n";
434 Logger::log($log_msg, Logger::DEBUG);
436 // If not, just "follow" the thread.
437 $emailBuilder->setHeader('References', $message_id);
438 $emailBuilder->setHeader('In-Reply-To', $message_id);
439 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
444 'preamble' => $preamble,
445 'type' => $params['type'],
446 'parent' => $parent_id,
447 'source_name' => $params['source_name'] ?? null,
448 'source_link' => $params['source_link'] ?? null,
449 'source_photo' => $params['source_photo'] ?? null,
450 'uid' => $params['uid'],
451 'hsitelink' => $hsitelink,
452 'tsitelink' => $tsitelink,
453 'itemlink' => $itemlink,
456 'subject' => $subject,
457 'headers' => $emailBuilder->getHeaders(),
460 Hook::callAll('enotify_mail', $datarray);
463 ->withHeaders($datarray['headers'])
464 ->withRecipient($params['to_email'])
466 'uid' => $datarray['uid'],
467 'language' => $params['language'],
469 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
470 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
471 ->withItemLink($datarray['itemlink']);
473 // If a photo is present, add it to the email
474 if (!empty($datarray['source_photo'])) {
475 $emailBuilder->withPhoto(
476 $datarray['source_photo'],
477 $datarray['source_link'] ?? $sitelink,
478 $datarray['source_name'] ?? $sitename);
481 $email = $emailBuilder->build();
483 // use the Emailer class to send the message
484 return DI::emailer()->send($email);
490 function notification_from_array(Notifications\Entity\Notification $Notification)
492 Logger::info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
494 if ($Notification->type === Post\UserNotification::TYPE_NONE) {
495 Logger::info('Not an item based notification, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
500 $params['verb'] = $Notification->verb;
501 $params['uid'] = $Notification->uid;
502 $params['otype'] = Notification\ObjectType::ITEM;
504 $user = User::getById($Notification->uid);
506 $params['notify_flags'] = $user['notify-flags'];
507 $params['language'] = $user['language'];
508 $params['to_name'] = $user['username'];
509 $params['to_email'] = $user['email'];
511 // from here on everything is in the recipients language
512 $l10n = DI::l10n()->withLang($user['language']);
514 $contact = Contact::getById($Notification->actorId, ['url', 'name', 'photo']);
515 if (DBA::isResult($contact)) {
516 $params['source_link'] = $contact['url'];
517 $params['source_name'] = $contact['name'];
518 $params['source_photo'] = $contact['photo'];
521 $item = Post::selectFirstForUser($Notification->uid, Item::ITEM_FIELDLIST,
522 ['uid' => [0, $Notification->uid], 'uri-id' => $Notification->targetUriId, 'deleted' => false],
523 ['order' => ['uid' => true]]);
525 Logger::info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
529 $params['item'] = $item;
530 $params['parent'] = $item['parent'];
531 $params['link'] = DI::baseUrl() . '/display/' . urlencode($item['guid']);
533 $subjectPrefix = $l10n->t('[Friendica:Notify]');
535 if (Post\ThreadUser::getIgnored($Notification->parentUriId, $Notification->uid)) {
536 Logger::info('Thread is ignored', ['parent-uri-id' => $Notification->parentUriId, 'type' => $Notification->type]);
540 // Check to see if there was already a tag notify or comment notify for this post.
541 // If so don't create a second notification
542 $condition = ['type' => [Notification\Type::TAG_SELF, Notification\Type::COMMENT, Notification\Type::SHARE],
543 'link' => $params['link'], 'verb' => Activity::POST];
544 if (DI::notify()->existsForUser($Notification->uid, $condition)) {
545 Logger::info('Duplicate found, quitting', $condition + ['uid' => $Notification->uid]);
549 $content = Plaintext::getPost($item, 70);
550 if (!empty($content['text'])) {
551 $title = '"' . trim(str_replace("\n", " ", $content['text'])) . '"';
553 $title = $item['title'];
556 // Some mail software relies on subject field for threading.
557 // So, we cannot have different subjects for notifications of the same thread.
558 // Before this we have the name of the replier on the subject rendering
559 // different subjects for messages on the same thread.
560 if ($Notification->type === Post\UserNotification::TYPE_EXPLICIT_TAGGED) {
561 $params['type'] = Notification\Type::TAG_SELF;
562 $subject = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
563 } elseif ($Notification->type === Post\UserNotification::TYPE_SHARED) {
564 $params['type'] = Notification\Type::SHARE;
565 $subject = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
567 $params['type'] = Notification\Type::COMMENT;
568 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
571 $msg = DI::notificationFactory()->getMessageFromNotification($Notification, DI::baseUrl(), $l10n);
573 Logger::info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
577 $preamble = $msg['plain'];
578 $epreamble = $msg['rich'];
580 $sitename = DI::config()->get('config', 'sitename');
581 $siteurl = DI::baseUrl()->get(true);
583 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
584 $tsitelink = sprintf($sitelink, $siteurl);
585 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
586 $itemlink = $params['link'];
588 Logger::info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
590 return notification_store_and_send($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);