]> git.mxchange.org Git - friendica.git/blob - src/Navigation/Notifications/Repository/Notify.php
Merge pull request #11677 from Quix0r/rewrites/type-hints-doc-001
[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          * @return Entity\Notify
92          * @throws HTTPException\NotFoundException
93          */
94         private function selectOne(array $condition, array $params = []): Entity\Notify
95         {
96                 return parent::_selectOne($condition, $params);
97         }
98
99         private function select(array $condition, array $params = []): Collection\Notifies
100         {
101                 return new Collection\Notifies(parent::_select($condition, $params)->getArrayCopy());
102         }
103
104         public function countForUser($uid, array $condition, array $params = []): int
105         {
106                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
107
108                 return $this->count($condition, $params);
109         }
110
111         public function existsForUser($uid, array $condition): bool
112         {
113                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
114
115                 return $this->exists($condition);
116         }
117
118         /**
119          * @param int $id
120          * @return Entity\Notify
121          * @throws HTTPException\NotFoundException
122          */
123         public function selectOneById(int $id): Entity\Notify
124         {
125                 return $this->selectOne(['id' => $id]);
126         }
127
128         public function selectForUser(int $uid, array $condition, array $params): Collection\Notifies
129         {
130                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
131
132                 return $this->select($condition, $params);
133         }
134
135         /**
136          * Returns notifications for the user, unread first, ordered in descending chronological order.
137          *
138          * @param int $uid
139          * @param int $limit
140          * @return Collection\Notifies
141          */
142         public function selectAllForUser(int $uid, int $limit): Collection\Notifies
143         {
144                 return $this->selectForUser($uid, [], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => $limit]);
145         }
146
147         public function setAllSeenForUser(int $uid, array $condition = []): bool
148         {
149                 $condition = DBA::mergeConditions($condition, ['uid' => $uid]);
150
151                 return $this->db->update(self::$table_name, ['seen' => true], $condition);
152         }
153
154         /**
155          * @param Entity\Notify $Notify
156          * @return Entity\Notify
157          * @throws HTTPException\NotFoundException
158          * @throws HTTPException\InternalServerErrorException
159          * @throws Exception\NotificationCreationInterceptedException
160          */
161         public function save(Entity\Notify $Notify): Entity\Notify
162         {
163                 $fields = [
164                         'type'          => $Notify->type,
165                         'name'          => $Notify->name,
166                         'url'           => $Notify->url,
167                         'photo'         => $Notify->photo,
168                         'msg'           => $Notify->msg,
169                         'uid'           => $Notify->uid,
170                         'link'          => $Notify->link,
171                         'iid'           => $Notify->itemId,
172                         'parent'        => $Notify->parent,
173                         'seen'          => $Notify->seen,
174                         'verb'          => $Notify->verb,
175                         'otype'         => $Notify->otype,
176                         'name_cache'    => $Notify->name_cache,
177                         'msg_cache'     => $Notify->msg_cache,
178                         'uri-id'        => $Notify->uriId,
179                         'parent-uri-id' => $Notify->parentUriId,
180                 ];
181
182                 if ($Notify->id) {
183                         $this->db->update(self::$table_name, $fields, ['id' => $Notify->id]);
184                 } else {
185                         $fields['date'] = DateTimeFormat::utcNow();
186                         Hook::callAll('enotify_store', $fields);
187
188                         $this->db->insert(self::$table_name, $fields);
189
190                         $Notify = $this->selectOneById($this->db->lastInsertId());
191                 }
192
193                 return $Notify;
194         }
195
196         public function setAllSeenForRelatedNotify(Entity\Notify $Notify): bool
197         {
198                 $condition = [
199                         '(`link` = ? OR (`parent` != 0 AND `parent` = ? AND `otype` = ?)) AND `uid` = ?',
200                         $Notify->link,
201                         $Notify->parent,
202                         $Notify->otype,
203                         $Notify->uid
204                 ];
205                 return $this->db->update(self::$table_name, ['seen' => true], $condition);
206         }
207
208         /**
209          * Creates a notification entry and possibly sends a mail
210          *
211          * @param array $params Array with the elements:
212          *                      type, event, otype, activity, verb, uid, cid, item, link,
213          *                      source_name, source_mail, source_nick, source_link, source_photo,
214          *                      show_in_notification_page
215          *
216          * @return bool
217          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218          */
219         function createFromArray($params)
220         {
221                 /** @var string the common prefix of a notification subject */
222                 $subjectPrefix = $this->l10n->t('[Friendica:Notify]');
223
224                 // Temporary logging for finding the origin
225                 if (!isset($params['uid'])) {
226                         $this->logger->notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
227                 }
228
229                 // Ensure that the important fields are set at any time
230                 $fields = ['nickname', 'account-type', 'notify-flags', 'language', 'username', 'email'];
231                 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
232
233                 if (!DBA::isResult($user)) {
234                         $this->logger->error('Unknown user', ['uid' =>  $params['uid']]);
235                         return false;
236                 }
237
238                 // There is no need to create notifications for forum accounts
239                 if ($user['account-type'] == Model\User::ACCOUNT_TYPE_COMMUNITY) {
240                         return false;
241                 }
242
243                 $params['notify_flags'] = $user['notify-flags'];
244                 $params['language']     = $user['language'];
245                 $params['to_name']      = $user['username'];
246                 $params['to_email']     = $user['email'];
247
248                 // from here on everything is in the recipients language
249                 $l10n = $this->l10n->withLang($params['language']);
250
251                 if (!empty($params['cid'])) {
252                         $contact = Model\Contact::getById($params['cid'], ['url', 'name', 'photo']);
253                         if (DBA::isResult($contact)) {
254                                 $params['source_link'] = $contact['url'];
255                                 $params['source_name'] = $contact['name'];
256                                 $params['source_photo'] = $contact['photo'];
257                         }
258                 }
259
260                 $siteurl = $this->baseUrl->get(true);
261                 $sitename = $this->config->get('config', 'sitename');
262
263                 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
264                 // the database, and an email is sent if applicable.
265                 // default, if not specified: true
266                 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
267
268                 $title = $params['item']['title'] ?? '';
269                 $body = $params['item']['body'] ?? '';
270
271                 $parent_id = $params['item']['parent'] ?? 0;
272                 $parent_uri_id = $params['item']['parent-uri-id'] ?? 0;
273
274                 $epreamble = '';
275                 $preamble  = '';
276                 $subject   = '';
277                 $sitelink  = '';
278                 $tsitelink = '';
279                 $hsitelink = '';
280                 $itemlink  = '';
281
282                 switch ($params['type']) {
283                         case Model\Notification\Type::MAIL:
284                                 $itemlink = $params['link'];
285
286                                 $subject = $l10n->t('%s New mail received at %s', $subjectPrefix, $sitename);
287
288                                 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
289                                 $epreamble = $l10n->t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=' . $itemlink . ']' . $l10n->t('a private message').'[/url]');
290
291                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
292                                 $tsitelink = sprintf($sitelink, $itemlink);
293                                 $hsitelink = sprintf($sitelink, '<a href="' . $itemlink . '">' . $sitename . '</a>');
294
295                                 // Mail notifications aren't using the "notify" table entry
296                                 $show_in_notification_page = false;
297                                 break;
298
299                         case Model\Notification\Type::COMMENT:
300                                 if (Model\Post\ThreadUser::getIgnored($parent_uri_id, $params['uid'])) {
301                                         $this->logger->info('Thread is ignored', ['parent' => $parent_id, 'parent-uri-id' => $parent_uri_id]);
302                                         return false;
303                                 }
304
305                                 $item = Model\Post::selectFirstForUser($params['uid'], Model\Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
306                                 if (empty($item)) {
307                                         return false;
308                                 }
309
310                                 $item_post_type = Model\Item::postType($item, $l10n);
311
312                                 $body = BBCode::toPlaintext($item['body'], false);
313                                 $title = Plaintext::shorten($body, 70);
314                                 if (!empty($title)) {
315                                         $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
316                                 }
317
318                                 // First go for the general message
319
320                                 // "George Bull's post"
321                                 $message = $l10n->t('%1$s commented on %2$s\'s %3$s %4$s');
322                                 $dest_str = sprintf($message, $params['source_name'], $item['author-name'], $item_post_type, $title);
323
324                                 // "your post"
325                                 if ($item['wall']) {
326                                         $message = $l10n->t('%1$s commented on your %2$s %3$s');
327                                         $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
328                                 // "their post"
329                                 } elseif ($item['author-link'] == $params['source_link']) {
330                                         $message = $l10n->t('%1$s commented on their %2$s %3$s');
331                                         $dest_str = sprintf($message, $params['source_name'], $item_post_type, $title);
332                                 }
333
334                                 $subject = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $parent_id, $params['source_name']);
335
336                                 $preamble = $l10n->t('%s commented on an item/conversation you have been following.', $params['source_name']);
337
338                                 $epreamble = $dest_str;
339
340                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
341                                 $tsitelink = sprintf($sitelink, $siteurl);
342                                 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
343                                 $itemlink =  $params['link'];
344                                 break;
345
346                         case Model\Notification\Type::WALL:
347                                 $subject = $l10n->t('%s %s posted to your profile wall', $subjectPrefix, $params['source_name']);
348
349                                 $preamble = $l10n->t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
350                                 $epreamble = $l10n->t('%1$s posted to [url=%2$s]your wall[/url]',
351                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
352                                         $params['link']
353                                 );
354
355                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
356                                 $tsitelink = sprintf($sitelink, $siteurl);
357                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
358                                 $itemlink =  $params['link'];
359                                 break;
360
361                         case Model\Notification\Type::POKE:
362                                 $subject = $l10n->t('%1$s %2$s poked you', $subjectPrefix, $params['source_name']);
363
364                                 $preamble = $l10n->t('%1$s poked you at %2$s', $params['source_name'], $sitename);
365                                 $epreamble = $l10n->t('%1$s [url=%2$s]poked you[/url].',
366                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
367                                         $params['link']
368                                 );
369
370                                 $subject = str_replace('poked', $l10n->t($params['activity']), $subject);
371                                 $preamble = str_replace('poked', $l10n->t($params['activity']), $preamble);
372                                 $epreamble = str_replace('poked', $l10n->t($params['activity']), $epreamble);
373
374                                 $sitelink = $l10n->t('Please visit %s to view and/or reply to the conversation.');
375                                 $tsitelink = sprintf($sitelink, $siteurl);
376                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
377                                 $itemlink =  $params['link'];
378                                 break;
379
380                         case Model\Notification\Type::INTRO:
381                                 $itemlink = $params['link'];
382                                 $subject = $l10n->t('%s Introduction received', $subjectPrefix);
383
384                                 $preamble = $l10n->t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
385                                 $epreamble = $l10n->t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
386                                         $itemlink,
387                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
388                                 );
389
390                                 $body = $l10n->t('You may visit their profile at %s', $params['source_link']);
391
392                                 $sitelink = $l10n->t('Please visit %s to approve or reject the introduction.');
393                                 $tsitelink = sprintf($sitelink, $siteurl);
394                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
395
396                                 switch ($params['verb']) {
397                                         case Activity::FRIEND:
398                                                 // someone started to share with user (mostly OStatus)
399                                                 $subject = $l10n->t('%s A new person is sharing with you', $subjectPrefix);
400
401                                                 $preamble = $l10n->t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
402                                                 $epreamble = $l10n->t('%1$s is sharing with you at %2$s',
403                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
404                                                         $sitename
405                                                 );
406                                                 break;
407                                         case Activity::FOLLOW:
408                                                 // someone started to follow the user (mostly OStatus)
409                                                 $subject = $l10n->t('%s You have a new follower', $subjectPrefix);
410
411                                                 $preamble = $l10n->t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
412                                                 $epreamble = $l10n->t('You have a new follower at %2$s : %1$s',
413                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
414                                                         $sitename
415                                                 );
416                                                 break;
417                                         default:
418                                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
419                                                 break;
420                                 }
421                                 break;
422
423                         case Model\Notification\Type::SUGGEST:
424                                 $itemlink =  $params['link'];
425                                 $subject = $l10n->t('%s Friend suggestion received', $subjectPrefix);
426
427                                 $preamble = $l10n->t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
428                                 $epreamble = $l10n->t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
429                                         $itemlink,
430                                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
431                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
432                                 );
433
434                                 $body = $l10n->t('Name:').' '.$params['item']['name']."\n";
435                                 $body .= $l10n->t('Photo:').' '.$params['item']['photo']."\n";
436                                 $body .= $l10n->t('You may visit their profile at %s', $params['item']['url']);
437
438                                 $sitelink = $l10n->t('Please visit %s to approve or reject the suggestion.');
439                                 $tsitelink = sprintf($sitelink, $siteurl);
440                                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
441                                 break;
442
443                         case Model\Notification\Type::CONFIRM:
444                                 if ($params['verb'] == Activity::FRIEND) { // mutual connection
445                                         $itemlink =  $params['link'];
446                                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
447
448                                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
449                                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
450                                                 $itemlink,
451                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
452                                         );
453
454                                         $body =  $l10n->t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
455
456                                         $sitelink = $l10n->t('Please visit %s if you wish to make any changes to this relationship.');
457                                         $tsitelink = sprintf($sitelink, $siteurl);
458                                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
459                                 } else { // ACTIVITY_FOLLOW
460                                         $itemlink =  $params['link'];
461                                         $subject = $l10n->t('%s Connection accepted', $subjectPrefix);
462
463                                         $preamble = $l10n->t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
464                                         $epreamble = $l10n->t('%2$s has accepted your [url=%1$s]connection request[/url].',
465                                                 $itemlink,
466                                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
467                                         );
468
469                                         $body =  $l10n->t('\'%1$s\' has chosen to accept you a fan, which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.', $params['source_name']);
470                                         $body .= "\n\n";
471                                         $body .= $l10n->t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
472
473                                         $sitelink = $l10n->t('Please visit %s  if you wish to make any changes to this relationship.');
474                                         $tsitelink = sprintf($sitelink, $siteurl);
475                                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
476                                 }
477                                 break;
478
479                         case Model\Notification\Type::SYSTEM:
480                                 switch($params['event']) {
481                                         case "SYSTEM_REGISTER_REQUEST":
482                                                 $itemlink =  $params['link'];
483                                                 $subject = $l10n->t('[Friendica System Notify]') . ' ' . $l10n->t('registration request');
484
485                                                 $preamble = $l10n->t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
486                                                 $epreamble = $l10n->t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
487                                                         $itemlink,
488                                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
489                                                 );
490
491                                                 $body = $l10n->t("Full Name:    %s\nSite Location:      %s\nLogin Name: %s (%s)",
492                                                         $params['source_name'],
493                                                         $siteurl, $params['source_mail'],
494                                                         $params['source_nick']
495                                                 );
496
497                                                 $sitelink = $l10n->t('Please visit %s to approve or reject the request.');
498                                                 $tsitelink = sprintf($sitelink, $params['link']);
499                                                 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
500                                                 break;
501                                         case "SYSTEM_DB_UPDATE_FAIL":
502                                                 break;
503                                 }
504                                 break;
505
506                         default:
507                                 $this->logger->notice('Unhandled type', ['type' => $params['type']]);
508                                 return false;
509                 }
510
511                 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page);
512         }
513
514         private function storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $body, $itemlink, $show_in_notification_page)
515         {
516                 $item_id = $params['item']['id'] ?? 0;
517                 $uri_id = $params['item']['uri-id'] ?? null;
518                 $parent_id = $params['item']['parent'] ?? 0;
519                 $parent_uri_id = $params['item']['parent-uri-id'] ?? null;
520
521                 // Ensure that the important fields are set at any time
522                 $fields = ['nickname'];
523                 $user = Model\User::getById($params['uid'], $fields);
524
525                 $sitename = $this->config->get('config', 'sitename');
526
527                 $nickname = $user['nickname'];
528
529                 $hostname = $this->baseUrl->getHostname();
530                 if (strpos($hostname, ':')) {
531                         $hostname = substr($hostname, 0, strpos($hostname, ':'));
532                 }
533
534                 // Creates a new email builder for the notification email
535                 $emailBuilder = $this->emailer->newNotifyMail();
536
537                 $emailBuilder->setHeader('X-Friendica-Account', '<' . $nickname . '@' . $hostname . '>');
538
539                 $subject .= " (".$nickname."@".$hostname.")";
540
541                 $h = [
542                         'params'    => $params,
543                         'subject'   => $subject,
544                         'preamble'  => $preamble,
545                         'epreamble' => $epreamble,
546                         'body'      => $body,
547                         'sitelink'  => $sitelink,
548                         'tsitelink' => $tsitelink,
549                         'hsitelink' => $hsitelink,
550                         'itemlink'  => $itemlink
551                 ];
552
553                 Hook::callAll('enotify', $h);
554
555                 $subject   = $h['subject'];
556
557                 $preamble  = $h['preamble'];
558                 $epreamble = $h['epreamble'];
559
560                 $body      = $h['body'];
561
562                 $tsitelink = $h['tsitelink'];
563                 $hsitelink = $h['hsitelink'];
564                 $itemlink  = $h['itemlink'];
565
566                 $notify_id = 0;
567
568                 if ($show_in_notification_page) {
569                         $Notify = $this->factory->createFromParams($params, $itemlink, $item_id, $uri_id, $parent_id, $parent_uri_id);
570                         try {
571                                 $Notify = $this->save($Notify);
572                         } catch (Exception\NotificationCreationInterceptedException $e) {
573                                 // Notification insertion can be intercepted by an addon registering the 'enotify_store' hook
574                                 return false;
575                         }
576
577                         $Notify->updateMsgFromPreamble($epreamble);
578                         $Notify = $this->save($Notify);
579
580                         $itemlink  = $this->baseUrl->get() . '/notify/' . $Notify->id;
581                         $notify_id = $Notify->id;
582                 }
583
584                 // send email notification if notification preferences permit
585                 if ((intval($params['notify_flags']) & intval($params['type']))
586                         || $params['type'] == Model\Notification\Type::SYSTEM) {
587
588                         $this->logger->notice('sending notification email');
589
590                         if (isset($params['parent']) && (intval($params['parent']) != 0)) {
591                                 $parent = Model\Post::selectFirst(['guid'], ['id' => $params['parent']]);
592                                 $message_id = "<" . $parent['guid'] . "@" . gethostname() . ">";
593
594                                 // Is this the first email notification for this parent item and user?
595                                 if (!DBA::exists('notify-threads', ['master-parent-uri-id' => $parent_uri_id, 'receiver-uid' => $params['uid']])) {
596                                         $this->logger->info("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']));
597
598                                         $fields = ['notify-id' => $notify_id, 'master-parent-uri-id' => $parent_uri_id,
599                                                 'receiver-uid' => $params['uid'], 'parent-item' => 0];
600                                         DBA::insert('notify-threads', $fields);
601
602                                         $emailBuilder->setHeader('Message-ID', $message_id);
603                                         $log_msg = "include/enotify: No previous notification found for this parent:\n" .
604                                                 "  parent: ${params['parent']}\n" . "  uid   : ${params['uid']}\n";
605                                         $this->logger->info($log_msg);
606                                 } else {
607                                         // If not, just "follow" the thread.
608                                         $emailBuilder->setHeader('References', $message_id);
609                                         $emailBuilder->setHeader('In-Reply-To', $message_id);
610                                         $this->logger->info("There's already a notification for this parent.");
611                                 }
612                         }
613
614                         $datarray = [
615                                 'preamble'     => $preamble,
616                                 'type'         => $params['type'],
617                                 'parent'       => $parent_id,
618                                 'source_name'  => $params['source_name'] ?? null,
619                                 'source_link'  => $params['source_link'] ?? null,
620                                 'source_photo' => $params['source_photo'] ?? null,
621                                 'uid'          => $params['uid'],
622                                 'hsitelink'    => $hsitelink,
623                                 'tsitelink'    => $tsitelink,
624                                 'itemlink'     => $itemlink,
625                                 'title'        => $title,
626                                 'body'         => $body,
627                                 'subject'      => $subject,
628                                 'headers'      => $emailBuilder->getHeaders(),
629                         ];
630
631                         Hook::callAll('enotify_mail', $datarray);
632
633                         $emailBuilder
634                                 ->withHeaders($datarray['headers'])
635                                 ->withRecipient($params['to_email'])
636                                 ->forUser([
637                                         'uid' => $datarray['uid'],
638                                         'language' => $params['language'],
639                                 ])
640                                 ->withNotification($datarray['subject'], $datarray['preamble'], $datarray['title'], $datarray['body'])
641                                 ->withSiteLink($datarray['tsitelink'], $datarray['hsitelink'])
642                                 ->withItemLink($datarray['itemlink']);
643
644                         // If a photo is present, add it to the email
645                         if (!empty($datarray['source_photo'])) {
646                                 $emailBuilder->withPhoto(
647                                         $datarray['source_photo'],
648                                         $datarray['source_link'] ?? $sitelink,
649                                         $datarray['source_name'] ?? $sitename);
650                         }
651
652                         $email = $emailBuilder->build();
653
654                         // use the Emailer class to send the message
655                         return $this->emailer->send($email);
656                 }
657
658                 return false;
659         }
660
661         public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool
662         {
663                 if (is_null($type)) {
664                         $type = NotificationFactory::getType($Notification);
665                 }
666
667                 if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {
668                         return true;
669                 }
670
671                 if ($this->pConfig->get($Notification->uid, 'system', 'notify_like') && ($type == Notification::TYPE_LIKE)) {
672                         return true;
673                 }
674
675                 if ($this->pConfig->get($Notification->uid, 'system', 'notify_announce') && ($type == Notification::TYPE_RESHARE)) {
676                         return true;
677                 }
678
679                 $notify_type = $this->pConfig->get($Notification->uid, 'system', 'notify_type');
680
681                 // Fallback for the case when the notify type isn't set at all
682                 if (is_null($notify_type) && !in_array($type, [Notification::TYPE_RESHARE, Notification::TYPE_LIKE])) {
683                                 return true;
684                 }
685
686                 if (!is_null($notify_type) && ($notify_type & $Notification->type)) {
687                         return true;
688                 }
689
690                 return false;
691         }
692
693         public function createFromNotification(Entity\Notification $Notification)
694         {
695                 $this->logger->info('Start', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
696
697                 if ($Notification->type === Model\Post\UserNotification::TYPE_NONE) {
698                         $this->logger->info('Not an item based notification, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
699                         return false;
700                 }
701
702                 $params = [];
703                 $params['verb']  = $Notification->verb;
704                 $params['uid']   = $Notification->uid;
705                 $params['otype'] = Model\Notification\ObjectType::ITEM;
706
707                 $user = Model\User::getById($Notification->uid);
708
709                 $params['notify_flags'] = $user['notify-flags'];
710                 $params['language']     = $user['language'];
711                 $params['to_name']      = $user['username'];
712                 $params['to_email']     = $user['email'];
713
714                 // from here on everything is in the recipients language
715                 $l10n = $this->l10n->withLang($user['language']);
716
717                 $contact = Model\Contact::getById($Notification->actorId, ['url', 'name', 'photo']);
718                 if (DBA::isResult($contact)) {
719                         $params['source_link']  = $contact['url'];
720                         $params['source_name']  = $contact['name'];
721                         $params['source_photo'] = $contact['photo'];
722                 }
723
724                 $item = Model\Post::selectFirstForUser($Notification->uid, Model\Item::ITEM_FIELDLIST,
725                         ['uid' => [0, $Notification->uid], 'uri-id' => $Notification->targetUriId, 'deleted' => false],
726                         ['order' => ['uid' => true]]);
727                 if (empty($item)) {
728                         $this->logger->info('Item not found', ['uri-id' => $Notification->targetUriId, 'type' => $Notification->type]);
729                         return false;
730                 }
731
732                 $params['item']   = $item;
733                 $params['parent'] = $item['parent'];
734                 $params['link']   = $this->baseUrl->get() . '/display/' . urlencode($item['guid']);
735
736                 $subjectPrefix = $l10n->t('[Friendica:Notify]');
737
738                 if (Model\Post\ThreadUser::getIgnored($Notification->parentUriId, $Notification->uid)) {
739                         $this->logger->info('Thread is ignored', ['parent-uri-id' => $Notification->parentUriId, 'type' => $Notification->type]);
740                         return false;
741                 }
742
743                 // Check to see if there was already a tag notify or comment notify for this post.
744                 // If so don't create a second notification
745                 $condition = ['type' => [Model\Notification\Type::TAG_SELF, Model\Notification\Type::COMMENT, Model\Notification\Type::SHARE],
746                         'link' => $params['link'], 'verb' => Activity::POST];
747                 if ($this->existsForUser($Notification->uid, $condition)) {
748                         $this->logger->info('Duplicate found, quitting', $condition + ['uid' => $Notification->uid]);
749                         return false;
750                 }
751
752                 $body = BBCode::toPlaintext($item['body'], false);
753                 $title = Plaintext::shorten($body, 70);
754                 if (!empty($title)) {
755                         $title = '"' . trim(str_replace("\n", " ", $title)) . '"';
756                 }
757
758                 // Some mail software relies on subject field for threading.
759                 // So, we cannot have different subjects for notifications of the same thread.
760                 // Before this we have the name of the replier on the subject rendering
761                 // different subjects for messages on the same thread.
762                 if ($Notification->type === Model\Post\UserNotification::TYPE_EXPLICIT_TAGGED) {
763                         $params['type'] = Model\Notification\Type::TAG_SELF;
764                         $subject        = $l10n->t('%s %s tagged you', $subjectPrefix, $contact['name']);
765                 } elseif ($Notification->type === Model\Post\UserNotification::TYPE_SHARED) {
766                         $params['type'] = Model\Notification\Type::SHARE;
767                         $subject        = $l10n->t('%s %s shared a new post', $subjectPrefix, $contact['name']);
768                 } else {
769                         $params['type'] = Model\Notification\Type::COMMENT;
770                         $subject        = $l10n->t('%1$s Comment to conversation #%2$d by %3$s', $subjectPrefix, $item['parent'], $contact['name']);
771                 }
772
773                 $msg = $this->notification->getMessageFromNotification($Notification);
774                 if (empty($msg)) {
775                         $this->logger->info('No notification message, quitting', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
776                         return false;
777                 }
778
779                 $preamble  = $msg['plain'];
780                 $epreamble = $msg['rich'];
781
782                 $sitename = $this->config->get('config', 'sitename');
783                 $siteurl  = $this->baseUrl->get(true);
784
785                 $sitelink  = $l10n->t('Please visit %s to view and/or reply to the conversation.');
786                 $tsitelink = sprintf($sitelink, $siteurl);
787                 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
788                 $itemlink  = $params['link'];
789
790                 $this->logger->info('Perform notification', ['uid' => $Notification->uid, 'id' => $Notification->id, 'type' => $Notification->type]);
791
792                 return $this->storeAndSend($params, $sitelink, $tsitelink, $hsitelink, $title, $subject, $preamble, $epreamble, $item['body'], $itemlink, true);
793         }
794 }