]> git.mxchange.org Git - friendica.git/blob - src/Navigation/Notifications/Repository/Notify.php
315b2e084ca5b23b8fbca7925dfc8acbcc591469
[friendica.git] / src / Navigation / Notifications / Repository / Notify.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Navigation\Notifications\Repository;
23
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;
36 use Friendica\Model;
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;
47
48 /**
49  * @deprecated since 2022.05 Use \Friendica\Navigation\Notifications\Repository\Notification instead
50  */
51 class Notify extends BaseRepository
52 {
53         /** @var Factory\Notify  */
54         protected $factory;
55
56         /** @var L10n  */
57         protected $l10n;
58
59         /** @var BaseURL  */
60         protected $baseUrl;
61
62         /** @var IManageConfigValues */
63         protected $config;
64
65         /** @var IManagePersonalConfigValues */
66         private $pConfig;
67
68         /** @var Emailer */
69         protected $emailer;
70
71         /** @var Factory\Notification */
72         protected $notification;
73
74         protected static $table_name = 'notify';
75
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)
77         {
78                 $this->l10n         = $l10n;
79                 $this->baseUrl      = $baseUrl;
80                 $this->config       = $config;
81                 $this->pConfig      = $pConfig;
82                 $this->emailer      = $emailer;
83                 $this->notification = $notification;
84
85                 parent::__construct($database, $logger, $factory ?? new Factory\Notify($logger));
86         }
87
88         /**
89          * @param array $condition
90          * @param array $params
91          *
92          * @return Entity\Notify
93          * @throws HTTPException\NotFoundException
94          */
95         private function selectOne(array $condition, array $params = []): Entity\Notify
96         {
97                 return parent::_selectOne($condition, $params);
98         }
99
100         private function select(array $condition, array $params = []): Collection\Notifies
101         {
102                 return new Collection\Notifies(parent::_select($condition, $params)->getArrayCopy());
103         }
104
105         public function countForUser($uid, array $condition, array $params = []): int
106         {
107                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
108
109                 return $this->count($condition, $params);
110         }
111
112         public function existsForUser($uid, array $condition): bool
113         {
114                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
115
116                 return $this->exists($condition);
117         }
118
119         /**
120          * @param int $id
121          *
122          * @return Entity\Notify
123          * @throws HTTPException\NotFoundException
124          */
125         public function selectOneById(int $id): Entity\Notify
126         {
127                 return $this->selectOne(['id' => $id]);
128         }
129
130         public function selectForUser(int $uid, array $condition, array $params): Collection\Notifies
131         {
132                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
133
134                 return $this->select($condition, $params);
135         }
136
137         /**
138          * Returns notifications for the user, unread first, ordered in descending chronological order.
139          *
140          * @param int $uid
141          * @param int $limit
142          * @return Collection\Notifies
143          */
144         public function selectAllForUser(int $uid, int $limit): Collection\Notifies
145         {
146                 return $this->selectForUser($uid, [], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => $limit]);
147         }
148
149         public function setAllSeenForUser(int $uid, array $condition = []): bool
150         {
151                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
152
153                 return $this->db->update(self::$table_name, ['seen' => true], $condition);
154         }
155
156         /**
157          * @param Entity\Notify $Notify
158          *
159          * @return Entity\Notify
160          * @throws HTTPException\NotFoundException
161          * @throws HTTPException\InternalServerErrorException
162          * @throws Exception\NotificationCreationInterceptedException
163          */
164         public function save(Entity\Notify $Notify): Entity\Notify
165         {
166                 $fields = [
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,
183                 ];
184
185                 if ($Notify->id) {
186                         $this->db->update(self::$table_name, $fields, ['id' => $Notify->id]);
187                 } else {
188                         $fields['date'] = DateTimeFormat::utcNow();
189                         Hook::callAll('enotify_store', $fields);
190
191                         $this->db->insert(self::$table_name, $fields);
192
193                         $Notify = $this->selectOneById($this->db->lastInsertId());
194                 }
195
196                 return $Notify;
197         }
198
199         public function setAllSeenForRelatedNotify(Entity\Notify $Notify): bool
200         {
201                 $condition = [
202                         '(`link` = ? OR (`parent` != 0 AND `parent` = ? AND `otype` = ?)) AND `uid` = ?',
203                         $Notify->link,
204                         $Notify->parent,
205                         $Notify->otype,
206                         $Notify->uid
207                 ];
208                 return $this->db->update(self::$table_name, ['seen' => true], $condition);
209         }
210
211         /**
212          * Creates a notification entry and possibly sends a mail
213          *
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
218          *
219          * @return bool
220          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
221          */
222         function createFromArray($params)
223         {
224                 /** @var string the common prefix of a notification subject */
225                 $subjectPrefix = $this->l10n->t('[Friendica:Notify]');
226
227                 // Temporary logging for finding the origin
228                 if (!isset($params['uid'])) {
229                         $this->logger->notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
230                 }
231
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']]);
235
236                 if (!DBA::isResult($user)) {
237                         $this->logger->error('Unknown user', ['uid' =>  $params['uid']]);
238                         return false;
239                 }
240
241                 // There is no need to create notifications for forum accounts
242                 if ($user['account-type'] == Model\User::ACCOUNT_TYPE_COMMUNITY) {
243                         return false;
244                 }
245
246                 $params['notify_flags'] = $user['notify-flags'];
247                 $params['language']     = $user['language'];
248                 $params['to_name']      = $user['username'];
249                 $params['to_email']     = $user['email'];
250
251                 // from here on everything is in the recipients language
252                 $l10n = $this->l10n->withLang($params['language']);
253
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'];
260                         }
261                 }
262
263                 $siteurl = $this->baseUrl->get(true);
264                 $sitename = $this->config->get('config', 'sitename');
265
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;
270
271                 $title = $params['item']['title'] ?? '';
272                 $body = $params['item']['body'] ?? '';
273
274                 $parent_id = $params['item']['parent'] ?? 0;
275                 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
276
277                 $epreamble = '';
278                 $preamble  = '';
279                 $subject   = '';
280                 $sitelink  = '';
281                 $tsitelink = '';
282                 $hsitelink = '';
283                 $itemlink  = '';
284
285                 switch ($params['type']) {
286                         case Model\Notification\Type::MAIL:
287                                 $itemlink = $params['link'];
288
289                                 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
290
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]');
293
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>');
297
298                                 // Mail notifications aren't using the "notify" table entry
299                                 $show_in_notification_page = false;
300                                 break;
301
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]);
305                                         return false;
306                                 }
307
308                                 $item = Model\Post::selectFirstForUser($params['uid'], Model\Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
309                                 if (empty($item)) {
310                                         return false;
311                                 }
312
313                                 $item_post_type = Model\Item::postType($item, $l10n);
314
315                                 $body = BBCode::toPlaintext($item['body'], false);
316                                 $title = Plaintext::shorten($body, 70);
317                                 if (!empty($title)) {
318                                         $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
319                                 }
320
321                                 // First go for the general message
322
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);
326
327                                 // "your post"
328                                 if ($item['wall']) {
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);
331                                 // "their post"
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);
335                                 }
336
337                                 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
338
339                                 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
340
341                                 $epreamble = $dest_str;
342
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'];
347                                 break;
348
349                         case Model\Notification\Type::WALL:
350                                 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
351
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]',
355                                         $params['link']
356                                 );
357
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'];
362                                 break;
363
364                         case Model\Notification\Type::INTRO:
365                                 $itemlink = $params['link'];
366                                 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
367
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.',
370                                         $itemlink,
371                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
372                                 );
373
374                                 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
375
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>');
379
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);
384
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]',
388                                                         $sitename
389                                                 );
390                                                 break;
391                                         case Activity::FOLLOW:
392                                                 // someone started to follow the user (mostly OStatus)
393                                                 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
394
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]',
398                                                         $sitename
399                                                 );
400                                                 break;
401                                         default:
402                                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
403                                                 break;
404                                 }
405                                 break;
406
407                         case Model\Notification\Type::SUGGEST:
408                                 $itemlink =  $params['link'];
409                                 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
410
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.',
413                                         $itemlink,
414                                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
415                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
416                                 );
417
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']);
421
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>');
425                                 break;
426
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);
431
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].',
434                                                 $itemlink,
435                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
436                                         );
437
438                                         $body =  $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
439
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);
446
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].',
449                                                 $itemlink,
450                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
451                                         );
452
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']);
454                                         $body .= "\n\n";
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']);
456
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>');
460                                 }
461                                 break;
462
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');
468
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.',
471                                                         $itemlink,
472                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
473                                                 );
474
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']
479                                                 );
480
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>');
484                                                 break;
485
486                                         case 'SYSTEM_DB_UPDATE_FAIL': // @TODO Unused (only here)
487                                                 break;
488                                 }
489                                 break;
490
491                         default:
492                                 $this->logger->notice('Unhandled type', ['type' => $params['type']]);
493                                 return false;
494                 }
495
496                 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
497         }
498
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
500         {
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;
505
506                 // Ensure that the important fields are set at any time
507                 $fields = ['nickname'];
508                 $user = Model\User::getById($params['uid'], $fields);
509
510                 $sitename = $this->config->get('config', 'sitename');
511
512                 $nickname = $user['nickname'];
513
514                 $hostname = $this->baseUrl->getHostname();
515                 if (strpos($hostname, ':')) {
516                         $hostname = substr($hostname, 0, strpos($hostname, ':'));
517                 }
518
519                 // Creates a new email builder for the notification email
520                 $emailBuilder = $this->emailer->newNotifyMail();
521
522                 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
523
524                 $subject .= " (".$nickname."@".$hostname.")";
525
526                 $h = [
527                         'params'    => $params,
528                         'subject'   => $subject,
529                         'preamble'  => $preamble,
530                         'epreamble' => $epreamble,
531                         'body'      => $body,
532                         'sitelink'  => $sitelink,
533                         'tsitelink' => $tsitelink,
534                         'hsitelink' => $hsitelink,
535                         'itemlink'  => $itemlink
536                 ];
537
538                 Hook::callAll('enotify', $h);
539
540                 $subject   = $h['subject'];
541
542                 $preamble  = $h['preamble'];
543                 $epreamble = $h['epreamble'];
544
545                 $body      = $h['body'];
546
547                 $tsitelink = $h['tsitelink'];
548                 $hsitelink = $h['hsitelink'];
549                 $itemlink  = $h['itemlink'];
550
551                 $notify_id = 0;
552
553                 if ($show_in_notification_page) {
554                         $Notify = $this->factory->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
555                         try {
556                                 $Notify = $this->save($Notify);
557                         } catch (Exception\NotificationCreationInterceptedException $e) {
558                                 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
559                                 return false;
560                         }
561
562                         $Notify->updateMsgFromPreamble($epreamble);
563                         $Notify = $this->save($Notify);
564
565                         $itemlink  = $this->baseUrl->get() . '/notify/' . $Notify->id;
566                         $notify_id = $Notify->id;
567                 }
568
569                 // send email notification if notification preferences permit
570                 if ((intval($params['notify_flags']) & intval($params['type']))
571                         || $params['type'] == Model\Notification\Type::SYSTEM) {
572
573                         $this->logger->notice('sending notification email');
574
575                         if (isset($params['parent']) && (intval($params['parent']) != 0)) {
576                                 $parent = Model\Post::selectFirst(['guid'], ['id' => $params['parent']]);
577                                 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
578
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']));
582
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);
586
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);
591                                 } else {
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.");
596                                 }
597                         }
598
599                         $datarray = [
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,
610                                 'title'        => $title,
611                                 'body'         => $body,
612                                 'subject'      => $subject,
613                                 'headers'      => $emailBuilder->getHeaders(),
614                         ];
615
616                         Hook::callAll('enotify_mail', $datarray);
617
618                         $emailBuilder
619                                 ->withHeaders($datarray['headers'])
620                                 ->withRecipient($params['to_email'])
621                                 ->forUser([
622                                         'uid' => $datarray['uid'],
623                                         'language' => $params['language'],
624                                 ])
625                                 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
626                                 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
627                                 ->withItemLink($datarray['itemlink']);
628
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);
635                         }
636
637                         $email = $emailBuilder->build();
638
639                         // use the Emailer class to send the message
640                         return $this->emailer->send($email);
641                 }
642
643                 return false;
644         }
645
646         public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool
647         {
648                 if (is_null($type)) {
649                         $type = NotificationFactory::getType($Notification);
650                 }
651
652                 if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {
653                         return true;
654                 }
655
656                 if ($this->pConfig->get($Notification->uid, 'system', 'notify_like') && ($type == Notification::TYPE_LIKE)) {
657                         return true;
658                 }
659
660                 if ($this->pConfig->get($Notification->uid, 'system', 'notify_announce') && ($type == Notification::TYPE_RESHARE)) {
661                         return true;
662                 }
663
664                 $notify_type = $this->pConfig->get($Notification->uid, 'system', 'notify_type');
665
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])) {
668                                 return true;
669                 }
670
671                 if (!is_null($notify_type) && ($notify_type & $Notification->type)) {
672                         return true;
673                 }
674
675                 return false;
676         }
677
678         public function createFromNotification(Entity\Notification $Notification): bool
679         {
680                 $this->logger->info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
681
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]);
684                         return false;
685                 }
686
687                 $params = [];
688                 $params['verb']  = $Notification->verb;
689                 $params['uid']   = $Notification->uid;
690                 $params['otype'] = Model\Notification\ObjectType::ITEM;
691
692                 $user = Model\User::getById($Notification->uid);
693
694                 $params['notify_flags'] = $user['notify-flags'];
695                 $params['language']     = $user['language'];
696                 $params['to_name']      = $user['username'];
697                 $params['to_email']     = $user['email'];
698
699                 // from here on everything is in the recipients language
700                 $l10n = $this->l10n->withLang($user['language']);
701
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'];
707                 }
708
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]]);
712                 if (empty($item)) {
713                         $this->logger->info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
714                         return false;
715                 }
716
717                 $params['item']   = $item;
718                 $params['parent'] = $item['parent'];
719                 $params['link']   = $this->baseUrl->get() . '/display/' . urlencode($item['guid']);
720
721                 $subjectPrefix = $l10n->t('[Friendica:Notify]');
722
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]);
725                         return false;
726                 }
727
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]);
734                         return false;
735                 }
736
737                 $body = BBCode::toPlaintext($item['body'], false);
738                 $title = Plaintext::shorten($body, 70);
739                 if (!empty($title)) {
740                         $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
741                 }
742
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']);
753                 } else {
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']);
756                 }
757
758                 $msg = $this->notification->getMessageFromNotification($Notification);
759                 if (empty($msg)) {
760                         $this->logger->info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
761                         return false;
762                 }
763
764                 $preamble  = $msg['plain'];
765                 $epreamble = $msg['rich'];
766
767                 $sitename = $this->config->get('config', 'sitename');
768                 $siteurl  = $this->baseUrl->get(true);
769
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'];
774
775                 $this->logger->info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
776
777                 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);
778         }
779 }