3 * @copyright Copyright (C) 2010-2022, 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'];
234 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
236 if (!DBA::isResult($user)) {
237 $this->logger->error('Unknown user', ['uid' => $params['uid']]);
241 // There is no need to create notifications for forum accounts
242 if ($user['account-type'] == Model\User::ACCOUNT_TYPE_COMMUNITY) {
246 $params['notify_flags'] = $user['notify-flags'];
247 $params['language'] = $user['language'];
248 $params['to_name'] = $user['username'];
249 $params['to_email'] = $user['email'];
251 // from here on everything is in the recipients language
252 $l10n = $this->l10n->withLang($params['language']);
254 if (!empty($params['cid'])) {
255 $contact = Model\Contact::getById($params['cid'], ['url', 'name', 'photo']);
256 if (DBA::isResult($contact)) {
257 $params['source_link'] = $contact['url'];
258 $params['source_name'] = $contact['name'];
259 $params['source_photo'] = $contact['photo'];
263 $siteurl = $this->baseUrl->get(true);
264 $sitename = $this->config->get('config', 'sitename');
266 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
267 // the database, and an email is sent if applicable.
268 // default, if not specified: true
269 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
271 $title = $params['item']['title'] ?? '';
272 $body = $params['item']['body'] ?? '';
274 $parent_id = $params['item']['parent'] ?? 0;
275 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
285 switch ($params['type']) {
286 case Model\Notification\Type::MAIL:
287 $itemlink = $params['link'];
289 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
291 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
292 $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]');
294 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
295 $tsitelink = sprintf($sitelink, $itemlink);
296 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
298 // Mail notifications aren't using the "notify" table entry
299 $show_in_notification_page = false;
302 case Model\Notification\Type::COMMENT:
303 if (Model\Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
304 $this->logger->info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
308 $item = Model\Post::selectFirstForUser($params['uid'], Model\Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
313 $item_post_type = Model\Item::postType($item, $l10n);
315 $body = BBCode::toPlaintext($item['body'], false);
316 $title = Plaintext::shorten($body, 70);
317 if (!empty($title)) {
318 $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
321 // First go for the general message
323 // "George Bull's post"
324 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
325 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
329 $message = $l10n->t('%1$s commented on your %2$s %3$s');
330 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
332 } elseif ($item['author-link'] == $params['source_link']) {
333 $message = $l10n->t('%1$s commented on their %2$s %3$s');
334 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
337 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
339 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
341 $epreamble = $dest_str;
343 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
344 $tsitelink = sprintf($sitelink, $siteurl);
345 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
346 $itemlink = $params['link'];
349 case Model\Notification\Type::WALL:
350 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
352 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
353 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
354 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
358 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
359 $tsitelink = sprintf($sitelink, $siteurl);
360 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
361 $itemlink = $params['link'];
364 case Model\Notification\Type::INTRO:
365 $itemlink = $params['link'];
366 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
368 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
369 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
371 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
374 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
376 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
377 $tsitelink = sprintf($sitelink, $siteurl);
378 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
380 switch ($params['verb']) {
381 case Activity::FRIEND:
382 // someone started to share with user (mostly OStatus)
383 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
385 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
386 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
387 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
391 case Activity::FOLLOW:
392 // someone started to follow the user (mostly OStatus)
393 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
395 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
396 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
397 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
402 // ACTIVITY_REQ_FRIEND is default activity for notifications
407 case Model\Notification\Type::SUGGEST:
408 $itemlink = $params['link'];
409 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
411 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
412 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
414 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
415 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
418 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
419 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
420 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
422 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
423 $tsitelink = sprintf($sitelink, $siteurl);
424 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
427 case Model\Notification\Type::CONFIRM:
428 if ($params['verb'] == Activity::FRIEND) { // mutual connection
429 $itemlink = $params['link'];
430 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
432 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
433 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
435 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
438 $body = $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
440 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
441 $tsitelink = sprintf($sitelink, $siteurl);
442 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
443 } else { // ACTIVITY_FOLLOW
444 $itemlink = $params['link'];
445 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
447 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
448 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
450 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
453 $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']);
455 $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
457 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
458 $tsitelink = sprintf($sitelink, $siteurl);
459 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
463 case Model\Notification\Type::SYSTEM:
464 switch($params['event']) {
465 case 'SYSTEM_REGISTER_REQUEST':
466 $itemlink = $params['link'];
467 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
469 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
470 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
472 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
475 $body = $l10n->t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
476 $params['source_name'],
477 $siteurl, $params['source_mail'],
478 $params['source_nick']
481 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
482 $tsitelink = sprintf($sitelink, $params['link']);
483 $hsitelink = sprintf($sitelink, '<a href="' . $params['link'] . '">' . $sitename . '</a><br><br>');
486 case 'SYSTEM_DB_UPDATE_FAIL': // @TODO Unused (only here)
492 $this->logger->notice('Unhandled type', ['type' => $params['type']]);
496 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
499 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
501 $item_id = $params['item']['id'] ?? 0;
502 $uri_id = $params['item']['uri-id'] ?? null;
503 $parent_id = $params['item']['parent'] ?? 0;
504 $parent_uri_id = $params['item']['parent-uri-id'] ?? null;
506 // Ensure that the important fields are set at any time
507 $fields = ['nickname'];
508 $user = Model\User::getById($params['uid'], $fields);
510 $sitename = $this->config->get('config', 'sitename');
512 $nickname = $user['nickname'];
514 $hostname = $this->baseUrl->getHostname();
515 if (strpos($hostname, ':')) {
516 $hostname = substr($hostname, 0, strpos($hostname, ':'));
519 // Creates a new email builder for the notification email
520 $emailBuilder = $this->emailer->newNotifyMail();
522 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
524 $subject .= " (".$nickname."@".$hostname.")";
528 'subject' => $subject,
529 'preamble' => $preamble,
530 'epreamble' => $epreamble,
532 'sitelink' => $sitelink,
533 'tsitelink' => $tsitelink,
534 'hsitelink' => $hsitelink,
535 'itemlink' => $itemlink
538 Hook::callAll('enotify', $h);
540 $subject = $h['subject'];
542 $preamble = $h['preamble'];
543 $epreamble = $h['epreamble'];
547 $tsitelink = $h['tsitelink'];
548 $hsitelink = $h['hsitelink'];
549 $itemlink = $h['itemlink'];
553 if ($show_in_notification_page) {
554 $Notify = $this->factory->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
556 $Notify = $this->save($Notify);
557 } catch (Exception\NotificationCreationInterceptedException $e) {
558 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
562 $Notify->updateMsgFromPreamble($epreamble);
563 $Notify = $this->save($Notify);
565 $itemlink = $this->baseUrl->get() . '/notify/' . $Notify->id;
566 $notify_id = $Notify->id;
569 // send email notification if notification preferences permit
570 if ((intval($params['notify_flags']) & intval($params['type']))
571 || $params['type'] == Model\Notification\Type::SYSTEM) {
573 $this->logger->notice('sending notification email');
575 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
576 $parent = Model\Post::selectFirst(['guid'], ['id' => $params['parent']]);
577 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
579 // Is this the first email notification for this parent item and user?
580 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
581 $this->logger->info("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']));
583 $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
584 'receiver-uid' => $params['uid'], 'parent-item' => 0];
585 DBA::insert('notify-threads', $fields);
587 $emailBuilder->setHeader('Message-ID', $message_id);
588 $log_msg = "include/enotify: No previous notification found for this parent:\n" .
589 " parent: ${params['parent']}\n" . " uid : ${params['uid']}\n";
590 $this->logger->info($log_msg);
592 // If not, just "follow" the thread.
593 $emailBuilder->setHeader('References', $message_id);
594 $emailBuilder->setHeader('In-Reply-To', $message_id);
595 $this->logger->info("There's already a notification for this parent.");
600 'preamble' => $preamble,
601 'type' => $params['type'],
602 'parent' => $parent_id,
603 'source_name' => $params['source_name'] ?? null,
604 'source_link' => $params['source_link'] ?? null,
605 'source_photo' => $params['source_photo'] ?? null,
606 'uid' => $params['uid'],
607 'hsitelink' => $hsitelink,
608 'tsitelink' => $tsitelink,
609 'itemlink' => $itemlink,
612 'subject' => $subject,
613 'headers' => $emailBuilder->getHeaders(),
616 Hook::callAll('enotify_mail', $datarray);
619 ->withHeaders($datarray['headers'])
620 ->withRecipient($params['to_email'])
622 'uid' => $datarray['uid'],
623 'language' => $params['language'],
625 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
626 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
627 ->withItemLink($datarray['itemlink']);
629 // If a photo is present, add it to the email
630 if (!empty($datarray['source_photo'])) {
631 $emailBuilder->withPhoto(
632 $datarray['source_photo'],
633 $datarray['source_link'] ?? $sitelink,
634 $datarray['source_name'] ?? $sitename);
637 $email = $emailBuilder->build();
639 // use the Emailer class to send the message
640 return $this->emailer->send($email);
646 public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool
648 if (is_null($type)) {
649 $type = NotificationFactory::getType($Notification);
652 if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {
656 if ($this->pConfig->get($Notification->uid, 'system', 'notify_like') && ($type == Notification::TYPE_LIKE)) {
660 if ($this->pConfig->get($Notification->uid, 'system', 'notify_announce') && ($type == Notification::TYPE_RESHARE)) {
664 $notify_type = $this->pConfig->get($Notification->uid, 'system', 'notify_type');
666 // Fallback for the case when the notify type isn't set at all
667 if (is_null($notify_type) && !in_array($type, [Notification::TYPE_RESHARE, Notification::TYPE_LIKE])) {
671 if (!is_null($notify_type) && ($notify_type & $Notification->type)) {
678 public function createFromNotification(Entity\Notification $Notification): bool
680 $this->logger->info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
682 if ($Notification->type === Model\Post\UserNotification::TYPE_NONE) {
683 $this->logger->info('Not an item based notification, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
688 $params['verb'] = $Notification->verb;
689 $params['uid'] = $Notification->uid;
690 $params['otype'] = Model\Notification\ObjectType::ITEM;
692 $user = Model\User::getById($Notification->uid);
694 $params['notify_flags'] = $user['notify-flags'];
695 $params['language'] = $user['language'];
696 $params['to_name'] = $user['username'];
697 $params['to_email'] = $user['email'];
699 // from here on everything is in the recipients language
700 $l10n = $this->l10n->withLang($user['language']);
702 $contact = Model\Contact::getById($Notification->actorId, ['url', 'name', 'photo']);
703 if (DBA::isResult($contact)) {
704 $params['source_link'] = $contact['url'];
705 $params['source_name'] = $contact['name'];
706 $params['source_photo'] = $contact['photo'];
709 $item = Model\Post::selectFirstForUser($Notification->uid, Model\Item::ITEM_FIELDLIST,
710 ['uid' => [0, $Notification->uid], 'uri-id' => $Notification->targetUriId, 'deleted' => false],
711 ['order' => ['uid' => true]]);
713 $this->logger->info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
717 $params['item'] = $item;
718 $params['parent'] = $item['parent'];
719 $params['link'] = $this->baseUrl->get() . '/display/' . urlencode($item['guid']);
721 $subjectPrefix = $l10n->t('[Friendica:Notify]');
723 if (Model\Post\ThreadUser::getIgnored($Notification->parentUriId, $Notification->uid)) {
724 $this->logger->info('Thread is ignored', ['parent-uri-id' => $Notification->parentUriId, 'type' => $Notification->type]);
728 // Check to see if there was already a tag notify or comment notify for this post.
729 // If so don't create a second notification
730 $condition = ['type' => [Model\Notification\Type::TAG_SELF, Model\Notification\Type::COMMENT, Model\Notification\Type::SHARE],
731 'link' => $params['link'], 'verb' => Activity::POST];
732 if ($this->existsForUser($Notification->uid, $condition)) {
733 $this->logger->info('Duplicate found, quitting', $condition + ['uid' => $Notification->uid]);
737 $body = BBCode::toPlaintext($item['body'], false);
738 $title = Plaintext::shorten($body, 70);
739 if (!empty($title)) {
740 $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
743 // Some mail software relies on subject field for threading.
744 // So, we cannot have different subjects for notifications of the same thread.
745 // Before this we have the name of the replier on the subject rendering
746 // different subjects for messages on the same thread.
747 if ($Notification->type === Model\Post\UserNotification::TYPE_EXPLICIT_TAGGED) {
748 $params['type'] = Model\Notification\Type::TAG_SELF;
749 $subject = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
750 } elseif ($Notification->type === Model\Post\UserNotification::TYPE_SHARED) {
751 $params['type'] = Model\Notification\Type::SHARE;
752 $subject = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
754 $params['type'] = Model\Notification\Type::COMMENT;
755 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
758 $msg = $this->notification->getMessageFromNotification($Notification);
760 $this->logger->info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
764 $preamble = $msg['plain'];
765 $epreamble = $msg['rich'];
767 $sitename = $this->config->get('config', 'sitename');
768 $siteurl = $this->baseUrl->get(true);
770 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
771 $tsitelink = sprintf($sitelink, $siteurl);
772 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
773 $itemlink = $params['link'];
775 $this->logger->info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
777 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);