]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Merge pull request #6093 from zeroadam/TextToItem
[friendica.git] / include / enotify.php
1 <?php
2 /**
3  * @file include/enotify.php
4  */
5
6 use Friendica\Content\Text\BBCode;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Renderer;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Emailer;
18
19 /**
20  * @brief Creates a notification entry and possibly sends a mail
21  *
22  * @param array $params Array with the elements:
23  *                      uid, item, parent, type, otype, verb, event,
24  *                      link, subject, body, to_name, to_email, source_name,
25  *                      source_link, activity, preamble, notify_flags,
26  *                      language, show_in_notification_page
27  */
28 function notification($params)
29 {
30         $a = get_app();
31
32         // Temporary logging for finding the origin
33         if (!isset($params['language']) || !isset($params['uid'])) {
34                 Logger::log('Missing parameters.' . System::callstack());
35         }
36
37         // Ensure that the important fields are set at any time
38         $fields = ['notify-flags', 'language', 'username', 'email'];
39         $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
40
41         if (!DBA::isResult($user)) {
42                 Logger::log('Unknown user ' . $params['uid']);
43                 return;
44         }
45
46         $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
47         $params['language']     = defaults($params, 'language'    , $user['language']);
48         $params['to_name']      = defaults($params, 'to_name'     , $user['username']);
49         $params['to_email']     = defaults($params, 'to_email'    , $user['email']);
50
51         // from here on everything is in the recipients language
52         L10n::pushLang($params['language']);
53
54         $banner = L10n::t('Friendica Notification');
55         $product = FRIENDICA_PLATFORM;
56         $siteurl = System::baseUrl(true);
57         $thanks = L10n::t('Thank You,');
58         $sitename = Config::get('config', 'sitename');
59         if (Config::get('config', 'admin_name')) {
60                 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
61         } else {
62                 $site_admin = L10n::t('%s Administrator', $sitename);
63         }
64
65         $sender_name = $sitename;
66         $hostname = $a->getHostName();
67         if (strpos($hostname, ':')) {
68                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
69         }
70
71         $sender_email = $a->getSenderEmailAddress();
72
73         if ($params['type'] != SYSTEM_EMAIL) {
74                 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
75                         ['uid' => $params['uid']]);
76
77                 // There is no need to create notifications for forum accounts
78                 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
79                         return;
80                 }
81                 $nickname = $user["nickname"];
82         } else {
83                 $nickname = '';
84         }
85
86         // with $params['show_in_notification_page'] == false, the notification isn't inserted into
87         // the database, and an email is sent if applicable.
88         // default, if not specified: true
89         $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
90
91         $additional_mail_header = "";
92         $additional_mail_header .= "Precedence: list\n";
93         $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
94         $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
95         $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
96         $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
97         $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
98         $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
99
100         if (array_key_exists('item', $params)) {
101                 $title = $params['item']['title'];
102                 $body = $params['item']['body'];
103         } else {
104                 $title = $body = '';
105         }
106
107         if (isset($params['item']['id'])) {
108                 $item_id = $params['item']['id'];
109         } else {
110                 $item_id = 0;
111         }
112
113         if (isset($params['parent'])) {
114                 $parent_id = $params['parent'];
115         } else {
116                 $parent_id = 0;
117         }
118
119         $epreamble = '';
120
121         if ($params['type'] == NOTIFY_MAIL) {
122                 $itemlink = $siteurl.'/message/'.$params['item']['id'];
123                 $params["link"] = $itemlink;
124
125                 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
126
127                 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
128                 $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]');
129
130                 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
131                 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
132                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
133         }
134
135         if ($params['type'] == NOTIFY_COMMENT) {
136                 $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
137                 if (DBA::isResult($thread) && $thread["ignored"]) {
138                         Logger::log("Thread ".$parent_id." will be ignored", Logger::DEBUG);
139                         L10n::popLang();
140                         return;
141                 }
142
143                 // Check to see if there was already a tag notify or comment notify for this post.
144                 // If so don't create a second notification
145                 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
146                         'link' => $params['link'], 'uid' => $params['uid']];
147                 if (DBA::exists('notify', $condition)) {
148                         L10n::popLang();
149                         return;
150                 }
151
152                 // if it's a post figure out who's post it is.
153
154                 $item = null;
155
156                 if ($params['otype'] === 'item' && $parent_id) {
157                         $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
158                 }
159
160                 $item_post_type = Item::postType($item);
161                 $itemlink = $item['plink'];
162
163                 // "a post"
164                 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
165                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
166                         $itemlink,
167                         $item_post_type
168                 );
169
170                 // "George Bull's post"
171                 if ($item) {
172                         $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
173                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
174                                 $itemlink,
175                                 $item['author-name'],
176                                 $item_post_type
177                         );
178                 }
179
180                 // "your post"
181                 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
182                         $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
183                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
184                                 $itemlink,
185                                 $item_post_type
186                         );
187                 }
188
189                 // Some mail softwares relies on subject field for threading.
190                 // So, we cannot have different subjects for notifications of the same thread.
191                 // Before this we have the name of the replier on the subject rendering
192                 // differents subjects for messages on the same thread.
193
194                 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
195
196                 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
197                 $epreamble = $dest_str;
198
199                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
200                 $tsitelink = sprintf($sitelink, $siteurl);
201                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
202                 $itemlink =  $params['link'];
203         }
204
205         if ($params['type'] == NOTIFY_WALL) {
206                 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
207
208                 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
209                 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
210                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
211                         $params['link']
212                 );
213
214                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
215                 $tsitelink = sprintf($sitelink, $siteurl);
216                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
217                 $itemlink =  $params['link'];
218         }
219
220         if ($params['type'] == NOTIFY_TAGSELF) {
221                 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
222
223                 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
224                 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
225                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
226                         $params['link']
227                 );
228
229                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
230                 $tsitelink = sprintf($sitelink, $siteurl);
231                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
232                 $itemlink =  $params['link'];
233         }
234
235         if ($params['type'] == NOTIFY_SHARE) {
236                 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
237
238                 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
239                 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
240                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
241                         $params['link']
242                 );
243
244                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
245                 $tsitelink = sprintf($sitelink, $siteurl);
246                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
247                 $itemlink =  $params['link'];
248         }
249
250         if ($params['type'] == NOTIFY_POKE) {
251                 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
252
253                 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
254                 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
255                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
256                         $params['link']
257                 );
258
259                 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
260                 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
261                 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
262
263                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
264                 $tsitelink = sprintf($sitelink, $siteurl);
265                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
266                 $itemlink =  $params['link'];
267         }
268
269         if ($params['type'] == NOTIFY_TAGSHARE) {
270                 $itemlink =  $params['link'];
271                 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
272
273                 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
274                 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
275                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
276                         $itemlink
277                 );
278
279                 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
280                 $tsitelink = sprintf($sitelink, $siteurl);
281                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
282         }
283
284         if ($params['type'] == NOTIFY_INTRO) {
285                 $itemlink = $params['link'];
286                 $subject = L10n::t('[Friendica:Notify] Introduction received');
287
288                 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
289                 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
290                         $itemlink,
291                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
292                 );
293
294                 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
295
296                 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
297                 $tsitelink = sprintf($sitelink, $siteurl);
298                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
299
300                 switch ($params['verb']) {
301                         case ACTIVITY_FRIEND:
302                                 // someone started to share with user (mostly OStatus)
303                                 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
304
305                                 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
306                                 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
307                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
308                                         $sitename
309                                 );
310                                 break;
311                         case ACTIVITY_FOLLOW:
312                                 // someone started to follow the user (mostly OStatus)
313                                 $subject = L10n::t('[Friendica:Notify] You have a new follower');
314
315                                 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
316                                 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
317                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
318                                         $sitename
319                                 );
320                                 break;
321                         default:
322                                 // ACTIVITY_REQ_FRIEND is default activity for notifications
323                                 break;
324                 }
325         }
326
327         if ($params['type'] == NOTIFY_SUGGEST) {
328                 $itemlink =  $params['link'];
329                 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
330
331                 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
332                 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
333                         $itemlink,
334                         '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
335                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
336                 );
337
338                 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
339                 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
340                 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
341
342                 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
343                 $tsitelink = sprintf($sitelink, $siteurl);
344                 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
345         }
346
347         if ($params['type'] == NOTIFY_CONFIRM) {
348                 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
349                         $itemlink =  $params['link'];
350                         $subject = L10n::t('[Friendica:Notify] Connection accepted');
351
352                         $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
353                         $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
354                                 $itemlink,
355                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
356                         );
357
358                         $body =  L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
359
360                         $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
361                         $tsitelink = sprintf($sitelink, $siteurl);
362                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
363                 } else { // ACTIVITY_FOLLOW
364                         $itemlink =  $params['link'];
365                         $subject = L10n::t('[Friendica:Notify] Connection accepted');
366
367                         $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
368                         $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
369                                 $itemlink,
370                                 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
371                         );
372
373                         $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']);
374                         $body .= "\n\n";
375                         $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
376
377                         $sitelink = L10n::t('Please visit %s  if you wish to make any changes to this relationship.');
378                         $tsitelink = sprintf($sitelink, $siteurl);
379                         $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
380                 }
381         }
382
383         if ($params['type'] == NOTIFY_SYSTEM) {
384                 switch($params['event']) {
385                         case "SYSTEM_REGISTER_REQUEST":
386                                 $itemlink =  $params['link'];
387                                 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
388
389                                 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
390                                 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
391                                         $itemlink,
392                                         '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
393                                 );
394
395                                 $body = L10n::t("Full Name:     %s\nSite Location:      %s\nLogin Name: %s (%s)",
396                                         $params['source_name'],
397                                         $siteurl, $params['source_mail'],
398                                         $params['source_nick']
399                                 );
400
401                                 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
402                                 $tsitelink = sprintf($sitelink, $params['link']);
403                                 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
404                                 break;
405                         case "SYSTEM_DB_UPDATE_FAIL":
406                                 break;
407                 }
408         }
409
410         if ($params['type'] == SYSTEM_EMAIL) {
411                 // not part of the notifications.
412                 // it just send a mail to the user.
413                 // It will be used by the system to send emails to users (like
414                 // password reset, invitations and so) using one look (but without
415                 // add a notification to the user, with could be inexistent)
416                 $subject = $params['subject'];
417
418                 $preamble = $params['preamble'];
419
420                 $body =  $params['body'];
421
422                 $sitelink = "";
423                 $tsitelink = "";
424                 $hsitelink = "";
425                 $itemlink =  "";
426                 $show_in_notification_page = false;
427         }
428
429         $subject .= " (".$nickname."@".$hostname.")";
430
431         $h = [
432                 'params'    => $params,
433                 'subject'   => $subject,
434                 'preamble'  => $preamble,
435                 'epreamble' => $epreamble,
436                 'body'      => $body,
437                 'sitelink'  => $sitelink,
438                 'tsitelink' => $tsitelink,
439                 'hsitelink' => $hsitelink,
440                 'itemlink'  => $itemlink
441         ];
442
443         Addon::callHooks('enotify', $h);
444
445         $subject   = $h['subject'];
446
447         $preamble  = $h['preamble'];
448         $epreamble = $h['epreamble'];
449
450         $body      = $h['body'];
451
452         $tsitelink = $h['tsitelink'];
453         $hsitelink = $h['hsitelink'];
454         $itemlink  = $h['itemlink'];
455
456         if ($show_in_notification_page) {
457                 Logger::log("adding notification entry", Logger::DEBUG);
458                 do {
459                         $dups = false;
460                         $hash = random_string();
461                         if (DBA::exists('notify', ['hash' => $hash])) {
462                                 $dups = true;
463                         }
464                 } while ($dups == true);
465
466                 /// @TODO One statement is enough
467                 $datarray = [];
468                 $datarray['hash']  = $hash;
469                 $datarray['name']  = $params['source_name'];
470                 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
471                 $datarray['url']   = $params['source_link'];
472                 $datarray['photo'] = $params['source_photo'];
473                 $datarray['date']  = DateTimeFormat::utcNow();
474                 $datarray['uid']   = $params['uid'];
475                 $datarray['link']  = $itemlink;
476                 $datarray['iid']   = $item_id;
477                 $datarray['parent'] = $parent_id;
478                 $datarray['type']  = $params['type'];
479                 $datarray['verb']  = $params['verb'];
480                 $datarray['otype'] = $params['otype'];
481                 $datarray['abort'] = false;
482
483                 Addon::callHooks('enotify_store', $datarray);
484
485                 if ($datarray['abort']) {
486                         L10n::popLang();
487                         return False;
488                 }
489
490                 // create notification entry in DB
491                 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
492                         'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
493                         'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
494                         'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
495                         'name_cache' => $datarray["name_cache"]];
496                 DBA::insert('notify', $fields);
497
498                 $notify_id = DBA::lastInsertId();
499
500                 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
501                 // After we've stored everything, look again to see if there are any duplicates and if so remove them
502                 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
503                         intval(NOTIFY_TAGSELF),
504                         intval(NOTIFY_COMMENT),
505                         DBA::escape($params['link']),
506                         intval($params['uid'])
507                 );
508                 if ($p && (count($p) > 1)) {
509                         for ($d = 1; $d < count($p); $d ++) {
510                                 DBA::delete('notify', ['id' => $p[$d]['id']]);
511                         }
512
513                         // only continue on if we stored the first one
514                         if ($notify_id != $p[0]['id']) {
515                                 L10n::popLang();
516                                 return false;
517                         }
518                 }
519
520                 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
521                 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
522                 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
523
524                 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
525                 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
526                 DBA::update('notify', $fields, $condition);
527         }
528
529         // send email notification if notification preferences permit
530         if ((intval($params['notify_flags']) & intval($params['type']))
531                 || $params['type'] == NOTIFY_SYSTEM
532                 || $params['type'] == SYSTEM_EMAIL) {
533
534                 Logger::log('sending notification email');
535
536                 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
537                         $id_for_parent = $params['parent']."@".$hostname;
538
539                         // Is this the first email notification for this parent item and user?
540                         if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], '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-item' => $params['parent'],
544                                         'receiver-uid' => $params['uid'], 'parent-item' => 0];
545                                 DBA::insert('notify-threads', $fields);
546
547                                 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
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                                 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
554                                 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
555                         }
556                 }
557
558                 $textversion = BBCode::toPlaintext($body);
559                 $htmlversion = BBCode::convert($body);
560
561                 $datarray = [];
562                 $datarray['banner'] = $banner;
563                 $datarray['product'] = $product;
564                 $datarray['preamble'] = $preamble;
565                 $datarray['sitename'] = $sitename;
566                 $datarray['siteurl'] = $siteurl;
567                 $datarray['type'] = $params['type'];
568                 $datarray['parent'] = $parent_id;
569                 $datarray['source_name'] = defaults($params, 'source_name', '');
570                 $datarray['source_link'] = defaults($params, 'source_link', '');
571                 $datarray['source_photo'] = defaults($params, 'source_photo', '');
572                 $datarray['uid'] = $params['uid'];
573                 $datarray['username'] = defaults($params, 'to_name', '');
574                 $datarray['hsitelink'] = $hsitelink;
575                 $datarray['tsitelink'] = $tsitelink;
576                 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
577                 $datarray['titemlink'] = $itemlink;
578                 $datarray['thanks'] = $thanks;
579                 $datarray['site_admin'] = $site_admin;
580                 $datarray['title'] = stripslashes($title);
581                 $datarray['htmlversion'] = $htmlversion;
582                 $datarray['textversion'] = $textversion;
583                 $datarray['subject'] = $subject;
584                 $datarray['headers'] = $additional_mail_header;
585
586                 Addon::callHooks('enotify_mail', $datarray);
587
588                 // check whether sending post content in email notifications is allowed
589                 // always true for SYSTEM_EMAIL
590                 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
591
592                 // load the template for private message notifications
593                 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
594                 $email_html_body = Renderer::replaceMacros($tpl, [
595                         '$banner'       => $datarray['banner'],
596                         '$product'      => $datarray['product'],
597                         '$preamble'     => str_replace("\n", "<br>\n", $datarray['preamble']),
598                         '$sitename'     => $datarray['sitename'],
599                         '$siteurl'      => $datarray['siteurl'],
600                         '$source_name'  => $datarray['source_name'],
601                         '$source_link'  => $datarray['source_link'],
602                         '$source_photo' => $datarray['source_photo'],
603                         '$username'     => $datarray['username'],
604                         '$hsitelink'    => $datarray['hsitelink'],
605                         '$hitemlink'    => $datarray['hitemlink'],
606                         '$thanks'       => $datarray['thanks'],
607                         '$site_admin'   => $datarray['site_admin'],
608                         '$title'        => $datarray['title'],
609                         '$htmlversion'  => $datarray['htmlversion'],
610                         '$content_allowed'      => $content_allowed,
611                 ]);
612
613                 // load the template for private message notifications
614                 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
615                 $email_text_body = Renderer::replaceMacros($tpl, [
616                         '$banner'       => $datarray['banner'],
617                         '$product'      => $datarray['product'],
618                         '$preamble'     => $datarray['preamble'],
619                         '$sitename'     => $datarray['sitename'],
620                         '$siteurl'      => $datarray['siteurl'],
621                         '$source_name'  => $datarray['source_name'],
622                         '$source_link'  => $datarray['source_link'],
623                         '$source_photo' => $datarray['source_photo'],
624                         '$username'     => $datarray['username'],
625                         '$tsitelink'    => $datarray['tsitelink'],
626                         '$titemlink'    => $datarray['titemlink'],
627                         '$thanks'       => $datarray['thanks'],
628                         '$site_admin'   => $datarray['site_admin'],
629                         '$title'        => $datarray['title'],
630                         '$textversion'  => $datarray['textversion'],
631                         '$content_allowed'      => $content_allowed,
632                 ]);
633
634                 L10n::popLang();
635                 // use the Emailer class to send the message
636                 return Emailer::send(
637                         [
638                         'uid' => $params['uid'],
639                         'fromName' => $sender_name,
640                         'fromEmail' => $sender_email,
641                         'replyTo' => $sender_email,
642                         'toEmail' => $params['to_email'],
643                         'messageSubject' => $datarray['subject'],
644                         'htmlVersion' => $email_html_body,
645                         'textVersion' => $email_text_body,
646                         'additionalMailHeader' => $datarray['headers']]
647                 );
648         }
649
650         L10n::popLang();
651         return false;
652 }
653
654 /**
655  * @brief Checks for users who should be notified
656  *
657  * @param int $itemid ID of the item for which the check should be done
658  */
659 function check_user_notification($itemid) {
660         // fetch all users in the thread
661         $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
662                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
663                         WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
664         while ($user = DBA::fetch($users)) {
665                 check_item_notification($itemid, $user['uid']);
666         }
667         DBA::close($users);
668 }
669
670 /**
671  * @brief Checks for item related notifications and sends them
672  *
673  * @param int $itemid ID of the item for which the check should be done
674  * @param int $uid User ID
675  * @param string $defaulttype (Optional) Forces a notification with this type.
676  */
677 function check_item_notification($itemid, $uid, $defaulttype = "") {
678         $notification_data = ["uid" => $uid, "profiles" => []];
679         Addon::callHooks('check_item_notification', $notification_data);
680
681         $profiles = $notification_data["profiles"];
682
683         $fields = ['nickname'];
684         $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
685         if (!DBA::isResult($user)) {
686                 return false;
687         }
688
689         $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
690         if (!DBA::isResult($owner)) {
691                 return false;
692         }
693
694         // This is our regular URL format
695         $profiles[] = $owner["url"];
696
697         // Notifications from Diaspora are often with an URL in the Diaspora format
698         $profiles[] = System::baseUrl()."/u/".$user["nickname"];
699
700         $profiles2 = [];
701
702         foreach ($profiles AS $profile) {
703                 // Check for invalid profile urls. 13 should be the shortest possible profile length:
704                 // http://a.bc/d
705                 // Additionally check for invalid urls that would return the normalised value "http:"
706                 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
707                         if (!in_array($profile, $profiles2))
708                                 $profiles2[] = $profile;
709
710                         $profile = normalise_link($profile);
711                         if (!in_array($profile, $profiles2))
712                                 $profiles2[] = $profile;
713
714                         $profile = str_replace("http://", "https://", $profile);
715                         if (!in_array($profile, $profiles2))
716                                 $profiles2[] = $profile;
717                 }
718         }
719
720         $profiles = $profiles2;
721
722         $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
723
724         $contacts = [];
725
726         while ($contact = DBA::fetch($ret)) {
727                 $contacts[] = $contact['id'];
728         }
729
730         DBA::close($ret);
731
732         // Only act if it is a "real" post
733         // We need the additional check for the "local_profile" because of mixed situations on connector networks
734         $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
735                 'author-link', 'author-name', 'author-avatar', 'author-id',
736                 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
737         $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
738         $item = Item::selectFirst($fields, $condition);
739         if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
740                 return;
741         }
742
743         // Generate the notification array
744         $params = [];
745         $params["uid"] = $uid;
746         $params["item"] = $item;
747         $params["parent"] = $item["parent"];
748         $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
749         $params["otype"] = 'item';
750         $params["source_name"] = $item["author-name"];
751         $params["source_link"] = $item["author-link"];
752         $params["source_photo"] = $item["author-avatar"];
753
754         if ($item["parent-uri"] === $item["uri"]) {
755                 // Send a notification for every new post?
756                 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
757
758                 if (!$send_notification) {
759                         $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
760                                 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
761
762                         if (DBA::isResult($tags)) {
763                                 foreach ($tags AS $tag) {
764                                         $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
765                                         $r = DBA::exists('contact', $condition);
766                                         if ($r) {
767                                                 $send_notification = true;
768                                         }
769                                 }
770                         }
771                 }
772
773                 if ($send_notification) {
774                         $params["type"] = NOTIFY_SHARE;
775                         $params["verb"] = ACTIVITY_TAG;
776                 }
777         }
778
779         // Is the user mentioned in this post?
780         $tagged = false;
781
782         foreach ($profiles AS $profile) {
783                 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
784                         $tagged = true;
785         }
786
787         if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
788                 $params["type"] = NOTIFY_TAGSELF;
789                 $params["verb"] = ACTIVITY_TAG;
790         }
791
792         // Is it a post that the user had started?
793         $fields = ['ignored', 'mention'];
794         $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
795
796         if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
797                 $params["type"] = NOTIFY_COMMENT;
798                 $params["verb"] = ACTIVITY_POST;
799         }
800
801         // And now we check for participation of one of our contacts in the thread
802         $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
803
804         if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
805                 $params["type"] = NOTIFY_COMMENT;
806                 $params["verb"] = ACTIVITY_POST;
807         }
808
809         if (isset($params["type"])) {
810                 notification($params);
811         }
812 }
813
814 /**
815  * @brief Formats a notification message with the notification author
816  *
817  * Replace the name with {0} but ensure to make that only once. The {0} is used
818  * later and prints the name in bold.
819  *
820  * @param string $name
821  * @param string $message
822  * @return string Formatted message
823  */
824 function format_notification_message($name, $message) {
825         if ($name != '') {
826                 $pos = strpos($message, $name);
827         } else {
828                 $pos = false;
829         }
830
831         if ($pos !== false) {
832                 $message = substr_replace($message, '{0}', $pos, strlen($name));
833         }
834
835         return $message;
836 }