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