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