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::pushLang($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);
154 // Check to see if there was already a tag notify or comment notify for this post.
155 // If so don't create a second notification
156 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
157 'link' => $params['link'], 'uid' => $params['uid']];
158 if (DBA::exists('notify', $condition)) {
163 // if it's a post figure out who's post it is.
165 if ($params['otype'] === 'item' && $parent_id) {
166 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
169 $item_post_type = Item::postType($item);
170 $itemlink = $item['plink'];
173 if ($params['type'] == NOTIFY_TAGSELF) {
174 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]a %3$s[/url]',
175 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
180 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
181 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
187 // "George Bull's post"
188 if (DBA::isResult($item)) {
189 if ($params['type'] == NOTIFY_TAGSELF) {
190 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]%3$s\'s %4$s[/url]',
191 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
193 $item['author-name'],
197 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
198 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
200 $item['author-name'],
207 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
208 if ($params['type'] == NOTIFY_TAGSELF) {
209 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]your %3$s[/url]',
210 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
215 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
216 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
224 if (DBA::isResult($item) && $item['author-link'] == $params['source_link']) {
225 if ($params['type'] == NOTIFY_TAGSELF) {
226 $dest_str = L10n::t('%1$s tagged you on [url=%2$s]their %3$s[/url]',
227 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
232 $dest_str = L10n::t('%1$s commented on [url=%2$s]their %3$s[/url]',
233 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
240 // Some mail software relies on subject field for threading.
241 // So, we cannot have different subjects for notifications of the same thread.
242 // Before this we have the name of the replier on the subject rendering
243 // different subjects for messages on the same thread.
244 if ($params['type'] == NOTIFY_TAGSELF) {
245 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
247 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
249 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
251 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
254 $epreamble = $dest_str;
256 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
257 $tsitelink = sprintf($sitelink, $siteurl);
258 $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
259 $itemlink = $params['link'];
262 if ($params['type'] == NOTIFY_WALL) {
263 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
265 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
266 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
267 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
271 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
272 $tsitelink = sprintf($sitelink, $siteurl);
273 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
274 $itemlink = $params['link'];
277 if ($params['type'] == NOTIFY_SHARE) {
278 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
280 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
281 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
282 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
286 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
287 $tsitelink = sprintf($sitelink, $siteurl);
288 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
289 $itemlink = $params['link'];
292 if ($params['type'] == NOTIFY_POKE) {
293 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
295 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
296 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
297 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
301 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
302 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
303 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
305 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
306 $tsitelink = sprintf($sitelink, $siteurl);
307 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
308 $itemlink = $params['link'];
311 if ($params['type'] == NOTIFY_TAGSHARE) {
312 $itemlink = $params['link'];
313 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
315 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
316 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
317 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
321 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
322 $tsitelink = sprintf($sitelink, $siteurl);
323 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
326 if ($params['type'] == NOTIFY_INTRO) {
327 $itemlink = $params['link'];
328 $subject = L10n::t('[Friendica:Notify] Introduction received');
330 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
331 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
333 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
336 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
338 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
339 $tsitelink = sprintf($sitelink, $siteurl);
340 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
342 switch ($params['verb']) {
343 case Activity::FRIEND:
344 // someone started to share with user (mostly OStatus)
345 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
347 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
348 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
349 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
353 case Activity::FOLLOW:
354 // someone started to follow the user (mostly OStatus)
355 $subject = L10n::t('[Friendica:Notify] You have a new follower');
357 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
358 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
359 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
364 // ACTIVITY_REQ_FRIEND is default activity for notifications
369 if ($params['type'] == NOTIFY_SUGGEST) {
370 $itemlink = $params['link'];
371 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
373 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
374 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
376 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
377 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
380 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
381 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
382 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
384 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
385 $tsitelink = sprintf($sitelink, $siteurl);
386 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
389 if ($params['type'] == NOTIFY_CONFIRM) {
390 if ($params['verb'] == Activity::FRIEND) { // mutual connection
391 $itemlink = $params['link'];
392 $subject = L10n::t('[Friendica:Notify] Connection accepted');
394 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
395 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
397 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
400 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
402 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
403 $tsitelink = sprintf($sitelink, $siteurl);
404 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
405 } else { // ACTIVITY_FOLLOW
406 $itemlink = $params['link'];
407 $subject = L10n::t('[Friendica:Notify] Connection accepted');
409 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
410 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
412 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
415 $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']);
417 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
419 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
420 $tsitelink = sprintf($sitelink, $siteurl);
421 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
425 if ($params['type'] == NOTIFY_SYSTEM) {
426 switch($params['event']) {
427 case "SYSTEM_REGISTER_REQUEST":
428 $itemlink = $params['link'];
429 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
431 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
432 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
434 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
437 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
438 $params['source_name'],
439 $siteurl, $params['source_mail'],
440 $params['source_nick']
443 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
444 $tsitelink = sprintf($sitelink, $params['link']);
445 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
447 case "SYSTEM_DB_UPDATE_FAIL":
452 if ($params['type'] == SYSTEM_EMAIL) {
453 // not part of the notifications.
454 // it just send a mail to the user.
455 // It will be used by the system to send emails to users (like
456 // password reset, invitations and so) using one look (but without
457 // add a notification to the user, with could be inexistent)
458 if (!isset($params['subject'])) {
459 Logger::warning('subject isn\'t set.', ['type' => $params['type']]);
461 $subject = $params['subject'] ?? '';
463 if (!isset($params['preamble'])) {
464 Logger::warning('preamble isn\'t set.', ['type' => $params['type'], 'subject' => $subject]);
466 $preamble = $params['preamble'] ?? '';
468 if (!isset($params['body'])) {
469 Logger::warning('body isn\'t set.', ['type' => $params['type'], 'subject' => $subject, 'preamble' => $preamble]);
471 $body = $params['body'] ?? '';
473 $show_in_notification_page = false;
476 $subject .= " (".$nickname."@".$hostname.")";
480 'subject' => $subject,
481 'preamble' => $preamble,
482 'epreamble' => $epreamble,
484 'sitelink' => $sitelink,
485 'tsitelink' => $tsitelink,
486 'hsitelink' => $hsitelink,
487 'itemlink' => $itemlink
490 Hook::callAll('enotify', $h);
492 $subject = $h['subject'];
494 $preamble = $h['preamble'];
495 $epreamble = $h['epreamble'];
499 $tsitelink = $h['tsitelink'];
500 $hsitelink = $h['hsitelink'];
501 $itemlink = $h['itemlink'];
505 if ($show_in_notification_page) {
506 Logger::log("adding notification entry", Logger::DEBUG);
508 /// @TODO One statement is enough
510 $datarray['name'] = $params['source_name'];
511 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
512 $datarray['url'] = $params['source_link'];
513 $datarray['photo'] = $params['source_photo'];
514 $datarray['date'] = DateTimeFormat::utcNow();
515 $datarray['uid'] = $params['uid'];
516 $datarray['link'] = $itemlink;
517 $datarray['iid'] = $item_id;
518 $datarray['parent'] = $parent_id;
519 $datarray['type'] = $params['type'];
520 $datarray['verb'] = $params['verb'];
521 $datarray['otype'] = $params['otype'];
522 $datarray['abort'] = false;
524 Hook::callAll('enotify_store', $datarray);
526 if ($datarray['abort']) {
531 // create notification entry in DB
532 $fields = ['name' => $datarray['name'], 'url' => $datarray['url'],
533 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
534 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
535 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
536 'name_cache' => $datarray["name_cache"]];
537 DBA::insert('notify', $fields);
539 $notify_id = DBA::lastInsertId();
541 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
542 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
543 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
545 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
546 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
547 DBA::update('notify', $fields, $condition);
550 // send email notification if notification preferences permit
551 if ((intval($params['notify_flags']) & intval($params['type']))
552 || $params['type'] == NOTIFY_SYSTEM
553 || $params['type'] == SYSTEM_EMAIL) {
555 Logger::log('sending notification email');
557 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
558 $id_for_parent = $params['parent']."@".$hostname;
560 // Is this the first email notification for this parent item and user?
561 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
562 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
564 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
565 'receiver-uid' => $params['uid'], 'parent-item' => 0];
566 DBA::insert('notify-threads', $fields);
568 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
569 $log_msg = "include/enotify: No previous notification found for this parent:\n".
570 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
571 Logger::log($log_msg, Logger::DEBUG);
573 // If not, just "follow" the thread.
574 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
575 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
579 $textversion = BBCode::toPlaintext($body);
580 $htmlversion = BBCode::convert($body);
583 $datarray['banner'] = $banner;
584 $datarray['product'] = $product;
585 $datarray['preamble'] = $preamble;
586 $datarray['sitename'] = $sitename;
587 $datarray['siteurl'] = $siteurl;
588 $datarray['type'] = $params['type'];
589 $datarray['parent'] = $parent_id;
590 $datarray['source_name'] = $params['source_name'] ?? '';
591 $datarray['source_link'] = $params['source_link'] ?? '';
592 $datarray['source_photo'] = $params['source_photo'] ?? '';
593 $datarray['uid'] = $params['uid'];
594 $datarray['username'] = $params['to_name'] ?? '';
595 $datarray['hsitelink'] = $hsitelink;
596 $datarray['tsitelink'] = $tsitelink;
597 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
598 $datarray['titemlink'] = $itemlink;
599 $datarray['thanks'] = $thanks;
600 $datarray['site_admin'] = $site_admin;
601 $datarray['title'] = stripslashes($title);
602 $datarray['htmlversion'] = $htmlversion;
603 $datarray['textversion'] = $textversion;
604 $datarray['subject'] = $subject;
605 $datarray['headers'] = $additional_mail_header;
607 Hook::callAll('enotify_mail', $datarray);
609 // check whether sending post content in email notifications is allowed
610 // always true for SYSTEM_EMAIL
611 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
613 // load the template for private message notifications
614 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
615 $email_html_body = Renderer::replaceMacros($tpl, [
616 '$banner' => $datarray['banner'],
617 '$product' => $datarray['product'],
618 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
619 '$sitename' => $datarray['sitename'],
620 '$siteurl' => $datarray['siteurl'],
621 '$source_name' => $datarray['source_name'],
622 '$source_link' => $datarray['source_link'],
623 '$source_photo' => $datarray['source_photo'],
624 '$username' => $datarray['username'],
625 '$hsitelink' => $datarray['hsitelink'],
626 '$hitemlink' => $datarray['hitemlink'],
627 '$thanks' => $datarray['thanks'],
628 '$site_admin' => $datarray['site_admin'],
629 '$title' => $datarray['title'],
630 '$htmlversion' => $datarray['htmlversion'],
631 '$content_allowed' => $content_allowed,
634 // load the template for private message notifications
635 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
636 $email_text_body = Renderer::replaceMacros($tpl, [
637 '$banner' => $datarray['banner'],
638 '$product' => $datarray['product'],
639 '$preamble' => $datarray['preamble'],
640 '$sitename' => $datarray['sitename'],
641 '$siteurl' => $datarray['siteurl'],
642 '$source_name' => $datarray['source_name'],
643 '$source_link' => $datarray['source_link'],
644 '$source_photo' => $datarray['source_photo'],
645 '$username' => $datarray['username'],
646 '$tsitelink' => $datarray['tsitelink'],
647 '$titemlink' => $datarray['titemlink'],
648 '$thanks' => $datarray['thanks'],
649 '$site_admin' => $datarray['site_admin'],
650 '$title' => $datarray['title'],
651 '$textversion' => $datarray['textversion'],
652 '$content_allowed' => $content_allowed,
656 // use the Emailer class to send the message
657 return Emailer::send([
658 'uid' => $params['uid'],
659 'fromName' => $sender_name,
660 'fromEmail' => $sender_email,
661 'replyTo' => $sender_email,
662 'toEmail' => $params['to_email'],
663 'messageSubject' => $datarray['subject'],
664 'htmlVersion' => $email_html_body,
665 'textVersion' => $email_text_body,
666 'additionalMailHeader' => $datarray['headers']
675 * @brief Checks for users who should be notified
677 * @param int $itemid ID of the item for which the check should be done
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
680 function check_user_notification($itemid) {
681 // fetch all users in the thread
682 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
683 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
684 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
685 while ($user = DBA::fetch($users)) {
686 check_item_notification($itemid, $user['uid']);
692 * @brief Checks for item related notifications and sends them
694 * @param int $itemid ID of the item for which the check should be done
695 * @param int $uid User ID
696 * @param string $defaulttype (Optional) Forces a notification with this type.
698 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700 function check_item_notification($itemid, $uid, $defaulttype = "") {
701 $notification_data = ["uid" => $uid, "profiles" => []];
702 Hook::callAll('check_item_notification', $notification_data);
704 $profiles = $notification_data["profiles"];
706 $fields = ['nickname'];
707 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
708 if (!DBA::isResult($user)) {
712 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
713 if (!DBA::isResult($owner)) {
717 // This is our regular URL format
718 $profiles[] = $owner["url"];
720 // Notifications from Diaspora are often with an URL in the Diaspora format
721 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
725 foreach ($profiles AS $profile) {
726 // Check for invalid profile urls. 13 should be the shortest possible profile length:
728 // Additionally check for invalid urls that would return the normalised value "http:"
729 if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
730 if (!in_array($profile, $profiles2))
731 $profiles2[] = $profile;
733 $profile = Strings::normaliseLink($profile);
734 if (!in_array($profile, $profiles2))
735 $profiles2[] = $profile;
737 $profile = str_replace("http://", "https://", $profile);
738 if (!in_array($profile, $profiles2))
739 $profiles2[] = $profile;
743 $profiles = $profiles2;
745 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
749 while ($contact = DBA::fetch($ret)) {
750 $contacts[] = $contact['id'];
755 // Only act if it is a "real" post
756 // We need the additional check for the "local_profile" because of mixed situations on connector networks
757 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
758 'author-link', 'author-name', 'author-avatar', 'author-id',
759 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
760 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false];
761 $item = Item::selectFirstForUser($uid, $fields, $condition);
762 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
766 // Generate the notification array
768 $params["uid"] = $uid;
769 $params["item"] = $item;
770 $params["parent"] = $item["parent"];
771 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
772 $params["otype"] = 'item';
773 $params["source_name"] = $item["author-name"];
774 $params["source_link"] = $item["author-link"];
775 $params["source_photo"] = $item["author-avatar"];
777 if ($item["parent-uri"] === $item["uri"]) {
778 // Send a notification for every new post?
779 // Either the contact had posted something directly
780 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
782 // Or the contact is a mentioned forum
783 if (!$send_notification) {
784 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
785 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
787 if (DBA::isResult($tags)) {
788 foreach ($tags AS $tag) {
789 $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
790 if (DBA::exists('contact', $condition)) {
791 $send_notification = true;
797 if ($send_notification) {
798 $params["type"] = NOTIFY_SHARE;
799 $params["verb"] = Activity::TAG;
803 // Is the user mentioned in this post?
806 foreach ($profiles AS $profile) {
807 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
811 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
812 $params["type"] = NOTIFY_TAGSELF;
813 $params["verb"] = Activity::TAG;
816 // Is it a post that the user had started?
817 $fields = ['ignored', 'mention'];
818 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"], 'deleted' => false]);
820 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
821 $params["type"] = NOTIFY_COMMENT;
822 $params["verb"] = Activity::POST;
825 // And now we check for participation of one of our contacts in the thread
826 $condition = ['parent' => $item["parent"], 'author-id' => $contacts, 'deleted' => false];
828 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
829 $params["type"] = NOTIFY_COMMENT;
830 $params["verb"] = Activity::POST;
833 if (isset($params["type"])) {
834 notification($params);
839 * @brief Formats a notification message with the notification author
841 * Replace the name with {0} but ensure to make that only once. The {0} is used
842 * later and prints the name in bold.
844 * @param string $name
845 * @param string $message
846 * @return string Formatted message
848 function format_notification_message($name, $message) {
850 $pos = strpos($message, $name);
855 if ($pos !== false) {
856 $message = substr_replace($message, '{0}', $pos, strlen($name));