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->getHostName();
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 = isset($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);
141 // Check to see if there was already a tag notify or comment notify for this post.
142 // If so don't create a second notification
143 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
144 'link' => $params['link'], 'uid' => $params['uid']];
145 if (DBA::exists('notify', $condition)) {
150 // if it's a post figure out who's post it is.
154 if ($params['otype'] === 'item' && $parent_id) {
155 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
158 $item_post_type = item_post_type($item);
159 $itemlink = $item['plink'];
162 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
163 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
168 // "George Bull's post"
170 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
171 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
173 $item['author-name'],
179 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
180 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
181 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
187 // Some mail softwares relies on subject field for threading.
188 // So, we cannot have different subjects for notifications of the same thread.
189 // Before this we have the name of the replier on the subject rendering
190 // differents subjects for messages on the same thread.
192 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
194 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
195 $epreamble = $dest_str;
197 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
198 $tsitelink = sprintf($sitelink, $siteurl);
199 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
200 $itemlink = $params['link'];
203 if ($params['type'] == NOTIFY_WALL) {
204 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
206 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
207 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
208 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
212 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
213 $tsitelink = sprintf($sitelink, $siteurl);
214 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
215 $itemlink = $params['link'];
218 if ($params['type'] == NOTIFY_TAGSELF) {
219 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
221 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
222 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
223 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
227 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
228 $tsitelink = sprintf($sitelink, $siteurl);
229 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
230 $itemlink = $params['link'];
233 if ($params['type'] == NOTIFY_SHARE) {
234 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
236 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
237 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
238 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
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_POKE) {
249 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
251 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
252 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
253 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
257 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
258 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
259 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
261 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
262 $tsitelink = sprintf($sitelink, $siteurl);
263 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
264 $itemlink = $params['link'];
267 if ($params['type'] == NOTIFY_TAGSHARE) {
268 $itemlink = $params['link'];
269 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
271 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
272 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
273 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
277 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
278 $tsitelink = sprintf($sitelink, $siteurl);
279 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
282 if ($params['type'] == NOTIFY_INTRO) {
283 $itemlink = $params['link'];
284 $subject = L10n::t('[Friendica:Notify] Introduction received');
286 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
287 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
289 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
292 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
294 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
295 $tsitelink = sprintf($sitelink, $siteurl);
296 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
298 switch ($params['verb']) {
299 case ACTIVITY_FRIEND:
300 // someone started to share with user (mostly OStatus)
301 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
303 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
304 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
305 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
309 case ACTIVITY_FOLLOW:
310 // someone started to follow the user (mostly OStatus)
311 $subject = L10n::t('[Friendica:Notify] You have a new follower');
313 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
314 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
315 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
320 // ACTIVITY_REQ_FRIEND is default activity for notifications
325 if ($params['type'] == NOTIFY_SUGGEST) {
326 $itemlink = $params['link'];
327 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
329 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
330 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
332 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
333 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
336 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
337 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
338 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
340 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
341 $tsitelink = sprintf($sitelink, $siteurl);
342 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
345 if ($params['type'] == NOTIFY_CONFIRM) {
346 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
347 $itemlink = $params['link'];
348 $subject = L10n::t('[Friendica:Notify] Connection accepted');
350 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
351 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
353 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
356 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
358 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
359 $tsitelink = sprintf($sitelink, $siteurl);
360 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
361 } else { // ACTIVITY_FOLLOW
362 $itemlink = $params['link'];
363 $subject = L10n::t('[Friendica:Notify] Connection accepted');
365 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
366 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
368 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
371 $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']);
373 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
375 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
376 $tsitelink = sprintf($sitelink, $siteurl);
377 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
381 if ($params['type'] == NOTIFY_SYSTEM) {
382 switch($params['event']) {
383 case "SYSTEM_REGISTER_REQUEST":
384 $itemlink = $params['link'];
385 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
387 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
388 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
390 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
393 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
394 $params['source_name'],
395 $siteurl, $params['source_mail'],
396 $params['source_nick']
399 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
400 $tsitelink = sprintf($sitelink, $params['link']);
401 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
403 case "SYSTEM_DB_UPDATE_FAIL":
408 if ($params['type'] == SYSTEM_EMAIL) {
409 // not part of the notifications.
410 // it just send a mail to the user.
411 // It will be used by the system to send emails to users (like
412 // password reset, invitations and so) using one look (but without
413 // add a notification to the user, with could be inexistent)
414 $subject = $params['subject'];
416 $preamble = $params['preamble'];
418 $body = $params['body'];
424 $show_in_notification_page = false;
427 $subject .= " (".$nickname."@".$hostname.")";
431 'subject' => $subject,
432 'preamble' => $preamble,
433 'epreamble' => $epreamble,
435 'sitelink' => $sitelink,
436 'tsitelink' => $tsitelink,
437 'hsitelink' => $hsitelink,
438 'itemlink' => $itemlink
441 Addon::callHooks('enotify', $h);
443 $subject = $h['subject'];
445 $preamble = $h['preamble'];
446 $epreamble = $h['epreamble'];
450 $tsitelink = $h['tsitelink'];
451 $hsitelink = $h['hsitelink'];
452 $itemlink = $h['itemlink'];
454 if ($show_in_notification_page) {
455 logger("adding notification entry", LOGGER_DEBUG);
458 $hash = random_string();
459 if (DBA::exists('notify', ['hash' => $hash])) {
462 } while ($dups == true);
464 /// @TODO One statement is enough
466 $datarray['hash'] = $hash;
467 $datarray['name'] = $params['source_name'];
468 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
469 $datarray['url'] = $params['source_link'];
470 $datarray['photo'] = $params['source_photo'];
471 $datarray['date'] = DateTimeFormat::utcNow();
472 $datarray['uid'] = $params['uid'];
473 $datarray['link'] = $itemlink;
474 $datarray['iid'] = $item_id;
475 $datarray['parent'] = $parent_id;
476 $datarray['type'] = $params['type'];
477 $datarray['verb'] = $params['verb'];
478 $datarray['otype'] = $params['otype'];
479 $datarray['abort'] = false;
481 Addon::callHooks('enotify_store', $datarray);
483 if ($datarray['abort']) {
488 // create notification entry in DB
489 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
490 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
491 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
492 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
493 'name_cache' => $datarray["name_cache"]];
494 DBA::insert('notify', $fields);
496 $notify_id = DBA::lastInsertId();
498 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
499 // After we've stored everything, look again to see if there are any duplicates and if so remove them
500 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
501 intval(NOTIFY_TAGSELF),
502 intval(NOTIFY_COMMENT),
503 DBA::escape($params['link']),
504 intval($params['uid'])
506 if ($p && (count($p) > 1)) {
507 for ($d = 1; $d < count($p); $d ++) {
508 DBA::delete('notify', ['id' => $p[$d]['id']]);
511 // only continue on if we stored the first one
512 if ($notify_id != $p[0]['id']) {
518 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
519 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
520 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
522 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
523 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
524 DBA::update('notify', $fields, $condition);
527 // send email notification if notification preferences permit
528 if ((intval($params['notify_flags']) & intval($params['type']))
529 || $params['type'] == NOTIFY_SYSTEM
530 || $params['type'] == SYSTEM_EMAIL) {
532 logger('sending notification email');
534 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
535 $id_for_parent = $params['parent']."@".$hostname;
537 // Is this the first email notification for this parent item and user?
538 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
539 logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
541 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
542 'receiver-uid' => $params['uid'], 'parent-item' => 0];
543 DBA::insert('notify-threads', $fields);
545 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
546 $log_msg = "include/enotify: No previous notification found for this parent:\n".
547 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
548 logger($log_msg, LOGGER_DEBUG);
550 // If not, just "follow" the thread.
551 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
552 logger("There's already a notification for this parent.", LOGGER_DEBUG);
556 $textversion = BBCode::toPlaintext($body);
557 $htmlversion = BBCode::convert($body);
560 $datarray['banner'] = $banner;
561 $datarray['product'] = $product;
562 $datarray['preamble'] = $preamble;
563 $datarray['sitename'] = $sitename;
564 $datarray['siteurl'] = $siteurl;
565 $datarray['type'] = $params['type'];
566 $datarray['parent'] = $parent_id;
567 $datarray['source_name'] = defaults($params, 'source_name', '');
568 $datarray['source_link'] = defaults($params, 'source_link', '');
569 $datarray['source_photo'] = defaults($params, 'source_photo', '');
570 $datarray['uid'] = $params['uid'];
571 $datarray['username'] = defaults($params, 'to_name', '');
572 $datarray['hsitelink'] = $hsitelink;
573 $datarray['tsitelink'] = $tsitelink;
574 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
575 $datarray['titemlink'] = $itemlink;
576 $datarray['thanks'] = $thanks;
577 $datarray['site_admin'] = $site_admin;
578 $datarray['title'] = stripslashes($title);
579 $datarray['htmlversion'] = $htmlversion;
580 $datarray['textversion'] = $textversion;
581 $datarray['subject'] = $subject;
582 $datarray['headers'] = $additional_mail_header;
584 Addon::callHooks('enotify_mail', $datarray);
586 // check whether sending post content in email notifications is allowed
587 // always true for SYSTEM_EMAIL
588 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
590 // load the template for private message notifications
591 $tpl = get_markup_template('email_notify_html.tpl');
592 $email_html_body = replace_macros($tpl, [
593 '$banner' => $datarray['banner'],
594 '$product' => $datarray['product'],
595 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
596 '$sitename' => $datarray['sitename'],
597 '$siteurl' => $datarray['siteurl'],
598 '$source_name' => $datarray['source_name'],
599 '$source_link' => $datarray['source_link'],
600 '$source_photo' => $datarray['source_photo'],
601 '$username' => $datarray['username'],
602 '$hsitelink' => $datarray['hsitelink'],
603 '$hitemlink' => $datarray['hitemlink'],
604 '$thanks' => $datarray['thanks'],
605 '$site_admin' => $datarray['site_admin'],
606 '$title' => $datarray['title'],
607 '$htmlversion' => $datarray['htmlversion'],
608 '$content_allowed' => $content_allowed,
611 // load the template for private message notifications
612 $tpl = get_markup_template('email_notify_text.tpl');
613 $email_text_body = replace_macros($tpl, [
614 '$banner' => $datarray['banner'],
615 '$product' => $datarray['product'],
616 '$preamble' => $datarray['preamble'],
617 '$sitename' => $datarray['sitename'],
618 '$siteurl' => $datarray['siteurl'],
619 '$source_name' => $datarray['source_name'],
620 '$source_link' => $datarray['source_link'],
621 '$source_photo' => $datarray['source_photo'],
622 '$username' => $datarray['username'],
623 '$tsitelink' => $datarray['tsitelink'],
624 '$titemlink' => $datarray['titemlink'],
625 '$thanks' => $datarray['thanks'],
626 '$site_admin' => $datarray['site_admin'],
627 '$title' => $datarray['title'],
628 '$textversion' => $datarray['textversion'],
629 '$content_allowed' => $content_allowed,
633 // use the Emailer class to send the message
634 return Emailer::send(
636 'uid' => $params['uid'],
637 'fromName' => $sender_name,
638 'fromEmail' => $sender_email,
639 'replyTo' => $sender_email,
640 'toEmail' => $params['to_email'],
641 'messageSubject' => $datarray['subject'],
642 'htmlVersion' => $email_html_body,
643 'textVersion' => $email_text_body,
644 'additionalMailHeader' => $datarray['headers']]
653 * @brief Checks for users who should be notified
655 * @param int $itemid ID of the item for which the check should be done
657 function check_user_notification($itemid) {
658 // fetch all users in the thread
659 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
660 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
661 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
662 while ($user = DBA::fetch($users)) {
663 check_item_notification($itemid, $user['uid']);
669 * @brief Checks for item related notifications and sends them
671 * @param int $itemid ID of the item for which the check should be done
672 * @param int $uid User ID
673 * @param string $defaulttype (Optional) Forces a notification with this type.
675 function check_item_notification($itemid, $uid, $defaulttype = "") {
676 $notification_data = ["uid" => $uid, "profiles" => []];
677 Addon::callHooks('check_item_notification', $notification_data);
679 $profiles = $notification_data["profiles"];
681 $fields = ['nickname'];
682 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
683 if (!DBA::isResult($user)) {
687 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
688 if (!DBA::isResult($owner)) {
692 // This is our regular URL format
693 $profiles[] = $owner["url"];
695 // Notifications from Diaspora are often with an URL in the Diaspora format
696 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
700 foreach ($profiles AS $profile) {
701 // Check for invalid profile urls. 13 should be the shortest possible profile length:
703 // Additionally check for invalid urls that would return the normalised value "http:"
704 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
705 if (!in_array($profile, $profiles2))
706 $profiles2[] = $profile;
708 $profile = normalise_link($profile);
709 if (!in_array($profile, $profiles2))
710 $profiles2[] = $profile;
712 $profile = str_replace("http://", "https://", $profile);
713 if (!in_array($profile, $profiles2))
714 $profiles2[] = $profile;
718 $profiles = $profiles2;
720 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
724 while ($contact = DBA::fetch($ret)) {
725 $contacts[] = $contact['id'];
730 // Only act if it is a "real" post
731 // We need the additional check for the "local_profile" because of mixed situations on connector networks
732 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
733 'author-link', 'author-name', 'author-avatar', 'author-id',
734 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
735 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
736 $item = Item::selectFirst($fields, $condition);
737 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
741 // Generate the notification array
743 $params["uid"] = $uid;
744 $params["item"] = $item;
745 $params["parent"] = $item["parent"];
746 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
747 $params["otype"] = 'item';
748 $params["source_name"] = $item["author-name"];
749 $params["source_link"] = $item["author-link"];
750 $params["source_photo"] = $item["author-avatar"];
752 if ($item["parent-uri"] === $item["uri"]) {
753 // Send a notification for every new post?
754 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
756 if (!$send_notification) {
757 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
758 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
760 if (DBA::isResult($tags)) {
761 foreach ($tags AS $tag) {
762 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
763 $r = DBA::exists('contact', $condition);
765 $send_notification = true;
771 if ($send_notification) {
772 $params["type"] = NOTIFY_SHARE;
773 $params["verb"] = ACTIVITY_TAG;
777 // Is the user mentioned in this post?
780 foreach ($profiles AS $profile) {
781 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
785 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
786 $params["type"] = NOTIFY_TAGSELF;
787 $params["verb"] = ACTIVITY_TAG;
790 // Is it a post that the user had started?
791 $fields = ['ignored', 'mention'];
792 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
794 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
795 $params["type"] = NOTIFY_COMMENT;
796 $params["verb"] = ACTIVITY_POST;
799 // And now we check for participation of one of our contacts in the thread
800 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
802 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
803 $params["type"] = NOTIFY_COMMENT;
804 $params["verb"] = ACTIVITY_POST;
807 if (isset($params["type"])) {
808 notification($params);
813 * @brief Formats a notification message with the notification author
815 * Replace the name with {0} but ensure to make that only once. The {0} is used
816 * later and prints the name in bold.
818 * @param string $name
819 * @param string $message
820 * @return string Formatted message
822 function format_notification_message($name, $message) {
824 $pos = strpos($message, $name);
829 if ($pos !== false) {
830 $message = substr_replace($message, '{0}', $pos, strlen($name));