3 * @file include/enotify.php
6 use Friendica\Content\Text\BBCode;
7 use Friendica\Core\Config;
8 use Friendica\Core\Hook;
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 use Friendica\Util\Strings;
21 * @brief Creates a notification entry and possibly sends a mail
23 * @param array $params Array with the elements:
24 * uid, item, parent, type, otype, verb, event,
25 * link, subject, body, to_name, to_email, source_name,
26 * source_link, activity, preamble, notify_flags,
27 * language, show_in_notification_page
29 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
31 function notification($params)
35 // Temporary logging for finding the origin
36 if (!isset($params['language']) || !isset($params['uid'])) {
37 Logger::log('Missing parameters.' . System::callstack());
40 // Ensure that the important fields are set at any time
41 $fields = ['notify-flags', 'language', 'username', 'email'];
42 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
44 if (!DBA::isResult($user)) {
45 Logger::log('Unknown user ' . $params['uid']);
49 $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
50 $params['language'] = defaults($params, 'language' , $user['language']);
51 $params['to_name'] = defaults($params, 'to_name' , $user['username']);
52 $params['to_email'] = defaults($params, 'to_email' , $user['email']);
54 // from here on everything is in the recipients language
55 L10n::pushLang($params['language']);
57 $banner = L10n::t('Friendica Notification');
58 $product = FRIENDICA_PLATFORM;
59 $siteurl = System::baseUrl(true);
60 $thanks = L10n::t('Thank You,');
61 $sitename = Config::get('config', 'sitename');
62 if (Config::get('config', 'admin_name')) {
63 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
65 $site_admin = L10n::t('%s Administrator', $sitename);
68 $sender_name = $sitename;
69 $hostname = $a->getHostName();
70 if (strpos($hostname, ':')) {
71 $hostname = substr($hostname, 0, strpos($hostname, ':'));
74 $sender_email = $a->getSenderEmailAddress();
76 if ($params['type'] != SYSTEM_EMAIL) {
77 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
78 ['uid' => $params['uid']]);
80 // There is no need to create notifications for forum accounts
81 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
84 $nickname = $user["nickname"];
89 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
90 // the database, and an email is sent if applicable.
91 // default, if not specified: true
92 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
94 $additional_mail_header = "";
95 $additional_mail_header .= "Precedence: list\n";
96 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
97 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
98 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
99 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
100 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
101 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
103 if (array_key_exists('item', $params)) {
104 $title = $params['item']['title'];
105 $body = $params['item']['body'];
110 if (isset($params['item']['id'])) {
111 $item_id = $params['item']['id'];
116 if (isset($params['parent'])) {
117 $parent_id = $params['parent'];
124 if ($params['type'] == NOTIFY_MAIL) {
125 $itemlink = $siteurl.'/message/'.$params['item']['id'];
126 $params["link"] = $itemlink;
128 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
130 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
131 $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]');
133 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
134 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
135 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
138 if ($params['type'] == NOTIFY_COMMENT || $params['type'] == NOTIFY_TAGSELF) {
139 $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id]);
140 if (DBA::isResult($thread) && $thread['ignored']) {
141 Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
146 // Check to see if there was already a tag notify or comment notify for this post.
147 // If so don't create a second notification
148 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
149 'link' => $params['link'], 'uid' => $params['uid']];
150 if (DBA::exists('notify', $condition)) {
155 // if it's a post figure out who's post it is.
157 if ($params['otype'] === 'item' && $parent_id) {
158 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
161 $item_post_type = Item::postType($item);
162 $itemlink = $item['plink'];
165 if ($params['type'] == NOTIFY_TAGSELF) {
166 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]a %3$s[/url]',
167 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
172 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
173 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
179 // "George Bull's post"
180 if (DBA::isResult($item)) {
181 if ($params['type'] == NOTIFY_TAGSELF) {
182 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]%3$s\'s %4$s[/url]',
183 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
185 $item['author-name'],
189 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
190 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
192 $item['author-name'],
199 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
200 if ($params['type'] == NOTIFY_TAGSELF) {
201 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]your %3$s[/url]',
202 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
207 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
208 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
216 if (DBA::isResult($item) && $item['author-link'] == $params['source_link']) {
217 if ($params['type'] == NOTIFY_TAGSELF) {
218 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]their %3$s[/url]',
219 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
224 $dest_str = L10n::t('%1$s commented on [url=%2$s]their %3$s[/url]',
225 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
232 // Some mail software relies on subject field for threading.
233 // So, we cannot have different subjects for notifications of the same thread.
234 // Before this we have the name of the replier on the subject rendering
235 // different subjects for messages on the same thread.
236 if ($params['type'] == NOTIFY_TAGSELF) {
237 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
239 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
241 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
243 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
246 $epreamble = $dest_str;
248 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
249 $tsitelink = sprintf($sitelink, $siteurl);
250 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
251 $itemlink = $params['link'];
254 if ($params['type'] == NOTIFY_WALL) {
255 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
257 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
258 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
259 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
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'];
269 if ($params['type'] == NOTIFY_SHARE) {
270 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
272 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
273 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
274 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
278 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
279 $tsitelink = sprintf($sitelink, $siteurl);
280 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
281 $itemlink = $params['link'];
284 if ($params['type'] == NOTIFY_POKE) {
285 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
287 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
288 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
289 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
293 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
294 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
295 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
297 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
298 $tsitelink = sprintf($sitelink, $siteurl);
299 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
300 $itemlink = $params['link'];
303 if ($params['type'] == NOTIFY_TAGSHARE) {
304 $itemlink = $params['link'];
305 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
307 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
308 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
309 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
313 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
314 $tsitelink = sprintf($sitelink, $siteurl);
315 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
318 if ($params['type'] == NOTIFY_INTRO) {
319 $itemlink = $params['link'];
320 $subject = L10n::t('[Friendica:Notify] Introduction received');
322 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
323 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
325 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
328 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
330 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
331 $tsitelink = sprintf($sitelink, $siteurl);
332 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
334 switch ($params['verb']) {
335 case ACTIVITY_FRIEND:
336 // someone started to share with user (mostly OStatus)
337 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
339 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
340 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
341 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
345 case ACTIVITY_FOLLOW:
346 // someone started to follow the user (mostly OStatus)
347 $subject = L10n::t('[Friendica:Notify] You have a new follower');
349 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
350 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
351 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
356 // ACTIVITY_REQ_FRIEND is default activity for notifications
361 if ($params['type'] == NOTIFY_SUGGEST) {
362 $itemlink = $params['link'];
363 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
365 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
366 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
368 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
369 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
372 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
373 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
374 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
376 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
377 $tsitelink = sprintf($sitelink, $siteurl);
378 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
381 if ($params['type'] == NOTIFY_CONFIRM) {
382 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
383 $itemlink = $params['link'];
384 $subject = L10n::t('[Friendica:Notify] Connection accepted');
386 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
387 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
389 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
392 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
394 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
395 $tsitelink = sprintf($sitelink, $siteurl);
396 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
397 } else { // ACTIVITY_FOLLOW
398 $itemlink = $params['link'];
399 $subject = L10n::t('[Friendica:Notify] Connection accepted');
401 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
402 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
404 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
407 $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']);
409 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
411 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
412 $tsitelink = sprintf($sitelink, $siteurl);
413 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
417 if ($params['type'] == NOTIFY_SYSTEM) {
418 switch($params['event']) {
419 case "SYSTEM_REGISTER_REQUEST":
420 $itemlink = $params['link'];
421 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
423 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
424 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
426 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
429 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
430 $params['source_name'],
431 $siteurl, $params['source_mail'],
432 $params['source_nick']
435 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
436 $tsitelink = sprintf($sitelink, $params['link']);
437 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
439 case "SYSTEM_DB_UPDATE_FAIL":
444 if ($params['type'] == SYSTEM_EMAIL) {
445 // not part of the notifications.
446 // it just send a mail to the user.
447 // It will be used by the system to send emails to users (like
448 // password reset, invitations and so) using one look (but without
449 // add a notification to the user, with could be inexistent)
450 $subject = $params['subject'];
452 $preamble = $params['preamble'];
454 $body = $params['body'];
460 $show_in_notification_page = false;
463 $subject .= " (".$nickname."@".$hostname.")";
467 'subject' => $subject,
468 'preamble' => $preamble,
469 'epreamble' => $epreamble,
471 'sitelink' => $sitelink,
472 'tsitelink' => $tsitelink,
473 'hsitelink' => $hsitelink,
474 'itemlink' => $itemlink
477 Hook::callAll('enotify', $h);
479 $subject = $h['subject'];
481 $preamble = $h['preamble'];
482 $epreamble = $h['epreamble'];
486 $tsitelink = $h['tsitelink'];
487 $hsitelink = $h['hsitelink'];
488 $itemlink = $h['itemlink'];
490 if ($show_in_notification_page) {
491 Logger::log("adding notification entry", Logger::DEBUG);
494 $hash = Strings::getRandomHex();
495 if (DBA::exists('notify', ['hash' => $hash])) {
498 } while ($dups == true);
500 /// @TODO One statement is enough
502 $datarray['hash'] = $hash;
503 $datarray['name'] = $params['source_name'];
504 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
505 $datarray['url'] = $params['source_link'];
506 $datarray['photo'] = $params['source_photo'];
507 $datarray['date'] = DateTimeFormat::utcNow();
508 $datarray['uid'] = $params['uid'];
509 $datarray['link'] = $itemlink;
510 $datarray['iid'] = $item_id;
511 $datarray['parent'] = $parent_id;
512 $datarray['type'] = $params['type'];
513 $datarray['verb'] = $params['verb'];
514 $datarray['otype'] = $params['otype'];
515 $datarray['abort'] = false;
517 Hook::callAll('enotify_store', $datarray);
519 if ($datarray['abort']) {
524 // create notification entry in DB
525 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
526 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
527 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
528 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
529 'name_cache' => $datarray["name_cache"]];
530 DBA::insert('notify', $fields);
532 $notify_id = DBA::lastInsertId();
534 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
535 // After we've stored everything, look again to see if there are any duplicates and if so remove them
536 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
537 intval(NOTIFY_TAGSELF),
538 intval(NOTIFY_COMMENT),
539 DBA::escape($params['link']),
540 intval($params['uid'])
542 if ($p && (count($p) > 1)) {
543 for ($d = 1; $d < count($p); $d ++) {
544 DBA::delete('notify', ['id' => $p[$d]['id']]);
547 // only continue on if we stored the first one
548 if ($notify_id != $p[0]['id']) {
554 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
555 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
556 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
558 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
559 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
560 DBA::update('notify', $fields, $condition);
563 // send email notification if notification preferences permit
564 if ((intval($params['notify_flags']) & intval($params['type']))
565 || $params['type'] == NOTIFY_SYSTEM
566 || $params['type'] == SYSTEM_EMAIL) {
568 Logger::log('sending notification email');
570 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
571 $id_for_parent = $params['parent']."@".$hostname;
573 // Is this the first email notification for this parent item and user?
574 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
575 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
577 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
578 'receiver-uid' => $params['uid'], 'parent-item' => 0];
579 DBA::insert('notify-threads', $fields);
581 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
582 $log_msg = "include/enotify: No previous notification found for this parent:\n".
583 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
584 Logger::log($log_msg, Logger::DEBUG);
586 // If not, just "follow" the thread.
587 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
588 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
592 $textversion = BBCode::toPlaintext($body);
593 $htmlversion = BBCode::convert($body);
596 $datarray['banner'] = $banner;
597 $datarray['product'] = $product;
598 $datarray['preamble'] = $preamble;
599 $datarray['sitename'] = $sitename;
600 $datarray['siteurl'] = $siteurl;
601 $datarray['type'] = $params['type'];
602 $datarray['parent'] = $parent_id;
603 $datarray['source_name'] = defaults($params, 'source_name', '');
604 $datarray['source_link'] = defaults($params, 'source_link', '');
605 $datarray['source_photo'] = defaults($params, 'source_photo', '');
606 $datarray['uid'] = $params['uid'];
607 $datarray['username'] = defaults($params, 'to_name', '');
608 $datarray['hsitelink'] = $hsitelink;
609 $datarray['tsitelink'] = $tsitelink;
610 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
611 $datarray['titemlink'] = $itemlink;
612 $datarray['thanks'] = $thanks;
613 $datarray['site_admin'] = $site_admin;
614 $datarray['title'] = stripslashes($title);
615 $datarray['htmlversion'] = $htmlversion;
616 $datarray['textversion'] = $textversion;
617 $datarray['subject'] = $subject;
618 $datarray['headers'] = $additional_mail_header;
620 Hook::callAll('enotify_mail', $datarray);
622 // check whether sending post content in email notifications is allowed
623 // always true for SYSTEM_EMAIL
624 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
626 // load the template for private message notifications
627 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
628 $email_html_body = Renderer::replaceMacros($tpl, [
629 '$banner' => $datarray['banner'],
630 '$product' => $datarray['product'],
631 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
632 '$sitename' => $datarray['sitename'],
633 '$siteurl' => $datarray['siteurl'],
634 '$source_name' => $datarray['source_name'],
635 '$source_link' => $datarray['source_link'],
636 '$source_photo' => $datarray['source_photo'],
637 '$username' => $datarray['username'],
638 '$hsitelink' => $datarray['hsitelink'],
639 '$hitemlink' => $datarray['hitemlink'],
640 '$thanks' => $datarray['thanks'],
641 '$site_admin' => $datarray['site_admin'],
642 '$title' => $datarray['title'],
643 '$htmlversion' => $datarray['htmlversion'],
644 '$content_allowed' => $content_allowed,
647 // load the template for private message notifications
648 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
649 $email_text_body = Renderer::replaceMacros($tpl, [
650 '$banner' => $datarray['banner'],
651 '$product' => $datarray['product'],
652 '$preamble' => $datarray['preamble'],
653 '$sitename' => $datarray['sitename'],
654 '$siteurl' => $datarray['siteurl'],
655 '$source_name' => $datarray['source_name'],
656 '$source_link' => $datarray['source_link'],
657 '$source_photo' => $datarray['source_photo'],
658 '$username' => $datarray['username'],
659 '$tsitelink' => $datarray['tsitelink'],
660 '$titemlink' => $datarray['titemlink'],
661 '$thanks' => $datarray['thanks'],
662 '$site_admin' => $datarray['site_admin'],
663 '$title' => $datarray['title'],
664 '$textversion' => $datarray['textversion'],
665 '$content_allowed' => $content_allowed,
669 // use the Emailer class to send the message
670 return Emailer::send(
672 'uid' => $params['uid'],
673 'fromName' => $sender_name,
674 'fromEmail' => $sender_email,
675 'replyTo' => $sender_email,
676 'toEmail' => $params['to_email'],
677 'messageSubject' => $datarray['subject'],
678 'htmlVersion' => $email_html_body,
679 'textVersion' => $email_text_body,
680 'additionalMailHeader' => $datarray['headers']]
689 * @brief Checks for users who should be notified
691 * @param int $itemid ID of the item for which the check should be done
692 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
694 function check_user_notification($itemid) {
695 // fetch all users in the thread
696 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
697 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
698 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
699 while ($user = DBA::fetch($users)) {
700 check_item_notification($itemid, $user['uid']);
706 * @brief Checks for item related notifications and sends them
708 * @param int $itemid ID of the item for which the check should be done
709 * @param int $uid User ID
710 * @param string $defaulttype (Optional) Forces a notification with this type.
712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
714 function check_item_notification($itemid, $uid, $defaulttype = "") {
715 $notification_data = ["uid" => $uid, "profiles" => []];
716 Hook::callAll('check_item_notification', $notification_data);
718 $profiles = $notification_data["profiles"];
720 $fields = ['nickname'];
721 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
722 if (!DBA::isResult($user)) {
726 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
727 if (!DBA::isResult($owner)) {
731 // This is our regular URL format
732 $profiles[] = $owner["url"];
734 // Notifications from Diaspora are often with an URL in the Diaspora format
735 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
739 foreach ($profiles AS $profile) {
740 // Check for invalid profile urls. 13 should be the shortest possible profile length:
742 // Additionally check for invalid urls that would return the normalised value "http:"
743 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
744 if (!in_array($profile, $profiles2))
745 $profiles2[] = $profile;
747 $profile = Strings::normaliseLink($profile);
748 if (!in_array($profile, $profiles2))
749 $profiles2[] = $profile;
751 $profile = str_replace("http://", "https://", $profile);
752 if (!in_array($profile, $profiles2))
753 $profiles2[] = $profile;
757 $profiles = $profiles2;
759 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
763 while ($contact = DBA::fetch($ret)) {
764 $contacts[] = $contact['id'];
769 // Only act if it is a "real" post
770 // We need the additional check for the "local_profile" because of mixed situations on connector networks
771 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
772 'author-link', 'author-name', 'author-avatar', 'author-id',
773 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
774 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
775 $item = Item::selectFirst($fields, $condition);
776 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
780 // Generate the notification array
782 $params["uid"] = $uid;
783 $params["item"] = $item;
784 $params["parent"] = $item["parent"];
785 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
786 $params["otype"] = 'item';
787 $params["source_name"] = $item["author-name"];
788 $params["source_link"] = $item["author-link"];
789 $params["source_photo"] = $item["author-avatar"];
791 if ($item["parent-uri"] === $item["uri"]) {
792 // Send a notification for every new post?
793 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
795 if (!$send_notification) {
796 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
797 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
799 if (DBA::isResult($tags)) {
800 foreach ($tags AS $tag) {
801 $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
802 $r = DBA::exists('contact', $condition);
804 $send_notification = true;
810 if ($send_notification) {
811 $params["type"] = NOTIFY_SHARE;
812 $params["verb"] = ACTIVITY_TAG;
816 // Is the user mentioned in this post?
819 foreach ($profiles AS $profile) {
820 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
824 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
825 $params["type"] = NOTIFY_TAGSELF;
826 $params["verb"] = ACTIVITY_TAG;
829 // Is it a post that the user had started?
830 $fields = ['ignored', 'mention'];
831 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
833 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
834 $params["type"] = NOTIFY_COMMENT;
835 $params["verb"] = ACTIVITY_POST;
838 // And now we check for participation of one of our contacts in the thread
839 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
841 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
842 $params["type"] = NOTIFY_COMMENT;
843 $params["verb"] = ACTIVITY_POST;
846 if (isset($params["type"])) {
847 notification($params);
852 * @brief Formats a notification message with the notification author
854 * Replace the name with {0} but ensure to make that only once. The {0} is used
855 * later and prints the name in bold.
857 * @param string $name
858 * @param string $message
859 * @return string Formatted message
861 function format_notification_message($name, $message) {
863 $pos = strpos($message, $name);
868 if ($pos !== false) {
869 $message = substr_replace($message, '{0}', $pos, strlen($name));