3 * @file include/enotify.php
6 use Friendica\Core\Addon;
7 use Friendica\Core\Config;
8 use Friendica\Core\System;
9 use Friendica\Database\DBM;
10 use Friendica\Util\Emailer;
12 require_once 'include/bbcode.php';
13 require_once 'include/html2bbcode.php';
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 push_lang($params['language']);
31 $banner = t('Friendica Notification');
32 $product = FRIENDICA_PLATFORM;
33 $siteurl = System::baseUrl(true);
34 $thanks = t('Thank You,');
35 $sitename = $a->config['sitename'];
36 if (!x($a->config['admin_name'])) {
37 $site_admin = sprintf(t('%s Administrator'), $sitename);
39 $site_admin = sprintf(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 = 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 = sprintf(t('[Friendica:Notify] New mail received at %s'), $sitename);
100 $preamble = sprintf(t('%1$s sent you a new private message at %2$s.'), $params['source_name'], $sitename);
101 $epreamble = sprintf(t('%1$s sent you %2$s.'), '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.t('a private message').'[/url]');
103 $sitelink = 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 = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
142 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
146 // "George Bull's post"
148 $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
149 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
151 $item['author-name'],
156 if (DBM::is_result($item) && $item['owner-name'] == $item['author-name'] && $item['wall']) {
157 $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
158 '[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 = sprintf(t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
170 $preamble = sprintf(t('%s commented on an item/conversation you have been following.'), $params['source_name']);
171 $epreamble = $dest_str;
173 $sitelink = 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 = sprintf(t('[Friendica:Notify] %s posted to your profile wall'), $params['source_name']);
182 $preamble = sprintf(t('%1$s posted to your profile wall at %2$s'), $params['source_name'], $sitename);
183 $epreamble = sprintf(t('%1$s posted to [url=%2$s]your wall[/url]'),
184 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
187 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
188 $tsitelink = sprintf($sitelink, $siteurl);
189 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
190 $itemlink = $params['link'];
193 if ($params['type'] == NOTIFY_TAGSELF) {
194 $subject = sprintf(t('[Friendica:Notify] %s tagged you'), $params['source_name']);
196 $preamble = sprintf(t('%1$s tagged you at %2$s'), $params['source_name'], $sitename);
197 $epreamble = sprintf(t('%1$s [url=%2$s]tagged you[/url].'),
198 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
201 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
202 $tsitelink = sprintf($sitelink, $siteurl);
203 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
204 $itemlink = $params['link'];
207 if ($params['type'] == NOTIFY_SHARE) {
208 $subject = sprintf(t('[Friendica:Notify] %s shared a new post'), $params['source_name']);
210 $preamble = sprintf(t('%1$s shared a new post at %2$s'), $params['source_name'], $sitename);
211 $epreamble = sprintf(t('%1$s [url=%2$s]shared a post[/url].'),
212 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
215 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
216 $tsitelink = sprintf($sitelink, $siteurl);
217 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
218 $itemlink = $params['link'];
221 if ($params['type'] == NOTIFY_POKE) {
222 $subject = sprintf(t('[Friendica:Notify] %1$s poked you'), $params['source_name']);
224 $preamble = sprintf(t('%1$s poked you at %2$s'), $params['source_name'], $sitename);
225 $epreamble = sprintf(t('%1$s [url=%2$s]poked you[/url].'),
226 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
229 $subject = str_replace('poked', t($params['activity']), $subject);
230 $preamble = str_replace('poked', t($params['activity']), $preamble);
231 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
233 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
234 $tsitelink = sprintf($sitelink, $siteurl);
235 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
236 $itemlink = $params['link'];
239 if ($params['type'] == NOTIFY_TAGSHARE) {
240 $subject = sprintf(t('[Friendica:Notify] %s tagged your post'), $params['source_name']);
242 $preamble = sprintf(t('%1$s tagged your post at %2$s'), $params['source_name'], $sitename);
243 $epreamble = sprintf(t('%1$s tagged [url=%2$s]your post[/url]'),
244 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
247 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
248 $tsitelink = sprintf($sitelink, $siteurl);
249 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
250 $itemlink = $params['link'];
253 if ($params['type'] == NOTIFY_INTRO) {
254 $subject = sprintf(t('[Friendica:Notify] Introduction received'));
256 $preamble = sprintf(t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
257 $epreamble = sprintf(t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
259 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
261 $body = sprintf(t('You may visit their profile at %s'), $params['source_link']);
263 $sitelink = t('Please visit %s to approve or reject the introduction.');
264 $tsitelink = sprintf($sitelink, $siteurl);
265 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
266 $itemlink = $params['link'];
268 switch ($params['verb']) {
269 case ACTIVITY_FRIEND:
270 // someone started to share with user (mostly OStatus)
271 $subject = sprintf(t('[Friendica:Notify] A new person is sharing with you'));
273 $preamble = sprintf(t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
274 $epreamble = sprintf(t('%1$s is sharing with you at %2$s'),
275 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
278 case ACTIVITY_FOLLOW:
279 // someone started to follow the user (mostly OStatus)
280 $subject = sprintf(t('[Friendica:Notify] You have a new follower'));
282 $preamble = sprintf(t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
283 $epreamble = sprintf(t('You have a new follower at %2$s : %1$s'),
284 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
288 // ACTIVITY_REQ_FRIEND is default activity for notifications
293 if ($params['type'] == NOTIFY_SUGGEST) {
294 $subject = sprintf(t('[Friendica:Notify] Friend suggestion received'));
296 $preamble = sprintf(t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
297 $epreamble = sprintf(t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
299 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
300 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
302 $body = t('Name:').' '.$params['item']['name']."\n";
303 $body .= t('Photo:').' '.$params['item']['photo']."\n";
304 $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
306 $sitelink = t('Please visit %s to approve or reject the suggestion.');
307 $tsitelink = sprintf($sitelink, $siteurl);
308 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
309 $itemlink = $params['link'];
312 if ($params['type'] == NOTIFY_CONFIRM) {
313 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
314 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
316 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
317 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
319 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
321 $body = t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
323 $sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
324 $tsitelink = sprintf($sitelink, $siteurl);
325 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
326 $itemlink = $params['link'];
327 } else { // ACTIVITY_FOLLOW
328 $subject = sprintf(t('[Friendica:Notify] Connection accepted'));
330 $preamble = sprintf(t('\'%1$s\' has accepted your connection request at %2$s'), $params['source_name'], $sitename);
331 $epreamble = sprintf(t('%2$s has accepted your [url=%1$s]connection request[/url].'),
333 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
335 $body = sprintf(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']);
337 $body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.'), $params['source_name']);
339 $sitelink = 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'];
346 if ($params['type'] == NOTIFY_SYSTEM) {
347 switch($params['event']) {
348 case "SYSTEM_REGISTER_REQUEST":
349 $subject = sprintf(t('[Friendica System:Notify] registration request'));
351 $preamble = sprintf(t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
352 $epreamble = sprintf(t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
354 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]');
356 $body = sprintf(t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
357 $params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
359 $sitelink = t('Please visit %s to approve or reject the request.');
360 $tsitelink = sprintf($sitelink, $params['link']);
361 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
362 $itemlink = $params['link'];
364 case "SYSTEM_DB_UPDATE_FAIL":
369 if ($params['type'] == SYSTEM_EMAIL) {
370 // not part of the notifications.
371 // it just send a mail to the user.
372 // It will be used by the system to send emails to users (like
373 // password reset, invitations and so) using one look (but without
374 // add a notification to the user, with could be inexistent)
375 $subject = $params['subject'];
377 $preamble = $params['preamble'];
379 $body = $params['body'];
385 $show_in_notification_page = false;
388 $subject .= " (".$nickname."@".$hostname.")";
392 'subject' => $subject,
393 'preamble' => $preamble,
394 'epreamble' => $epreamble,
396 'sitelink' => $sitelink,
397 'tsitelink' => $tsitelink,
398 'hsitelink' => $hsitelink,
399 'itemlink' => $itemlink
402 Addon::callHooks('enotify', $h);
404 $subject = $h['subject'];
406 $preamble = $h['preamble'];
407 $epreamble = $h['epreamble'];
411 $tsitelink = $h['tsitelink'];
412 $hsitelink = $h['hsitelink'];
413 $itemlink = $h['itemlink'];
415 if ($show_in_notification_page) {
416 logger("adding notification entry", LOGGER_DEBUG);
419 $hash = random_string();
420 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
422 if (DBM::is_result($r)) {
425 } while ($dups == true);
427 /// @TODO One statement is enough
429 $datarray['hash'] = $hash;
430 $datarray['name'] = $params['source_name'];
431 $datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
432 $datarray['url'] = $params['source_link'];
433 $datarray['photo'] = $params['source_photo'];
434 $datarray['date'] = datetime_convert();
435 $datarray['uid'] = $params['uid'];
436 $datarray['link'] = $itemlink;
437 $datarray['iid'] = $item_id;
438 $datarray['parent'] = $parent_id;
439 $datarray['type'] = $params['type'];
440 $datarray['verb'] = $params['verb'];
441 $datarray['otype'] = $params['otype'];
442 $datarray['abort'] = false;
444 Addon::callHooks('enotify_store', $datarray);
446 if ($datarray['abort']) {
451 // create notification entry in DB
452 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
453 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
454 dbesc($datarray['hash']),
455 dbesc($datarray['name']),
456 dbesc($datarray['url']),
457 dbesc($datarray['photo']),
458 dbesc($datarray['date']),
459 intval($datarray['uid']),
460 dbesc($datarray['link']),
461 intval($datarray['iid']),
462 intval($datarray['parent']),
463 intval($datarray['type']),
464 dbesc($datarray['verb']),
465 dbesc($datarray['otype']),
466 dbesc($datarray["name_cache"])
469 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
471 intval($params['uid'])
474 $notify_id = $r[0]['id'];
480 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
481 // After we've stored everything, look again to see if there are any duplicates and if so remove them
482 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
483 intval(NOTIFY_TAGSELF),
484 intval(NOTIFY_COMMENT),
485 dbesc($params['link']),
486 intval($params['uid'])
488 if ($p && (count($p) > 1)) {
489 for ($d = 1; $d < count($p); $d ++) {
490 dba::delete('notify', ['id' => $p[$d]['id']]);
493 // only continue on if we stored the first one
494 if ($notify_id != $p[0]['id']) {
500 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
501 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
502 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(bbcode($msg)));
503 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
507 intval($params['uid'])
511 // send email notification if notification preferences permit
512 if ((intval($params['notify_flags']) & intval($params['type']))
513 || $params['type'] == NOTIFY_SYSTEM
514 || $params['type'] == SYSTEM_EMAIL) {
516 logger('sending notification email');
518 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
519 $id_for_parent = $params['parent']."@".$hostname;
521 // Is this the first email notification for this parent item and user?
523 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
524 intval($params['parent']),
525 intval($params['uid']));
527 // If so, create the record of it and use a message-id smtp header.
530 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
531 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
532 values(%d, %d, %d, %d)",
534 intval($params['parent']),
535 intval($params['uid']),
538 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
539 $log_msg = "include/enotify: No previous notification found for this parent:\n".
540 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
541 logger($log_msg, LOGGER_DEBUG);
543 // If not, just "follow" the thread.
544 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
545 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
549 // textversion keeps linebreaks
550 $textversion = strip_tags(str_replace("<br>", "\n", html_entity_decode(bbcode(stripslashes(str_replace(["\\r\\n", "\\r", "\\n"], "\n",
551 $body))),ENT_QUOTES, 'UTF-8')));
552 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(["\\r\\n", "\\r", "\\n\\n", "\\n"],
553 "<br />\n", $body))), ENT_QUOTES, 'UTF-8');
556 $datarray['banner'] = $banner;
557 $datarray['product'] = $product;
558 $datarray['preamble'] = $preamble;
559 $datarray['sitename'] = $sitename;
560 $datarray['siteurl'] = $siteurl;
561 $datarray['type'] = $params['type'];
562 $datarray['parent'] = $params['parent'];
563 $datarray['source_name'] = $params['source_name'];
564 $datarray['source_link'] = $params['source_link'];
565 $datarray['source_photo'] = $params['source_photo'];
566 $datarray['uid'] = $params['uid'];
567 $datarray['username'] = $params['to_name'];
568 $datarray['hsitelink'] = $hsitelink;
569 $datarray['tsitelink'] = $tsitelink;
570 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
571 $datarray['titemlink'] = $itemlink;
572 $datarray['thanks'] = $thanks;
573 $datarray['site_admin'] = $site_admin;
574 $datarray['title'] = stripslashes($title);
575 $datarray['htmlversion'] = $htmlversion;
576 $datarray['textversion'] = $textversion;
577 $datarray['subject'] = $subject;
578 $datarray['headers'] = $additional_mail_header;
580 Addon::callHooks('enotify_mail', $datarray);
582 // check whether sending post content in email notifications is allowed
583 // always true for SYSTEM_EMAIL
584 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
586 // load the template for private message notifications
587 $tpl = get_markup_template('email_notify_html.tpl');
588 $email_html_body = replace_macros($tpl, [
589 '$banner' => $datarray['banner'],
590 '$product' => $datarray['product'],
591 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
592 '$sitename' => $datarray['sitename'],
593 '$siteurl' => $datarray['siteurl'],
594 '$source_name' => $datarray['source_name'],
595 '$source_link' => $datarray['source_link'],
596 '$source_photo' => $datarray['source_photo'],
597 '$username' => $datarray['to_name'],
598 '$hsitelink' => $datarray['hsitelink'],
599 '$hitemlink' => $datarray['hitemlink'],
600 '$thanks' => $datarray['thanks'],
601 '$site_admin' => $datarray['site_admin'],
602 '$title' => $datarray['title'],
603 '$htmlversion' => $datarray['htmlversion'],
604 '$content_allowed' => $content_allowed,
607 // load the template for private message notifications
608 $tpl = get_markup_template('email_notify_text.tpl');
609 $email_text_body = replace_macros($tpl, [
610 '$banner' => $datarray['banner'],
611 '$product' => $datarray['product'],
612 '$preamble' => $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 '$tsitelink' => $datarray['tsitelink'],
620 '$titemlink' => $datarray['titemlink'],
621 '$thanks' => $datarray['thanks'],
622 '$site_admin' => $datarray['site_admin'],
623 '$title' => $datarray['title'],
624 '$textversion' => $datarray['textversion'],
625 '$content_allowed' => $content_allowed,
628 // use the Emailer class to send the message
629 return Emailer::send(
631 'uid' => $params['uid'],
632 'fromName' => $sender_name,
633 'fromEmail' => $sender_email,
634 'replyTo' => $sender_email,
635 'toEmail' => $params['to_email'],
636 'messageSubject' => $datarray['subject'],
637 'htmlVersion' => $email_html_body,
638 'textVersion' => $email_text_body,
639 'additionalMailHeader' => $datarray['headers']]
647 * @brief Checks for users who should be notified
649 * @param int $itemid ID of the item for which the check should be done
651 function check_user_notification($itemid) {
652 // fetch all users in the thread
653 $users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
654 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
655 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
656 while ($user = dba::fetch($users)) {
657 check_item_notification($itemid, $user['uid']);
663 * @brief Checks for item related notifications and sends them
665 * @param int $itemid ID of the item for which the check should be done
666 * @param int $uid User ID
667 * @param str $defaulttype (Optional) Forces a notification with this type.
669 function check_item_notification($itemid, $uid, $defaulttype = "") {
670 $notification_data = ["uid" => $uid, "profiles" => []];
671 Addon::callHooks('check_item_notification', $notification_data);
673 $profiles = $notification_data["profiles"];
675 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
676 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
677 if (!DBM::is_result($user)) {
681 $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
682 if (!DBM::is_result($owner)) {
686 // This is our regular URL format
687 $profiles[] = $owner["url"];
689 // Notifications from Diaspora are often with an URL in the Diaspora format
690 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
694 foreach ($profiles AS $profile) {
695 // Check for invalid profile urls. 13 should be the shortest possible profile length:
697 // Additionally check for invalid urls that would return the normalised value "http:"
698 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
699 if (!in_array($profile, $profiles2))
700 $profiles2[] = $profile;
702 $profile = normalise_link($profile);
703 if (!in_array($profile, $profiles2))
704 $profiles2[] = $profile;
706 $profile = str_replace("http://", "https://", $profile);
707 if (!in_array($profile, $profiles2))
708 $profiles2[] = $profile;
712 $profiles = $profiles2;
716 foreach ($profiles AS $profile) {
717 if ($profile_list != "")
718 $profile_list .= "', '";
720 $profile_list .= dbesc($profile);
723 $profile_list = "'".$profile_list."'";
725 // Only act if it is a "real" post
726 // We need the additional check for the "local_profile" because of mixed situations on connector networks
727 $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
728 `parent-uri`, `uri`, `contact-id`
729 FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
730 NOT (`author-link` IN ($profile_list)) LIMIT 1",
731 intval($itemid), dbesc(ACTIVITY_POST));
735 // Generate the notification array
737 $params["uid"] = $uid;
738 $params["notify_flags"] = $user["notify-flags"];
739 $params["language"] = $user["language"];
740 $params["to_name"] = $user["username"];
741 $params["to_email"] = $user["email"];
742 $params["item"] = $item[0];
743 $params["parent"] = $item[0]["parent"];
744 $params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
745 $params["otype"] = 'item';
746 $params["source_name"] = $item[0]["author-name"];
747 $params["source_link"] = $item[0]["author-link"];
748 $params["source_photo"] = $item[0]["author-avatar"];
750 if ($item[0]["parent-uri"] === $item[0]["uri"]) {
751 // Send a notification for every new post?
752 $send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
754 if (!$send_notification) {
755 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
756 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
758 if (DBM::is_result($tags)) {
759 foreach ($tags AS $tag) {
760 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
761 $r = dba::exists('contact', $condition);
763 $send_notification = true;
769 if ($send_notification) {
770 $params["type"] = NOTIFY_SHARE;
771 $params["verb"] = ACTIVITY_TAG;
775 // Is the user mentioned in this post?
778 foreach ($profiles AS $profile) {
779 if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
783 if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
784 $params["type"] = NOTIFY_TAGSELF;
785 $params["verb"] = ACTIVITY_TAG;
788 // Is it a post that the user had started or where he interacted?
789 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
790 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
791 (`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
793 intval($item[0]["parent"]));
795 if ($parent && !isset($params["type"])) {
796 $params["type"] = NOTIFY_COMMENT;
797 $params["verb"] = ACTIVITY_POST;
800 if (isset($params["type"]))
801 notification($params);
805 * @brief Formats a notification message with the notification author
807 * Replace the name with {0} but ensure to make that only once. The {0} is used
808 * later and prints the name in bold.
810 * @param string $name
811 * @param string $message
812 * @return string Formatted message
814 function format_notification_message($name, $message) {
816 $pos = strpos($message, $name);
821 if ($pos !== false) {
822 $message = substr_replace($message, '{0}', $pos, strlen($name));