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