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;
16 * @brief Creates a notification entry and possibly sends a mail
18 * @param array $params Array with the elements:
19 * uid, item, parent, type, otype, verb, event,
20 * link, subject, body, to_name, to_email, source_name,
21 * source_link, activity, preamble, notify_flags,
22 * language, show_in_notification_page
24 function notification($params)
28 // from here on everything is in the recipients language
29 L10n::pushLang($params['language']);
31 $banner = L10n::t('Friendica Notification');
32 $product = FRIENDICA_PLATFORM;
33 $siteurl = System::baseUrl(true);
34 $thanks = L10n::t('Thank You,');
35 $sitename = $a->config['sitename'];
36 if (!x($a->config['admin_name'])) {
37 $site_admin = L10n::t('%s Administrator', $sitename);
39 $site_admin = L10n::t('%1$s, %2$s Administrator', $a->config['admin_name'], $sitename);
42 $sender_name = $sitename;
43 $hostname = $a->get_hostname();
44 if (strpos($hostname, ':')) {
45 $hostname = substr($hostname, 0, strpos($hostname, ':'));
48 $sender_email = $a->getSenderEmailAddress();
50 if ($params['type'] != SYSTEM_EMAIL) {
51 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
52 ['uid' => $params['uid']]);
54 // There is no need to create notifications for forum accounts
55 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
59 $nickname = $user["nickname"];
61 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
62 // the database, and an email is sent if applicable.
63 // default, if not specified: true
64 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
66 $additional_mail_header = "";
67 $additional_mail_header .= "Precedence: list\n";
68 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
69 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
70 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
71 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
72 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
73 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
75 if (array_key_exists('item', $params)) {
76 $title = $params['item']['title'];
77 $body = $params['item']['body'];
82 if (isset($params['item']['id'])) {
83 $item_id = $params['item']['id'];
88 if (isset($params['parent'])) {
89 $parent_id = $params['parent'];
94 if ($params['type'] == NOTIFY_MAIL) {
95 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
97 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
98 $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]');
100 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
101 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
102 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
103 $itemlink = $siteurl.'/message/'.$params['item']['id'];
106 if ($params['type'] == NOTIFY_COMMENT) {
107 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
108 if (DBM::is_result($thread) && $thread["ignored"]) {
109 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
113 // Check to see if there was already a tag notify or comment notify for this post.
114 // If so don't create a second notification
115 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
116 intval(NOTIFY_TAGSELF),
117 intval(NOTIFY_COMMENT),
118 intval(NOTIFY_SHARE),
119 dbesc($params['link']),
120 intval($params['uid'])
122 if ($p && count($p)) {
127 // if it's a post figure out who's post it is.
131 if ($params['otype'] === 'item' && $parent_id) {
132 $item = dba::selectFirst('item', [], ['id' => $parent_id]);
135 $item_post_type = item_post_type($item);
138 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
139 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
144 // "George Bull's post"
146 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
147 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
149 $item['author-name'],
155 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
156 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
157 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
163 // Some mail softwares relies on subject field for threading.
164 // So, we cannot have different subjects for notifications of the same thread.
165 // Before this we have the name of the replier on the subject rendering
166 // differents subjects for messages on the same thread.
168 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
170 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
171 $epreamble = $dest_str;
173 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
174 $tsitelink = sprintf($sitelink, $siteurl);
175 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
176 $itemlink = $params['link'];
179 if ($params['type'] == NOTIFY_WALL) {
180 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
182 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
183 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
184 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
188 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
189 $tsitelink = sprintf($sitelink, $siteurl);
190 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
191 $itemlink = $params['link'];
194 if ($params['type'] == NOTIFY_TAGSELF) {
195 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
197 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
198 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
199 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
203 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
204 $tsitelink = sprintf($sitelink, $siteurl);
205 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
206 $itemlink = $params['link'];
209 if ($params['type'] == NOTIFY_SHARE) {
210 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
212 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
213 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
214 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
218 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
219 $tsitelink = sprintf($sitelink, $siteurl);
220 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
221 $itemlink = $params['link'];
224 if ($params['type'] == NOTIFY_POKE) {
225 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
227 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
228 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
229 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
233 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
234 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
235 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
237 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
238 $tsitelink = sprintf($sitelink, $siteurl);
239 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
240 $itemlink = $params['link'];
243 if ($params['type'] == NOTIFY_TAGSHARE) {
244 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
246 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
247 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
248 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
252 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
253 $tsitelink = sprintf($sitelink, $siteurl);
254 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
255 $itemlink = $params['link'];
258 if ($params['type'] == NOTIFY_INTRO) {
259 $subject = L10n::t('[Friendica:Notify] Introduction received');
261 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
262 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
264 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
267 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
269 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
270 $tsitelink = sprintf($sitelink, $siteurl);
271 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
272 $itemlink = $params['link'];
274 switch ($params['verb']) {
275 case ACTIVITY_FRIEND:
276 // someone started to share with user (mostly OStatus)
277 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
279 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
280 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
281 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
285 case ACTIVITY_FOLLOW:
286 // someone started to follow the user (mostly OStatus)
287 $subject = L10n::t('[Friendica:Notify] You have a new follower');
289 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
290 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
291 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
296 // ACTIVITY_REQ_FRIEND is default activity for notifications
301 if ($params['type'] == NOTIFY_SUGGEST) {
302 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
304 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
305 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
307 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
308 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
311 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
312 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
313 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
315 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
316 $tsitelink = sprintf($sitelink, $siteurl);
317 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
318 $itemlink = $params['link'];
321 if ($params['type'] == NOTIFY_CONFIRM) {
322 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
323 $subject = L10n::t('[Friendica:Notify] Connection accepted');
325 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
326 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
328 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
331 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
333 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
334 $tsitelink = sprintf($sitelink, $siteurl);
335 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
336 $itemlink = $params['link'];
337 } else { // ACTIVITY_FOLLOW
338 $subject = L10n::t('[Friendica:Notify] Connection accepted');
340 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
341 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
343 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
346 $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']);
348 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
350 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
351 $tsitelink = sprintf($sitelink, $siteurl);
352 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
353 $itemlink = $params['link'];
357 if ($params['type'] == NOTIFY_SYSTEM) {
358 switch($params['event']) {
359 case "SYSTEM_REGISTER_REQUEST":
360 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
362 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
363 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
365 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
368 $body = L10n::t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s ' . "\x28" . '%4$s' . "\x29",
369 $params['source_name'],
370 $siteurl, $params['source_mail'],
371 $params['source_nick']
374 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
375 $tsitelink = sprintf($sitelink, $params['link']);
376 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
377 $itemlink = $params['link'];
379 case "SYSTEM_DB_UPDATE_FAIL":
384 if ($params['type'] == SYSTEM_EMAIL) {
385 // not part of the notifications.
386 // it just send a mail to the user.
387 // It will be used by the system to send emails to users (like
388 // password reset, invitations and so) using one look (but without
389 // add a notification to the user, with could be inexistent)
390 $subject = $params['subject'];
392 $preamble = $params['preamble'];
394 $body = $params['body'];
400 $show_in_notification_page = false;
403 $subject .= " (".$nickname."@".$hostname.")";
407 'subject' => $subject,
408 'preamble' => $preamble,
409 'epreamble' => $epreamble,
411 'sitelink' => $sitelink,
412 'tsitelink' => $tsitelink,
413 'hsitelink' => $hsitelink,
414 'itemlink' => $itemlink
417 Addon::callHooks('enotify', $h);
419 $subject = $h['subject'];
421 $preamble = $h['preamble'];
422 $epreamble = $h['epreamble'];
426 $tsitelink = $h['tsitelink'];
427 $hsitelink = $h['hsitelink'];
428 $itemlink = $h['itemlink'];
430 if ($show_in_notification_page) {
431 logger("adding notification entry", LOGGER_DEBUG);
434 $hash = random_string();
435 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
437 if (DBM::is_result($r)) {
440 } while ($dups == true);
442 /// @TODO One statement is enough
444 $datarray['hash'] = $hash;
445 $datarray['name'] = $params['source_name'];
446 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
447 $datarray['url'] = $params['source_link'];
448 $datarray['photo'] = $params['source_photo'];
449 $datarray['date'] = DateTimeFormat::utcNow();
450 $datarray['uid'] = $params['uid'];
451 $datarray['link'] = $itemlink;
452 $datarray['iid'] = $item_id;
453 $datarray['parent'] = $parent_id;
454 $datarray['type'] = $params['type'];
455 $datarray['verb'] = $params['verb'];
456 $datarray['otype'] = $params['otype'];
457 $datarray['abort'] = false;
459 Addon::callHooks('enotify_store', $datarray);
461 if ($datarray['abort']) {
466 // create notification entry in DB
467 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
468 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
469 dbesc($datarray['hash']),
470 dbesc($datarray['name']),
471 dbesc($datarray['url']),
472 dbesc($datarray['photo']),
473 dbesc($datarray['date']),
474 intval($datarray['uid']),
475 dbesc($datarray['link']),
476 intval($datarray['iid']),
477 intval($datarray['parent']),
478 intval($datarray['type']),
479 dbesc($datarray['verb']),
480 dbesc($datarray['otype']),
481 dbesc($datarray["name_cache"])
484 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
486 intval($params['uid'])
489 $notify_id = $r[0]['id'];
495 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
496 // After we've stored everything, look again to see if there are any duplicates and if so remove them
497 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
498 intval(NOTIFY_TAGSELF),
499 intval(NOTIFY_COMMENT),
500 dbesc($params['link']),
501 intval($params['uid'])
503 if ($p && (count($p) > 1)) {
504 for ($d = 1; $d < count($p); $d ++) {
505 dba::delete('notify', ['id' => $p[$d]['id']]);
508 // only continue on if we stored the first one
509 if ($notify_id != $p[0]['id']) {
515 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
516 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
517 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
518 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
522 intval($params['uid'])
526 // send email notification if notification preferences permit
527 if ((intval($params['notify_flags']) & intval($params['type']))
528 || $params['type'] == NOTIFY_SYSTEM
529 || $params['type'] == SYSTEM_EMAIL) {
531 logger('sending notification email');
533 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
534 $id_for_parent = $params['parent']."@".$hostname;
536 // Is this the first email notification for this parent item and user?
538 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
539 intval($params['parent']),
540 intval($params['uid']));
542 // If so, create the record of it and use a message-id smtp header.
545 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
546 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
547 values(%d, %d, %d, %d)",
549 intval($params['parent']),
550 intval($params['uid']),
553 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
554 $log_msg = "include/enotify: No previous notification found for this parent:\n".
555 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
556 logger($log_msg, LOGGER_DEBUG);
558 // If not, just "follow" the thread.
559 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
560 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
564 // textversion keeps linebreaks
565 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n"], "\n",
566 $body))),ENT_QUOTES, 'UTF-8')));
567 $htmlversion = html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n\\n", "\\n"],
568 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
571 $datarray['banner'] = $banner;
572 $datarray['product'] = $product;
573 $datarray['preamble'] = $preamble;
574 $datarray['sitename'] = $sitename;
575 $datarray['siteurl'] = $siteurl;
576 $datarray['type'] = $params['type'];
577 $datarray['parent'] = $params['parent'];
578 $datarray['source_name'] = $params['source_name'];
579 $datarray['source_link'] = $params['source_link'];
580 $datarray['source_photo'] = $params['source_photo'];
581 $datarray['uid'] = $params['uid'];
582 $datarray['username'] = $params['to_name'];
583 $datarray['hsitelink'] = $hsitelink;
584 $datarray['tsitelink'] = $tsitelink;
585 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
586 $datarray['titemlink'] = $itemlink;
587 $datarray['thanks'] = $thanks;
588 $datarray['site_admin'] = $site_admin;
589 $datarray['title'] = stripslashes($title);
590 $datarray['htmlversion'] = $htmlversion;
591 $datarray['textversion'] = $textversion;
592 $datarray['subject'] = $subject;
593 $datarray['headers'] = $additional_mail_header;
595 Addon::callHooks('enotify_mail', $datarray);
597 // check whether sending post content in email notifications is allowed
598 // always true for SYSTEM_EMAIL
599 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
601 // load the template for private message notifications
602 $tpl = get_markup_template('email_notify_html.tpl');
603 $email_html_body = replace_macros($tpl, [
604 '$banner' => $datarray['banner'],
605 '$product' => $datarray['product'],
606 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
607 '$sitename' => $datarray['sitename'],
608 '$siteurl' => $datarray['siteurl'],
609 '$source_name' => $datarray['source_name'],
610 '$source_link' => $datarray['source_link'],
611 '$source_photo' => $datarray['source_photo'],
612 '$username' => $datarray['to_name'],
613 '$hsitelink' => $datarray['hsitelink'],
614 '$hitemlink' => $datarray['hitemlink'],
615 '$thanks' => $datarray['thanks'],
616 '$site_admin' => $datarray['site_admin'],
617 '$title' => $datarray['title'],
618 '$htmlversion' => $datarray['htmlversion'],
619 '$content_allowed' => $content_allowed,
622 // load the template for private message notifications
623 $tpl = get_markup_template('email_notify_text.tpl');
624 $email_text_body = replace_macros($tpl, [
625 '$banner' => $datarray['banner'],
626 '$product' => $datarray['product'],
627 '$preamble' => $datarray['preamble'],
628 '$sitename' => $datarray['sitename'],
629 '$siteurl' => $datarray['siteurl'],
630 '$source_name' => $datarray['source_name'],
631 '$source_link' => $datarray['source_link'],
632 '$source_photo' => $datarray['source_photo'],
633 '$username' => $datarray['to_name'],
634 '$tsitelink' => $datarray['tsitelink'],
635 '$titemlink' => $datarray['titemlink'],
636 '$thanks' => $datarray['thanks'],
637 '$site_admin' => $datarray['site_admin'],
638 '$title' => $datarray['title'],
639 '$textversion' => $datarray['textversion'],
640 '$content_allowed' => $content_allowed,
643 // use the Emailer class to send the message
644 return Emailer::send(
646 'uid' => $params['uid'],
647 'fromName' => $sender_name,
648 'fromEmail' => $sender_email,
649 'replyTo' => $sender_email,
650 'toEmail' => $params['to_email'],
651 'messageSubject' => $datarray['subject'],
652 'htmlVersion' => $email_html_body,
653 'textVersion' => $email_text_body,
654 'additionalMailHeader' => $datarray['headers']]
662 * @brief Checks for users who should be notified
664 * @param int $itemid ID of the item for which the check should be done
666 function check_user_notification($itemid) {
667 // fetch all users in the thread
668 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
669 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
670 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
671 while ($user = dba::fetch($users)) {
672 check_item_notification($itemid, $user['uid']);
678 * @brief Checks for item related notifications and sends them
680 * @param int $itemid ID of the item for which the check should be done
681 * @param int $uid User ID
682 * @param str $defaulttype (Optional) Forces a notification with this type.
684 function check_item_notification($itemid, $uid, $defaulttype = "") {
685 $notification_data = ["uid" => $uid, "profiles" => []];
686 Addon::callHooks('check_item_notification', $notification_data);
688 $profiles = $notification_data["profiles"];
690 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
691 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
692 if (!DBM::is_result($user)) {
696 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
697 if (!DBM::is_result($owner)) {
701 // This is our regular URL format
702 $profiles[] = $owner["url"];
704 // Notifications from Diaspora are often with an URL in the Diaspora format
705 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
709 foreach ($profiles AS $profile) {
710 // Check for invalid profile urls. 13 should be the shortest possible profile length:
712 // Additionally check for invalid urls that would return the normalised value "http:"
713 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
714 if (!in_array($profile, $profiles2))
715 $profiles2[] = $profile;
717 $profile = normalise_link($profile);
718 if (!in_array($profile, $profiles2))
719 $profiles2[] = $profile;
721 $profile = str_replace("http://", "https://", $profile);
722 if (!in_array($profile, $profiles2))
723 $profiles2[] = $profile;
727 $profiles = $profiles2;
731 foreach ($profiles AS $profile) {
732 if ($profile_list != "")
733 $profile_list .= "', '";
735 $profile_list .= dbesc($profile);
738 $profile_list = "'".$profile_list."'";
740 // Only act if it is a "real" post
741 // We need the additional check for the "local_profile" because of mixed situations on connector networks
742 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
743 `parent-uri`, `uri`, `contact-id`
744 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
745 NOT (`author-link` IN ($profile_list)) LIMIT 1",
746 intval($itemid), dbesc(ACTIVITY_POST));
750 // Generate the notification array
752 $params["uid"] = $uid;
753 $params["notify_flags"] = $user["notify-flags"];
754 $params["language"] = $user["language"];
755 $params["to_name"] = $user["username"];
756 $params["to_email"] = $user["email"];
757 $params["item"] = $item[0];
758 $params["parent"] = $item[0]["parent"];
759 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
760 $params["otype"] = 'item';
761 $params["source_name"] = $item[0]["author-name"];
762 $params["source_link"] = $item[0]["author-link"];
763 $params["source_photo"] = $item[0]["author-avatar"];
765 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
766 // Send a notification for every new post?
767 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
769 if (!$send_notification) {
770 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
771 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
773 if (DBM::is_result($tags)) {
774 foreach ($tags AS $tag) {
775 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
776 $r = dba::exists('contact', $condition);
778 $send_notification = true;
784 if ($send_notification) {
785 $params["type"] = NOTIFY_SHARE;
786 $params["verb"] = ACTIVITY_TAG;
790 // Is the user mentioned in this post?
793 foreach ($profiles AS $profile) {
794 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
798 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
799 $params["type"] = NOTIFY_TAGSELF;
800 $params["verb"] = ACTIVITY_TAG;
803 // Is it a post that the user had started or where he interacted?
804 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
805 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
806 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
808 intval($item[0]["parent"]));
810 if ($parent && !isset($params["type"])) {
811 $params["type"] = NOTIFY_COMMENT;
812 $params["verb"] = ACTIVITY_POST;
815 if (isset($params["type"]))
816 notification($params);
820 * @brief Formats a notification message with the notification author
822 * Replace the name with {0} but ensure to make that only once. The {0} is used
823 * later and prints the name in bold.
825 * @param string $name
826 * @param string $message
827 * @return string Formatted message
829 function format_notification_message($name, $message) {
831 $pos = strpos($message, $name);
836 if ($pos !== false) {
837 $message = substr_replace($message, '{0}', $pos, strlen($name));