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