]> git.mxchange.org Git - friendica.git/blob - src/Navigation/Notifications/Repository/Notify.php
Merge pull request #13193 from annando/fix-notification-link
[friendica.git] / src / Navigation / Notifications / Repository / Notify.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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', 'account_removed', 'account_expired'];
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                 if ($user['account_removed'] || $user['account_expired']) {
242                         return false;
243                 }
244
245                 // There is no need to create notifications for group accounts
246                 if ($user['account-type'] == Model\User::ACCOUNT_TYPE_COMMUNITY) {
247                         return false;
248                 }
249
250                 $params['notify_flags'] = $user['notify-flags'];
251                 $params['language']     = $user['language'];
252                 $params['to_name']      = $user['username'];
253                 $params['to_email']     = $user['email'];
254
255                 // from here on everything is in the recipients language
256                 $l10n = $this->l10n->withLang($params['language']);
257
258                 if (!empty($params['cid'])) {
259                         $contact = Model\Contact::getById($params['cid'], ['url', 'name', 'photo']);
260                         if (DBA::isResult($contact)) {
261                                 $params['source_link'] = $contact['url'];
262                                 $params['source_name'] = $contact['name'];
263                                 $params['source_photo'] = $contact['photo'];
264                         }
265                 }
266
267                 $siteurl = (string)$this->baseUrl;
268                 $sitename = $this->config->get('config', 'sitename');
269
270                 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
271                 // the database, and an email is sent if applicable.
272                 // default, if not specified: true
273                 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
274
275                 $title = $params['item']['title'] ?? '';
276                 $body = $params['item']['body'] ?? '';
277
278                 $parent_id = $params['item']['parent'] ?? 0;
279                 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
280
281                 $epreamble = '';
282                 $preamble  = '';
283                 $subject   = '';
284                 $sitelink  = '';
285                 $tsitelink = '';
286                 $hsitelink = '';
287                 $itemlink  = '';
288
289                 switch ($params['type']) {
290                         case Model\Notification\Type::MAIL:
291                                 $itemlink = $params['link'];
292
293                                 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
294
295                                 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
296                                 $epreamble = $l10n->t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=' . $itemlink . ']' . $l10n->t('a private message').'[/url]');
297
298                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
299                                 $tsitelink = sprintf($sitelink, $itemlink);
300                                 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
301
302                                 // Mail notifications aren't using the "notify" table entry
303                                 $show_in_notification_page = false;
304                                 break;
305
306                         case Model\Notification\Type::COMMENT:
307                                 if (Model\Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
308                                         $this->logger->info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
309                                         return false;
310                                 }
311
312                                 $item = Model\Post::selectFirstForUser($params['uid'], Model\Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
313                                 if (empty($item)) {
314                                         return false;
315                                 }
316
317                                 $item_post_type = Model\Item::postType($item, $l10n);
318
319                                 $body = BBCode::toPlaintext($item['body'], false);
320                                 $title = Plaintext::shorten($body, 70);
321                                 if (!empty($title)) {
322                                         $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
323                                 }
324
325                                 // First go for the general message
326
327                                 // "George Bull's post"
328                                 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
329                                 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
330
331                                 // "your post"
332                                 if ($item['wall']) {
333                                         $message = $l10n->t('%1$s commented on your %2$s %3$s');
334                                         $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
335                                 // "their post"
336                                 } elseif ($item['author-link'] == $params['source_link']) {
337                                         $message = $l10n->t('%1$s commented on their %2$s %3$s');
338                                         $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
339                                 }
340
341                                 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
342
343                                 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
344
345                                 $epreamble = $dest_str;
346
347                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
348                                 $tsitelink = sprintf($sitelink, $siteurl);
349                                 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
350                                 $itemlink =  $params['link'];
351                                 break;
352
353                         case Model\Notification\Type::WALL:
354                                 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
355
356                                 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
357                                 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
358                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
359                                         $params['link']
360                                 );
361
362                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
363                                 $tsitelink = sprintf($sitelink, $siteurl);
364                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
365                                 $itemlink =  $params['link'];
366                                 break;
367
368                         case Model\Notification\Type::INTRO:
369                                 $itemlink = $params['link'];
370                                 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
371
372                                 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
373                                 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
374                                         $itemlink,
375                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
376                                 );
377
378                                 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
379
380                                 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
381                                 $tsitelink = sprintf($sitelink, $siteurl);
382                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
383
384                                 switch ($params['verb']) {
385                                         case Activity::FRIEND:
386                                                 // someone started to share with user (mostly OStatus)
387                                                 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
388
389                                                 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
390                                                 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
391                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
392                                                         $sitename
393                                                 );
394                                                 break;
395                                         case Activity::FOLLOW:
396                                                 // someone started to follow the user (mostly OStatus)
397                                                 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
398
399                                                 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
400                                                 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
401                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
402                                                         $sitename
403                                                 );
404                                                 break;
405                                         default:
406                                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
407                                                 break;
408                                 }
409                                 break;
410
411                         case Model\Notification\Type::SUGGEST:
412                                 $itemlink =  $params['link'];
413                                 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
414
415                                 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
416                                 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
417                                         $itemlink,
418                                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
419                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
420                                 );
421
422                                 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
423                                 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
424                                 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
425
426                                 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
427                                 $tsitelink = sprintf($sitelink, $siteurl);
428                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
429                                 break;
430
431                         case Model\Notification\Type::CONFIRM:
432                                 if ($params['verb'] == Activity::FRIEND) { // mutual connection
433                                         $itemlink =  $params['link'];
434                                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
435
436                                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
437                                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
438                                                 $itemlink,
439                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
440                                         );
441
442                                         $body =  $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
443
444                                         $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
445                                         $tsitelink = sprintf($sitelink, $siteurl);
446                                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
447                                 } else { // ACTIVITY_FOLLOW
448                                         $itemlink =  $params['link'];
449                                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
450
451                                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
452                                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
453                                                 $itemlink,
454                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
455                                         );
456
457                                         $body =  $l10n->t('\'%1$s\' has chosen to accept you a fan, which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.', $params['source_name']);
458                                         $body .= "\n\n";
459                                         $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
460
461                                         $sitelink = $l10n->t('Please visit %s  if you wish to make any changes to this relationship.');
462                                         $tsitelink = sprintf($sitelink, $siteurl);
463                                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
464                                 }
465                                 break;
466
467                         case Model\Notification\Type::SYSTEM:
468                                 switch($params['event']) {
469                                         case 'SYSTEM_REGISTER_REQUEST':
470                                                 $itemlink =  $params['link'];
471                                                 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
472
473                                                 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
474                                                 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
475                                                         $itemlink,
476                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
477                                                 );
478
479                                                 $body = $l10n->t("Full Name:    %s\nSite Location:      %s\nLogin Name: %s (%s)",
480                                                         $params['source_name'],
481                                                         $siteurl, $params['source_mail'],
482                                                         $params['source_nick']
483                                                 );
484
485                                                 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
486                                                 $tsitelink = sprintf($sitelink, $params['link']);
487                                                 $hsitelink = sprintf($sitelink, '<a href="' . $params['link'] . '">' . $sitename . '</a><br><br>');
488                                                 break;
489
490                                         case 'SYSTEM_REGISTER_NEW':
491                                                 $itemlink =  $params['link'];
492                                                 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('new registration');
493
494                                                 $preamble = $l10n->t('You\'ve received a new registration from \'%1$s\' at %2$s', $params['source_name'], $sitename);
495                                                 $epreamble = $l10n->t('You\'ve received a [url=%1$s]new registration[/url] from %2$s.',
496                                                         $itemlink,
497                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
498                                                 );
499
500                                                 $body = $l10n->t("Full Name:    %s\nSite Location:      %s\nLogin Name: %s (%s)",
501                                                         $params['source_name'],
502                                                         $siteurl, $params['source_mail'],
503                                                         $params['source_nick']
504                                                 );
505
506                                                 $sitelink = $l10n->t('Please visit %s to have a look at the new registration.');
507                                                 $tsitelink = sprintf($sitelink, $params['link']);
508                                                 $hsitelink = sprintf($sitelink, '<a href="' . $params['link'] . '">' . $sitename . '</a><br><br>');
509                                                 break;
510
511                                         case 'SYSTEM_DB_UPDATE_FAIL': // @TODO Unused (only here)
512                                                 break;
513                                 }
514                                 break;
515
516                         default:
517                                 $this->logger->notice('Unhandled type', ['type' => $params['type']]);
518                                 return false;
519                 }
520
521                 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
522         }
523
524         private function storeAndSend(array $params, string $sitelink, string $tsitelink, string $hsitelink, string $title, string $subject, string $preamble, string $epreamble, string $body, string $itemlink, bool $show_in_notification_page): bool
525         {
526                 $item_id = $params['item']['id'] ?? 0;
527                 $uri_id = $params['item']['uri-id'] ?? null;
528                 $parent_id = $params['item']['parent'] ?? 0;
529                 $parent_uri_id = $params['item']['parent-uri-id'] ?? null;
530
531                 // Ensure that the important fields are set at any time
532                 $fields = ['nickname', 'account_removed', 'account_expired'];
533                 $user = Model\User::getById($params['uid'], $fields);
534                 if ($user['account_removed'] || $user['account_expired']) {
535                         return false;
536                 }
537
538                 $sitename = $this->config->get('config', 'sitename');
539
540                 $nickname = $user['nickname'];
541
542                 $hostname = $this->baseUrl->getHost();
543                 if (strpos($hostname, ':')) {
544                         $hostname = substr($hostname, 0, strpos($hostname, ':'));
545                 }
546
547                 // Creates a new email builder for the notification email
548                 $emailBuilder = $this->emailer->newNotifyMail();
549
550                 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
551
552                 $subject .= " (".$nickname."@".$hostname.")";
553
554                 $h = [
555                         'params'    => $params,
556                         'subject'   => $subject,
557                         'preamble'  => $preamble,
558                         'epreamble' => $epreamble,
559                         'body'      => $body,
560                         'sitelink'  => $sitelink,
561                         'tsitelink' => $tsitelink,
562                         'hsitelink' => $hsitelink,
563                         'itemlink'  => $itemlink
564                 ];
565
566                 Hook::callAll('enotify', $h);
567
568                 $subject   = $h['subject'];
569
570                 $preamble  = $h['preamble'];
571                 $epreamble = $h['epreamble'];
572
573                 $body      = $h['body'];
574
575                 $tsitelink = $h['tsitelink'];
576                 $hsitelink = $h['hsitelink'];
577                 $itemlink  = $h['itemlink'];
578
579                 $notify_id = 0;
580
581                 if ($show_in_notification_page) {
582                         $Notify = $this->factory->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
583                         try {
584                                 $Notify = $this->save($Notify);
585                         } catch (Exception\NotificationCreationInterceptedException $e) {
586                                 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
587                                 return false;
588                         }
589
590                         $Notify->updateMsgFromPreamble($epreamble);
591                         $Notify = $this->save($Notify);
592
593                         $itemlink  = $this->baseUrl . '/notify/' . $Notify->id;
594                         $notify_id = $Notify->id;
595                 }
596
597                 // send email notification if notification preferences permit
598                 if ((intval($params['notify_flags']) & intval($params['type']))
599                         || $params['type'] == Model\Notification\Type::SYSTEM) {
600
601                         $this->logger->notice('sending notification email');
602
603                         if (isset($params['parent']) && (intval($params['parent']) != 0)) {
604                                 $parent = Model\Post::selectFirst(['guid'], ['id' => $params['parent']]);
605                                 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
606
607                                 // Is this the first email notification for this parent item and user?
608                                 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
609                                         $this->logger->info("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']));
610
611                                         $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
612                                                 'receiver-uid' => $params['uid'], 'parent-item' => 0];
613                                         DBA::insert('notify-threads', $fields);
614
615                                         $emailBuilder->setHeader('Message-ID', $message_id);
616                                         $log_msg = "No previous notification found for this parent:\n" .
617                                                 "  parent: {$params['parent']}\n" . "  uid   : {$params['uid']}\n";
618                                         $this->logger->info($log_msg);
619                                 } else {
620                                         // If not, just "follow" the thread.
621                                         $emailBuilder->setHeader('References', $message_id);
622                                         $emailBuilder->setHeader('In-Reply-To', $message_id);
623                                         $this->logger->info("There's already a notification for this parent.");
624                                 }
625                         }
626
627                         $datarray = [
628                                 'preamble'     => $preamble,
629                                 'type'         => $params['type'],
630                                 'parent'       => $parent_id,
631                                 'source_name'  => $params['source_name'] ?? null,
632                                 'source_link'  => $params['source_link'] ?? null,
633                                 'source_photo' => $params['source_photo'] ?? null,
634                                 'uid'          => $params['uid'],
635                                 'hsitelink'    => $hsitelink,
636                                 'tsitelink'    => $tsitelink,
637                                 'itemlink'     => $itemlink,
638                                 'title'        => $title,
639                                 'body'         => $body,
640                                 'subject'      => $subject,
641                                 'headers'      => $emailBuilder->getHeaders(),
642                         ];
643
644                         Hook::callAll('enotify_mail', $datarray);
645
646                         $emailBuilder
647                                 ->withHeaders($datarray['headers'])
648                                 ->withRecipient($params['to_email'])
649                                 ->forUser([
650                                         'uid' => $datarray['uid'],
651                                         'language' => $params['language'],
652                                 ])
653                                 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
654                                 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
655                                 ->withItemLink($datarray['itemlink']);
656
657                         // If a photo is present, add it to the email
658                         if (!empty($datarray['source_photo'])) {
659                                 $emailBuilder->withPhoto(
660                                         $datarray['source_photo'],
661                                         $datarray['source_link'] ?? $sitelink,
662                                         $datarray['source_name'] ?? $sitename);
663                         }
664
665                         $email = $emailBuilder->build();
666
667                         // use the Emailer class to send the message
668                         return $this->emailer->send($email);
669                 }
670
671                 return false;
672         }
673
674         public function shouldShowOnDesktop(Entity\Notification $Notification, string $type = null): bool
675         {
676                 if (is_null($type)) {
677                         $type = NotificationFactory::getType($Notification);
678                 }
679
680                 if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {
681                         return true;
682                 }
683
684                 if ($this->pConfig->get($Notification->uid, 'system', 'notify_like') && ($type == Notification::TYPE_LIKE)) {
685                         return true;
686                 }
687
688                 if ($this->pConfig->get($Notification->uid, 'system', 'notify_announce') && ($type == Notification::TYPE_RESHARE)) {
689                         return true;
690                 }
691
692                 $notify_type = $this->pConfig->get($Notification->uid, 'system', 'notify_type');
693
694                 // Fallback for the case when the notify type isn't set at all
695                 if (is_null($notify_type) && !in_array($type, [Notification::TYPE_RESHARE, Notification::TYPE_LIKE])) {
696                                 return true;
697                 }
698
699                 if (!is_null($notify_type) && ($notify_type & $Notification->type)) {
700                         return true;
701                 }
702
703                 return false;
704         }
705
706         public function createFromNotification(Entity\Notification $Notification): bool
707         {
708                 $this->logger->info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
709
710                 if ($Notification->type === Model\Post\UserNotification::TYPE_NONE) {
711                         $this->logger->info('Not an item based notification, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
712                         return false;
713                 }
714
715                 $params = [];
716                 $params['verb']  = $Notification->verb;
717                 $params['uid']   = $Notification->uid;
718                 $params['otype'] = Model\Notification\ObjectType::ITEM;
719
720                 $user = Model\User::getById($Notification->uid);
721                 if ($user['account_removed'] || $user['account_expired']) {
722                         return false;
723                 }
724
725                 $params['notify_flags'] = $user['notify-flags'];
726                 $params['language']     = $user['language'];
727                 $params['to_name']      = $user['username'];
728                 $params['to_email']     = $user['email'];
729
730                 // from here on everything is in the recipients language
731                 $l10n = $this->l10n->withLang($user['language']);
732
733                 $contact = Model\Contact::getById($Notification->actorId, ['url', 'name', 'photo']);
734                 if (DBA::isResult($contact)) {
735                         $params['source_link']  = $contact['url'];
736                         $params['source_name']  = $contact['name'];
737                         $params['source_photo'] = $contact['photo'];
738                 }
739
740                 $item = Model\Post::selectFirstForUser($Notification->uid, Model\Item::ITEM_FIELDLIST,
741                         ['uid' => [0, $Notification->uid], 'uri-id' => $Notification->targetUriId, 'deleted' => false],
742                         ['order' => ['uid' => true]]);
743                 if (empty($item)) {
744                         $this->logger->info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
745                         return false;
746                 }
747
748                 $params['item']   = $item;
749                 $params['parent'] = $item['parent'];
750                 $params['link']   = $this->baseUrl . '/display/' . urlencode($item['guid']);
751
752                 $subjectPrefix = $l10n->t('[Friendica:Notify]');
753
754                 if (Model\Post\ThreadUser::getIgnored($Notification->parentUriId, $Notification->uid)) {
755                         $this->logger->info('Thread is ignored', ['parent-uri-id' => $Notification->parentUriId, 'type' => $Notification->type]);
756                         return false;
757                 }
758
759                 // Check to see if there was already a tag notify or comment notify for this post.
760                 // If so don't create a second notification
761                 $condition = ['type' => [Model\Notification\Type::TAG_SELF, Model\Notification\Type::COMMENT, Model\Notification\Type::SHARE],
762                         'link' => $params['link'], 'verb' => Activity::POST];
763                 if ($this->existsForUser($Notification->uid, $condition)) {
764                         $this->logger->info('Duplicate found, quitting', $condition + ['uid' => $Notification->uid]);
765                         return false;
766                 }
767
768                 $body = BBCode::toPlaintext($item['body'], false);
769                 $title = Plaintext::shorten($body, 70);
770                 if (!empty($title)) {
771                         $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
772                 }
773
774                 // Some mail software relies on the subject field for threading.
775                 // So, we cannot have different subjects for notifications of the same thread.
776                 // Before this we have the name of the replier on the subject rendering
777                 // different subjects for messages on the same thread.
778                 if ($Notification->type === Model\Post\UserNotification::TYPE_EXPLICIT_TAGGED) {
779                         $params['type'] = Model\Notification\Type::TAG_SELF;
780                         $subject        = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
781                 } elseif ($Notification->type === Model\Post\UserNotification::TYPE_SHARED) {
782                         $params['type'] = Model\Notification\Type::SHARE;
783                         $subject        = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
784                 } else {
785                         $params['type'] = Model\Notification\Type::COMMENT;
786                         $subject        = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
787
788                         if ($params['verb'] == Activity::LIKE) {
789                                 switch ($Notification->type) {
790                                         case Model\Post\UserNotification::TYPE_DIRECT_COMMENT:
791                                                 $subject = $l10n->t('%1$s %2$s liked your post #%3$d', $subjectPrefix, $contact['name'], $item['parent']);
792                                                 break;
793                                         case Model\Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT:
794                                                 $subject = $l10n->t('%1$s %2$s liked your comment on #%3$d', $subjectPrefix, $contact['name'], $item['parent']);
795                                                 break;
796                                 }
797                         }
798                 }
799
800                 $msg = $this->notification->getMessageFromNotification($Notification);
801                 if (empty($msg)) {
802                         $this->logger->info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
803                         return false;
804                 }
805
806                 $preamble  = $msg['plain'];
807                 $epreamble = $msg['rich'];
808
809                 $sitename = $this->config->get('config', 'sitename');
810                 $siteurl  = (string)$this->baseUrl;
811
812                 $sitelink  = $l10n->t('Please visit %s to view and/or reply to the conversation.');
813                 $tsitelink = sprintf($sitelink, $siteurl);
814                 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
815                 $itemlink  = $params['link'];
816
817                 $this->logger->info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
818
819                 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);
820         }
821
822         public function deleteForItem(int $itemUriId): void
823         {
824                 $this->db->delete('notify', ['otype' => 'item', 'uri-id' => $itemUriId]);
825                 $this->db->delete('notify', ['otype' => 'item', 'parent-uri-id' => $itemUriId]);
826         }
827 }