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['uid'])) {
37 Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => 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::error('Unknown user', ['uid' => $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 if (!isset($params['subject'])) {
457 Logger::warning('subject isn\'t set.', ['type' => $params['type']]);
459 $subject = defaults($params, 'subject', '');
461 if (!isset($params['preamble'])) {
462 Logger::warning('preamble isn\'t set.', ['type' => $params['type'], 'subject' => $subject]);
464 $preamble = defaults($params, 'preamble', '');
466 if (!isset($params['body'])) {
467 Logger::warning('body isn\'t set.', ['type' => $params['type'], 'subject' => $subject, 'preamble' => $preamble]);
469 $body = defaults($params, 'body', '');
471 $show_in_notification_page = false;
474 $subject .= " (".$nickname."@".$hostname.")";
478 'subject' => $subject,
479 'preamble' => $preamble,
480 'epreamble' => $epreamble,
482 'sitelink' => $sitelink,
483 'tsitelink' => $tsitelink,
484 'hsitelink' => $hsitelink,
485 'itemlink' => $itemlink
488 Hook::callAll('enotify', $h);
490 $subject = $h['subject'];
492 $preamble = $h['preamble'];
493 $epreamble = $h['epreamble'];
497 $tsitelink = $h['tsitelink'];
498 $hsitelink = $h['hsitelink'];
499 $itemlink = $h['itemlink'];
503 if ($show_in_notification_page) {
504 Logger::log("adding notification entry", Logger::DEBUG);
507 $hash = Strings::getRandomHex();
508 if (DBA::exists('notify', ['hash' => $hash])) {
511 } while ($dups == true);
513 /// @TODO One statement is enough
515 $datarray['hash'] = $hash;
516 $datarray['name'] = $params['source_name'];
517 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
518 $datarray['url'] = $params['source_link'];
519 $datarray['photo'] = $params['source_photo'];
520 $datarray['date'] = DateTimeFormat::utcNow();
521 $datarray['uid'] = $params['uid'];
522 $datarray['link'] = $itemlink;
523 $datarray['iid'] = $item_id;
524 $datarray['parent'] = $parent_id;
525 $datarray['type'] = $params['type'];
526 $datarray['verb'] = $params['verb'];
527 $datarray['otype'] = $params['otype'];
528 $datarray['abort'] = false;
530 Hook::callAll('enotify_store', $datarray);
532 if ($datarray['abort']) {
537 // create notification entry in DB
538 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
539 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
540 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
541 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
542 'name_cache' => $datarray["name_cache"]];
543 DBA::insert('notify', $fields);
545 $notify_id = DBA::lastInsertId();
547 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
548 // After we've stored everything, look again to see if there are any duplicates and if so remove them
549 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
550 intval(NOTIFY_TAGSELF),
551 intval(NOTIFY_COMMENT),
552 DBA::escape($params['link']),
553 intval($params['uid'])
555 if ($p && (count($p) > 1)) {
556 for ($d = 1; $d < count($p); $d ++) {
557 DBA::delete('notify', ['id' => $p[$d]['id']]);
560 // only continue on if we stored the first one
561 if ($notify_id != $p[0]['id']) {
567 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
568 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
569 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
571 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
572 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
573 DBA::update('notify', $fields, $condition);
576 // send email notification if notification preferences permit
577 if ((intval($params['notify_flags']) & intval($params['type']))
578 || $params['type'] == NOTIFY_SYSTEM
579 || $params['type'] == SYSTEM_EMAIL) {
581 Logger::log('sending notification email');
583 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
584 $id_for_parent = $params['parent']."@".$hostname;
586 // Is this the first email notification for this parent item and user?
587 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
588 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
590 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
591 'receiver-uid' => $params['uid'], 'parent-item' => 0];
592 DBA::insert('notify-threads', $fields);
594 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
595 $log_msg = "include/enotify: No previous notification found for this parent:\n".
596 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
597 Logger::log($log_msg, Logger::DEBUG);
599 // If not, just "follow" the thread.
600 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
601 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
605 $textversion = BBCode::toPlaintext($body);
606 $htmlversion = BBCode::convert($body);
609 $datarray['banner'] = $banner;
610 $datarray['product'] = $product;
611 $datarray['preamble'] = $preamble;
612 $datarray['sitename'] = $sitename;
613 $datarray['siteurl'] = $siteurl;
614 $datarray['type'] = $params['type'];
615 $datarray['parent'] = $parent_id;
616 $datarray['source_name'] = defaults($params, 'source_name', '');
617 $datarray['source_link'] = defaults($params, 'source_link', '');
618 $datarray['source_photo'] = defaults($params, 'source_photo', '');
619 $datarray['uid'] = $params['uid'];
620 $datarray['username'] = defaults($params, 'to_name', '');
621 $datarray['hsitelink'] = $hsitelink;
622 $datarray['tsitelink'] = $tsitelink;
623 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
624 $datarray['titemlink'] = $itemlink;
625 $datarray['thanks'] = $thanks;
626 $datarray['site_admin'] = $site_admin;
627 $datarray['title'] = stripslashes($title);
628 $datarray['htmlversion'] = $htmlversion;
629 $datarray['textversion'] = $textversion;
630 $datarray['subject'] = $subject;
631 $datarray['headers'] = $additional_mail_header;
633 Hook::callAll('enotify_mail', $datarray);
635 // check whether sending post content in email notifications is allowed
636 // always true for SYSTEM_EMAIL
637 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
639 // load the template for private message notifications
640 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
641 $email_html_body = Renderer::replaceMacros($tpl, [
642 '$banner' => $datarray['banner'],
643 '$product' => $datarray['product'],
644 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
645 '$sitename' => $datarray['sitename'],
646 '$siteurl' => $datarray['siteurl'],
647 '$source_name' => $datarray['source_name'],
648 '$source_link' => $datarray['source_link'],
649 '$source_photo' => $datarray['source_photo'],
650 '$username' => $datarray['username'],
651 '$hsitelink' => $datarray['hsitelink'],
652 '$hitemlink' => $datarray['hitemlink'],
653 '$thanks' => $datarray['thanks'],
654 '$site_admin' => $datarray['site_admin'],
655 '$title' => $datarray['title'],
656 '$htmlversion' => $datarray['htmlversion'],
657 '$content_allowed' => $content_allowed,
660 // load the template for private message notifications
661 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
662 $email_text_body = Renderer::replaceMacros($tpl, [
663 '$banner' => $datarray['banner'],
664 '$product' => $datarray['product'],
665 '$preamble' => $datarray['preamble'],
666 '$sitename' => $datarray['sitename'],
667 '$siteurl' => $datarray['siteurl'],
668 '$source_name' => $datarray['source_name'],
669 '$source_link' => $datarray['source_link'],
670 '$source_photo' => $datarray['source_photo'],
671 '$username' => $datarray['username'],
672 '$tsitelink' => $datarray['tsitelink'],
673 '$titemlink' => $datarray['titemlink'],
674 '$thanks' => $datarray['thanks'],
675 '$site_admin' => $datarray['site_admin'],
676 '$title' => $datarray['title'],
677 '$textversion' => $datarray['textversion'],
678 '$content_allowed' => $content_allowed,
682 // use the Emailer class to send the message
683 return Emailer::send([
684 'uid' => $params['uid'],
685 'fromName' => $sender_name,
686 'fromEmail' => $sender_email,
687 'replyTo' => $sender_email,
688 'toEmail' => $params['to_email'],
689 'messageSubject' => $datarray['subject'],
690 'htmlVersion' => $email_html_body,
691 'textVersion' => $email_text_body,
692 'additionalMailHeader' => $datarray['headers']
701 * @brief Checks for users who should be notified
703 * @param int $itemid ID of the item for which the check should be done
704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 function check_user_notification($itemid) {
707 // fetch all users in the thread
708 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
709 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
710 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
711 while ($user = DBA::fetch($users)) {
712 check_item_notification($itemid, $user['uid']);
718 * @brief Checks for item related notifications and sends them
720 * @param int $itemid ID of the item for which the check should be done
721 * @param int $uid User ID
722 * @param string $defaulttype (Optional) Forces a notification with this type.
724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
726 function check_item_notification($itemid, $uid, $defaulttype = "") {
727 $notification_data = ["uid" => $uid, "profiles" => []];
728 Hook::callAll('check_item_notification', $notification_data);
730 $profiles = $notification_data["profiles"];
732 $fields = ['nickname'];
733 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
734 if (!DBA::isResult($user)) {
738 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
739 if (!DBA::isResult($owner)) {
743 // This is our regular URL format
744 $profiles[] = $owner["url"];
746 // Notifications from Diaspora are often with an URL in the Diaspora format
747 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
751 foreach ($profiles AS $profile) {
752 // Check for invalid profile urls. 13 should be the shortest possible profile length:
754 // Additionally check for invalid urls that would return the normalised value "http:"
755 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
756 if (!in_array($profile, $profiles2))
757 $profiles2[] = $profile;
759 $profile = Strings::normaliseLink($profile);
760 if (!in_array($profile, $profiles2))
761 $profiles2[] = $profile;
763 $profile = str_replace("http://", "https://", $profile);
764 if (!in_array($profile, $profiles2))
765 $profiles2[] = $profile;
769 $profiles = $profiles2;
771 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
775 while ($contact = DBA::fetch($ret)) {
776 $contacts[] = $contact['id'];
781 // Only act if it is a "real" post
782 // We need the additional check for the "local_profile" because of mixed situations on connector networks
783 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
784 'author-link', 'author-name', 'author-avatar', 'author-id',
785 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
786 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
787 $item = Item::selectFirstForUser($uid, $fields, $condition);
788 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
792 // Generate the notification array
794 $params["uid"] = $uid;
795 $params["item"] = $item;
796 $params["parent"] = $item["parent"];
797 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
798 $params["otype"] = 'item';
799 $params["source_name"] = $item["author-name"];
800 $params["source_link"] = $item["author-link"];
801 $params["source_photo"] = $item["author-avatar"];
803 if ($item["parent-uri"] === $item["uri"]) {
804 // Send a notification for every new post?
805 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
807 if (!$send_notification) {
808 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
809 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
811 if (DBA::isResult($tags)) {
812 foreach ($tags AS $tag) {
813 $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
814 $r = DBA::exists('contact', $condition);
816 $send_notification = true;
822 if ($send_notification) {
823 $params["type"] = NOTIFY_SHARE;
824 $params["verb"] = ACTIVITY_TAG;
828 // Is the user mentioned in this post?
831 foreach ($profiles AS $profile) {
832 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
836 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
837 $params["type"] = NOTIFY_TAGSELF;
838 $params["verb"] = ACTIVITY_TAG;
841 // Is it a post that the user had started?
842 $fields = ['ignored', 'mention'];
843 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
845 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
846 $params["type"] = NOTIFY_COMMENT;
847 $params["verb"] = ACTIVITY_POST;
850 // And now we check for participation of one of our contacts in the thread
851 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
853 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
854 $params["type"] = NOTIFY_COMMENT;
855 $params["verb"] = ACTIVITY_POST;
858 if (isset($params["type"])) {
859 notification($params);
864 * @brief Formats a notification message with the notification author
866 * Replace the name with {0} but ensure to make that only once. The {0} is used
867 * later and prints the name in bold.
869 * @param string $name
870 * @param string $message
871 * @return string Formatted message
873 function format_notification_message($name, $message) {
875 $pos = strpos($message, $name);
880 if ($pos !== false) {
881 $message = substr_replace($message, '{0}', $pos, strlen($name));