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
91 * @return Entity\Notify
92 * @throws HTTPException\NotFoundException
94 private function selectOne(array $condition, array $params = []): Entity\Notify
96 return parent::_selectOne($condition, $params);
99 private function select(array $condition, array $params = []): Collection\Notifies
101 return new Collection\Notifies(parent::_select($condition, $params)->getArrayCopy());
104 public function countForUser($uid, array $condition, array $params = []): int
106 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
108 return $this->count($condition, $params);
111 public function existsForUser($uid, array $condition): bool
113 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
115 return $this->exists($condition);
120 * @return Entity\Notify
121 * @throws HTTPException\NotFoundException
123 public function selectOneById(int $id): Entity\Notify
125 return $this->selectOne(['id' => $id]);
128 public function selectForUser(int $uid, array $condition, array $params): Collection\Notifies
130 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
132 return $this->select($condition, $params);
136 * Returns notifications for the user, unread first, ordered in descending chronological order.
140 * @return Collection\Notifies
142 public function selectAllForUser(int $uid, int $limit): Collection\Notifies
144 return $this->selectForUser($uid, [], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => $limit]);
147 public function setAllSeenForUser(int $uid, array $condition = []): bool
149 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
151 return $this->db->update(self::$table_name, ['seen' => true], $condition);
155 * @param Entity\Notify $Notify
156 * @return Entity\Notify
157 * @throws HTTPException\NotFoundException
158 * @throws HTTPException\InternalServerErrorException
159 * @throws Exception\NotificationCreationInterceptedException
161 public function save(Entity\Notify $Notify): Entity\Notify
164 'type' => $Notify->type,
165 'name' => $Notify->name,
166 'url' => $Notify->url,
167 'photo' => $Notify->photo,
168 'msg' => $Notify->msg,
169 'uid' => $Notify->uid,
170 'link' => $Notify->link,
171 'iid' => $Notify->itemId,
172 'parent' => $Notify->parent,
173 'seen' => $Notify->seen,
174 'verb' => $Notify->verb,
175 'otype' => $Notify->otype,
176 'name_cache' => $Notify->name_cache,
177 'msg_cache' => $Notify->msg_cache,
178 'uri-id' => $Notify->uriId,
179 'parent-uri-id' => $Notify->parentUriId,
183 $this->db->update(self::$table_name, $fields, ['id' => $Notify->id]);
185 $fields['date'] = DateTimeFormat::utcNow();
186 Hook::callAll('enotify_store', $fields);
188 $this->db->insert(self::$table_name, $fields);
190 $Notify = $this->selectOneById($this->db->lastInsertId());
196 public function setAllSeenForRelatedNotify(Entity\Notify $Notify): bool
199 '(`link` = ? OR (`parent` != 0 AND `parent` = ? AND `otype` = ?)) AND `uid` = ?',
205 return $this->db->update(self::$table_name, ['seen' => true], $condition);
209 * Creates a notification entry and possibly sends a mail
211 * @param array $params Array with the elements:
212 * type, event, otype, activity, verb, uid, cid, item, link,
213 * source_name, source_mail, source_nick, source_link, source_photo,
214 * show_in_notification_page
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
219 function createFromArray($params)
221 /** @var string the common prefix of a notification subject */
222 $subjectPrefix = $this->l10n->t('[Friendica:Notify]');
224 // Temporary logging for finding the origin
225 if (!isset($params['uid'])) {
226 $this->logger->notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
229 // Ensure that the important fields are set at any time
230 $fields = ['nickname', 'account-type', 'notify-flags', 'language', 'username', 'email'];
231 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
233 if (!DBA::isResult($user)) {
234 $this->logger->error('Unknown user', ['uid' => $params['uid']]);
238 // There is no need to create notifications for forum accounts
239 if ($user['account-type'] == Model\User::ACCOUNT_TYPE_COMMUNITY) {
243 $params['notify_flags'] = $user['notify-flags'];
244 $params['language'] = $user['language'];
245 $params['to_name'] = $user['username'];
246 $params['to_email'] = $user['email'];
248 // from here on everything is in the recipients language
249 $l10n = $this->l10n->withLang($params['language']);
251 if (!empty($params['cid'])) {
252 $contact = Model\Contact::getById($params['cid'], ['url', 'name', 'photo']);
253 if (DBA::isResult($contact)) {
254 $params['source_link'] = $contact['url'];
255 $params['source_name'] = $contact['name'];
256 $params['source_photo'] = $contact['photo'];
260 $siteurl = $this->baseUrl->get(true);
261 $sitename = $this->config->get('config', 'sitename');
263 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
264 // the database, and an email is sent if applicable.
265 // default, if not specified: true
266 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
268 $title = $params['item']['title'] ?? '';
269 $body = $params['item']['body'] ?? '';
271 $parent_id = $params['item']['parent'] ?? 0;
272 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
282 switch ($params['type']) {
283 case Model\Notification\Type::MAIL:
284 $itemlink = $params['link'];
286 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
288 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
289 $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]');
291 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
292 $tsitelink = sprintf($sitelink, $itemlink);
293 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
295 // Mail notifications aren't using the "notify" table entry
296 $show_in_notification_page = false;
299 case Model\Notification\Type::COMMENT:
300 if (Model\Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
301 $this->logger->info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
305 $item = Model\Post::selectFirstForUser($params['uid'], Model\Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
310 $item_post_type = Model\Item::postType($item, $l10n);
312 $body = BBCode::toPlaintext($item['body'], false);
313 $title = Plaintext::shorten($body, 70);
314 if (!empty($title)) {
315 $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
318 // First go for the general message
320 // "George Bull's post"
321 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
322 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
326 $message = $l10n->t('%1$s commented on your %2$s %3$s');
327 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
329 } elseif ($item['author-link'] == $params['source_link']) {
330 $message = $l10n->t('%1$s commented on their %2$s %3$s');
331 $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
334 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
336 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
338 $epreamble = $dest_str;
340 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
341 $tsitelink = sprintf($sitelink, $siteurl);
342 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
343 $itemlink = $params['link'];
346 case Model\Notification\Type::WALL:
347 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
349 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
350 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
351 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
355 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
356 $tsitelink = sprintf($sitelink, $siteurl);
357 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
358 $itemlink = $params['link'];
361 case Model\Notification\Type::POKE:
362 $subject = $l10n->t('%1$s %2$s poked you', $subjectPrefix, $params['source_name']);
364 $preamble = $l10n->t('%1$s poked you at %2$s', $params['source_name'], $sitename);
365 $epreamble = $l10n->t('%1$s [url=%2$s]poked you[/url].',
366 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
370 $subject = str_replace('poked', $l10n->t($params['activity']), $subject);
371 $preamble = str_replace('poked', $l10n->t($params['activity']), $preamble);
372 $epreamble = str_replace('poked', $l10n->t($params['activity']), $epreamble);
374 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
375 $tsitelink = sprintf($sitelink, $siteurl);
376 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
377 $itemlink = $params['link'];
380 case Model\Notification\Type::INTRO:
381 $itemlink = $params['link'];
382 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
384 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
385 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
387 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
390 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
392 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
393 $tsitelink = sprintf($sitelink, $siteurl);
394 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
396 switch ($params['verb']) {
397 case Activity::FRIEND:
398 // someone started to share with user (mostly OStatus)
399 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
401 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
402 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
403 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
407 case Activity::FOLLOW:
408 // someone started to follow the user (mostly OStatus)
409 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
411 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
412 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
413 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
418 // ACTIVITY_REQ_FRIEND is default activity for notifications
423 case Model\Notification\Type::SUGGEST:
424 $itemlink = $params['link'];
425 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
427 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
428 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
430 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
431 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
434 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
435 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
436 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
438 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
439 $tsitelink = sprintf($sitelink, $siteurl);
440 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
443 case Model\Notification\Type::CONFIRM:
444 if ($params['verb'] == Activity::FRIEND) { // mutual connection
445 $itemlink = $params['link'];
446 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
448 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
449 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
451 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
454 $body = $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
456 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
457 $tsitelink = sprintf($sitelink, $siteurl);
458 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
459 } else { // ACTIVITY_FOLLOW
460 $itemlink = $params['link'];
461 $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
463 $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
464 $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
466 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
469 $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']);
471 $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
473 $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
474 $tsitelink = sprintf($sitelink, $siteurl);
475 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
479 case Model\Notification\Type::SYSTEM:
480 switch($params['event']) {
481 case "SYSTEM_REGISTER_REQUEST":
482 $itemlink = $params['link'];
483 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
485 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
486 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
488 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
491 $body = $l10n->t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
492 $params['source_name'],
493 $siteurl, $params['source_mail'],
494 $params['source_nick']
497 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
498 $tsitelink = sprintf($sitelink, $params['link']);
499 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
501 case "SYSTEM_DB_UPDATE_FAIL":
507 $this->logger->notice('Unhandled type', ['type' => $params['type']]);
511 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
514 private function storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page)
516 $item_id = $params['item']['id'] ?? 0;
517 $uri_id = $params['item']['uri-id'] ?? null;
518 $parent_id = $params['item']['parent'] ?? 0;
519 $parent_uri_id = $params['item']['parent-uri-id'] ?? null;
521 // Ensure that the important fields are set at any time
522 $fields = ['nickname'];
523 $user = Model\User::getById($params['uid'], $fields);
525 $sitename = $this->config->get('config', 'sitename');
527 $nickname = $user['nickname'];
529 $hostname = $this->baseUrl->getHostname();
530 if (strpos($hostname, ':')) {
531 $hostname = substr($hostname, 0, strpos($hostname, ':'));
534 // Creates a new email builder for the notification email
535 $emailBuilder = $this->emailer->newNotifyMail();
537 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
539 $subject .= " (".$nickname."@".$hostname.")";
543 'subject' => $subject,
544 'preamble' => $preamble,
545 'epreamble' => $epreamble,
547 'sitelink' => $sitelink,
548 'tsitelink' => $tsitelink,
549 'hsitelink' => $hsitelink,
550 'itemlink' => $itemlink
553 Hook::callAll('enotify', $h);
555 $subject = $h['subject'];
557 $preamble = $h['preamble'];
558 $epreamble = $h['epreamble'];
562 $tsitelink = $h['tsitelink'];
563 $hsitelink = $h['hsitelink'];
564 $itemlink = $h['itemlink'];
568 if ($show_in_notification_page) {
569 $Notify = $this->factory->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
571 $Notify = $this->save($Notify);
572 } catch (Exception\NotificationCreationInterceptedException $e) {
573 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
577 $Notify->updateMsgFromPreamble($epreamble);
578 $Notify = $this->save($Notify);
580 $itemlink = $this->baseUrl->get() . '/notify/' . $Notify->id;
581 $notify_id = $Notify->id;
584 // send email notification if notification preferences permit
585 if ((intval($params['notify_flags']) & intval($params['type']))
586 || $params['type'] == Model\Notification\Type::SYSTEM) {
588 $this->logger->notice('sending notification email');
590 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
591 $parent = Model\Post::selectFirst(['guid'], ['id' => $params['parent']]);
592 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
594 // Is this the first email notification for this parent item and user?
595 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
596 $this->logger->info("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']));
598 $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
599 'receiver-uid' => $params['uid'], 'parent-item' => 0];
600 DBA::insert('notify-threads', $fields);
602 $emailBuilder->setHeader('Message-ID', $message_id);
603 $log_msg = "include/enotify: No previous notification found for this parent:\n" .
604 " parent: ${params['parent']}\n" . " uid : ${params['uid']}\n";
605 $this->logger->info($log_msg);
607 // If not, just "follow" the thread.
608 $emailBuilder->setHeader('References', $message_id);
609 $emailBuilder->setHeader('In-Reply-To', $message_id);
610 $this->logger->info("There's already a notification for this parent.");
615 'preamble' => $preamble,
616 'type' => $params['type'],
617 'parent' => $parent_id,
618 'source_name' => $params['source_name'] ?? null,
619 'source_link' => $params['source_link'] ?? null,
620 'source_photo' => $params['source_photo'] ?? null,
621 'uid' => $params['uid'],
622 'hsitelink' => $hsitelink,
623 'tsitelink' => $tsitelink,
624 'itemlink' => $itemlink,
627 'subject' => $subject,
628 'headers' => $emailBuilder->getHeaders(),
631 Hook::callAll('enotify_mail', $datarray);
634 ->withHeaders($datarray['headers'])
635 ->withRecipient($params['to_email'])
637 'uid' => $datarray['uid'],
638 'language' => $params['language'],
640 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
641 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
642 ->withItemLink($datarray['itemlink']);
644 // If a photo is present, add it to the email
645 if (!empty($datarray['source_photo'])) {
646 $emailBuilder->withPhoto(
647 $datarray['source_photo'],
648 $datarray['source_link'] ?? $sitelink,
649 $datarray['source_name'] ?? $sitename);
652 $email = $emailBuilder->build();
654 // use the Emailer class to send the message
655 return $this->emailer->send($email);
661 public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool
663 if (is_null($type)) {
664 $type = NotificationFactory::getType($Notification);
667 if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {
671 if ($this->pConfig->get($Notification->uid, 'system', 'notify_like') && ($type == Notification::TYPE_LIKE)) {
675 if ($this->pConfig->get($Notification->uid, 'system', 'notify_announce') && ($type == Notification::TYPE_RESHARE)) {
679 $notify_type = $this->pConfig->get($Notification->uid, 'system', 'notify_type');
681 // Fallback for the case when the notify type isn't set at all
682 if (is_null($notify_type) && !in_array($type, [Notification::TYPE_RESHARE, Notification::TYPE_LIKE])) {
686 if (!is_null($notify_type) && ($notify_type & $Notification->type)) {
693 public function createFromNotification(Entity\Notification $Notification)
695 $this->logger->info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
697 if ($Notification->type === Model\Post\UserNotification::TYPE_NONE) {
698 $this->logger->info('Not an item based notification, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
703 $params['verb'] = $Notification->verb;
704 $params['uid'] = $Notification->uid;
705 $params['otype'] = Model\Notification\ObjectType::ITEM;
707 $user = Model\User::getById($Notification->uid);
709 $params['notify_flags'] = $user['notify-flags'];
710 $params['language'] = $user['language'];
711 $params['to_name'] = $user['username'];
712 $params['to_email'] = $user['email'];
714 // from here on everything is in the recipients language
715 $l10n = $this->l10n->withLang($user['language']);
717 $contact = Model\Contact::getById($Notification->actorId, ['url', 'name', 'photo']);
718 if (DBA::isResult($contact)) {
719 $params['source_link'] = $contact['url'];
720 $params['source_name'] = $contact['name'];
721 $params['source_photo'] = $contact['photo'];
724 $item = Model\Post::selectFirstForUser($Notification->uid, Model\Item::ITEM_FIELDLIST,
725 ['uid' => [0, $Notification->uid], 'uri-id' => $Notification->targetUriId, 'deleted' => false],
726 ['order' => ['uid' => true]]);
728 $this->logger->info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
732 $params['item'] = $item;
733 $params['parent'] = $item['parent'];
734 $params['link'] = $this->baseUrl->get() . '/display/' . urlencode($item['guid']);
736 $subjectPrefix = $l10n->t('[Friendica:Notify]');
738 if (Model\Post\ThreadUser::getIgnored($Notification->parentUriId, $Notification->uid)) {
739 $this->logger->info('Thread is ignored', ['parent-uri-id' => $Notification->parentUriId, 'type' => $Notification->type]);
743 // Check to see if there was already a tag notify or comment notify for this post.
744 // If so don't create a second notification
745 $condition = ['type' => [Model\Notification\Type::TAG_SELF, Model\Notification\Type::COMMENT, Model\Notification\Type::SHARE],
746 'link' => $params['link'], 'verb' => Activity::POST];
747 if ($this->existsForUser($Notification->uid, $condition)) {
748 $this->logger->info('Duplicate found, quitting', $condition + ['uid' => $Notification->uid]);
752 $body = BBCode::toPlaintext($item['body'], false);
753 $title = Plaintext::shorten($body, 70);
754 if (!empty($title)) {
755 $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
758 // Some mail software relies on subject field for threading.
759 // So, we cannot have different subjects for notifications of the same thread.
760 // Before this we have the name of the replier on the subject rendering
761 // different subjects for messages on the same thread.
762 if ($Notification->type === Model\Post\UserNotification::TYPE_EXPLICIT_TAGGED) {
763 $params['type'] = Model\Notification\Type::TAG_SELF;
764 $subject = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
765 } elseif ($Notification->type === Model\Post\UserNotification::TYPE_SHARED) {
766 $params['type'] = Model\Notification\Type::SHARE;
767 $subject = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
769 $params['type'] = Model\Notification\Type::COMMENT;
770 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
773 $msg = $this->notification->getMessageFromNotification($Notification);
775 $this->logger->info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
779 $preamble = $msg['plain'];
780 $epreamble = $msg['rich'];
782 $sitename = $this->config->get('config', 'sitename');
783 $siteurl = $this->baseUrl->get(true);
785 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
786 $tsitelink = sprintf($sitelink, $siteurl);
787 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
788 $itemlink = $params['link'];
790 $this->logger->info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
792 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);