3 * @file include/enotify.php
6 use Friendica\Core\Addon;
7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Util\Emailer;
13 require_once 'include/bbcode.php';
14 require_once 'include/html2bbcode.php';
17 * @brief Creates a notification entry and possibly sends a mail
19 * @param array $params Array with the elements:
20 uid, item, parent, type, otype, verb, event,
21 link, subject, body, to_name, to_email, source_name,
22 source_link, activity, preamble, notify_flags,
23 language, show_in_notification_page
25 function notification($params)
29 // from here on everything is in the recipients language
30 L10n::pushLang($params['language']);
32 $banner = L10n::t('Friendica Notification');
33 $product = FRIENDICA_PLATFORM;
34 $siteurl = System::baseUrl(true);
35 $thanks = L10n::t('Thank You,');
36 $sitename = $a->config['sitename'];
37 if (!x($a->config['admin_name'])) {
38 $site_admin = L10n::t('%s Administrator', $sitename);
40 $site_admin = L10n::t('%1$s, %2$s Administrator', $a->config['admin_name'], $sitename);
43 $sender_name = $sitename;
44 $hostname = $a->get_hostname();
45 if (strpos($hostname, ':')) {
46 $hostname = substr($hostname, 0, strpos($hostname, ':'));
49 $sender_email = $a->config['sender_email'];
50 if (empty($sender_email)) {
51 $sender_email = L10n::t('noreply').'@'.$hostname;
54 if ($params['type'] != SYSTEM_EMAIL) {
55 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
56 ['uid' => $params['uid']]);
58 // There is no need to create notifications for forum accounts
59 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
63 $nickname = $user["nickname"];
65 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
66 // the database, and an email is sent if applicable.
67 // default, if not specified: true
68 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
70 $additional_mail_header = "";
71 $additional_mail_header .= "Precedence: list\n";
72 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
73 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
74 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
75 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
76 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
77 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
79 if (array_key_exists('item', $params)) {
80 $title = $params['item']['title'];
81 $body = $params['item']['body'];
86 if (isset($params['item']['id'])) {
87 $item_id = $params['item']['id'];
92 if (isset($params['parent'])) {
93 $parent_id = $params['parent'];
98 if ($params['type'] == NOTIFY_MAIL) {
99 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
101 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
102 $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]');
104 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
105 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
106 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
107 $itemlink = $siteurl.'/message/'.$params['item']['id'];
110 if ($params['type'] == NOTIFY_COMMENT) {
111 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
112 if (DBM::is_result($thread) && $thread["ignored"]) {
113 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
117 // Check to see if there was already a tag notify or comment notify for this post.
118 // If so don't create a second notification
119 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
120 intval(NOTIFY_TAGSELF),
121 intval(NOTIFY_COMMENT),
122 intval(NOTIFY_SHARE),
123 dbesc($params['link']),
124 intval($params['uid'])
126 if ($p && count($p)) {
131 // if it's a post figure out who's post it is.
135 if ($params['otype'] === 'item' && $parent_id) {
136 $item = dba::selectFirst('item', [], ['id' => $parent_id]);
139 $item_post_type = item_post_type($item);
142 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
143 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
148 // "George Bull's post"
150 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
151 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
153 $item['author-name'],
159 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
160 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
161 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
167 // Some mail softwares relies on subject field for threading.
168 // So, we cannot have different subjects for notifications of the same thread.
169 // Before this we have the name of the replier on the subject rendering
170 // differents subjects for messages on the same thread.
172 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
174 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
175 $epreamble = $dest_str;
177 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
178 $tsitelink = sprintf($sitelink, $siteurl);
179 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
180 $itemlink = $params['link'];
183 if ($params['type'] == NOTIFY_WALL) {
184 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
186 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
187 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
188 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
192 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
193 $tsitelink = sprintf($sitelink, $siteurl);
194 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
195 $itemlink = $params['link'];
198 if ($params['type'] == NOTIFY_TAGSELF) {
199 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
201 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
202 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
203 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
207 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
208 $tsitelink = sprintf($sitelink, $siteurl);
209 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
210 $itemlink = $params['link'];
213 if ($params['type'] == NOTIFY_SHARE) {
214 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
216 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
217 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
218 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
222 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
223 $tsitelink = sprintf($sitelink, $siteurl);
224 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
225 $itemlink = $params['link'];
228 if ($params['type'] == NOTIFY_POKE) {
229 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
231 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
232 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
233 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
237 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
238 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
239 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
241 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
242 $tsitelink = sprintf($sitelink, $siteurl);
243 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
244 $itemlink = $params['link'];
247 if ($params['type'] == NOTIFY_TAGSHARE) {
248 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
250 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
251 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
252 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
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_INTRO) {
263 $subject = L10n::t('[Friendica:Notify] Introduction received');
265 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
266 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
268 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
271 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
273 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
274 $tsitelink = sprintf($sitelink, $siteurl);
275 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
276 $itemlink = $params['link'];
278 switch ($params['verb']) {
279 case ACTIVITY_FRIEND:
280 // someone started to share with user (mostly OStatus)
281 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
283 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
284 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
285 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
289 case ACTIVITY_FOLLOW:
290 // someone started to follow the user (mostly OStatus)
291 $subject = L10n::t('[Friendica:Notify] You have a new follower');
293 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
294 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
295 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
300 // ACTIVITY_REQ_FRIEND is default activity for notifications
305 if ($params['type'] == NOTIFY_SUGGEST) {
306 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
308 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
309 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
311 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
312 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
315 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
316 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
317 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
319 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
320 $tsitelink = sprintf($sitelink, $siteurl);
321 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
322 $itemlink = $params['link'];
325 if ($params['type'] == NOTIFY_CONFIRM) {
326 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
327 $subject = L10n::t('[Friendica:Notify] Connection accepted');
329 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
330 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
332 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
335 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
337 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
338 $tsitelink = sprintf($sitelink, $siteurl);
339 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
340 $itemlink = $params['link'];
341 } else { // ACTIVITY_FOLLOW
342 $subject = L10n::t('[Friendica:Notify] Connection accepted');
344 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
345 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
347 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
350 $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']);
352 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
354 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
355 $tsitelink = sprintf($sitelink, $siteurl);
356 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
357 $itemlink = $params['link'];
361 if ($params['type'] == NOTIFY_SYSTEM) {
362 switch($params['event']) {
363 case "SYSTEM_REGISTER_REQUEST":
364 $subject = L10n::t('[Friendica System:Notify] registration request');
366 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
367 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
369 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
372 $body = L10n::t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)',
373 $params['source_name'],
374 $siteurl, $params['source_mail'],
375 $params['source_nick']
378 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
379 $tsitelink = sprintf($sitelink, $params['link']);
380 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
381 $itemlink = $params['link'];
383 case "SYSTEM_DB_UPDATE_FAIL":
388 if ($params['type'] == SYSTEM_EMAIL) {
389 // not part of the notifications.
390 // it just send a mail to the user.
391 // It will be used by the system to send emails to users (like
392 // password reset, invitations and so) using one look (but without
393 // add a notification to the user, with could be inexistent)
394 $subject = $params['subject'];
396 $preamble = $params['preamble'];
398 $body = $params['body'];
404 $show_in_notification_page = false;
407 $subject .= " (".$nickname."@".$hostname.")";
411 'subject' => $subject,
412 'preamble' => $preamble,
413 'epreamble' => $epreamble,
415 'sitelink' => $sitelink,
416 'tsitelink' => $tsitelink,
417 'hsitelink' => $hsitelink,
418 'itemlink' => $itemlink
421 Addon::callHooks('enotify', $h);
423 $subject = $h['subject'];
425 $preamble = $h['preamble'];
426 $epreamble = $h['epreamble'];
430 $tsitelink = $h['tsitelink'];
431 $hsitelink = $h['hsitelink'];
432 $itemlink = $h['itemlink'];
434 if ($show_in_notification_page) {
435 logger("adding notification entry", LOGGER_DEBUG);
438 $hash = random_string();
439 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
441 if (DBM::is_result($r)) {
444 } while ($dups == true);
446 /// @TODO One statement is enough
448 $datarray['hash'] = $hash;
449 $datarray['name'] = $params['source_name'];
450 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
451 $datarray['url'] = $params['source_link'];
452 $datarray['photo'] = $params['source_photo'];
453 $datarray['date'] = datetime_convert();
454 $datarray['uid'] = $params['uid'];
455 $datarray['link'] = $itemlink;
456 $datarray['iid'] = $item_id;
457 $datarray['parent'] = $parent_id;
458 $datarray['type'] = $params['type'];
459 $datarray['verb'] = $params['verb'];
460 $datarray['otype'] = $params['otype'];
461 $datarray['abort'] = false;
463 Addon::callHooks('enotify_store', $datarray);
465 if ($datarray['abort']) {
470 // create notification entry in DB
471 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
472 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
473 dbesc($datarray['hash']),
474 dbesc($datarray['name']),
475 dbesc($datarray['url']),
476 dbesc($datarray['photo']),
477 dbesc($datarray['date']),
478 intval($datarray['uid']),
479 dbesc($datarray['link']),
480 intval($datarray['iid']),
481 intval($datarray['parent']),
482 intval($datarray['type']),
483 dbesc($datarray['verb']),
484 dbesc($datarray['otype']),
485 dbesc($datarray["name_cache"])
488 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
490 intval($params['uid'])
493 $notify_id = $r[0]['id'];
499 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
500 // After we've stored everything, look again to see if there are any duplicates and if so remove them
501 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
502 intval(NOTIFY_TAGSELF),
503 intval(NOTIFY_COMMENT),
504 dbesc($params['link']),
505 intval($params['uid'])
507 if ($p && (count($p) > 1)) {
508 for ($d = 1; $d < count($p); $d ++) {
509 dba::delete('notify', ['id' => $p[$d]['id']]);
512 // only continue on if we stored the first one
513 if ($notify_id != $p[0]['id']) {
519 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
520 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
521 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
522 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
526 intval($params['uid'])
530 // send email notification if notification preferences permit
531 if ((intval($params['notify_flags']) & intval($params['type']))
532 || $params['type'] == NOTIFY_SYSTEM
533 || $params['type'] == SYSTEM_EMAIL) {
535 logger('sending notification email');
537 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
538 $id_for_parent = $params['parent']."@".$hostname;
540 // Is this the first email notification for this parent item and user?
542 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
543 intval($params['parent']),
544 intval($params['uid']));
546 // If so, create the record of it and use a message-id smtp header.
549 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
550 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
551 values(%d, %d, %d, %d)",
553 intval($params['parent']),
554 intval($params['uid']),
557 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
558 $log_msg = "include/enotify: No previous notification found for this parent:\n".
559 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
560 logger($log_msg, LOGGER_DEBUG);
562 // If not, just "follow" the thread.
563 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
564 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
568 // textversion keeps linebreaks
569 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(["\\r\\n", "\\r", "\\n"], "\n",
570 $body))),ENT_QUOTES, 'UTF-8')));
571 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(["\\r\\n", "\\r", "\\n\\n", "\\n"],
572 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
575 $datarray['banner'] = $banner;
576 $datarray['product'] = $product;
577 $datarray['preamble'] = $preamble;
578 $datarray['sitename'] = $sitename;
579 $datarray['siteurl'] = $siteurl;
580 $datarray['type'] = $params['type'];
581 $datarray['parent'] = $params['parent'];
582 $datarray['source_name'] = $params['source_name'];
583 $datarray['source_link'] = $params['source_link'];
584 $datarray['source_photo'] = $params['source_photo'];
585 $datarray['uid'] = $params['uid'];
586 $datarray['username'] = $params['to_name'];
587 $datarray['hsitelink'] = $hsitelink;
588 $datarray['tsitelink'] = $tsitelink;
589 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
590 $datarray['titemlink'] = $itemlink;
591 $datarray['thanks'] = $thanks;
592 $datarray['site_admin'] = $site_admin;
593 $datarray['title'] = stripslashes($title);
594 $datarray['htmlversion'] = $htmlversion;
595 $datarray['textversion'] = $textversion;
596 $datarray['subject'] = $subject;
597 $datarray['headers'] = $additional_mail_header;
599 Addon::callHooks('enotify_mail', $datarray);
601 // check whether sending post content in email notifications is allowed
602 // always true for SYSTEM_EMAIL
603 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
605 // load the template for private message notifications
606 $tpl = get_markup_template('email_notify_html.tpl');
607 $email_html_body = replace_macros($tpl, [
608 '$banner' => $datarray['banner'],
609 '$product' => $datarray['product'],
610 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
611 '$sitename' => $datarray['sitename'],
612 '$siteurl' => $datarray['siteurl'],
613 '$source_name' => $datarray['source_name'],
614 '$source_link' => $datarray['source_link'],
615 '$source_photo' => $datarray['source_photo'],
616 '$username' => $datarray['to_name'],
617 '$hsitelink' => $datarray['hsitelink'],
618 '$hitemlink' => $datarray['hitemlink'],
619 '$thanks' => $datarray['thanks'],
620 '$site_admin' => $datarray['site_admin'],
621 '$title' => $datarray['title'],
622 '$htmlversion' => $datarray['htmlversion'],
623 '$content_allowed' => $content_allowed,
626 // load the template for private message notifications
627 $tpl = get_markup_template('email_notify_text.tpl');
628 $email_text_body = replace_macros($tpl, [
629 '$banner' => $datarray['banner'],
630 '$product' => $datarray['product'],
631 '$preamble' => $datarray['preamble'],
632 '$sitename' => $datarray['sitename'],
633 '$siteurl' => $datarray['siteurl'],
634 '$source_name' => $datarray['source_name'],
635 '$source_link' => $datarray['source_link'],
636 '$source_photo' => $datarray['source_photo'],
637 '$username' => $datarray['to_name'],
638 '$tsitelink' => $datarray['tsitelink'],
639 '$titemlink' => $datarray['titemlink'],
640 '$thanks' => $datarray['thanks'],
641 '$site_admin' => $datarray['site_admin'],
642 '$title' => $datarray['title'],
643 '$textversion' => $datarray['textversion'],
644 '$content_allowed' => $content_allowed,
647 // use the Emailer class to send the message
648 return Emailer::send(
650 'uid' => $params['uid'],
651 'fromName' => $sender_name,
652 'fromEmail' => $sender_email,
653 'replyTo' => $sender_email,
654 'toEmail' => $params['to_email'],
655 'messageSubject' => $datarray['subject'],
656 'htmlVersion' => $email_html_body,
657 'textVersion' => $email_text_body,
658 'additionalMailHeader' => $datarray['headers']]
666 * @brief Checks for users who should be notified
668 * @param int $itemid ID of the item for which the check should be done
670 function check_user_notification($itemid) {
671 // fetch all users in the thread
672 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
673 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
674 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
675 while ($user = dba::fetch($users)) {
676 check_item_notification($itemid, $user['uid']);
682 * @brief Checks for item related notifications and sends them
684 * @param int $itemid ID of the item for which the check should be done
685 * @param int $uid User ID
686 * @param str $defaulttype (Optional) Forces a notification with this type.
688 function check_item_notification($itemid, $uid, $defaulttype = "") {
689 $notification_data = ["uid" => $uid, "profiles" => []];
690 Addon::callHooks('check_item_notification', $notification_data);
692 $profiles = $notification_data["profiles"];
694 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
695 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
696 if (!DBM::is_result($user)) {
700 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
701 if (!DBM::is_result($owner)) {
705 // This is our regular URL format
706 $profiles[] = $owner["url"];
708 // Notifications from Diaspora are often with an URL in the Diaspora format
709 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
713 foreach ($profiles AS $profile) {
714 // Check for invalid profile urls. 13 should be the shortest possible profile length:
716 // Additionally check for invalid urls that would return the normalised value "http:"
717 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
718 if (!in_array($profile, $profiles2))
719 $profiles2[] = $profile;
721 $profile = normalise_link($profile);
722 if (!in_array($profile, $profiles2))
723 $profiles2[] = $profile;
725 $profile = str_replace("http://", "https://", $profile);
726 if (!in_array($profile, $profiles2))
727 $profiles2[] = $profile;
731 $profiles = $profiles2;
735 foreach ($profiles AS $profile) {
736 if ($profile_list != "")
737 $profile_list .= "', '";
739 $profile_list .= dbesc($profile);
742 $profile_list = "'".$profile_list."'";
744 // Only act if it is a "real" post
745 // We need the additional check for the "local_profile" because of mixed situations on connector networks
746 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
747 `parent-uri`, `uri`, `contact-id`
748 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
749 NOT (`author-link` IN ($profile_list)) LIMIT 1",
750 intval($itemid), dbesc(ACTIVITY_POST));
754 // Generate the notification array
756 $params["uid"] = $uid;
757 $params["notify_flags"] = $user["notify-flags"];
758 $params["language"] = $user["language"];
759 $params["to_name"] = $user["username"];
760 $params["to_email"] = $user["email"];
761 $params["item"] = $item[0];
762 $params["parent"] = $item[0]["parent"];
763 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
764 $params["otype"] = 'item';
765 $params["source_name"] = $item[0]["author-name"];
766 $params["source_link"] = $item[0]["author-link"];
767 $params["source_photo"] = $item[0]["author-avatar"];
769 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
770 // Send a notification for every new post?
771 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
773 if (!$send_notification) {
774 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
775 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
777 if (DBM::is_result($tags)) {
778 foreach ($tags AS $tag) {
779 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
780 $r = dba::exists('contact', $condition);
782 $send_notification = true;
788 if ($send_notification) {
789 $params["type"] = NOTIFY_SHARE;
790 $params["verb"] = ACTIVITY_TAG;
794 // Is the user mentioned in this post?
797 foreach ($profiles AS $profile) {
798 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
802 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
803 $params["type"] = NOTIFY_TAGSELF;
804 $params["verb"] = ACTIVITY_TAG;
807 // Is it a post that the user had started or where he interacted?
808 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
809 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
810 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
812 intval($item[0]["parent"]));
814 if ($parent && !isset($params["type"])) {
815 $params["type"] = NOTIFY_COMMENT;
816 $params["verb"] = ACTIVITY_POST;
819 if (isset($params["type"]))
820 notification($params);
824 * @brief Formats a notification message with the notification author
826 * Replace the name with {0} but ensure to make that only once. The {0} is used
827 * later and prints the name in bold.
829 * @param string $name
830 * @param string $message
831 * @return string Formatted message
833 function format_notification_message($name, $message) {
835 $pos = strpos($message, $name);
840 if ($pos !== false) {
841 $message = substr_replace($message, '{0}', $pos, strlen($name));