3 * @copyright Copyright (C) 2010-2023, 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 namespace Friendica\Navigation\Notifications\Repository;
24 use Friendica\App\BaseURL;
25 use Friendica\BaseRepository;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\Plaintext;
28 use Friendica\Core\Config\Capability\IManageConfigValues;
29 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
30 use Friendica\Core\Hook;
31 use Friendica\Core\L10n;
32 use Friendica\Core\System;
33 use Friendica\Database\Database;
34 use Friendica\Database\DBA;
35 use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
37 use Friendica\Navigation\Notifications\Collection;
38 use Friendica\Navigation\Notifications\Entity;
39 use Friendica\Navigation\Notifications\Exception;
40 use Friendica\Navigation\Notifications\Factory;
41 use Friendica\Network\HTTPException;
42 use Friendica\Object\Api\Mastodon\Notification;
43 use Friendica\Protocol\Activity;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Emailer;
46 use Psr\Log\LoggerInterface;
49 * @deprecated since 2022.05 Use \Friendica\Navigation\Notifications\Repository\Notification instead
51 class Notify extends BaseRepository
53 /** @var Factory\Notify */
62 /** @var IManageConfigValues */
65 /** @var IManagePersonalConfigValues */
71 /** @var Factory\Notification */
72 protected $notification;
74 protected static $table_name = 'notify';
76 public function __construct(Database $database, LoggerInterface $logger, L10n $l10n, BaseURL $baseUrl, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Emailer $emailer, Factory\Notification $notification, Factory\Notify $factory = null)
79 $this->baseUrl = $baseUrl;
80 $this->config = $config;
81 $this->pConfig = $pConfig;
82 $this->emailer = $emailer;
83 $this->notification = $notification;
85 parent::__construct($database, $logger, $factory ?? new Factory\Notify($logger));
89 * @param array $condition
90 * @param array $params
92 * @return Entity\Notify
93 * @throws HTTPException\NotFoundException
95 private function selectOne(array $condition, array $params = []): Entity\Notify
97 return parent::_selectOne($condition, $params);
100 private function select(array $condition, array $params = []): Collection\Notifies
102 return new Collection\Notifies(parent::_select($condition, $params)->getArrayCopy());
105 public function countForUser($uid, array $condition, array $params = []): int
107 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
109 return $this->count($condition, $params);
112 public function existsForUser($uid, array $condition): bool
114 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
116 return $this->exists($condition);
122 * @return Entity\Notify
123 * @throws HTTPException\NotFoundException
125 public function selectOneById(int $id): Entity\Notify
127 return $this->selectOne(['id' => $id]);
130 public function selectForUser(int $uid, array $condition, array $params): Collection\Notifies
132 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
134 return $this->select($condition, $params);
138 * Returns notifications for the user, unread first, ordered in descending chronological order.
142 * @return Collection\Notifies
144 public function selectAllForUser(int $uid, int $limit): Collection\Notifies
146 return $this->selectForUser($uid, [], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => $limit]);
149 public function setAllSeenForUser(int $uid, array $condition = []): bool
151 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
153 return $this->db->update(self::$table_name, ['seen' => true], $condition);
157 * @param Entity\Notify $Notify
159 * @return Entity\Notify
160 * @throws HTTPException\NotFoundException
161 * @throws HTTPException\InternalServerErrorException
162 * @throws Exception\NotificationCreationInterceptedException
164 public function save(Entity\Notify $Notify): Entity\Notify
167 'type' => $Notify->type,
168 'name' => $Notify->name,
169 'url' => $Notify->url,
170 'photo' => $Notify->photo,
171 'msg' => $Notify->msg,
172 'uid' => $Notify->uid,
173 'link' => $Notify->link,
174 'iid' => $Notify->itemId,
175 'parent' => $Notify->parent,
176 'seen' => $Notify->seen,
177 'verb' => $Notify->verb,
178 'otype' => $Notify->otype,
179 'name_cache' => $Notify->name_cache,
180 'msg_cache' => $Notify->msg_cache,
181 'uri-id' => $Notify->uriId,
182 'parent-uri-id' => $Notify->parentUriId,
186 $this->db->update(self::$table_name, $fields, ['id' => $Notify->id]);
188 $fields['date'] = DateTimeFormat::utcNow();
189 Hook::callAll('enotify_store', $fields);
191 $this->db->insert(self::$table_name, $fields);
193 $Notify = $this->selectOneById($this->db->lastInsertId());
199 public function setAllSeenForRelatedNotify(Entity\Notify $Notify): bool
202 '(`link` = ? OR (`parent` != 0 AND `parent` = ? AND `otype` = ?)) AND `uid` = ?',
208 return $this->db->update(self::$table_name, ['seen' => true], $condition);
212 * Creates a notification entry and possibly sends a mail
214 * @param array $params Array with the elements:
215 * type, event, otype, activity, verb, uid, cid, item, link,
216 * source_name, source_mail, source_nick, source_link, source_photo,
217 * show_in_notification_page
220 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222 function createFromArray($params)
224 /** @var string the common prefix of a notification subject */
225 $subjectPrefix = $this->l10n->t('[Friendica:Notify]');
227 // Temporary logging for finding the origin
228 if (!isset($params['uid'])) {
229 $this->logger->notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
232 // Ensure that the important fields are set at any time
233 $fields = ['nickname', 'account-type', 'notify-flags', 'language', 'username', 'email', 'account_removed', 'account_expired'];
234 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
236 if (!DBA::isResult($user)) {
237 $this->logger->error('Unknown user', ['uid' => $params['uid']]);
241 if ($user['account_removed'] || $user['account_expired']) {
245 // There is no need to create notifications for forum accounts
246 if ($user['account-type'] == Model\User::ACCOUNT_TYPE_COMMUNITY) {
250 $params['notify_flags'] = $user['notify-flags'];
251 $params['language'] = $user['language'];
252 $params['to_name'] = $user['username'];
253 $params['to_email'] = $user['email'];
255 // from here on everything is in the recipients language
256 $l10n = $this->l10n->withLang($params['language']);
258 if (!empty($params['cid'])) {
259 $contact = Model\Contact::getById($params['cid'], ['url', 'name', 'photo']);
260 if (DBA::isResult($contact)) {
261 $params['source_link'] = $contact['url'];
262 $params['source_name'] = $contact['name'];
263 $params['source_photo'] = $contact['photo'];
267 $siteurl = $this->baseUrl;
268 $sitename = $this->config->get('config', 'sitename');
270 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
271 // the database, and an email is sent if applicable.
272 // default, if not specified: true
273 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
275 $title = $params['item']['title'] ?? '';
276 $body = $params['item']['body'] ?? '';
278 $parent_id = $params['item']['parent'] ?? 0;
279 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
289 switch ($params['type']) {
290 case Model\Notification\Type::MAIL:
291 $itemlink = $params['link'];
293 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
295 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
296 $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]');
298 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
299 $tsitelink = sprintf($sitelink, $itemlink);
300 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
302 // Mail notifications aren't using the "notify" table entry
303 $show_in_notification_page = false;
306 case Model\Notification\Type::COMMENT:
307 if (Model\Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
308 $this->logger->info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
312 $item = Model\Post::selectFirstForUser($params['uid'], Model\Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
317 $item_post_type = Model\Item::postType($item, $l10n);
319 $body = BBCode::toPlaintext($item['body'], false);
320 $title = Plaintext::shorten($body, 70);
321 if (!empty($title)) {
322 $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
325 // First go for the general message
327 // "George Bull's post"
328 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
329 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
333 $message = $l10n->t('%1$s commented on your %2$s %3$s');
334 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
336 } elseif ($item['author-link'] == $params['source_link']) {
337 $message = $l10n->t('%1$s commented on their %2$s %3$s');
338 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
341 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
343 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
345 $epreamble = $dest_str;
347 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
348 $tsitelink = sprintf($sitelink, $siteurl);
349 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
350 $itemlink = $params['link'];
353 case Model\Notification\Type::WALL:
354 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
356 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
357 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
358 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
362 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
363 $tsitelink = sprintf($sitelink, $siteurl);
364 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
365 $itemlink = $params['link'];
368 case Model\Notification\Type::INTRO:
369 $itemlink = $params['link'];
370 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
372 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
373 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
375 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
378 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
380 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
381 $tsitelink = sprintf($sitelink, $siteurl);
382 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
384 switch ($params['verb']) {
385 case Activity::FRIEND:
386 // someone started to share with user (mostly OStatus)
387 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
389 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
390 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
391 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
395 case Activity::FOLLOW:
396 // someone started to follow the user (mostly OStatus)
397 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
399 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
400 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
401 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
406 // ACTIVITY_REQ_FRIEND is default activity for notifications
411 case Model\Notification\Type::SUGGEST:
412 $itemlink = $params['link'];
413 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
415 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
416 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
418 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
419 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
422 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
423 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
424 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
426 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
427 $tsitelink = sprintf($sitelink, $siteurl);
428 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
431 case Model\Notification\Type::CONFIRM:
432 if ($params['verb'] == Activity::FRIEND) { // mutual connection
433 $itemlink = $params['link'];
434 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
436 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
437 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
439 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
442 $body = $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
444 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
445 $tsitelink = sprintf($sitelink, $siteurl);
446 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
447 } else { // ACTIVITY_FOLLOW
448 $itemlink = $params['link'];
449 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
451 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
452 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
454 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
457 $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']);
459 $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
461 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
462 $tsitelink = sprintf($sitelink, $siteurl);
463 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
467 case Model\Notification\Type::SYSTEM:
468 switch($params['event']) {
469 case 'SYSTEM_REGISTER_REQUEST':
470 $itemlink = $params['link'];
471 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
473 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
474 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
476 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
479 $body = $l10n->t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
480 $params['source_name'],
481 $siteurl, $params['source_mail'],
482 $params['source_nick']
485 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
486 $tsitelink = sprintf($sitelink, $params['link']);
487 $hsitelink = sprintf($sitelink, '<a href="' . $params['link'] . '">' . $sitename . '</a><br><br>');
490 case 'SYSTEM_REGISTER_NEW':
491 $itemlink = $params['link'];
492 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('new registration');
494 $preamble = $l10n->t('You\'ve received a new registration from \'%1$s\' at %2$s', $params['source_name'], $sitename);
495 $epreamble = $l10n->t('You\'ve received a [url=%1$s]new registration[/url] from %2$s.',
497 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
500 $body = $l10n->t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
501 $params['source_name'],
502 $siteurl, $params['source_mail'],
503 $params['source_nick']
506 $sitelink = $l10n->t('Please visit %s to have a look at the new registration.');
507 $tsitelink = sprintf($sitelink, $params['link']);
508 $hsitelink = sprintf($sitelink, '<a href="' . $params['link'] . '">' . $sitename . '</a><br><br>');
511 case 'SYSTEM_DB_UPDATE_FAIL': // @TODO Unused (only here)
517 $this->logger->notice('Unhandled type', ['type' => $params['type']]);
521 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
524 private function storeAndSend(array $params, string $sitelink, string $tsitelink, string $hsitelink, string $title, string $subject, string $preamble, string $epreamble, string $body, string $itemlink, bool $show_in_notification_page): bool
526 $item_id = $params['item']['id'] ?? 0;
527 $uri_id = $params['item']['uri-id'] ?? null;
528 $parent_id = $params['item']['parent'] ?? 0;
529 $parent_uri_id = $params['item']['parent-uri-id'] ?? null;
531 // Ensure that the important fields are set at any time
532 $fields = ['nickname', 'account_removed', 'account_expired'];
533 $user = Model\User::getById($params['uid'], $fields);
534 if ($user['account_removed'] || $user['account_expired']) {
538 $sitename = $this->config->get('config', 'sitename');
540 $nickname = $user['nickname'];
542 $hostname = $this->baseUrl->getHost();
543 if (strpos($hostname, ':')) {
544 $hostname = substr($hostname, 0, strpos($hostname, ':'));
547 // Creates a new email builder for the notification email
548 $emailBuilder = $this->emailer->newNotifyMail();
550 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
552 $subject .= " (".$nickname."@".$hostname.")";
556 'subject' => $subject,
557 'preamble' => $preamble,
558 'epreamble' => $epreamble,
560 'sitelink' => $sitelink,
561 'tsitelink' => $tsitelink,
562 'hsitelink' => $hsitelink,
563 'itemlink' => $itemlink
566 Hook::callAll('enotify', $h);
568 $subject = $h['subject'];
570 $preamble = $h['preamble'];
571 $epreamble = $h['epreamble'];
575 $tsitelink = $h['tsitelink'];
576 $hsitelink = $h['hsitelink'];
577 $itemlink = $h['itemlink'];
581 if ($show_in_notification_page) {
582 $Notify = $this->factory->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
584 $Notify = $this->save($Notify);
585 } catch (Exception\NotificationCreationInterceptedException $e) {
586 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
590 $Notify->updateMsgFromPreamble($epreamble);
591 $Notify = $this->save($Notify);
593 $itemlink = $this->baseUrl . '/notify/' . $Notify->id;
594 $notify_id = $Notify->id;
597 // send email notification if notification preferences permit
598 if ((intval($params['notify_flags']) & intval($params['type']))
599 || $params['type'] == Model\Notification\Type::SYSTEM) {
601 $this->logger->notice('sending notification email');
603 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
604 $parent = Model\Post::selectFirst(['guid'], ['id' => $params['parent']]);
605 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
607 // Is this the first email notification for this parent item and user?
608 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
609 $this->logger->info("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']));
611 $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
612 'receiver-uid' => $params['uid'], 'parent-item' => 0];
613 DBA::insert('notify-threads', $fields);
615 $emailBuilder->setHeader('Message-ID', $message_id);
616 $log_msg = "No previous notification found for this parent:\n" .
617 " parent: {$params['parent']}\n" . " uid : {$params['uid']}\n";
618 $this->logger->info($log_msg);
620 // If not, just "follow" the thread.
621 $emailBuilder->setHeader('References', $message_id);
622 $emailBuilder->setHeader('In-Reply-To', $message_id);
623 $this->logger->info("There's already a notification for this parent.");
628 'preamble' => $preamble,
629 'type' => $params['type'],
630 'parent' => $parent_id,
631 'source_name' => $params['source_name'] ?? null,
632 'source_link' => $params['source_link'] ?? null,
633 'source_photo' => $params['source_photo'] ?? null,
634 'uid' => $params['uid'],
635 'hsitelink' => $hsitelink,
636 'tsitelink' => $tsitelink,
637 'itemlink' => $itemlink,
640 'subject' => $subject,
641 'headers' => $emailBuilder->getHeaders(),
644 Hook::callAll('enotify_mail', $datarray);
647 ->withHeaders($datarray['headers'])
648 ->withRecipient($params['to_email'])
650 'uid' => $datarray['uid'],
651 'language' => $params['language'],
653 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
654 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
655 ->withItemLink($datarray['itemlink']);
657 // If a photo is present, add it to the email
658 if (!empty($datarray['source_photo'])) {
659 $emailBuilder->withPhoto(
660 $datarray['source_photo'],
661 $datarray['source_link'] ?? $sitelink,
662 $datarray['source_name'] ?? $sitename);
665 $email = $emailBuilder->build();
667 // use the Emailer class to send the message
668 return $this->emailer->send($email);
674 public function shouldShowOnDesktop(Entity\Notification $Notification, string $type = null): bool
676 if (is_null($type)) {
677 $type = NotificationFactory::getType($Notification);
680 if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {
684 if ($this->pConfig->get($Notification->uid, 'system', 'notify_like') && ($type == Notification::TYPE_LIKE)) {
688 if ($this->pConfig->get($Notification->uid, 'system', 'notify_announce') && ($type == Notification::TYPE_RESHARE)) {
692 $notify_type = $this->pConfig->get($Notification->uid, 'system', 'notify_type');
694 // Fallback for the case when the notify type isn't set at all
695 if (is_null($notify_type) && !in_array($type, [Notification::TYPE_RESHARE, Notification::TYPE_LIKE])) {
699 if (!is_null($notify_type) && ($notify_type & $Notification->type)) {
706 public function createFromNotification(Entity\Notification $Notification): bool
708 $this->logger->info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
710 if ($Notification->type === Model\Post\UserNotification::TYPE_NONE) {
711 $this->logger->info('Not an item based notification, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
716 $params['verb'] = $Notification->verb;
717 $params['uid'] = $Notification->uid;
718 $params['otype'] = Model\Notification\ObjectType::ITEM;
720 $user = Model\User::getById($Notification->uid);
721 if ($user['account_removed'] || $user['account_expired']) {
725 $params['notify_flags'] = $user['notify-flags'];
726 $params['language'] = $user['language'];
727 $params['to_name'] = $user['username'];
728 $params['to_email'] = $user['email'];
730 // from here on everything is in the recipients language
731 $l10n = $this->l10n->withLang($user['language']);
733 $contact = Model\Contact::getById($Notification->actorId, ['url', 'name', 'photo']);
734 if (DBA::isResult($contact)) {
735 $params['source_link'] = $contact['url'];
736 $params['source_name'] = $contact['name'];
737 $params['source_photo'] = $contact['photo'];
740 $item = Model\Post::selectFirstForUser($Notification->uid, Model\Item::ITEM_FIELDLIST,
741 ['uid' => [0, $Notification->uid], 'uri-id' => $Notification->targetUriId, 'deleted' => false],
742 ['order' => ['uid' => true]]);
744 $this->logger->info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
748 $params['item'] = $item;
749 $params['parent'] = $item['parent'];
750 $params['link'] = $this->baseUrl . '/display/' . urlencode($item['guid']);
752 $subjectPrefix = $l10n->t('[Friendica:Notify]');
754 if (Model\Post\ThreadUser::getIgnored($Notification->parentUriId, $Notification->uid)) {
755 $this->logger->info('Thread is ignored', ['parent-uri-id' => $Notification->parentUriId, 'type' => $Notification->type]);
759 // Check to see if there was already a tag notify or comment notify for this post.
760 // If so don't create a second notification
761 $condition = ['type' => [Model\Notification\Type::TAG_SELF, Model\Notification\Type::COMMENT, Model\Notification\Type::SHARE],
762 'link' => $params['link'], 'verb' => Activity::POST];
763 if ($this->existsForUser($Notification->uid, $condition)) {
764 $this->logger->info('Duplicate found, quitting', $condition + ['uid' => $Notification->uid]);
768 $body = BBCode::toPlaintext($item['body'], false);
769 $title = Plaintext::shorten($body, 70);
770 if (!empty($title)) {
771 $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
774 // Some mail software relies on the subject field for threading.
775 // So, we cannot have different subjects for notifications of the same thread.
776 // Before this we have the name of the replier on the subject rendering
777 // different subjects for messages on the same thread.
778 if ($Notification->type === Model\Post\UserNotification::TYPE_EXPLICIT_TAGGED) {
779 $params['type'] = Model\Notification\Type::TAG_SELF;
780 $subject = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
781 } elseif ($Notification->type === Model\Post\UserNotification::TYPE_SHARED) {
782 $params['type'] = Model\Notification\Type::SHARE;
783 $subject = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
785 $params['type'] = Model\Notification\Type::COMMENT;
786 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
788 if ($params['verb'] = Activity::LIKE) {
789 switch ($Notification->type) {
790 case Model\Post\UserNotification::TYPE_DIRECT_COMMENT:
791 $subject = $l10n->t('%1$s %2$s liked your post #%3$d', $subjectPrefix, $contact['name'], $item['parent']);
793 case Model\Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT:
794 $subject = $l10n->t('%1$s %2$s liked your comment on #%3$d', $subjectPrefix, $contact['name'], $item['parent']);
800 $msg = $this->notification->getMessageFromNotification($Notification);
802 $this->logger->info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
806 $preamble = $msg['plain'];
807 $epreamble = $msg['rich'];
809 $sitename = $this->config->get('config', 'sitename');
810 $siteurl = $this->baseUrl;
812 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
813 $tsitelink = sprintf($sitelink, $siteurl);
814 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
815 $itemlink = $params['link'];
817 $this->logger->info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
819 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);
822 public function deleteForItem(int $itemUriId): void
824 $this->db->delete('notify', ['otype' => 'item', 'uri-id' => $itemUriId]);
825 $this->db->delete('notify', ['otype' => 'item', 'parent-uri-id' => $itemUriId]);