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/bbcode.php';
16 require_once 'include/html2bbcode.php';
19 * @brief Creates a notification entry and possibly sends a mail
21 * @param array $params Array with the elements:
22 uid, item, parent, type, otype, verb, event,
23 link, subject, body, to_name, to_email, source_name,
24 source_link, activity, preamble, notify_flags,
25 language, show_in_notification_page
27 function notification($params)
31 // from here on everything is in the recipients language
32 L10n::pushLang($params['language']);
34 $banner = L10n::t('Friendica Notification');
35 $product = FRIENDICA_PLATFORM;
36 $siteurl = System::baseUrl(true);
37 $thanks = L10n::t('Thank You,');
38 $sitename = $a->config['sitename'];
39 if (!x($a->config['admin_name'])) {
40 $site_admin = L10n::t('%s Administrator', $sitename);
42 $site_admin = L10n::t('%1$s, %2$s Administrator', $a->config['admin_name'], $sitename);
45 $sender_name = $sitename;
46 $hostname = $a->get_hostname();
47 if (strpos($hostname, ':')) {
48 $hostname = substr($hostname, 0, strpos($hostname, ':'));
51 $sender_email = $a->config['sender_email'];
52 if (empty($sender_email)) {
53 $sender_email = L10n::t('noreply').'@'.$hostname;
56 if ($params['type'] != SYSTEM_EMAIL) {
57 $user = dba::selectFirst('user', ['nickname', 'page-flags'],
58 ['uid' => $params['uid']]);
60 // There is no need to create notifications for forum accounts
61 if (!DBM::is_result($user) || in_array($user["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
65 $nickname = $user["nickname"];
67 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
68 // the database, and an email is sent if applicable.
69 // default, if not specified: true
70 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
72 $additional_mail_header = "";
73 $additional_mail_header .= "Precedence: list\n";
74 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
75 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
76 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
77 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
78 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
79 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
81 if (array_key_exists('item', $params)) {
82 $title = $params['item']['title'];
83 $body = $params['item']['body'];
88 if (isset($params['item']['id'])) {
89 $item_id = $params['item']['id'];
94 if (isset($params['parent'])) {
95 $parent_id = $params['parent'];
100 if ($params['type'] == NOTIFY_MAIL) {
101 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
103 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
104 $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]');
106 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
107 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
108 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
109 $itemlink = $siteurl.'/message/'.$params['item']['id'];
112 if ($params['type'] == NOTIFY_COMMENT) {
113 $thread = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
114 if (DBM::is_result($thread) && $thread["ignored"]) {
115 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
119 // Check to see if there was already a tag notify or comment notify for this post.
120 // If so don't create a second notification
121 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
122 intval(NOTIFY_TAGSELF),
123 intval(NOTIFY_COMMENT),
124 intval(NOTIFY_SHARE),
125 dbesc($params['link']),
126 intval($params['uid'])
128 if ($p && count($p)) {
133 // if it's a post figure out who's post it is.
137 if ($params['otype'] === 'item' && $parent_id) {
138 $item = dba::selectFirst('item', [], ['id' => $parent_id]);
141 $item_post_type = item_post_type($item);
144 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
145 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
150 // "George Bull's post"
152 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
153 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
155 $item['author-name'],
161 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
162 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
163 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
169 // Some mail softwares relies on subject field for threading.
170 // So, we cannot have different subjects for notifications of the same thread.
171 // Before this we have the name of the replier on the subject rendering
172 // differents subjects for messages on the same thread.
174 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
176 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
177 $epreamble = $dest_str;
179 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
180 $tsitelink = sprintf($sitelink, $siteurl);
181 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
182 $itemlink = $params['link'];
185 if ($params['type'] == NOTIFY_WALL) {
186 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
188 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
189 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
190 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
194 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
195 $tsitelink = sprintf($sitelink, $siteurl);
196 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
197 $itemlink = $params['link'];
200 if ($params['type'] == NOTIFY_TAGSELF) {
201 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
203 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
204 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
205 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
209 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
210 $tsitelink = sprintf($sitelink, $siteurl);
211 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
212 $itemlink = $params['link'];
215 if ($params['type'] == NOTIFY_SHARE) {
216 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
218 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
219 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
220 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
224 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
225 $tsitelink = sprintf($sitelink, $siteurl);
226 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
227 $itemlink = $params['link'];
230 if ($params['type'] == NOTIFY_POKE) {
231 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
233 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
234 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
235 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
239 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
240 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
241 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
243 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
244 $tsitelink = sprintf($sitelink, $siteurl);
245 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
246 $itemlink = $params['link'];
249 if ($params['type'] == NOTIFY_TAGSHARE) {
250 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
252 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
253 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
254 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
258 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
259 $tsitelink = sprintf($sitelink, $siteurl);
260 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
261 $itemlink = $params['link'];
264 if ($params['type'] == NOTIFY_INTRO) {
265 $subject = L10n::t('[Friendica:Notify] Introduction received');
267 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
268 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
270 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
273 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
275 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
276 $tsitelink = sprintf($sitelink, $siteurl);
277 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
278 $itemlink = $params['link'];
280 switch ($params['verb']) {
281 case ACTIVITY_FRIEND:
282 // someone started to share with user (mostly OStatus)
283 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
285 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
286 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
287 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
291 case ACTIVITY_FOLLOW:
292 // someone started to follow the user (mostly OStatus)
293 $subject = L10n::t('[Friendica:Notify] You have a new follower');
295 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
296 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
297 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
302 // ACTIVITY_REQ_FRIEND is default activity for notifications
307 if ($params['type'] == NOTIFY_SUGGEST) {
308 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
310 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
311 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
313 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
314 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
317 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
318 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
319 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
321 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
322 $tsitelink = sprintf($sitelink, $siteurl);
323 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
324 $itemlink = $params['link'];
327 if ($params['type'] == NOTIFY_CONFIRM) {
328 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
329 $subject = L10n::t('[Friendica:Notify] Connection accepted');
331 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
332 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
334 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
337 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
339 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
340 $tsitelink = sprintf($sitelink, $siteurl);
341 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
342 $itemlink = $params['link'];
343 } else { // ACTIVITY_FOLLOW
344 $subject = L10n::t('[Friendica:Notify] Connection accepted');
346 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
347 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
349 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
352 $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']);
354 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
356 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
357 $tsitelink = sprintf($sitelink, $siteurl);
358 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
359 $itemlink = $params['link'];
363 if ($params['type'] == NOTIFY_SYSTEM) {
364 switch($params['event']) {
365 case "SYSTEM_REGISTER_REQUEST":
366 $subject = L10n::t('[Friendica System:Notify] registration request');
368 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
369 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
371 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
374 $body = L10n::t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s ' . "\x28" . '%4$s' . "\x28",
375 $params['source_name'],
376 $siteurl, $params['source_mail'],
377 $params['source_nick']
380 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
381 $tsitelink = sprintf($sitelink, $params['link']);
382 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
383 $itemlink = $params['link'];
385 case "SYSTEM_DB_UPDATE_FAIL":
390 if ($params['type'] == SYSTEM_EMAIL) {
391 // not part of the notifications.
392 // it just send a mail to the user.
393 // It will be used by the system to send emails to users (like
394 // password reset, invitations and so) using one look (but without
395 // add a notification to the user, with could be inexistent)
396 $subject = $params['subject'];
398 $preamble = $params['preamble'];
400 $body = $params['body'];
406 $show_in_notification_page = false;
409 $subject .= " (".$nickname."@".$hostname.")";
413 'subject' => $subject,
414 'preamble' => $preamble,
415 'epreamble' => $epreamble,
417 'sitelink' => $sitelink,
418 'tsitelink' => $tsitelink,
419 'hsitelink' => $hsitelink,
420 'itemlink' => $itemlink
423 Addon::callHooks('enotify', $h);
425 $subject = $h['subject'];
427 $preamble = $h['preamble'];
428 $epreamble = $h['epreamble'];
432 $tsitelink = $h['tsitelink'];
433 $hsitelink = $h['hsitelink'];
434 $itemlink = $h['itemlink'];
436 if ($show_in_notification_page) {
437 logger("adding notification entry", LOGGER_DEBUG);
440 $hash = random_string();
441 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
443 if (DBM::is_result($r)) {
446 } while ($dups == true);
448 /// @TODO One statement is enough
450 $datarray['hash'] = $hash;
451 $datarray['name'] = $params['source_name'];
452 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
453 $datarray['url'] = $params['source_link'];
454 $datarray['photo'] = $params['source_photo'];
455 $datarray['date'] = DateTimeFormat::utcNow();
456 $datarray['uid'] = $params['uid'];
457 $datarray['link'] = $itemlink;
458 $datarray['iid'] = $item_id;
459 $datarray['parent'] = $parent_id;
460 $datarray['type'] = $params['type'];
461 $datarray['verb'] = $params['verb'];
462 $datarray['otype'] = $params['otype'];
463 $datarray['abort'] = false;
465 Addon::callHooks('enotify_store', $datarray);
467 if ($datarray['abort']) {
472 // create notification entry in DB
473 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
474 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
475 dbesc($datarray['hash']),
476 dbesc($datarray['name']),
477 dbesc($datarray['url']),
478 dbesc($datarray['photo']),
479 dbesc($datarray['date']),
480 intval($datarray['uid']),
481 dbesc($datarray['link']),
482 intval($datarray['iid']),
483 intval($datarray['parent']),
484 intval($datarray['type']),
485 dbesc($datarray['verb']),
486 dbesc($datarray['otype']),
487 dbesc($datarray["name_cache"])
490 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
492 intval($params['uid'])
495 $notify_id = $r[0]['id'];
501 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
502 // After we've stored everything, look again to see if there are any duplicates and if so remove them
503 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
504 intval(NOTIFY_TAGSELF),
505 intval(NOTIFY_COMMENT),
506 dbesc($params['link']),
507 intval($params['uid'])
509 if ($p && (count($p) > 1)) {
510 for ($d = 1; $d < count($p); $d ++) {
511 dba::delete('notify', ['id' => $p[$d]['id']]);
514 // only continue on if we stored the first one
515 if ($notify_id != $p[0]['id']) {
521 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
522 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
523 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
524 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
528 intval($params['uid'])
532 // send email notification if notification preferences permit
533 if ((intval($params['notify_flags']) & intval($params['type']))
534 || $params['type'] == NOTIFY_SYSTEM
535 || $params['type'] == SYSTEM_EMAIL) {
537 logger('sending notification email');
539 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
540 $id_for_parent = $params['parent']."@".$hostname;
542 // Is this the first email notification for this parent item and user?
544 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
545 intval($params['parent']),
546 intval($params['uid']));
548 // If so, create the record of it and use a message-id smtp header.
551 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
552 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
553 values(%d, %d, %d, %d)",
555 intval($params['parent']),
556 intval($params['uid']),
559 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
560 $log_msg = "include/enotify: No previous notification found for this parent:\n".
561 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
562 logger($log_msg, LOGGER_DEBUG);
564 // If not, just "follow" the thread.
565 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
566 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
570 // textversion keeps linebreaks
571 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n"], "\n",
572 $body))),ENT_QUOTES, 'UTF-8')));
573 $htmlversion = html_entity_decode(BBCode::convert(stripslashes(str_replace(["\\r\\n", "\\r", "\\n\\n", "\\n"],
574 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
577 $datarray['banner'] = $banner;
578 $datarray['product'] = $product;
579 $datarray['preamble'] = $preamble;
580 $datarray['sitename'] = $sitename;
581 $datarray['siteurl'] = $siteurl;
582 $datarray['type'] = $params['type'];
583 $datarray['parent'] = $params['parent'];
584 $datarray['source_name'] = $params['source_name'];
585 $datarray['source_link'] = $params['source_link'];
586 $datarray['source_photo'] = $params['source_photo'];
587 $datarray['uid'] = $params['uid'];
588 $datarray['username'] = $params['to_name'];
589 $datarray['hsitelink'] = $hsitelink;
590 $datarray['tsitelink'] = $tsitelink;
591 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
592 $datarray['titemlink'] = $itemlink;
593 $datarray['thanks'] = $thanks;
594 $datarray['site_admin'] = $site_admin;
595 $datarray['title'] = stripslashes($title);
596 $datarray['htmlversion'] = $htmlversion;
597 $datarray['textversion'] = $textversion;
598 $datarray['subject'] = $subject;
599 $datarray['headers'] = $additional_mail_header;
601 Addon::callHooks('enotify_mail', $datarray);
603 // check whether sending post content in email notifications is allowed
604 // always true for SYSTEM_EMAIL
605 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
607 // load the template for private message notifications
608 $tpl = get_markup_template('email_notify_html.tpl');
609 $email_html_body = replace_macros($tpl, [
610 '$banner' => $datarray['banner'],
611 '$product' => $datarray['product'],
612 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
613 '$sitename' => $datarray['sitename'],
614 '$siteurl' => $datarray['siteurl'],
615 '$source_name' => $datarray['source_name'],
616 '$source_link' => $datarray['source_link'],
617 '$source_photo' => $datarray['source_photo'],
618 '$username' => $datarray['to_name'],
619 '$hsitelink' => $datarray['hsitelink'],
620 '$hitemlink' => $datarray['hitemlink'],
621 '$thanks' => $datarray['thanks'],
622 '$site_admin' => $datarray['site_admin'],
623 '$title' => $datarray['title'],
624 '$htmlversion' => $datarray['htmlversion'],
625 '$content_allowed' => $content_allowed,
628 // load the template for private message notifications
629 $tpl = get_markup_template('email_notify_text.tpl');
630 $email_text_body = replace_macros($tpl, [
631 '$banner' => $datarray['banner'],
632 '$product' => $datarray['product'],
633 '$preamble' => $datarray['preamble'],
634 '$sitename' => $datarray['sitename'],
635 '$siteurl' => $datarray['siteurl'],
636 '$source_name' => $datarray['source_name'],
637 '$source_link' => $datarray['source_link'],
638 '$source_photo' => $datarray['source_photo'],
639 '$username' => $datarray['to_name'],
640 '$tsitelink' => $datarray['tsitelink'],
641 '$titemlink' => $datarray['titemlink'],
642 '$thanks' => $datarray['thanks'],
643 '$site_admin' => $datarray['site_admin'],
644 '$title' => $datarray['title'],
645 '$textversion' => $datarray['textversion'],
646 '$content_allowed' => $content_allowed,
649 // use the Emailer class to send the message
650 return Emailer::send(
652 'uid' => $params['uid'],
653 'fromName' => $sender_name,
654 'fromEmail' => $sender_email,
655 'replyTo' => $sender_email,
656 'toEmail' => $params['to_email'],
657 'messageSubject' => $datarray['subject'],
658 'htmlVersion' => $email_html_body,
659 'textVersion' => $email_text_body,
660 'additionalMailHeader' => $datarray['headers']]
668 * @brief Checks for users who should be notified
670 * @param int $itemid ID of the item for which the check should be done
672 function check_user_notification($itemid) {
673 // fetch all users in the thread
674 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
675 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
676 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
677 while ($user = dba::fetch($users)) {
678 check_item_notification($itemid, $user['uid']);
684 * @brief Checks for item related notifications and sends them
686 * @param int $itemid ID of the item for which the check should be done
687 * @param int $uid User ID
688 * @param str $defaulttype (Optional) Forces a notification with this type.
690 function check_item_notification($itemid, $uid, $defaulttype = "") {
691 $notification_data = ["uid" => $uid, "profiles" => []];
692 Addon::callHooks('check_item_notification', $notification_data);
694 $profiles = $notification_data["profiles"];
696 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
697 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
698 if (!DBM::is_result($user)) {
702 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
703 if (!DBM::is_result($owner)) {
707 // This is our regular URL format
708 $profiles[] = $owner["url"];
710 // Notifications from Diaspora are often with an URL in the Diaspora format
711 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
715 foreach ($profiles AS $profile) {
716 // Check for invalid profile urls. 13 should be the shortest possible profile length:
718 // Additionally check for invalid urls that would return the normalised value "http:"
719 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
720 if (!in_array($profile, $profiles2))
721 $profiles2[] = $profile;
723 $profile = normalise_link($profile);
724 if (!in_array($profile, $profiles2))
725 $profiles2[] = $profile;
727 $profile = str_replace("http://", "https://", $profile);
728 if (!in_array($profile, $profiles2))
729 $profiles2[] = $profile;
733 $profiles = $profiles2;
737 foreach ($profiles AS $profile) {
738 if ($profile_list != "")
739 $profile_list .= "', '";
741 $profile_list .= dbesc($profile);
744 $profile_list = "'".$profile_list."'";
746 // Only act if it is a "real" post
747 // We need the additional check for the "local_profile" because of mixed situations on connector networks
748 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
749 `parent-uri`, `uri`, `contact-id`
750 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
751 NOT (`author-link` IN ($profile_list)) LIMIT 1",
752 intval($itemid), dbesc(ACTIVITY_POST));
756 // Generate the notification array
758 $params["uid"] = $uid;
759 $params["notify_flags"] = $user["notify-flags"];
760 $params["language"] = $user["language"];
761 $params["to_name"] = $user["username"];
762 $params["to_email"] = $user["email"];
763 $params["item"] = $item[0];
764 $params["parent"] = $item[0]["parent"];
765 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
766 $params["otype"] = 'item';
767 $params["source_name"] = $item[0]["author-name"];
768 $params["source_link"] = $item[0]["author-link"];
769 $params["source_photo"] = $item[0]["author-avatar"];
771 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
772 // Send a notification for every new post?
773 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
775 if (!$send_notification) {
776 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
777 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
779 if (DBM::is_result($tags)) {
780 foreach ($tags AS $tag) {
781 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
782 $r = dba::exists('contact', $condition);
784 $send_notification = true;
790 if ($send_notification) {
791 $params["type"] = NOTIFY_SHARE;
792 $params["verb"] = ACTIVITY_TAG;
796 // Is the user mentioned in this post?
799 foreach ($profiles AS $profile) {
800 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
804 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
805 $params["type"] = NOTIFY_TAGSELF;
806 $params["verb"] = ACTIVITY_TAG;
809 // Is it a post that the user had started or where he interacted?
810 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
811 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
812 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
814 intval($item[0]["parent"]));
816 if ($parent && !isset($params["type"])) {
817 $params["type"] = NOTIFY_COMMENT;
818 $params["verb"] = ACTIVITY_POST;
821 if (isset($params["type"]))
822 notification($params);
826 * @brief Formats a notification message with the notification author
828 * Replace the name with {0} but ensure to make that only once. The {0} is used
829 * later and prints the name in bold.
831 * @param string $name
832 * @param string $message
833 * @return string Formatted message
835 function format_notification_message($name, $message) {
837 $pos = strpos($message, $name);
842 if ($pos !== false) {
843 $message = substr_replace($message, '{0}', $pos, strlen($name));