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\DBA;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Item;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Emailer;
18 * @brief Creates a notification entry and possibly sends a mail
20 * @param array $params Array with the elements:
21 * uid, item, parent, type, otype, verb, event,
22 * link, subject, body, to_name, to_email, source_name,
23 * source_link, activity, preamble, notify_flags,
24 * language, show_in_notification_page
26 function notification($params)
30 // from here on everything is in the recipients language
31 L10n::pushLang($params['language']);
33 $banner = L10n::t('Friendica Notification');
34 $product = FRIENDICA_PLATFORM;
35 $siteurl = System::baseUrl(true);
36 $thanks = L10n::t('Thank You,');
37 $sitename = Config::get('config', 'sitename');
38 if (Config::get('config', 'admin_name')) {
39 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
41 $site_admin = L10n::t('%s Administrator', $sitename);
44 $sender_name = $sitename;
45 $hostname = $a->get_hostname();
46 if (strpos($hostname, ':')) {
47 $hostname = substr($hostname, 0, strpos($hostname, ':'));
50 $sender_email = $a->getSenderEmailAddress();
52 if ($params['type'] != SYSTEM_EMAIL) {
53 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
54 ['uid' => $params['uid']]);
56 // There is no need to create notifications for forum accounts
57 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
61 $nickname = $user["nickname"];
63 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
64 // the database, and an email is sent if applicable.
65 // default, if not specified: true
66 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
68 $additional_mail_header = "";
69 $additional_mail_header .= "Precedence: list\n";
70 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
71 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
72 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
73 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
74 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
75 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
77 if (array_key_exists('item', $params)) {
78 $title = $params['item']['title'];
79 $body = $params['item']['body'];
84 if (isset($params['item']['id'])) {
85 $item_id = $params['item']['id'];
90 if (isset($params['parent'])) {
91 $parent_id = $params['parent'];
96 if ($params['type'] == NOTIFY_MAIL) {
97 $itemlink = $siteurl.'/message/'.$params['item']['id'];
98 $params["link"] = $itemlink;
100 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
102 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
103 $epreamble = L10n::t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=$itemlink]'.L10n::t('a private message').'[/url]');
105 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
106 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
107 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
110 if ($params['type'] == NOTIFY_COMMENT) {
111 $thread = DBA::selectFirst('thread', ['ignored'], ['iid' => $parent_id]);
112 if (DBA::isResult($thread) && $thread["ignored"]) {
113 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
117 // Check to see if there was already a tag notify or comment notify for this post.
118 // If so don't create a second notification
119 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1",
120 intval(NOTIFY_TAGSELF),
121 intval(NOTIFY_COMMENT),
122 intval(NOTIFY_SHARE),
123 DBA::escape($params['link']),
124 intval($params['uid'])
126 if ($p && count($p)) {
131 // if it's a post figure out who's post it is.
135 if ($params['otype'] === 'item' && $parent_id) {
136 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
139 $item_post_type = item_post_type($item);
140 $itemlink = $item['plink'];
143 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
144 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
149 // "George Bull's post"
151 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
152 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
154 $item['author-name'],
160 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
161 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
162 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
168 // Some mail softwares relies on subject field for threading.
169 // So, we cannot have different subjects for notifications of the same thread.
170 // Before this we have the name of the replier on the subject rendering
171 // differents subjects for messages on the same thread.
173 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
175 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
176 $epreamble = $dest_str;
178 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
179 $tsitelink = sprintf($sitelink, $siteurl);
180 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
181 $itemlink = $params['link'];
184 if ($params['type'] == NOTIFY_WALL) {
185 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
187 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
188 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
189 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
193 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
194 $tsitelink = sprintf($sitelink, $siteurl);
195 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
196 $itemlink = $params['link'];
199 if ($params['type'] == NOTIFY_TAGSELF) {
200 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
202 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
203 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
204 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
208 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
209 $tsitelink = sprintf($sitelink, $siteurl);
210 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
211 $itemlink = $params['link'];
214 if ($params['type'] == NOTIFY_SHARE) {
215 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
217 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
218 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
219 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
223 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
224 $tsitelink = sprintf($sitelink, $siteurl);
225 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
226 $itemlink = $params['link'];
229 if ($params['type'] == NOTIFY_POKE) {
230 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
232 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
233 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
234 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
238 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
239 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
240 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
242 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
243 $tsitelink = sprintf($sitelink, $siteurl);
244 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
245 $itemlink = $params['link'];
248 if ($params['type'] == NOTIFY_TAGSHARE) {
249 $itemlink = $params['link'];
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>');
263 if ($params['type'] == NOTIFY_INTRO) {
264 $itemlink = $params['link'];
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>');
279 switch ($params['verb']) {
280 case ACTIVITY_FRIEND:
281 // someone started to share with user (mostly OStatus)
282 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
284 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
285 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
286 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
290 case ACTIVITY_FOLLOW:
291 // someone started to follow the user (mostly OStatus)
292 $subject = L10n::t('[Friendica:Notify] You have a new follower');
294 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
295 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
296 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
301 // ACTIVITY_REQ_FRIEND is default activity for notifications
306 if ($params['type'] == NOTIFY_SUGGEST) {
307 $itemlink = $params['link'];
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>');
326 if ($params['type'] == NOTIFY_CONFIRM) {
327 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
328 $itemlink = $params['link'];
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 } else { // ACTIVITY_FOLLOW
343 $itemlink = $params['link'];
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>');
362 if ($params['type'] == NOTIFY_SYSTEM) {
363 switch($params['event']) {
364 case "SYSTEM_REGISTER_REQUEST":
365 $itemlink = $params['link'];
366 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('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: %s\nSite Location: %s\nLogin Name: %s (%s)",
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>');
384 case "SYSTEM_DB_UPDATE_FAIL":
389 if ($params['type'] == SYSTEM_EMAIL) {
390 // not part of the notifications.
391 // it just send a mail to the user.
392 // It will be used by the system to send emails to users (like
393 // password reset, invitations and so) using one look (but without
394 // add a notification to the user, with could be inexistent)
395 $subject = $params['subject'];
397 $preamble = $params['preamble'];
399 $body = $params['body'];
405 $show_in_notification_page = false;
408 $subject .= " (".$nickname."@".$hostname.")";
412 'subject' => $subject,
413 'preamble' => $preamble,
414 'epreamble' => $epreamble,
416 'sitelink' => $sitelink,
417 'tsitelink' => $tsitelink,
418 'hsitelink' => $hsitelink,
419 'itemlink' => $itemlink
422 Addon::callHooks('enotify', $h);
424 $subject = $h['subject'];
426 $preamble = $h['preamble'];
427 $epreamble = $h['epreamble'];
431 $tsitelink = $h['tsitelink'];
432 $hsitelink = $h['hsitelink'];
433 $itemlink = $h['itemlink'];
435 if ($show_in_notification_page) {
436 logger("adding notification entry", LOGGER_DEBUG);
439 $hash = random_string();
440 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
442 if (DBA::isResult($r)) {
445 } while ($dups == true);
447 /// @TODO One statement is enough
449 $datarray['hash'] = $hash;
450 $datarray['name'] = $params['source_name'];
451 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
452 $datarray['url'] = $params['source_link'];
453 $datarray['photo'] = $params['source_photo'];
454 $datarray['date'] = DateTimeFormat::utcNow();
455 $datarray['uid'] = $params['uid'];
456 $datarray['link'] = $itemlink;
457 $datarray['iid'] = $item_id;
458 $datarray['parent'] = $parent_id;
459 $datarray['type'] = $params['type'];
460 $datarray['verb'] = $params['verb'];
461 $datarray['otype'] = $params['otype'];
462 $datarray['abort'] = false;
464 Addon::callHooks('enotify_store', $datarray);
466 if ($datarray['abort']) {
471 // create notification entry in DB
472 q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`)
473 values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
474 DBA::escape($datarray['hash']),
475 DBA::escape($datarray['name']),
476 DBA::escape($datarray['url']),
477 DBA::escape($datarray['photo']),
478 DBA::escape($datarray['date']),
479 intval($datarray['uid']),
480 DBA::escape($datarray['link']),
481 intval($datarray['iid']),
482 intval($datarray['parent']),
483 intval($datarray['type']),
484 DBA::escape($datarray['verb']),
485 DBA::escape($datarray['otype']),
486 DBA::escape($datarray["name_cache"])
489 $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1",
491 intval($params['uid'])
494 $notify_id = $r[0]['id'];
500 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
501 // After we've stored everything, look again to see if there are any duplicates and if so remove them
502 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
503 intval(NOTIFY_TAGSELF),
504 intval(NOTIFY_COMMENT),
505 DBA::escape($params['link']),
506 intval($params['uid'])
508 if ($p && (count($p) > 1)) {
509 for ($d = 1; $d < count($p); $d ++) {
510 DBA::delete('notify', ['id' => $p[$d]['id']]);
513 // only continue on if we stored the first one
514 if ($notify_id != $p[0]['id']) {
520 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
521 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
522 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
523 q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
525 DBA::escape($msg_cache),
527 intval($params['uid'])
531 // send email notification if notification preferences permit
532 if ((intval($params['notify_flags']) & intval($params['type']))
533 || $params['type'] == NOTIFY_SYSTEM
534 || $params['type'] == SYSTEM_EMAIL) {
536 logger('sending notification email');
538 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
539 $id_for_parent = $params['parent']."@".$hostname;
541 // Is this the first email notification for this parent item and user?
543 $r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
544 intval($params['parent']),
545 intval($params['uid']));
547 // If so, create the record of it and use a message-id smtp header.
550 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
551 q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
552 values(%d, %d, %d, %d)",
554 intval($params['parent']),
555 intval($params['uid']),
558 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
559 $log_msg = "include/enotify: No previous notification found for this parent:\n".
560 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
561 logger($log_msg, LOGGER_DEBUG);
563 // If not, just "follow" the thread.
564 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
565 logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG);
569 $textversion = BBCode::toPlaintext($body);
570 $htmlversion = BBCode::convert($body);
573 $datarray['banner'] = $banner;
574 $datarray['product'] = $product;
575 $datarray['preamble'] = $preamble;
576 $datarray['sitename'] = $sitename;
577 $datarray['siteurl'] = $siteurl;
578 $datarray['type'] = $params['type'];
579 $datarray['parent'] = $parent_id;
580 $datarray['source_name'] = $params['source_name'];
581 $datarray['source_link'] = $params['source_link'];
582 $datarray['source_photo'] = $params['source_photo'];
583 $datarray['uid'] = $params['uid'];
584 $datarray['username'] = $params['to_name'];
585 $datarray['hsitelink'] = $hsitelink;
586 $datarray['tsitelink'] = $tsitelink;
587 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
588 $datarray['titemlink'] = $itemlink;
589 $datarray['thanks'] = $thanks;
590 $datarray['site_admin'] = $site_admin;
591 $datarray['title'] = stripslashes($title);
592 $datarray['htmlversion'] = $htmlversion;
593 $datarray['textversion'] = $textversion;
594 $datarray['subject'] = $subject;
595 $datarray['headers'] = $additional_mail_header;
597 Addon::callHooks('enotify_mail', $datarray);
599 // check whether sending post content in email notifications is allowed
600 // always true for SYSTEM_EMAIL
601 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
603 // load the template for private message notifications
604 $tpl = get_markup_template('email_notify_html.tpl');
605 $email_html_body = replace_macros($tpl, [
606 '$banner' => $datarray['banner'],
607 '$product' => $datarray['product'],
608 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
609 '$sitename' => $datarray['sitename'],
610 '$siteurl' => $datarray['siteurl'],
611 '$source_name' => $datarray['source_name'],
612 '$source_link' => $datarray['source_link'],
613 '$source_photo' => $datarray['source_photo'],
614 '$username' => $datarray['username'],
615 '$hsitelink' => $datarray['hsitelink'],
616 '$hitemlink' => $datarray['hitemlink'],
617 '$thanks' => $datarray['thanks'],
618 '$site_admin' => $datarray['site_admin'],
619 '$title' => $datarray['title'],
620 '$htmlversion' => $datarray['htmlversion'],
621 '$content_allowed' => $content_allowed,
624 // load the template for private message notifications
625 $tpl = get_markup_template('email_notify_text.tpl');
626 $email_text_body = replace_macros($tpl, [
627 '$banner' => $datarray['banner'],
628 '$product' => $datarray['product'],
629 '$preamble' => $datarray['preamble'],
630 '$sitename' => $datarray['sitename'],
631 '$siteurl' => $datarray['siteurl'],
632 '$source_name' => $datarray['source_name'],
633 '$source_link' => $datarray['source_link'],
634 '$source_photo' => $datarray['source_photo'],
635 '$username' => $datarray['username'],
636 '$tsitelink' => $datarray['tsitelink'],
637 '$titemlink' => $datarray['titemlink'],
638 '$thanks' => $datarray['thanks'],
639 '$site_admin' => $datarray['site_admin'],
640 '$title' => $datarray['title'],
641 '$textversion' => $datarray['textversion'],
642 '$content_allowed' => $content_allowed,
645 // use the Emailer class to send the message
646 return Emailer::send(
648 'uid' => $params['uid'],
649 'fromName' => $sender_name,
650 'fromEmail' => $sender_email,
651 'replyTo' => $sender_email,
652 'toEmail' => $params['to_email'],
653 'messageSubject' => $datarray['subject'],
654 'htmlVersion' => $email_html_body,
655 'textVersion' => $email_text_body,
656 'additionalMailHeader' => $datarray['headers']]
664 * @brief Checks for users who should be notified
666 * @param int $itemid ID of the item for which the check should be done
668 function check_user_notification($itemid) {
669 // fetch all users in the thread
670 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
671 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
672 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
673 while ($user = DBA::fetch($users)) {
674 check_item_notification($itemid, $user['uid']);
680 * @brief Checks for item related notifications and sends them
682 * @param int $itemid ID of the item for which the check should be done
683 * @param int $uid User ID
684 * @param string $defaulttype (Optional) Forces a notification with this type.
686 function check_item_notification($itemid, $uid, $defaulttype = "") {
687 $notification_data = ["uid" => $uid, "profiles" => []];
688 Addon::callHooks('check_item_notification', $notification_data);
690 $profiles = $notification_data["profiles"];
692 $fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
693 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
694 if (!DBA::isResult($user)) {
698 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
699 if (!DBA::isResult($owner)) {
703 // This is our regular URL format
704 $profiles[] = $owner["url"];
706 // Notifications from Diaspora are often with an URL in the Diaspora format
707 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
711 foreach ($profiles AS $profile) {
712 // Check for invalid profile urls. 13 should be the shortest possible profile length:
714 // Additionally check for invalid urls that would return the normalised value "http:"
715 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
716 if (!in_array($profile, $profiles2))
717 $profiles2[] = $profile;
719 $profile = normalise_link($profile);
720 if (!in_array($profile, $profiles2))
721 $profiles2[] = $profile;
723 $profile = str_replace("http://", "https://", $profile);
724 if (!in_array($profile, $profiles2))
725 $profiles2[] = $profile;
729 $profiles = $profiles2;
731 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
735 while ($contact = DBA::fetch($ret)) {
736 $contacts[] = $contact['id'];
739 $contact_list = implode(',', $contacts);
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 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
746 'author-link', 'author-name', 'author-avatar', 'author-id',
747 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
748 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
749 $item = Item::selectFirst($fields, $condition);
750 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
754 // Generate the notification array
756 $params["uid"] = $uid;
757 $params["notify_flags"] = $user["notify-flags"];
758 $params["language"] = $user["language"];
759 $params["to_name"] = $user["username"];
760 $params["to_email"] = $user["email"];
761 $params["item"] = $item;
762 $params["parent"] = $item["parent"];
763 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
764 $params["otype"] = 'item';
765 $params["source_name"] = $item["author-name"];
766 $params["source_link"] = $item["author-link"];
767 $params["source_photo"] = $item["author-avatar"];
769 if ($item["parent-uri"] === $item["uri"]) {
770 // Send a notification for every new post?
771 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
773 if (!$send_notification) {
774 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
775 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
777 if (DBA::isResult($tags)) {
778 foreach ($tags AS $tag) {
779 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
780 $r = DBA::exists('contact', $condition);
782 $send_notification = true;
788 if ($send_notification) {
789 $params["type"] = NOTIFY_SHARE;
790 $params["verb"] = ACTIVITY_TAG;
794 // Is the user mentioned in this post?
797 foreach ($profiles AS $profile) {
798 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
802 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
803 $params["type"] = NOTIFY_TAGSELF;
804 $params["verb"] = ACTIVITY_TAG;
807 // Is it a post that the user had started or where he interacted?
808 $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
809 WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
810 (`thread`.`mention` OR `item`.`author-id` IN ($contact_list))
812 intval($item["parent"]));
814 if ($parent && !isset($params["type"])) {
815 $params["type"] = NOTIFY_COMMENT;
816 $params["verb"] = ACTIVITY_POST;
819 if (isset($params["type"]))
820 notification($params);
824 * @brief Formats a notification message with the notification author
826 * Replace the name with {0} but ensure to make that only once. The {0} is used
827 * later and prints the name in bold.
829 * @param string $name
830 * @param string $message
831 * @return string Formatted message
833 function format_notification_message($name, $message) {
835 $pos = strpos($message, $name);
840 if ($pos !== false) {
841 $message = substr_replace($message, '{0}', $pos, strlen($name));