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 // Temporary logging for finding the origin
31 if (!isset($params['language']) || !isset($params['uid'])) {
32 logger('Missing parameters.' . System::callstack());
35 // Ensure that the important fields are set at any time
36 $fields = ['notify-flags', 'language', 'username', 'email'];
37 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
39 if (!DBA::isResult($user)) {
40 logger('Unknown user ' . $params['uid']);
44 $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
45 $params['language'] = defaults($params, 'language', $user['language']);
46 $params['to_name'] = defaults($params, 'to_name', $user['username']);
47 $params['to_email'] = defaults($params, 'to_email', $user['email']);
49 // from here on everything is in the recipients language
50 L10n::pushLang($params['language']);
52 $banner = L10n::t('Friendica Notification');
53 $product = FRIENDICA_PLATFORM;
54 $siteurl = System::baseUrl(true);
55 $thanks = L10n::t('Thank You,');
56 $sitename = Config::get('config', 'sitename');
57 if (Config::get('config', 'admin_name')) {
58 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
60 $site_admin = L10n::t('%s Administrator', $sitename);
63 $sender_name = $sitename;
64 $hostname = $a->get_hostname();
65 if (strpos($hostname, ':')) {
66 $hostname = substr($hostname, 0, strpos($hostname, ':'));
69 $sender_email = $a->getSenderEmailAddress();
71 if ($params['type'] != SYSTEM_EMAIL) {
72 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
73 ['uid' => $params['uid']]);
75 // There is no need to create notifications for forum accounts
76 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
79 $nickname = $user["nickname"];
84 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
85 // the database, and an email is sent if applicable.
86 // default, if not specified: true
87 $show_in_notification_page = ((x($params, 'show_in_notification_page')) ? $params['show_in_notification_page']:true);
89 $additional_mail_header = "";
90 $additional_mail_header .= "Precedence: list\n";
91 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
92 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
93 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
94 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
95 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
96 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
98 if (array_key_exists('item', $params)) {
99 $title = $params['item']['title'];
100 $body = $params['item']['body'];
105 if (isset($params['item']['id'])) {
106 $item_id = $params['item']['id'];
111 if (isset($params['parent'])) {
112 $parent_id = $params['parent'];
119 if ($params['type'] == NOTIFY_MAIL) {
120 $itemlink = $siteurl.'/message/'.$params['item']['id'];
121 $params["link"] = $itemlink;
123 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
125 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
126 $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]');
128 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
129 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
130 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
133 if ($params['type'] == NOTIFY_COMMENT) {
134 $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
135 if (DBA::isResult($thread) && $thread["ignored"]) {
136 logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
140 // Check to see if there was already a tag notify or comment notify for this post.
141 // If so don't create a second notification
142 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
143 'link' => $params['link'], 'uid' => $params['uid']];
144 if (DBA::exists('notify', $condition)) {
149 // if it's a post figure out who's post it is.
153 if ($params['otype'] === 'item' && $parent_id) {
154 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
157 $item_post_type = item_post_type($item);
158 $itemlink = $item['plink'];
161 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
162 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
167 // "George Bull's post"
169 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
170 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
172 $item['author-name'],
178 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
179 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
180 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
186 // Some mail softwares relies on subject field for threading.
187 // So, we cannot have different subjects for notifications of the same thread.
188 // Before this we have the name of the replier on the subject rendering
189 // differents subjects for messages on the same thread.
191 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
193 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
194 $epreamble = $dest_str;
196 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
197 $tsitelink = sprintf($sitelink, $siteurl);
198 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
199 $itemlink = $params['link'];
202 if ($params['type'] == NOTIFY_WALL) {
203 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
205 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
206 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
207 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
211 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
212 $tsitelink = sprintf($sitelink, $siteurl);
213 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
214 $itemlink = $params['link'];
217 if ($params['type'] == NOTIFY_TAGSELF) {
218 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
220 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
221 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
222 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
226 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
227 $tsitelink = sprintf($sitelink, $siteurl);
228 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
229 $itemlink = $params['link'];
232 if ($params['type'] == NOTIFY_SHARE) {
233 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
235 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
236 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
237 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
241 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
242 $tsitelink = sprintf($sitelink, $siteurl);
243 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
244 $itemlink = $params['link'];
247 if ($params['type'] == NOTIFY_POKE) {
248 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
250 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
251 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
252 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
256 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
257 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
258 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
260 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
261 $tsitelink = sprintf($sitelink, $siteurl);
262 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
263 $itemlink = $params['link'];
266 if ($params['type'] == NOTIFY_TAGSHARE) {
267 $itemlink = $params['link'];
268 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
270 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
271 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
272 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
276 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
277 $tsitelink = sprintf($sitelink, $siteurl);
278 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
281 if ($params['type'] == NOTIFY_INTRO) {
282 $itemlink = $params['link'];
283 $subject = L10n::t('[Friendica:Notify] Introduction received');
285 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
286 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
288 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
291 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
293 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
294 $tsitelink = sprintf($sitelink, $siteurl);
295 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
297 switch ($params['verb']) {
298 case ACTIVITY_FRIEND:
299 // someone started to share with user (mostly OStatus)
300 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
302 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
303 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
304 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
308 case ACTIVITY_FOLLOW:
309 // someone started to follow the user (mostly OStatus)
310 $subject = L10n::t('[Friendica:Notify] You have a new follower');
312 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
313 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
314 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
319 // ACTIVITY_REQ_FRIEND is default activity for notifications
324 if ($params['type'] == NOTIFY_SUGGEST) {
325 $itemlink = $params['link'];
326 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
328 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
329 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
331 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
332 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
335 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
336 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
337 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
339 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
340 $tsitelink = sprintf($sitelink, $siteurl);
341 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
344 if ($params['type'] == NOTIFY_CONFIRM) {
345 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
346 $itemlink = $params['link'];
347 $subject = L10n::t('[Friendica:Notify] Connection accepted');
349 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
350 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
352 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
355 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
357 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
358 $tsitelink = sprintf($sitelink, $siteurl);
359 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
360 } else { // ACTIVITY_FOLLOW
361 $itemlink = $params['link'];
362 $subject = L10n::t('[Friendica:Notify] Connection accepted');
364 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
365 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
367 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
370 $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']);
372 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
374 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
375 $tsitelink = sprintf($sitelink, $siteurl);
376 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
380 if ($params['type'] == NOTIFY_SYSTEM) {
381 switch($params['event']) {
382 case "SYSTEM_REGISTER_REQUEST":
383 $itemlink = $params['link'];
384 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
386 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
387 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
389 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
392 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
393 $params['source_name'],
394 $siteurl, $params['source_mail'],
395 $params['source_nick']
398 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
399 $tsitelink = sprintf($sitelink, $params['link']);
400 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
402 case "SYSTEM_DB_UPDATE_FAIL":
407 if ($params['type'] == SYSTEM_EMAIL) {
408 // not part of the notifications.
409 // it just send a mail to the user.
410 // It will be used by the system to send emails to users (like
411 // password reset, invitations and so) using one look (but without
412 // add a notification to the user, with could be inexistent)
413 $subject = $params['subject'];
415 $preamble = $params['preamble'];
417 $body = $params['body'];
423 $show_in_notification_page = false;
426 $subject .= " (".$nickname."@".$hostname.")";
430 'subject' => $subject,
431 'preamble' => $preamble,
432 'epreamble' => $epreamble,
434 'sitelink' => $sitelink,
435 'tsitelink' => $tsitelink,
436 'hsitelink' => $hsitelink,
437 'itemlink' => $itemlink
440 Addon::callHooks('enotify', $h);
442 $subject = $h['subject'];
444 $preamble = $h['preamble'];
445 $epreamble = $h['epreamble'];
449 $tsitelink = $h['tsitelink'];
450 $hsitelink = $h['hsitelink'];
451 $itemlink = $h['itemlink'];
453 if ($show_in_notification_page) {
454 logger("adding notification entry", LOGGER_DEBUG);
457 $hash = random_string();
458 if (DBA::exists('notify', ['hash' => $hash])) {
461 } while ($dups == true);
463 /// @TODO One statement is enough
465 $datarray['hash'] = $hash;
466 $datarray['name'] = $params['source_name'];
467 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
468 $datarray['url'] = $params['source_link'];
469 $datarray['photo'] = $params['source_photo'];
470 $datarray['date'] = DateTimeFormat::utcNow();
471 $datarray['uid'] = $params['uid'];
472 $datarray['link'] = $itemlink;
473 $datarray['iid'] = $item_id;
474 $datarray['parent'] = $parent_id;
475 $datarray['type'] = $params['type'];
476 $datarray['verb'] = $params['verb'];
477 $datarray['otype'] = $params['otype'];
478 $datarray['abort'] = false;
480 Addon::callHooks('enotify_store', $datarray);
482 if ($datarray['abort']) {
487 // create notification entry in DB
488 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
489 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
490 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
491 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
492 'name_cache' => $datarray["name_cache"]];
493 DBA::insert('notify', $fields);
495 $notify_id = DBA::lastInsertId();
497 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
498 // After we've stored everything, look again to see if there are any duplicates and if so remove them
499 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
500 intval(NOTIFY_TAGSELF),
501 intval(NOTIFY_COMMENT),
502 DBA::escape($params['link']),
503 intval($params['uid'])
505 if ($p && (count($p) > 1)) {
506 for ($d = 1; $d < count($p); $d ++) {
507 DBA::delete('notify', ['id' => $p[$d]['id']]);
510 // only continue on if we stored the first one
511 if ($notify_id != $p[0]['id']) {
517 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
518 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
519 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
521 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
522 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
523 DBA::update('notify', $fields, $condition);
526 // send email notification if notification preferences permit
527 if ((intval($params['notify_flags']) & intval($params['type']))
528 || $params['type'] == NOTIFY_SYSTEM
529 || $params['type'] == SYSTEM_EMAIL) {
531 logger('sending notification email');
533 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
534 $id_for_parent = $params['parent']."@".$hostname;
536 // Is this the first email notification for this parent item and user?
537 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
538 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
540 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
541 'receiver-uid' => $params['uid'], 'parent-item' => 0];
542 DBA::insert('notify-threads', $fields);
544 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
545 $log_msg = "include/enotify: No previous notification found for this parent:\n".
546 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
547 logger($log_msg, LOGGER_DEBUG);
549 // If not, just "follow" the thread.
550 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
551 logger("There's already a notification for this parent.", LOGGER_DEBUG);
555 $textversion = BBCode::toPlaintext($body);
556 $htmlversion = BBCode::convert($body);
559 $datarray['banner'] = $banner;
560 $datarray['product'] = $product;
561 $datarray['preamble'] = $preamble;
562 $datarray['sitename'] = $sitename;
563 $datarray['siteurl'] = $siteurl;
564 $datarray['type'] = $params['type'];
565 $datarray['parent'] = $parent_id;
566 $datarray['source_name'] = defaults($params, 'source_name', '');
567 $datarray['source_link'] = defaults($params, 'source_link', '');
568 $datarray['source_photo'] = defaults($params, 'source_photo', '');
569 $datarray['uid'] = $params['uid'];
570 $datarray['username'] = defaults($params, 'to_name', '');
571 $datarray['hsitelink'] = $hsitelink;
572 $datarray['tsitelink'] = $tsitelink;
573 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
574 $datarray['titemlink'] = $itemlink;
575 $datarray['thanks'] = $thanks;
576 $datarray['site_admin'] = $site_admin;
577 $datarray['title'] = stripslashes($title);
578 $datarray['htmlversion'] = $htmlversion;
579 $datarray['textversion'] = $textversion;
580 $datarray['subject'] = $subject;
581 $datarray['headers'] = $additional_mail_header;
583 Addon::callHooks('enotify_mail', $datarray);
585 // check whether sending post content in email notifications is allowed
586 // always true for SYSTEM_EMAIL
587 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
589 // load the template for private message notifications
590 $tpl = get_markup_template('email_notify_html.tpl');
591 $email_html_body = replace_macros($tpl, [
592 '$banner' => $datarray['banner'],
593 '$product' => $datarray['product'],
594 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
595 '$sitename' => $datarray['sitename'],
596 '$siteurl' => $datarray['siteurl'],
597 '$source_name' => $datarray['source_name'],
598 '$source_link' => $datarray['source_link'],
599 '$source_photo' => $datarray['source_photo'],
600 '$username' => $datarray['username'],
601 '$hsitelink' => $datarray['hsitelink'],
602 '$hitemlink' => $datarray['hitemlink'],
603 '$thanks' => $datarray['thanks'],
604 '$site_admin' => $datarray['site_admin'],
605 '$title' => $datarray['title'],
606 '$htmlversion' => $datarray['htmlversion'],
607 '$content_allowed' => $content_allowed,
610 // load the template for private message notifications
611 $tpl = get_markup_template('email_notify_text.tpl');
612 $email_text_body = replace_macros($tpl, [
613 '$banner' => $datarray['banner'],
614 '$product' => $datarray['product'],
615 '$preamble' => $datarray['preamble'],
616 '$sitename' => $datarray['sitename'],
617 '$siteurl' => $datarray['siteurl'],
618 '$source_name' => $datarray['source_name'],
619 '$source_link' => $datarray['source_link'],
620 '$source_photo' => $datarray['source_photo'],
621 '$username' => $datarray['username'],
622 '$tsitelink' => $datarray['tsitelink'],
623 '$titemlink' => $datarray['titemlink'],
624 '$thanks' => $datarray['thanks'],
625 '$site_admin' => $datarray['site_admin'],
626 '$title' => $datarray['title'],
627 '$textversion' => $datarray['textversion'],
628 '$content_allowed' => $content_allowed,
631 // use the Emailer class to send the message
632 return Emailer::send(
634 'uid' => $params['uid'],
635 'fromName' => $sender_name,
636 'fromEmail' => $sender_email,
637 'replyTo' => $sender_email,
638 'toEmail' => $params['to_email'],
639 'messageSubject' => $datarray['subject'],
640 'htmlVersion' => $email_html_body,
641 'textVersion' => $email_text_body,
642 'additionalMailHeader' => $datarray['headers']]
650 * @brief Checks for users who should be notified
652 * @param int $itemid ID of the item for which the check should be done
654 function check_user_notification($itemid) {
655 // fetch all users in the thread
656 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
657 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
658 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
659 while ($user = DBA::fetch($users)) {
660 check_item_notification($itemid, $user['uid']);
666 * @brief Checks for item related notifications and sends them
668 * @param int $itemid ID of the item for which the check should be done
669 * @param int $uid User ID
670 * @param string $defaulttype (Optional) Forces a notification with this type.
672 function check_item_notification($itemid, $uid, $defaulttype = "") {
673 $notification_data = ["uid" => $uid, "profiles" => []];
674 Addon::callHooks('check_item_notification', $notification_data);
676 $profiles = $notification_data["profiles"];
678 $fields = ['nickname'];
679 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
680 if (!DBA::isResult($user)) {
684 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
685 if (!DBA::isResult($owner)) {
689 // This is our regular URL format
690 $profiles[] = $owner["url"];
692 // Notifications from Diaspora are often with an URL in the Diaspora format
693 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
697 foreach ($profiles AS $profile) {
698 // Check for invalid profile urls. 13 should be the shortest possible profile length:
700 // Additionally check for invalid urls that would return the normalised value "http:"
701 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
702 if (!in_array($profile, $profiles2))
703 $profiles2[] = $profile;
705 $profile = normalise_link($profile);
706 if (!in_array($profile, $profiles2))
707 $profiles2[] = $profile;
709 $profile = str_replace("http://", "https://", $profile);
710 if (!in_array($profile, $profiles2))
711 $profiles2[] = $profile;
715 $profiles = $profiles2;
717 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
721 while ($contact = DBA::fetch($ret)) {
722 $contacts[] = $contact['id'];
727 // Only act if it is a "real" post
728 // We need the additional check for the "local_profile" because of mixed situations on connector networks
729 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
730 'author-link', 'author-name', 'author-avatar', 'author-id',
731 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
732 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
733 $item = Item::selectFirst($fields, $condition);
734 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
738 // Generate the notification array
740 $params["uid"] = $uid;
741 $params["item"] = $item;
742 $params["parent"] = $item["parent"];
743 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
744 $params["otype"] = 'item';
745 $params["source_name"] = $item["author-name"];
746 $params["source_link"] = $item["author-link"];
747 $params["source_photo"] = $item["author-avatar"];
749 if ($item["parent-uri"] === $item["uri"]) {
750 // Send a notification for every new post?
751 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
753 if (!$send_notification) {
754 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
755 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
757 if (DBA::isResult($tags)) {
758 foreach ($tags AS $tag) {
759 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
760 $r = DBA::exists('contact', $condition);
762 $send_notification = true;
768 if ($send_notification) {
769 $params["type"] = NOTIFY_SHARE;
770 $params["verb"] = ACTIVITY_TAG;
774 // Is the user mentioned in this post?
777 foreach ($profiles AS $profile) {
778 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
782 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
783 $params["type"] = NOTIFY_TAGSELF;
784 $params["verb"] = ACTIVITY_TAG;
787 // Is it a post that the user had started?
788 $fields = ['ignored', 'mention'];
789 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
791 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
792 $params["type"] = NOTIFY_COMMENT;
793 $params["verb"] = ACTIVITY_POST;
796 // And now we check for participation of one of our contacts in the thread
797 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
799 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
800 $params["type"] = NOTIFY_COMMENT;
801 $params["verb"] = ACTIVITY_POST;
804 if (isset($params["type"])) {
805 notification($params);
810 * @brief Formats a notification message with the notification author
812 * Replace the name with {0} but ensure to make that only once. The {0} is used
813 * later and prints the name in bold.
815 * @param string $name
816 * @param string $message
817 * @return string Formatted message
819 function format_notification_message($name, $message) {
821 $pos = strpos($message, $name);
826 if ($pos !== false) {
827 $message = substr_replace($message, '{0}', $pos, strlen($name));