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->config['sender_email'];
49 if (empty($sender_email)) {
50 $sender_email = L10n::t('noreply').'@'.$hostname;
53 if ($params['type'] != SYSTEM_EMAIL) {
54 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
55 ['uid' => $params['uid']]);
57 // There is no need to create notifications for forum accounts
58 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
62 $nickname = $user["nickname"];
64 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
65 // the database, and an email is sent if applicable.
66 // default, if not specified: true
67 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
69 $additional_mail_header = "";
70 $additional_mail_header .= "Precedence: list\n";
71 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
72 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
73 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
74 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
75 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
76 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
78 if (array_key_exists('item', $params)) {
79 $title = $params['item']['title'];
80 $body = $params['item']['body'];
85 if (isset($params['item']['id'])) {
86 $item_id = $params['item']['id'];
91 if (isset($params['parent'])) {
92 $parent_id = $params['parent'];
97 if ($params['type'] == NOTIFY_MAIL) {
98 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
100 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
101 $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]');
103 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
104 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
105 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
106 $itemlink = $siteurl.'/message/'.$params['item']['id'];
109 if ($params['type'] == NOTIFY_COMMENT) {
110 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
111 if (DBM::is_result($thread) && $thread["ignored"]) {
112 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
116 // Check to see if there was already a tag notify or comment notify for this post.
117 // If so don't create a second notification
118 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
119 intval(NOTIFY_TAGSELF),
120 intval(NOTIFY_COMMENT),
121 intval(NOTIFY_SHARE),
122 dbesc($params['link']),
123 intval($params['uid'])
125 if ($p && count($p)) {
130 // if it's a post figure out who's post it is.
134 if ($params['otype'] === 'item' && $parent_id) {
135 $item = dba::selectFirst('item', [], ['id' => $parent_id]);
138 $item_post_type = item_post_type($item);
141 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
142 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
147 // "George Bull's post"
149 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
150 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
152 $item['author-name'],
158 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
159 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
160 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
166 // Some mail softwares relies on subject field for threading.
167 // So, we cannot have different subjects for notifications of the same thread.
168 // Before this we have the name of the replier on the subject rendering
169 // differents subjects for messages on the same thread.
171 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
173 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
174 $epreamble = $dest_str;
176 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
177 $tsitelink = sprintf($sitelink, $siteurl);
178 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
179 $itemlink = $params['link'];
182 if ($params['type'] == NOTIFY_WALL) {
183 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
185 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
186 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
187 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
191 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
192 $tsitelink = sprintf($sitelink, $siteurl);
193 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
194 $itemlink = $params['link'];
197 if ($params['type'] == NOTIFY_TAGSELF) {
198 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
200 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
201 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
202 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
206 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
207 $tsitelink = sprintf($sitelink, $siteurl);
208 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
209 $itemlink = $params['link'];
212 if ($params['type'] == NOTIFY_SHARE) {
213 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
215 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
216 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
217 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
221 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
222 $tsitelink = sprintf($sitelink, $siteurl);
223 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
224 $itemlink = $params['link'];
227 if ($params['type'] == NOTIFY_POKE) {
228 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
230 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
231 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
232 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
236 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
237 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
238 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
240 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
241 $tsitelink = sprintf($sitelink, $siteurl);
242 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
243 $itemlink = $params['link'];
246 if ($params['type'] == NOTIFY_TAGSHARE) {
247 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
249 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
250 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
251 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
255 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
256 $tsitelink = sprintf($sitelink, $siteurl);
257 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
258 $itemlink = $params['link'];
261 if ($params['type'] == NOTIFY_INTRO) {
262 $subject = L10n::t('[Friendica:Notify] Introduction received');
264 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
265 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
267 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
270 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
272 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
273 $tsitelink = sprintf($sitelink, $siteurl);
274 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
275 $itemlink = $params['link'];
277 switch ($params['verb']) {
278 case ACTIVITY_FRIEND:
279 // someone started to share with user (mostly OStatus)
280 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
282 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
283 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
284 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
288 case ACTIVITY_FOLLOW:
289 // someone started to follow the user (mostly OStatus)
290 $subject = L10n::t('[Friendica:Notify] You have a new follower');
292 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
293 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
294 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
299 // ACTIVITY_REQ_FRIEND is default activity for notifications
304 if ($params['type'] == NOTIFY_SUGGEST) {
305 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
307 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
308 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
310 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
311 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
314 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
315 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
316 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
318 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
319 $tsitelink = sprintf($sitelink, $siteurl);
320 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
321 $itemlink = $params['link'];
324 if ($params['type'] == NOTIFY_CONFIRM) {
325 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
326 $subject = L10n::t('[Friendica:Notify] Connection accepted');
328 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
329 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
331 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
334 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
336 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
337 $tsitelink = sprintf($sitelink, $siteurl);
338 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
339 $itemlink = $params['link'];
340 } else { // ACTIVITY_FOLLOW
341 $subject = L10n::t('[Friendica:Notify] Connection accepted');
343 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
344 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
346 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
349 $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']);
351 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
353 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
354 $tsitelink = sprintf($sitelink, $siteurl);
355 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
356 $itemlink = $params['link'];
360 if ($params['type'] == NOTIFY_SYSTEM) {
361 switch($params['event']) {
362 case "SYSTEM_REGISTER_REQUEST":
363 $subject = L10n::t('[Friendica System:Notify] registration request');
365 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
366 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
368 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
371 $body = L10n::t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s ' . "\x28" . '%4$s' . "\x29",
372 $params['source_name'],
373 $siteurl, $params['source_mail'],
374 $params['source_nick']
377 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
378 $tsitelink = sprintf($sitelink, $params['link']);
379 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
380 $itemlink = $params['link'];
382 case "SYSTEM_DB_UPDATE_FAIL":
387 if ($params['type'] == SYSTEM_EMAIL) {
388 // not part of the notifications.
389 // it just send a mail to the user.
390 // It will be used by the system to send emails to users (like
391 // password reset, invitations and so) using one look (but without
392 // add a notification to the user, with could be inexistent)
393 $subject = $params['subject'];
395 $preamble = $params['preamble'];
397 $body = $params['body'];
403 $show_in_notification_page = false;
406 $subject .= " (".$nickname."@".$hostname.")";
410 'subject' => $subject,
411 'preamble' => $preamble,
412 'epreamble' => $epreamble,
414 'sitelink' => $sitelink,
415 'tsitelink' => $tsitelink,
416 'hsitelink' => $hsitelink,
417 'itemlink' => $itemlink
420 Addon::callHooks('enotify', $h);
422 $subject = $h['subject'];
424 $preamble = $h['preamble'];
425 $epreamble = $h['epreamble'];
429 $tsitelink = $h['tsitelink'];
430 $hsitelink = $h['hsitelink'];
431 $itemlink = $h['itemlink'];
433 if ($show_in_notification_page) {
434 logger("adding notification entry", LOGGER_DEBUG);
437 $hash = random_string();
438 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
440 if (DBM::is_result($r)) {
443 } while ($dups == true);
445 /// @TODO One statement is enough
447 $datarray['hash'] = $hash;
448 $datarray['name'] = $params['source_name'];
449 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
450 $datarray['url'] = $params['source_link'];
451 $datarray['photo'] = $params['source_photo'];
452 $datarray['date'] = DateTimeFormat::utcNow();
453 $datarray['uid'] = $params['uid'];
454 $datarray['link'] = $itemlink;
455 $datarray['iid'] = $item_id;
456 $datarray['parent'] = $parent_id;
457 $datarray['type'] = $params['type'];
458 $datarray['verb'] = $params['verb'];
459 $datarray['otype'] = $params['otype'];
460 $datarray['abort'] = false;
462 Addon::callHooks('enotify_store', $datarray);
464 if ($datarray['abort']) {
469 // create notification entry in DB
470 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
471 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
472 dbesc($datarray['hash']),
473 dbesc($datarray['name']),
474 dbesc($datarray['url']),
475 dbesc($datarray['photo']),
476 dbesc($datarray['date']),
477 intval($datarray['uid']),
478 dbesc($datarray['link']),
479 intval($datarray['iid']),
480 intval($datarray['parent']),
481 intval($datarray['type']),
482 dbesc($datarray['verb']),
483 dbesc($datarray['otype']),
484 dbesc($datarray["name_cache"])
487 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
489 intval($params['uid'])
492 $notify_id = $r[0]['id'];
498 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
499 // After we've stored everything, look again to see if there are any duplicates and if so remove them
500 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
501 intval(NOTIFY_TAGSELF),
502 intval(NOTIFY_COMMENT),
503 dbesc($params['link']),
504 intval($params['uid'])
506 if ($p && (count($p) > 1)) {
507 for ($d = 1; $d < count($p); $d ++) {
508 dba::delete('notify', ['id' => $p[$d]['id']]);
511 // only continue on if we stored the first one
512 if ($notify_id != $p[0]['id']) {
518 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
519 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
520 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
521 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
525 intval($params['uid'])
529 // send email notification if notification preferences permit
530 if ((intval($params['notify_flags']) & intval($params['type']))
531 || $params['type'] == NOTIFY_SYSTEM
532 || $params['type'] == SYSTEM_EMAIL) {
534 logger('sending notification email');
536 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
537 $id_for_parent = $params['parent']."@".$hostname;
539 // Is this the first email notification for this parent item and user?
541 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
542 intval($params['parent']),
543 intval($params['uid']));
545 // If so, create the record of it and use a message-id smtp header.
548 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
549 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
550 values(%d, %d, %d, %d)",
552 intval($params['parent']),
553 intval($params['uid']),
556 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
557 $log_msg = "include/enotify: No previous notification found for this parent:\n".
558 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
559 logger($log_msg, LOGGER_DEBUG);
561 // If not, just "follow" the thread.
562 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
563 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
567 // textversion keeps linebreaks
568 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n"], "\n",
569 $body))),ENT_QUOTES, 'UTF-8')));
570 $htmlversion = html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n\\n", "\\n"],
571 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
574 $datarray['banner'] = $banner;
575 $datarray['product'] = $product;
576 $datarray['preamble'] = $preamble;
577 $datarray['sitename'] = $sitename;
578 $datarray['siteurl'] = $siteurl;
579 $datarray['type'] = $params['type'];
580 $datarray['parent'] = $params['parent'];
581 $datarray['source_name'] = $params['source_name'];
582 $datarray['source_link'] = $params['source_link'];
583 $datarray['source_photo'] = $params['source_photo'];
584 $datarray['uid'] = $params['uid'];
585 $datarray['username'] = $params['to_name'];
586 $datarray['hsitelink'] = $hsitelink;
587 $datarray['tsitelink'] = $tsitelink;
588 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
589 $datarray['titemlink'] = $itemlink;
590 $datarray['thanks'] = $thanks;
591 $datarray['site_admin'] = $site_admin;
592 $datarray['title'] = stripslashes($title);
593 $datarray['htmlversion'] = $htmlversion;
594 $datarray['textversion'] = $textversion;
595 $datarray['subject'] = $subject;
596 $datarray['headers'] = $additional_mail_header;
598 Addon::callHooks('enotify_mail', $datarray);
600 // check whether sending post content in email notifications is allowed
601 // always true for SYSTEM_EMAIL
602 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
604 // load the template for private message notifications
605 $tpl = get_markup_template('email_notify_html.tpl');
606 $email_html_body = replace_macros($tpl, [
607 '$banner' => $datarray['banner'],
608 '$product' => $datarray['product'],
609 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
610 '$sitename' => $datarray['sitename'],
611 '$siteurl' => $datarray['siteurl'],
612 '$source_name' => $datarray['source_name'],
613 '$source_link' => $datarray['source_link'],
614 '$source_photo' => $datarray['source_photo'],
615 '$username' => $datarray['to_name'],
616 '$hsitelink' => $datarray['hsitelink'],
617 '$hitemlink' => $datarray['hitemlink'],
618 '$thanks' => $datarray['thanks'],
619 '$site_admin' => $datarray['site_admin'],
620 '$title' => $datarray['title'],
621 '$htmlversion' => $datarray['htmlversion'],
622 '$content_allowed' => $content_allowed,
625 // load the template for private message notifications
626 $tpl = get_markup_template('email_notify_text.tpl');
627 $email_text_body = replace_macros($tpl, [
628 '$banner' => $datarray['banner'],
629 '$product' => $datarray['product'],
630 '$preamble' => $datarray['preamble'],
631 '$sitename' => $datarray['sitename'],
632 '$siteurl' => $datarray['siteurl'],
633 '$source_name' => $datarray['source_name'],
634 '$source_link' => $datarray['source_link'],
635 '$source_photo' => $datarray['source_photo'],
636 '$username' => $datarray['to_name'],
637 '$tsitelink' => $datarray['tsitelink'],
638 '$titemlink' => $datarray['titemlink'],
639 '$thanks' => $datarray['thanks'],
640 '$site_admin' => $datarray['site_admin'],
641 '$title' => $datarray['title'],
642 '$textversion' => $datarray['textversion'],
643 '$content_allowed' => $content_allowed,
646 // use the Emailer class to send the message
647 return Emailer::send(
649 'uid' => $params['uid'],
650 'fromName' => $sender_name,
651 'fromEmail' => $sender_email,
652 'replyTo' => $sender_email,
653 'toEmail' => $params['to_email'],
654 'messageSubject' => $datarray['subject'],
655 'htmlVersion' => $email_html_body,
656 'textVersion' => $email_text_body,
657 'additionalMailHeader' => $datarray['headers']]
665 * @brief Checks for users who should be notified
667 * @param int $itemid ID of the item for which the check should be done
669 function check_user_notification($itemid) {
670 // fetch all users in the thread
671 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
672 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
673 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
674 while ($user = dba::fetch($users)) {
675 check_item_notification($itemid, $user['uid']);
681 * @brief Checks for item related notifications and sends them
683 * @param int $itemid ID of the item for which the check should be done
684 * @param int $uid User ID
685 * @param str $defaulttype (Optional) Forces a notification with this type.
687 function check_item_notification($itemid, $uid, $defaulttype = "") {
688 $notification_data = ["uid" => $uid, "profiles" => []];
689 Addon::callHooks('check_item_notification', $notification_data);
691 $profiles = $notification_data["profiles"];
693 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
694 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
695 if (!DBM::is_result($user)) {
699 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
700 if (!DBM::is_result($owner)) {
704 // This is our regular URL format
705 $profiles[] = $owner["url"];
707 // Notifications from Diaspora are often with an URL in the Diaspora format
708 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
712 foreach ($profiles AS $profile) {
713 // Check for invalid profile urls. 13 should be the shortest possible profile length:
715 // Additionally check for invalid urls that would return the normalised value "http:"
716 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
717 if (!in_array($profile, $profiles2))
718 $profiles2[] = $profile;
720 $profile = normalise_link($profile);
721 if (!in_array($profile, $profiles2))
722 $profiles2[] = $profile;
724 $profile = str_replace("http://", "https://", $profile);
725 if (!in_array($profile, $profiles2))
726 $profiles2[] = $profile;
730 $profiles = $profiles2;
734 foreach ($profiles AS $profile) {
735 if ($profile_list != "")
736 $profile_list .= "', '";
738 $profile_list .= dbesc($profile);
741 $profile_list = "'".$profile_list."'";
743 // Only act if it is a "real" post
744 // We need the additional check for the "local_profile" because of mixed situations on connector networks
745 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
746 `parent-uri`, `uri`, `contact-id`
747 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
748 NOT (`author-link` IN ($profile_list)) LIMIT 1",
749 intval($itemid), dbesc(ACTIVITY_POST));
753 // Generate the notification array
755 $params["uid"] = $uid;
756 $params["notify_flags"] = $user["notify-flags"];
757 $params["language"] = $user["language"];
758 $params["to_name"] = $user["username"];
759 $params["to_email"] = $user["email"];
760 $params["item"] = $item[0];
761 $params["parent"] = $item[0]["parent"];
762 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
763 $params["otype"] = 'item';
764 $params["source_name"] = $item[0]["author-name"];
765 $params["source_link"] = $item[0]["author-link"];
766 $params["source_photo"] = $item[0]["author-avatar"];
768 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
769 // Send a notification for every new post?
770 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
772 if (!$send_notification) {
773 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
774 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
776 if (DBM::is_result($tags)) {
777 foreach ($tags AS $tag) {
778 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
779 $r = dba::exists('contact', $condition);
781 $send_notification = true;
787 if ($send_notification) {
788 $params["type"] = NOTIFY_SHARE;
789 $params["verb"] = ACTIVITY_TAG;
793 // Is the user mentioned in this post?
796 foreach ($profiles AS $profile) {
797 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
801 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
802 $params["type"] = NOTIFY_TAGSELF;
803 $params["verb"] = ACTIVITY_TAG;
806 // Is it a post that the user had started or where he interacted?
807 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
808 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
809 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
811 intval($item[0]["parent"]));
813 if ($parent && !isset($params["type"])) {
814 $params["type"] = NOTIFY_COMMENT;
815 $params["verb"] = ACTIVITY_POST;
818 if (isset($params["type"]))
819 notification($params);
823 * @brief Formats a notification message with the notification author
825 * Replace the name with {0} but ensure to make that only once. The {0} is used
826 * later and prints the name in bold.
828 * @param string $name
829 * @param string $message
830 * @return string Formatted message
832 function format_notification_message($name, $message) {
834 $pos = strpos($message, $name);
839 if ($pos !== false) {
840 $message = substr_replace($message, '{0}', $pos, strlen($name));