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\Model\User;
17 use Friendica\Protocol\Activity;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Emailer;
20 use Friendica\Util\Strings;
23 * @brief Creates a notification entry and possibly sends a mail
25 * @param array $params Array with the elements:
26 * uid, item, parent, type, otype, verb, event,
27 * link, subject, body, to_name, to_email, source_name,
28 * source_link, activity, preamble, notify_flags,
29 * language, show_in_notification_page
31 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
33 function notification($params)
37 // Temporary logging for finding the origin
38 if (!isset($params['uid'])) {
39 Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
42 // Ensure that the important fields are set at any time
43 $fields = ['notify-flags', 'language', 'username', 'email'];
44 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
46 if (!DBA::isResult($user)) {
47 Logger::error('Unknown user', ['uid' => $params['uid']]);
51 $params['notify_flags'] = ($params['notify_flags'] ?? '') ?: $user['notify-flags'];
52 $params['language'] = ($params['language'] ?? '') ?: $user['language'];
53 $params['to_name'] = ($params['to_name'] ?? '') ?: $user['username'];
54 $params['to_email'] = ($params['to_email'] ?? '') ?: $user['email'];
56 // from here on everything is in the recipients language
57 $l10n = L10n::withLang($params['language']);
59 $banner = $l10n->t('Friendica Notification');
60 $product = FRIENDICA_PLATFORM;
61 $siteurl = System::baseUrl(true);
62 $thanks = $l10n->t('Thank You,');
63 $sitename = Config::get('config', 'sitename');
64 if (Config::get('config', 'admin_name')) {
65 $site_admin = $l10n->t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
67 $site_admin = $l10n->t('%s Administrator', $sitename);
70 $sender_name = $sitename;
71 $hostname = $a->getHostName();
72 if (strpos($hostname, ':')) {
73 $hostname = substr($hostname, 0, strpos($hostname, ':'));
76 $sender_email = $a->getSenderEmailAddress();
78 if ($params['type'] != SYSTEM_EMAIL) {
79 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
80 ['uid' => $params['uid']]);
82 // There is no need to create notifications for forum accounts
83 if (!DBA::isResult($user) || in_array($user["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
86 $nickname = $user["nickname"];
91 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
92 // the database, and an email is sent if applicable.
93 // default, if not specified: true
94 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
96 $additional_mail_header = "";
97 $additional_mail_header .= "Precedence: list\n";
98 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
99 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
100 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
101 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
102 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
103 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
105 if (array_key_exists('item', $params)) {
106 $title = $params['item']['title'];
107 $body = $params['item']['body'];
112 if (isset($params['item']['id'])) {
113 $item_id = $params['item']['id'];
118 if (isset($params['parent'])) {
119 $parent_id = $params['parent'];
132 if ($params['type'] == NOTIFY_MAIL) {
133 $itemlink = $siteurl.'/message/'.$params['item']['id'];
134 $params["link"] = $itemlink;
136 $subject = $l10n->t('[Friendica:Notify] New mail received at %s', $sitename);
138 $preamble = $l10n->t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
139 $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]');
141 $sitelink = $l10n->t('Please visit %s to view and/or reply to your private messages.');
142 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
143 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
146 if ($params['type'] == NOTIFY_COMMENT || $params['type'] == NOTIFY_TAGSELF) {
147 $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id, 'deleted' => false]);
148 if (DBA::isResult($thread) && $thread['ignored']) {
149 Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
153 // Check to see if there was already a tag notify or comment notify for this post.
154 // If so don't create a second notification
155 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
156 'link' => $params['link'], 'uid' => $params['uid']];
157 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, 'deleted' => false]);
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 = $params['subject'] ?? '';
461 if (!isset($params['preamble'])) {
462 Logger::warning('preamble isn\'t set.', ['type' => $params['type'], 'subject' => $subject]);
464 $preamble = $params['preamble'] ?? '';
466 if (!isset($params['body'])) {
467 Logger::warning('body isn\'t set.', ['type' => $params['type'], 'subject' => $subject, 'preamble' => $preamble]);
469 $body = $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);
506 /// @TODO One statement is enough
508 $datarray['name'] = $params['source_name'];
509 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
510 $datarray['url'] = $params['source_link'];
511 $datarray['photo'] = $params['source_photo'];
512 $datarray['date'] = DateTimeFormat::utcNow();
513 $datarray['uid'] = $params['uid'];
514 $datarray['link'] = $itemlink;
515 $datarray['iid'] = $item_id;
516 $datarray['parent'] = $parent_id;
517 $datarray['type'] = $params['type'];
518 $datarray['verb'] = $params['verb'];
519 $datarray['otype'] = $params['otype'];
520 $datarray['abort'] = false;
522 Hook::callAll('enotify_store', $datarray);
524 if ($datarray['abort']) {
528 // create notification entry in DB
529 $fields = ['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 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
539 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
540 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
542 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
543 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
544 DBA::update('notify', $fields, $condition);
547 // send email notification if notification preferences permit
548 if ((intval($params['notify_flags']) & intval($params['type']))
549 || $params['type'] == NOTIFY_SYSTEM
550 || $params['type'] == SYSTEM_EMAIL) {
552 Logger::log('sending notification email');
554 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
555 $id_for_parent = $params['parent']."@".$hostname;
557 // Is this the first email notification for this parent item and user?
558 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
559 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
561 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
562 'receiver-uid' => $params['uid'], 'parent-item' => 0];
563 DBA::insert('notify-threads', $fields);
565 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
566 $log_msg = "include/enotify: No previous notification found for this parent:\n".
567 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
568 Logger::log($log_msg, Logger::DEBUG);
570 // If not, just "follow" the thread.
571 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
572 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
576 $textversion = BBCode::toPlaintext($body);
577 $htmlversion = BBCode::convert($body);
580 $datarray['banner'] = $banner;
581 $datarray['product'] = $product;
582 $datarray['preamble'] = $preamble;
583 $datarray['sitename'] = $sitename;
584 $datarray['siteurl'] = $siteurl;
585 $datarray['type'] = $params['type'];
586 $datarray['parent'] = $parent_id;
587 $datarray['source_name'] = $params['source_name'] ?? '';
588 $datarray['source_link'] = $params['source_link'] ?? '';
589 $datarray['source_photo'] = $params['source_photo'] ?? '';
590 $datarray['uid'] = $params['uid'];
591 $datarray['username'] = $params['to_name'] ?? '';
592 $datarray['hsitelink'] = $hsitelink;
593 $datarray['tsitelink'] = $tsitelink;
594 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
595 $datarray['titemlink'] = $itemlink;
596 $datarray['thanks'] = $thanks;
597 $datarray['site_admin'] = $site_admin;
598 $datarray['title'] = stripslashes($title);
599 $datarray['htmlversion'] = $htmlversion;
600 $datarray['textversion'] = $textversion;
601 $datarray['subject'] = $subject;
602 $datarray['headers'] = $additional_mail_header;
604 Hook::callAll('enotify_mail', $datarray);
606 // check whether sending post content in email notifications is allowed
607 // always true for SYSTEM_EMAIL
608 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
610 // load the template for private message notifications
611 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
612 $email_html_body = Renderer::replaceMacros($tpl, [
613 '$banner' => $datarray['banner'],
614 '$product' => $datarray['product'],
615 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
616 '$sitename' => $datarray['sitename'],
617 '$siteurl' => $datarray['siteurl'],
618 '$source_name' => $datarray['source_name'],
619 '$source_link' => $datarray['source_link'],
620 '$source_photo' => $datarray['source_photo'],
621 '$username' => $datarray['username'],
622 '$hsitelink' => $datarray['hsitelink'],
623 '$hitemlink' => $datarray['hitemlink'],
624 '$thanks' => $datarray['thanks'],
625 '$site_admin' => $datarray['site_admin'],
626 '$title' => $datarray['title'],
627 '$htmlversion' => $datarray['htmlversion'],
628 '$content_allowed' => $content_allowed,
631 // load the template for private message notifications
632 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
633 $email_text_body = Renderer::replaceMacros($tpl, [
634 '$banner' => $datarray['banner'],
635 '$product' => $datarray['product'],
636 '$preamble' => $datarray['preamble'],
637 '$sitename' => $datarray['sitename'],
638 '$siteurl' => $datarray['siteurl'],
639 '$source_name' => $datarray['source_name'],
640 '$source_link' => $datarray['source_link'],
641 '$source_photo' => $datarray['source_photo'],
642 '$username' => $datarray['username'],
643 '$tsitelink' => $datarray['tsitelink'],
644 '$titemlink' => $datarray['titemlink'],
645 '$thanks' => $datarray['thanks'],
646 '$site_admin' => $datarray['site_admin'],
647 '$title' => $datarray['title'],
648 '$textversion' => $datarray['textversion'],
649 '$content_allowed' => $content_allowed,
652 // use the Emailer class to send the message
653 return Emailer::send([
654 'uid' => $params['uid'],
655 'fromName' => $sender_name,
656 'fromEmail' => $sender_email,
657 'replyTo' => $sender_email,
658 'toEmail' => $params['to_email'],
659 'messageSubject' => $datarray['subject'],
660 'htmlVersion' => $email_html_body,
661 'textVersion' => $email_text_body,
662 'additionalMailHeader' => $datarray['headers']
670 * @brief Checks for users who should be notified
672 * @param int $itemid ID of the item for which the check should be done
673 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675 function check_user_notification($itemid) {
676 // fetch all users in the thread
677 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
678 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
679 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
680 while ($user = DBA::fetch($users)) {
681 check_item_notification($itemid, $user['uid']);
687 * @brief Checks for item related notifications and sends them
689 * @param int $itemid ID of the item for which the check should be done
690 * @param int $uid User ID
691 * @param string $defaulttype (Optional) Forces a notification with this type.
693 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
695 function check_item_notification($itemid, $uid, $defaulttype = "") {
696 $notification_data = ["uid" => $uid, "profiles" => []];
697 Hook::callAll('check_item_notification', $notification_data);
699 $profiles = $notification_data["profiles"];
701 $fields = ['nickname'];
702 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
703 if (!DBA::isResult($user)) {
707 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
708 if (!DBA::isResult($owner)) {
712 // This is our regular URL format
713 $profiles[] = $owner["url"];
715 // Notifications from Diaspora are often with an URL in the Diaspora format
716 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
720 foreach ($profiles AS $profile) {
721 // Check for invalid profile urls. 13 should be the shortest possible profile length:
723 // Additionally check for invalid urls that would return the normalised value "http:"
724 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
725 if (!in_array($profile, $profiles2))
726 $profiles2[] = $profile;
728 $profile = Strings::normaliseLink($profile);
729 if (!in_array($profile, $profiles2))
730 $profiles2[] = $profile;
732 $profile = str_replace("http://", "https://", $profile);
733 if (!in_array($profile, $profiles2))
734 $profiles2[] = $profile;
738 $profiles = $profiles2;
740 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
744 while ($contact = DBA::fetch($ret)) {
745 $contacts[] = $contact['id'];
750 // Only act if it is a "real" post
751 // We need the additional check for the "local_profile" because of mixed situations on connector networks
752 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
753 'author-link', 'author-name', 'author-avatar', 'author-id',
754 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
755 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false];
756 $item = Item::selectFirstForUser($uid, $fields, $condition);
757 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
761 // Generate the notification array
763 $params["uid"] = $uid;
764 $params["item"] = $item;
765 $params["parent"] = $item["parent"];
766 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
767 $params["otype"] = 'item';
768 $params["source_name"] = $item["author-name"];
769 $params["source_link"] = $item["author-link"];
770 $params["source_photo"] = $item["author-avatar"];
772 if ($item["parent-uri"] === $item["uri"]) {
773 // Send a notification for every new post?
774 // Either the contact had posted something directly
775 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
777 // Or the contact is a mentioned forum
778 if (!$send_notification) {
779 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
780 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
782 if (DBA::isResult($tags)) {
783 foreach ($tags AS $tag) {
784 $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
785 if (DBA::exists('contact', $condition)) {
786 $send_notification = true;
792 if ($send_notification) {
793 $params["type"] = NOTIFY_SHARE;
794 $params["verb"] = Activity::TAG;
798 // Is the user mentioned in this post?
801 foreach ($profiles AS $profile) {
802 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
806 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
807 $params["type"] = NOTIFY_TAGSELF;
808 $params["verb"] = Activity::TAG;
811 // Is it a post that the user had started?
812 $fields = ['ignored', 'mention'];
813 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"], 'deleted' => false]);
815 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
816 $params["type"] = NOTIFY_COMMENT;
817 $params["verb"] = Activity::POST;
820 // And now we check for participation of one of our contacts in the thread
821 $condition = ['parent' => $item["parent"], 'author-id' => $contacts, 'deleted' => false];
823 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
824 $params["type"] = NOTIFY_COMMENT;
825 $params["verb"] = Activity::POST;
828 if (isset($params["type"])) {
829 notification($params);
834 * @brief Formats a notification message with the notification author
836 * Replace the name with {0} but ensure to make that only once. The {0} is used
837 * later and prints the name in bold.
839 * @param string $name
840 * @param string $message
841 * @return string Formatted message
843 function format_notification_message($name, $message) {
845 $pos = strpos($message, $name);
850 if ($pos !== false) {
851 $message = substr_replace($message, '{0}', $pos, strlen($name));