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\Item;
15 use Friendica\Model\User;
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"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_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'];
130 if ($params['type'] == NOTIFY_MAIL) {
131 $itemlink = $siteurl.'/message/'.$params['item']['id'];
132 $params["link"] = $itemlink;
134 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
136 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
137 $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]');
139 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
140 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
141 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
144 if ($params['type'] == NOTIFY_COMMENT || $params['type'] == NOTIFY_TAGSELF) {
145 $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id]);
146 if (DBA::isResult($thread) && $thread['ignored']) {
147 Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
152 // Check to see if there was already a tag notify or comment notify for this post.
153 // If so don't create a second notification
154 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
155 'link' => $params['link'], 'uid' => $params['uid']];
156 if (DBA::exists('notify', $condition)) {
161 // if it's a post figure out who's post it is.
163 if ($params['otype'] === 'item' && $parent_id) {
164 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
167 $item_post_type = Item::postType($item);
168 $itemlink = $item['plink'];
171 if ($params['type'] == NOTIFY_TAGSELF) {
172 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]a %3$s[/url]',
173 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
178 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
179 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
185 // "George Bull's post"
186 if (DBA::isResult($item)) {
187 if ($params['type'] == NOTIFY_TAGSELF) {
188 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]%3$s\'s %4$s[/url]',
189 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
191 $item['author-name'],
195 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
196 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
198 $item['author-name'],
205 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
206 if ($params['type'] == NOTIFY_TAGSELF) {
207 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]your %3$s[/url]',
208 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
213 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
214 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
222 if (DBA::isResult($item) && $item['author-link'] == $params['source_link']) {
223 if ($params['type'] == NOTIFY_TAGSELF) {
224 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]their %3$s[/url]',
225 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
230 $dest_str = L10n::t('%1$s commented on [url=%2$s]their %3$s[/url]',
231 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
238 // Some mail software relies on subject field for threading.
239 // So, we cannot have different subjects for notifications of the same thread.
240 // Before this we have the name of the replier on the subject rendering
241 // different subjects for messages on the same thread.
242 if ($params['type'] == NOTIFY_TAGSELF) {
243 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
245 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
247 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
249 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
252 $epreamble = $dest_str;
254 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
255 $tsitelink = sprintf($sitelink, $siteurl);
256 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
257 $itemlink = $params['link'];
260 if ($params['type'] == NOTIFY_WALL) {
261 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
263 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
264 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
265 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
269 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
270 $tsitelink = sprintf($sitelink, $siteurl);
271 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
272 $itemlink = $params['link'];
275 if ($params['type'] == NOTIFY_SHARE) {
276 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
278 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
279 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
280 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
284 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
285 $tsitelink = sprintf($sitelink, $siteurl);
286 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
287 $itemlink = $params['link'];
290 if ($params['type'] == NOTIFY_POKE) {
291 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
293 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
294 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
295 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
299 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
300 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
301 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
303 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
304 $tsitelink = sprintf($sitelink, $siteurl);
305 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
306 $itemlink = $params['link'];
309 if ($params['type'] == NOTIFY_TAGSHARE) {
310 $itemlink = $params['link'];
311 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
313 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
314 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
315 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
319 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
320 $tsitelink = sprintf($sitelink, $siteurl);
321 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
324 if ($params['type'] == NOTIFY_INTRO) {
325 $itemlink = $params['link'];
326 $subject = L10n::t('[Friendica:Notify] Introduction received');
328 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
329 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
331 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
334 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
336 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
337 $tsitelink = sprintf($sitelink, $siteurl);
338 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
340 switch ($params['verb']) {
341 case ACTIVITY_FRIEND:
342 // someone started to share with user (mostly OStatus)
343 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
345 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
346 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
347 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
351 case ACTIVITY_FOLLOW:
352 // someone started to follow the user (mostly OStatus)
353 $subject = L10n::t('[Friendica:Notify] You have a new follower');
355 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
356 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
357 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
362 // ACTIVITY_REQ_FRIEND is default activity for notifications
367 if ($params['type'] == NOTIFY_SUGGEST) {
368 $itemlink = $params['link'];
369 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
371 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
372 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
374 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
375 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
378 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
379 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
380 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
382 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
383 $tsitelink = sprintf($sitelink, $siteurl);
384 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
387 if ($params['type'] == NOTIFY_CONFIRM) {
388 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
389 $itemlink = $params['link'];
390 $subject = L10n::t('[Friendica:Notify] Connection accepted');
392 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
393 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
395 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
398 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
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 } else { // ACTIVITY_FOLLOW
404 $itemlink = $params['link'];
405 $subject = L10n::t('[Friendica:Notify] Connection accepted');
407 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
408 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
410 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
413 $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']);
415 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
417 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
418 $tsitelink = sprintf($sitelink, $siteurl);
419 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
423 if ($params['type'] == NOTIFY_SYSTEM) {
424 switch($params['event']) {
425 case "SYSTEM_REGISTER_REQUEST":
426 $itemlink = $params['link'];
427 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
429 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
430 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
432 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
435 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
436 $params['source_name'],
437 $siteurl, $params['source_mail'],
438 $params['source_nick']
441 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
442 $tsitelink = sprintf($sitelink, $params['link']);
443 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
445 case "SYSTEM_DB_UPDATE_FAIL":
450 if ($params['type'] == SYSTEM_EMAIL) {
451 // not part of the notifications.
452 // it just send a mail to the user.
453 // It will be used by the system to send emails to users (like
454 // password reset, invitations and so) using one look (but without
455 // add a notification to the user, with could be inexistent)
456 $subject = $params['subject'];
458 $preamble = $params['preamble'];
460 $body = $params['body'];
462 $show_in_notification_page = false;
465 $subject .= " (".$nickname."@".$hostname.")";
469 'subject' => $subject,
470 'preamble' => $preamble,
471 'epreamble' => $epreamble,
473 'sitelink' => $sitelink,
474 'tsitelink' => $tsitelink,
475 'hsitelink' => $hsitelink,
476 'itemlink' => $itemlink
479 Hook::callAll('enotify', $h);
481 $subject = $h['subject'];
483 $preamble = $h['preamble'];
484 $epreamble = $h['epreamble'];
488 $tsitelink = $h['tsitelink'];
489 $hsitelink = $h['hsitelink'];
490 $itemlink = $h['itemlink'];
494 if ($show_in_notification_page) {
495 Logger::log("adding notification entry", Logger::DEBUG);
498 $hash = Strings::getRandomHex();
499 if (DBA::exists('notify', ['hash' => $hash])) {
502 } while ($dups == true);
504 /// @TODO One statement is enough
506 $datarray['hash'] = $hash;
507 $datarray['name'] = $params['source_name'];
508 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
509 $datarray['url'] = $params['source_link'];
510 $datarray['photo'] = $params['source_photo'];
511 $datarray['date'] = DateTimeFormat::utcNow();
512 $datarray['uid'] = $params['uid'];
513 $datarray['link'] = $itemlink;
514 $datarray['iid'] = $item_id;
515 $datarray['parent'] = $parent_id;
516 $datarray['type'] = $params['type'];
517 $datarray['verb'] = $params['verb'];
518 $datarray['otype'] = $params['otype'];
519 $datarray['abort'] = false;
521 Hook::callAll('enotify_store', $datarray);
523 if ($datarray['abort']) {
528 // create notification entry in DB
529 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
530 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
531 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
532 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
533 'name_cache' => $datarray["name_cache"]];
534 DBA::insert('notify', $fields);
536 $notify_id = DBA::lastInsertId();
538 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
539 // After we've stored everything, look again to see if there are any duplicates and if so remove them
540 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
541 intval(NOTIFY_TAGSELF),
542 intval(NOTIFY_COMMENT),
543 DBA::escape($params['link']),
544 intval($params['uid'])
546 if ($p && (count($p) > 1)) {
547 for ($d = 1; $d < count($p); $d ++) {
548 DBA::delete('notify', ['id' => $p[$d]['id']]);
551 // only continue on if we stored the first one
552 if ($notify_id != $p[0]['id']) {
558 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
559 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
560 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
562 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
563 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
564 DBA::update('notify', $fields, $condition);
567 // send email notification if notification preferences permit
568 if ((intval($params['notify_flags']) & intval($params['type']))
569 || $params['type'] == NOTIFY_SYSTEM
570 || $params['type'] == SYSTEM_EMAIL) {
572 Logger::log('sending notification email');
574 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
575 $id_for_parent = $params['parent']."@".$hostname;
577 // Is this the first email notification for this parent item and user?
578 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
579 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
581 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
582 'receiver-uid' => $params['uid'], 'parent-item' => 0];
583 DBA::insert('notify-threads', $fields);
585 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
586 $log_msg = "include/enotify: No previous notification found for this parent:\n".
587 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
588 Logger::log($log_msg, Logger::DEBUG);
590 // If not, just "follow" the thread.
591 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
592 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
596 $textversion = BBCode::toPlaintext($body);
597 $htmlversion = BBCode::convert($body);
600 $datarray['banner'] = $banner;
601 $datarray['product'] = $product;
602 $datarray['preamble'] = $preamble;
603 $datarray['sitename'] = $sitename;
604 $datarray['siteurl'] = $siteurl;
605 $datarray['type'] = $params['type'];
606 $datarray['parent'] = $parent_id;
607 $datarray['source_name'] = defaults($params, 'source_name', '');
608 $datarray['source_link'] = defaults($params, 'source_link', '');
609 $datarray['source_photo'] = defaults($params, 'source_photo', '');
610 $datarray['uid'] = $params['uid'];
611 $datarray['username'] = defaults($params, 'to_name', '');
612 $datarray['hsitelink'] = $hsitelink;
613 $datarray['tsitelink'] = $tsitelink;
614 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
615 $datarray['titemlink'] = $itemlink;
616 $datarray['thanks'] = $thanks;
617 $datarray['site_admin'] = $site_admin;
618 $datarray['title'] = stripslashes($title);
619 $datarray['htmlversion'] = $htmlversion;
620 $datarray['textversion'] = $textversion;
621 $datarray['subject'] = $subject;
622 $datarray['headers'] = $additional_mail_header;
624 Hook::callAll('enotify_mail', $datarray);
626 // check whether sending post content in email notifications is allowed
627 // always true for SYSTEM_EMAIL
628 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
630 // load the template for private message notifications
631 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
632 $email_html_body = Renderer::replaceMacros($tpl, [
633 '$banner' => $datarray['banner'],
634 '$product' => $datarray['product'],
635 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
636 '$sitename' => $datarray['sitename'],
637 '$siteurl' => $datarray['siteurl'],
638 '$source_name' => $datarray['source_name'],
639 '$source_link' => $datarray['source_link'],
640 '$source_photo' => $datarray['source_photo'],
641 '$username' => $datarray['username'],
642 '$hsitelink' => $datarray['hsitelink'],
643 '$hitemlink' => $datarray['hitemlink'],
644 '$thanks' => $datarray['thanks'],
645 '$site_admin' => $datarray['site_admin'],
646 '$title' => $datarray['title'],
647 '$htmlversion' => $datarray['htmlversion'],
648 '$content_allowed' => $content_allowed,
651 // load the template for private message notifications
652 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
653 $email_text_body = Renderer::replaceMacros($tpl, [
654 '$banner' => $datarray['banner'],
655 '$product' => $datarray['product'],
656 '$preamble' => $datarray['preamble'],
657 '$sitename' => $datarray['sitename'],
658 '$siteurl' => $datarray['siteurl'],
659 '$source_name' => $datarray['source_name'],
660 '$source_link' => $datarray['source_link'],
661 '$source_photo' => $datarray['source_photo'],
662 '$username' => $datarray['username'],
663 '$tsitelink' => $datarray['tsitelink'],
664 '$titemlink' => $datarray['titemlink'],
665 '$thanks' => $datarray['thanks'],
666 '$site_admin' => $datarray['site_admin'],
667 '$title' => $datarray['title'],
668 '$textversion' => $datarray['textversion'],
669 '$content_allowed' => $content_allowed,
673 // use the Emailer class to send the message
674 return Emailer::send([
675 'uid' => $params['uid'],
676 'fromName' => $sender_name,
677 'fromEmail' => $sender_email,
678 'replyTo' => $sender_email,
679 'toEmail' => $params['to_email'],
680 'messageSubject' => $datarray['subject'],
681 'htmlVersion' => $email_html_body,
682 'textVersion' => $email_text_body,
683 'additionalMailHeader' => $datarray['headers']
692 * @brief Checks for users who should be notified
694 * @param int $itemid ID of the item for which the check should be done
695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
697 function check_user_notification($itemid) {
698 // fetch all users in the thread
699 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
700 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
701 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
702 while ($user = DBA::fetch($users)) {
703 check_item_notification($itemid, $user['uid']);
709 * @brief Checks for item related notifications and sends them
711 * @param int $itemid ID of the item for which the check should be done
712 * @param int $uid User ID
713 * @param string $defaulttype (Optional) Forces a notification with this type.
715 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
717 function check_item_notification($itemid, $uid, $defaulttype = "") {
718 $notification_data = ["uid" => $uid, "profiles" => []];
719 Hook::callAll('check_item_notification', $notification_data);
721 $profiles = $notification_data["profiles"];
723 $fields = ['nickname'];
724 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
725 if (!DBA::isResult($user)) {
729 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
730 if (!DBA::isResult($owner)) {
734 // This is our regular URL format
735 $profiles[] = $owner["url"];
737 // Notifications from Diaspora are often with an URL in the Diaspora format
738 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
742 foreach ($profiles AS $profile) {
743 // Check for invalid profile urls. 13 should be the shortest possible profile length:
745 // Additionally check for invalid urls that would return the normalised value "http:"
746 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
747 if (!in_array($profile, $profiles2))
748 $profiles2[] = $profile;
750 $profile = Strings::normaliseLink($profile);
751 if (!in_array($profile, $profiles2))
752 $profiles2[] = $profile;
754 $profile = str_replace("http://", "https://", $profile);
755 if (!in_array($profile, $profiles2))
756 $profiles2[] = $profile;
760 $profiles = $profiles2;
762 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
766 while ($contact = DBA::fetch($ret)) {
767 $contacts[] = $contact['id'];
772 // Only act if it is a "real" post
773 // We need the additional check for the "local_profile" because of mixed situations on connector networks
774 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
775 'author-link', 'author-name', 'author-avatar', 'author-id',
776 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
777 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
778 $item = Item::selectFirst($fields, $condition);
779 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
783 // Generate the notification array
785 $params["uid"] = $uid;
786 $params["item"] = $item;
787 $params["parent"] = $item["parent"];
788 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
789 $params["otype"] = 'item';
790 $params["source_name"] = $item["author-name"];
791 $params["source_link"] = $item["author-link"];
792 $params["source_photo"] = $item["author-avatar"];
794 if ($item["parent-uri"] === $item["uri"]) {
795 // Send a notification for every new post?
796 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
798 if (!$send_notification) {
799 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
800 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
802 if (DBA::isResult($tags)) {
803 foreach ($tags AS $tag) {
804 $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
805 $r = DBA::exists('contact', $condition);
807 $send_notification = true;
813 if ($send_notification) {
814 $params["type"] = NOTIFY_SHARE;
815 $params["verb"] = ACTIVITY_TAG;
819 // Is the user mentioned in this post?
822 foreach ($profiles AS $profile) {
823 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
827 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
828 $params["type"] = NOTIFY_TAGSELF;
829 $params["verb"] = ACTIVITY_TAG;
832 // Is it a post that the user had started?
833 $fields = ['ignored', 'mention'];
834 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
836 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
837 $params["type"] = NOTIFY_COMMENT;
838 $params["verb"] = ACTIVITY_POST;
841 // And now we check for participation of one of our contacts in the thread
842 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
844 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
845 $params["type"] = NOTIFY_COMMENT;
846 $params["verb"] = ACTIVITY_POST;
849 if (isset($params["type"])) {
850 notification($params);
855 * @brief Formats a notification message with the notification author
857 * Replace the name with {0} but ensure to make that only once. The {0} is used
858 * later and prints the name in bold.
860 * @param string $name
861 * @param string $message
862 * @return string Formatted message
864 function format_notification_message($name, $message) {
866 $pos = strpos($message, $name);
871 if ($pos !== false) {
872 $message = substr_replace($message, '{0}', $pos, strlen($name));