3 * @file include/enotify.php
6 use Friendica\Content\Text\BBCode;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Util\DateTimeFormat;
13 use Friendica\Util\Emailer;
15 require_once 'include/html2bbcode.php';
18 * @brief Creates a notification entry and possibly sends a mail
20 * @param array $params Array with the elements:
21 uid, item, parent, type, otype, verb, event,
22 link, subject, body, to_name, to_email, source_name,
23 source_link, activity, preamble, notify_flags,
24 language, show_in_notification_page
26 function notification($params)
30 // from here on everything is in the recipients language
31 L10n::pushLang($params['language']);
33 $banner = L10n::t('Friendica Notification');
34 $product = FRIENDICA_PLATFORM;
35 $siteurl = System::baseUrl(true);
36 $thanks = L10n::t('Thank You,');
37 $sitename = $a->config['sitename'];
38 if (!x($a->config['admin_name'])) {
39 $site_admin = L10n::t('%s Administrator', $sitename);
41 $site_admin = L10n::t('%1$s, %2$s Administrator', $a->config['admin_name'], $sitename);
44 $sender_name = $sitename;
45 $hostname = $a->get_hostname();
46 if (strpos($hostname, ':')) {
47 $hostname = substr($hostname, 0, strpos($hostname, ':'));
50 $sender_email = $a->config['sender_email'];
51 if (empty($sender_email)) {
52 $sender_email = L10n::t('noreply').'@'.$hostname;
55 if ($params['type'] != SYSTEM_EMAIL) {
56 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
57 ['uid' => $params['uid']]);
59 // There is no need to create notifications for forum accounts
60 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
64 $nickname = $user["nickname"];
66 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
67 // the database, and an email is sent if applicable.
68 // default, if not specified: true
69 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
71 $additional_mail_header = "";
72 $additional_mail_header .= "Precedence: list\n";
73 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
74 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
75 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
76 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
77 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
78 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
80 if (array_key_exists('item', $params)) {
81 $title = $params['item']['title'];
82 $body = $params['item']['body'];
87 if (isset($params['item']['id'])) {
88 $item_id = $params['item']['id'];
93 if (isset($params['parent'])) {
94 $parent_id = $params['parent'];
99 if ($params['type'] == NOTIFY_MAIL) {
100 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
102 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
103 $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]');
105 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
106 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
107 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
108 $itemlink = $siteurl.'/message/'.$params['item']['id'];
111 if ($params['type'] == NOTIFY_COMMENT) {
112 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
113 if (DBM::is_result($thread) && $thread["ignored"]) {
114 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
118 // Check to see if there was already a tag notify or comment notify for this post.
119 // If so don't create a second notification
120 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
121 intval(NOTIFY_TAGSELF),
122 intval(NOTIFY_COMMENT),
123 intval(NOTIFY_SHARE),
124 dbesc($params['link']),
125 intval($params['uid'])
127 if ($p && count($p)) {
132 // if it's a post figure out who's post it is.
136 if ($params['otype'] === 'item' && $parent_id) {
137 $item = dba::selectFirst('item', [], ['id' => $parent_id]);
140 $item_post_type = item_post_type($item);
143 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
144 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
149 // "George Bull's post"
151 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
152 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
154 $item['author-name'],
160 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
161 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
162 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
168 // Some mail softwares relies on subject field for threading.
169 // So, we cannot have different subjects for notifications of the same thread.
170 // Before this we have the name of the replier on the subject rendering
171 // differents subjects for messages on the same thread.
173 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
175 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
176 $epreamble = $dest_str;
178 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
179 $tsitelink = sprintf($sitelink, $siteurl);
180 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
181 $itemlink = $params['link'];
184 if ($params['type'] == NOTIFY_WALL) {
185 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
187 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
188 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
189 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
193 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
194 $tsitelink = sprintf($sitelink, $siteurl);
195 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
196 $itemlink = $params['link'];
199 if ($params['type'] == NOTIFY_TAGSELF) {
200 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
202 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
203 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
204 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
208 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
209 $tsitelink = sprintf($sitelink, $siteurl);
210 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
211 $itemlink = $params['link'];
214 if ($params['type'] == NOTIFY_SHARE) {
215 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
217 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
218 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
219 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
223 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
224 $tsitelink = sprintf($sitelink, $siteurl);
225 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
226 $itemlink = $params['link'];
229 if ($params['type'] == NOTIFY_POKE) {
230 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
232 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
233 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
234 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
238 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
239 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
240 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
242 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
243 $tsitelink = sprintf($sitelink, $siteurl);
244 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
245 $itemlink = $params['link'];
248 if ($params['type'] == NOTIFY_TAGSHARE) {
249 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
251 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
252 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
253 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
257 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
258 $tsitelink = sprintf($sitelink, $siteurl);
259 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
260 $itemlink = $params['link'];
263 if ($params['type'] == NOTIFY_INTRO) {
264 $subject = L10n::t('[Friendica:Notify] Introduction received');
266 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
267 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
269 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
272 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
274 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
275 $tsitelink = sprintf($sitelink, $siteurl);
276 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
277 $itemlink = $params['link'];
279 switch ($params['verb']) {
280 case ACTIVITY_FRIEND:
281 // someone started to share with user (mostly OStatus)
282 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
284 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
285 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
286 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
290 case ACTIVITY_FOLLOW:
291 // someone started to follow the user (mostly OStatus)
292 $subject = L10n::t('[Friendica:Notify] You have a new follower');
294 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
295 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
296 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
301 // ACTIVITY_REQ_FRIEND is default activity for notifications
306 if ($params['type'] == NOTIFY_SUGGEST) {
307 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
309 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
310 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
312 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
313 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
316 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
317 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
318 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
320 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
321 $tsitelink = sprintf($sitelink, $siteurl);
322 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
323 $itemlink = $params['link'];
326 if ($params['type'] == NOTIFY_CONFIRM) {
327 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
328 $subject = L10n::t('[Friendica:Notify] Connection accepted');
330 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
331 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
333 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
336 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
338 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
339 $tsitelink = sprintf($sitelink, $siteurl);
340 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
341 $itemlink = $params['link'];
342 } else { // ACTIVITY_FOLLOW
343 $subject = L10n::t('[Friendica:Notify] Connection accepted');
345 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
346 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
348 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
351 $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']);
353 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
355 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
356 $tsitelink = sprintf($sitelink, $siteurl);
357 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
358 $itemlink = $params['link'];
362 if ($params['type'] == NOTIFY_SYSTEM) {
363 switch($params['event']) {
364 case "SYSTEM_REGISTER_REQUEST":
365 $subject = L10n::t('[Friendica System:Notify] registration request');
367 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
368 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
370 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
373 $body = L10n::t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s ' . "\x28" . '%4$s' . "\x28",
374 $params['source_name'],
375 $siteurl, $params['source_mail'],
376 $params['source_nick']
379 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
380 $tsitelink = sprintf($sitelink, $params['link']);
381 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
382 $itemlink = $params['link'];
384 case "SYSTEM_DB_UPDATE_FAIL":
389 if ($params['type'] == SYSTEM_EMAIL) {
390 // not part of the notifications.
391 // it just send a mail to the user.
392 // It will be used by the system to send emails to users (like
393 // password reset, invitations and so) using one look (but without
394 // add a notification to the user, with could be inexistent)
395 $subject = $params['subject'];
397 $preamble = $params['preamble'];
399 $body = $params['body'];
405 $show_in_notification_page = false;
408 $subject .= " (".$nickname."@".$hostname.")";
412 'subject' => $subject,
413 'preamble' => $preamble,
414 'epreamble' => $epreamble,
416 'sitelink' => $sitelink,
417 'tsitelink' => $tsitelink,
418 'hsitelink' => $hsitelink,
419 'itemlink' => $itemlink
422 Addon::callHooks('enotify', $h);
424 $subject = $h['subject'];
426 $preamble = $h['preamble'];
427 $epreamble = $h['epreamble'];
431 $tsitelink = $h['tsitelink'];
432 $hsitelink = $h['hsitelink'];
433 $itemlink = $h['itemlink'];
435 if ($show_in_notification_page) {
436 logger("adding notification entry", LOGGER_DEBUG);
439 $hash = random_string();
440 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
442 if (DBM::is_result($r)) {
445 } while ($dups == true);
447 /// @TODO One statement is enough
449 $datarray['hash'] = $hash;
450 $datarray['name'] = $params['source_name'];
451 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
452 $datarray['url'] = $params['source_link'];
453 $datarray['photo'] = $params['source_photo'];
454 $datarray['date'] = DateTimeFormat::utcNow();
455 $datarray['uid'] = $params['uid'];
456 $datarray['link'] = $itemlink;
457 $datarray['iid'] = $item_id;
458 $datarray['parent'] = $parent_id;
459 $datarray['type'] = $params['type'];
460 $datarray['verb'] = $params['verb'];
461 $datarray['otype'] = $params['otype'];
462 $datarray['abort'] = false;
464 Addon::callHooks('enotify_store', $datarray);
466 if ($datarray['abort']) {
471 // create notification entry in DB
472 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
473 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
474 dbesc($datarray['hash']),
475 dbesc($datarray['name']),
476 dbesc($datarray['url']),
477 dbesc($datarray['photo']),
478 dbesc($datarray['date']),
479 intval($datarray['uid']),
480 dbesc($datarray['link']),
481 intval($datarray['iid']),
482 intval($datarray['parent']),
483 intval($datarray['type']),
484 dbesc($datarray['verb']),
485 dbesc($datarray['otype']),
486 dbesc($datarray["name_cache"])
489 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
491 intval($params['uid'])
494 $notify_id = $r[0]['id'];
500 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
501 // After we've stored everything, look again to see if there are any duplicates and if so remove them
502 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
503 intval(NOTIFY_TAGSELF),
504 intval(NOTIFY_COMMENT),
505 dbesc($params['link']),
506 intval($params['uid'])
508 if ($p && (count($p) > 1)) {
509 for ($d = 1; $d < count($p); $d ++) {
510 dba::delete('notify', ['id' => $p[$d]['id']]);
513 // only continue on if we stored the first one
514 if ($notify_id != $p[0]['id']) {
520 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
521 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
522 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
523 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
527 intval($params['uid'])
531 // send email notification if notification preferences permit
532 if ((intval($params['notify_flags']) & intval($params['type']))
533 || $params['type'] == NOTIFY_SYSTEM
534 || $params['type'] == SYSTEM_EMAIL) {
536 logger('sending notification email');
538 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
539 $id_for_parent = $params['parent']."@".$hostname;
541 // Is this the first email notification for this parent item and user?
543 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
544 intval($params['parent']),
545 intval($params['uid']));
547 // If so, create the record of it and use a message-id smtp header.
550 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
551 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
552 values(%d, %d, %d, %d)",
554 intval($params['parent']),
555 intval($params['uid']),
558 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
559 $log_msg = "include/enotify: No previous notification found for this parent:\n".
560 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
561 logger($log_msg, LOGGER_DEBUG);
563 // If not, just "follow" the thread.
564 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
565 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
569 // textversion keeps linebreaks
570 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n"], "\n",
571 $body))),ENT_QUOTES, 'UTF-8')));
572 $htmlversion = html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n\\n", "\\n"],
573 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
576 $datarray['banner'] = $banner;
577 $datarray['product'] = $product;
578 $datarray['preamble'] = $preamble;
579 $datarray['sitename'] = $sitename;
580 $datarray['siteurl'] = $siteurl;
581 $datarray['type'] = $params['type'];
582 $datarray['parent'] = $params['parent'];
583 $datarray['source_name'] = $params['source_name'];
584 $datarray['source_link'] = $params['source_link'];
585 $datarray['source_photo'] = $params['source_photo'];
586 $datarray['uid'] = $params['uid'];
587 $datarray['username'] = $params['to_name'];
588 $datarray['hsitelink'] = $hsitelink;
589 $datarray['tsitelink'] = $tsitelink;
590 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
591 $datarray['titemlink'] = $itemlink;
592 $datarray['thanks'] = $thanks;
593 $datarray['site_admin'] = $site_admin;
594 $datarray['title'] = stripslashes($title);
595 $datarray['htmlversion'] = $htmlversion;
596 $datarray['textversion'] = $textversion;
597 $datarray['subject'] = $subject;
598 $datarray['headers'] = $additional_mail_header;
600 Addon::callHooks('enotify_mail', $datarray);
602 // check whether sending post content in email notifications is allowed
603 // always true for SYSTEM_EMAIL
604 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
606 // load the template for private message notifications
607 $tpl = get_markup_template('email_notify_html.tpl');
608 $email_html_body = replace_macros($tpl, [
609 '$banner' => $datarray['banner'],
610 '$product' => $datarray['product'],
611 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
612 '$sitename' => $datarray['sitename'],
613 '$siteurl' => $datarray['siteurl'],
614 '$source_name' => $datarray['source_name'],
615 '$source_link' => $datarray['source_link'],
616 '$source_photo' => $datarray['source_photo'],
617 '$username' => $datarray['to_name'],
618 '$hsitelink' => $datarray['hsitelink'],
619 '$hitemlink' => $datarray['hitemlink'],
620 '$thanks' => $datarray['thanks'],
621 '$site_admin' => $datarray['site_admin'],
622 '$title' => $datarray['title'],
623 '$htmlversion' => $datarray['htmlversion'],
624 '$content_allowed' => $content_allowed,
627 // load the template for private message notifications
628 $tpl = get_markup_template('email_notify_text.tpl');
629 $email_text_body = replace_macros($tpl, [
630 '$banner' => $datarray['banner'],
631 '$product' => $datarray['product'],
632 '$preamble' => $datarray['preamble'],
633 '$sitename' => $datarray['sitename'],
634 '$siteurl' => $datarray['siteurl'],
635 '$source_name' => $datarray['source_name'],
636 '$source_link' => $datarray['source_link'],
637 '$source_photo' => $datarray['source_photo'],
638 '$username' => $datarray['to_name'],
639 '$tsitelink' => $datarray['tsitelink'],
640 '$titemlink' => $datarray['titemlink'],
641 '$thanks' => $datarray['thanks'],
642 '$site_admin' => $datarray['site_admin'],
643 '$title' => $datarray['title'],
644 '$textversion' => $datarray['textversion'],
645 '$content_allowed' => $content_allowed,
648 // use the Emailer class to send the message
649 return Emailer::send(
651 'uid' => $params['uid'],
652 'fromName' => $sender_name,
653 'fromEmail' => $sender_email,
654 'replyTo' => $sender_email,
655 'toEmail' => $params['to_email'],
656 'messageSubject' => $datarray['subject'],
657 'htmlVersion' => $email_html_body,
658 'textVersion' => $email_text_body,
659 'additionalMailHeader' => $datarray['headers']]
667 * @brief Checks for users who should be notified
669 * @param int $itemid ID of the item for which the check should be done
671 function check_user_notification($itemid) {
672 // fetch all users in the thread
673 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
674 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
675 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
676 while ($user = dba::fetch($users)) {
677 check_item_notification($itemid, $user['uid']);
683 * @brief Checks for item related notifications and sends them
685 * @param int $itemid ID of the item for which the check should be done
686 * @param int $uid User ID
687 * @param str $defaulttype (Optional) Forces a notification with this type.
689 function check_item_notification($itemid, $uid, $defaulttype = "") {
690 $notification_data = ["uid" => $uid, "profiles" => []];
691 Addon::callHooks('check_item_notification', $notification_data);
693 $profiles = $notification_data["profiles"];
695 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
696 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
697 if (!DBM::is_result($user)) {
701 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
702 if (!DBM::is_result($owner)) {
706 // This is our regular URL format
707 $profiles[] = $owner["url"];
709 // Notifications from Diaspora are often with an URL in the Diaspora format
710 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
714 foreach ($profiles AS $profile) {
715 // Check for invalid profile urls. 13 should be the shortest possible profile length:
717 // Additionally check for invalid urls that would return the normalised value "http:"
718 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
719 if (!in_array($profile, $profiles2))
720 $profiles2[] = $profile;
722 $profile = normalise_link($profile);
723 if (!in_array($profile, $profiles2))
724 $profiles2[] = $profile;
726 $profile = str_replace("http://", "https://", $profile);
727 if (!in_array($profile, $profiles2))
728 $profiles2[] = $profile;
732 $profiles = $profiles2;
736 foreach ($profiles AS $profile) {
737 if ($profile_list != "")
738 $profile_list .= "', '";
740 $profile_list .= dbesc($profile);
743 $profile_list = "'".$profile_list."'";
745 // Only act if it is a "real" post
746 // We need the additional check for the "local_profile" because of mixed situations on connector networks
747 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
748 `parent-uri`, `uri`, `contact-id`
749 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
750 NOT (`author-link` IN ($profile_list)) LIMIT 1",
751 intval($itemid), dbesc(ACTIVITY_POST));
755 // Generate the notification array
757 $params["uid"] = $uid;
758 $params["notify_flags"] = $user["notify-flags"];
759 $params["language"] = $user["language"];
760 $params["to_name"] = $user["username"];
761 $params["to_email"] = $user["email"];
762 $params["item"] = $item[0];
763 $params["parent"] = $item[0]["parent"];
764 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
765 $params["otype"] = 'item';
766 $params["source_name"] = $item[0]["author-name"];
767 $params["source_link"] = $item[0]["author-link"];
768 $params["source_photo"] = $item[0]["author-avatar"];
770 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
771 // Send a notification for every new post?
772 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
774 if (!$send_notification) {
775 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
776 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
778 if (DBM::is_result($tags)) {
779 foreach ($tags AS $tag) {
780 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
781 $r = dba::exists('contact', $condition);
783 $send_notification = true;
789 if ($send_notification) {
790 $params["type"] = NOTIFY_SHARE;
791 $params["verb"] = ACTIVITY_TAG;
795 // Is the user mentioned in this post?
798 foreach ($profiles AS $profile) {
799 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
803 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
804 $params["type"] = NOTIFY_TAGSELF;
805 $params["verb"] = ACTIVITY_TAG;
808 // Is it a post that the user had started or where he interacted?
809 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
810 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
811 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
813 intval($item[0]["parent"]));
815 if ($parent && !isset($params["type"])) {
816 $params["type"] = NOTIFY_COMMENT;
817 $params["verb"] = ACTIVITY_POST;
820 if (isset($params["type"]))
821 notification($params);
825 * @brief Formats a notification message with the notification author
827 * Replace the name with {0} but ensure to make that only once. The {0} is used
828 * later and prints the name in bold.
830 * @param string $name
831 * @param string $message
832 * @return string Formatted message
834 function format_notification_message($name, $message) {
836 $pos = strpos($message, $name);
841 if ($pos !== false) {
842 $message = substr_replace($message, '{0}', $pos, strlen($name));