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\Logger;
11 use Friendica\Core\System;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Emailer;
19 * @brief Creates a notification entry and possibly sends a mail
21 * @param array $params Array with the elements:
22 * uid, item, parent, type, otype, verb, event,
23 * link, subject, body, to_name, to_email, source_name,
24 * source_link, activity, preamble, notify_flags,
25 * language, show_in_notification_page
27 function notification($params)
31 // Temporary logging for finding the origin
32 if (!isset($params['language']) || !isset($params['uid'])) {
33 Logger::log('Missing parameters.' . System::callstack());
36 // Ensure that the important fields are set at any time
37 $fields = ['notify-flags', 'language', 'username', 'email'];
38 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
40 if (!DBA::isResult($user)) {
41 Logger::log('Unknown user ' . $params['uid']);
45 $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
46 $params['language'] = defaults($params, 'language' , $user['language']);
47 $params['to_name'] = defaults($params, 'to_name' , $user['username']);
48 $params['to_email'] = defaults($params, 'to_email' , $user['email']);
50 // from here on everything is in the recipients language
51 L10n::pushLang($params['language']);
53 $banner = L10n::t('Friendica Notification');
54 $product = FRIENDICA_PLATFORM;
55 $siteurl = System::baseUrl(true);
56 $thanks = L10n::t('Thank You,');
57 $sitename = Config::get('config', 'sitename');
58 if (Config::get('config', 'admin_name')) {
59 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
61 $site_admin = L10n::t('%s Administrator', $sitename);
64 $sender_name = $sitename;
65 $hostname = $a->getHostName();
66 if (strpos($hostname, ':')) {
67 $hostname = substr($hostname, 0, strpos($hostname, ':'));
70 $sender_email = $a->getSenderEmailAddress();
72 if ($params['type'] != SYSTEM_EMAIL) {
73 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
74 ['uid' => $params['uid']]);
76 // There is no need to create notifications for forum accounts
77 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
80 $nickname = $user["nickname"];
85 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
86 // the database, and an email is sent if applicable.
87 // default, if not specified: true
88 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
90 $additional_mail_header = "";
91 $additional_mail_header .= "Precedence: list\n";
92 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
93 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
94 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
95 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
96 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
97 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
99 if (array_key_exists('item', $params)) {
100 $title = $params['item']['title'];
101 $body = $params['item']['body'];
106 if (isset($params['item']['id'])) {
107 $item_id = $params['item']['id'];
112 if (isset($params['parent'])) {
113 $parent_id = $params['parent'];
120 if ($params['type'] == NOTIFY_MAIL) {
121 $itemlink = $siteurl.'/message/'.$params['item']['id'];
122 $params["link"] = $itemlink;
124 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
126 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
127 $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]');
129 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
130 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
131 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
134 if ($params['type'] == NOTIFY_COMMENT) {
135 $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
136 if (DBA::isResult($thread) && $thread["ignored"]) {
137 Logger::log("Thread ".$parent_id." will be ignored", Logger::DEBUG);
142 // Check to see if there was already a tag notify or comment notify for this post.
143 // If so don't create a second notification
144 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
145 'link' => $params['link'], 'uid' => $params['uid']];
146 if (DBA::exists('notify', $condition)) {
151 // if it's a post figure out who's post it is.
155 if ($params['otype'] === 'item' && $parent_id) {
156 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
159 $item_post_type = item_post_type($item);
160 $itemlink = $item['plink'];
163 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
164 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
169 // "George Bull's post"
171 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
172 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
174 $item['author-name'],
180 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
181 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
182 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
188 // Some mail softwares relies on subject field for threading.
189 // So, we cannot have different subjects for notifications of the same thread.
190 // Before this we have the name of the replier on the subject rendering
191 // differents subjects for messages on the same thread.
193 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
195 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
196 $epreamble = $dest_str;
198 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
199 $tsitelink = sprintf($sitelink, $siteurl);
200 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
201 $itemlink = $params['link'];
204 if ($params['type'] == NOTIFY_WALL) {
205 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
207 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
208 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
209 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
213 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
214 $tsitelink = sprintf($sitelink, $siteurl);
215 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
216 $itemlink = $params['link'];
219 if ($params['type'] == NOTIFY_TAGSELF) {
220 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
222 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
223 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
224 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
228 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
229 $tsitelink = sprintf($sitelink, $siteurl);
230 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
231 $itemlink = $params['link'];
234 if ($params['type'] == NOTIFY_SHARE) {
235 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
237 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
238 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
239 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
243 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
244 $tsitelink = sprintf($sitelink, $siteurl);
245 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
246 $itemlink = $params['link'];
249 if ($params['type'] == NOTIFY_POKE) {
250 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
252 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
253 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
254 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
258 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
259 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
260 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
262 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
263 $tsitelink = sprintf($sitelink, $siteurl);
264 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
265 $itemlink = $params['link'];
268 if ($params['type'] == NOTIFY_TAGSHARE) {
269 $itemlink = $params['link'];
270 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
272 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
273 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
274 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
278 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
279 $tsitelink = sprintf($sitelink, $siteurl);
280 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
283 if ($params['type'] == NOTIFY_INTRO) {
284 $itemlink = $params['link'];
285 $subject = L10n::t('[Friendica:Notify] Introduction received');
287 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
288 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
290 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
293 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
295 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
296 $tsitelink = sprintf($sitelink, $siteurl);
297 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
299 switch ($params['verb']) {
300 case ACTIVITY_FRIEND:
301 // someone started to share with user (mostly OStatus)
302 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
304 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
305 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
306 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
310 case ACTIVITY_FOLLOW:
311 // someone started to follow the user (mostly OStatus)
312 $subject = L10n::t('[Friendica:Notify] You have a new follower');
314 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
315 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
316 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
321 // ACTIVITY_REQ_FRIEND is default activity for notifications
326 if ($params['type'] == NOTIFY_SUGGEST) {
327 $itemlink = $params['link'];
328 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
330 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
331 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
333 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
334 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
337 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
338 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
339 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
341 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
342 $tsitelink = sprintf($sitelink, $siteurl);
343 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
346 if ($params['type'] == NOTIFY_CONFIRM) {
347 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
348 $itemlink = $params['link'];
349 $subject = L10n::t('[Friendica:Notify] Connection accepted');
351 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
352 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
354 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
357 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
359 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
360 $tsitelink = sprintf($sitelink, $siteurl);
361 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
362 } else { // ACTIVITY_FOLLOW
363 $itemlink = $params['link'];
364 $subject = L10n::t('[Friendica:Notify] Connection accepted');
366 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
367 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
369 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
372 $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']);
374 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
376 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
377 $tsitelink = sprintf($sitelink, $siteurl);
378 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
382 if ($params['type'] == NOTIFY_SYSTEM) {
383 switch($params['event']) {
384 case "SYSTEM_REGISTER_REQUEST":
385 $itemlink = $params['link'];
386 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
388 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
389 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
391 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
394 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
395 $params['source_name'],
396 $siteurl, $params['source_mail'],
397 $params['source_nick']
400 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
401 $tsitelink = sprintf($sitelink, $params['link']);
402 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
404 case "SYSTEM_DB_UPDATE_FAIL":
409 if ($params['type'] == SYSTEM_EMAIL) {
410 // not part of the notifications.
411 // it just send a mail to the user.
412 // It will be used by the system to send emails to users (like
413 // password reset, invitations and so) using one look (but without
414 // add a notification to the user, with could be inexistent)
415 $subject = $params['subject'];
417 $preamble = $params['preamble'];
419 $body = $params['body'];
425 $show_in_notification_page = false;
428 $subject .= " (".$nickname."@".$hostname.")";
432 'subject' => $subject,
433 'preamble' => $preamble,
434 'epreamble' => $epreamble,
436 'sitelink' => $sitelink,
437 'tsitelink' => $tsitelink,
438 'hsitelink' => $hsitelink,
439 'itemlink' => $itemlink
442 Addon::callHooks('enotify', $h);
444 $subject = $h['subject'];
446 $preamble = $h['preamble'];
447 $epreamble = $h['epreamble'];
451 $tsitelink = $h['tsitelink'];
452 $hsitelink = $h['hsitelink'];
453 $itemlink = $h['itemlink'];
455 if ($show_in_notification_page) {
456 Logger::log("adding notification entry", Logger::DEBUG);
459 $hash = random_string();
460 if (DBA::exists('notify', ['hash' => $hash])) {
463 } while ($dups == true);
465 /// @TODO One statement is enough
467 $datarray['hash'] = $hash;
468 $datarray['name'] = $params['source_name'];
469 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
470 $datarray['url'] = $params['source_link'];
471 $datarray['photo'] = $params['source_photo'];
472 $datarray['date'] = DateTimeFormat::utcNow();
473 $datarray['uid'] = $params['uid'];
474 $datarray['link'] = $itemlink;
475 $datarray['iid'] = $item_id;
476 $datarray['parent'] = $parent_id;
477 $datarray['type'] = $params['type'];
478 $datarray['verb'] = $params['verb'];
479 $datarray['otype'] = $params['otype'];
480 $datarray['abort'] = false;
482 Addon::callHooks('enotify_store', $datarray);
484 if ($datarray['abort']) {
489 // create notification entry in DB
490 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
491 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
492 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
493 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
494 'name_cache' => $datarray["name_cache"]];
495 DBA::insert('notify', $fields);
497 $notify_id = DBA::lastInsertId();
499 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
500 // After we've stored everything, look again to see if there are any duplicates and if so remove them
501 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
502 intval(NOTIFY_TAGSELF),
503 intval(NOTIFY_COMMENT),
504 DBA::escape($params['link']),
505 intval($params['uid'])
507 if ($p && (count($p) > 1)) {
508 for ($d = 1; $d < count($p); $d ++) {
509 DBA::delete('notify', ['id' => $p[$d]['id']]);
512 // only continue on if we stored the first one
513 if ($notify_id != $p[0]['id']) {
519 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
520 $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
521 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
523 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
524 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
525 DBA::update('notify', $fields, $condition);
528 // send email notification if notification preferences permit
529 if ((intval($params['notify_flags']) & intval($params['type']))
530 || $params['type'] == NOTIFY_SYSTEM
531 || $params['type'] == SYSTEM_EMAIL) {
533 Logger::log('sending notification email');
535 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
536 $id_for_parent = $params['parent']."@".$hostname;
538 // Is this the first email notification for this parent item and user?
539 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
540 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
542 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
543 'receiver-uid' => $params['uid'], 'parent-item' => 0];
544 DBA::insert('notify-threads', $fields);
546 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
547 $log_msg = "include/enotify: No previous notification found for this parent:\n".
548 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
549 Logger::log($log_msg, Logger::DEBUG);
551 // If not, just "follow" the thread.
552 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
553 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
557 $textversion = BBCode::toPlaintext($body);
558 $htmlversion = BBCode::convert($body);
561 $datarray['banner'] = $banner;
562 $datarray['product'] = $product;
563 $datarray['preamble'] = $preamble;
564 $datarray['sitename'] = $sitename;
565 $datarray['siteurl'] = $siteurl;
566 $datarray['type'] = $params['type'];
567 $datarray['parent'] = $parent_id;
568 $datarray['source_name'] = defaults($params, 'source_name', '');
569 $datarray['source_link'] = defaults($params, 'source_link', '');
570 $datarray['source_photo'] = defaults($params, 'source_photo', '');
571 $datarray['uid'] = $params['uid'];
572 $datarray['username'] = defaults($params, 'to_name', '');
573 $datarray['hsitelink'] = $hsitelink;
574 $datarray['tsitelink'] = $tsitelink;
575 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
576 $datarray['titemlink'] = $itemlink;
577 $datarray['thanks'] = $thanks;
578 $datarray['site_admin'] = $site_admin;
579 $datarray['title'] = stripslashes($title);
580 $datarray['htmlversion'] = $htmlversion;
581 $datarray['textversion'] = $textversion;
582 $datarray['subject'] = $subject;
583 $datarray['headers'] = $additional_mail_header;
585 Addon::callHooks('enotify_mail', $datarray);
587 // check whether sending post content in email notifications is allowed
588 // always true for SYSTEM_EMAIL
589 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
591 // load the template for private message notifications
592 $tpl = get_markup_template('email_notify_html.tpl');
593 $email_html_body = replace_macros($tpl, [
594 '$banner' => $datarray['banner'],
595 '$product' => $datarray['product'],
596 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
597 '$sitename' => $datarray['sitename'],
598 '$siteurl' => $datarray['siteurl'],
599 '$source_name' => $datarray['source_name'],
600 '$source_link' => $datarray['source_link'],
601 '$source_photo' => $datarray['source_photo'],
602 '$username' => $datarray['username'],
603 '$hsitelink' => $datarray['hsitelink'],
604 '$hitemlink' => $datarray['hitemlink'],
605 '$thanks' => $datarray['thanks'],
606 '$site_admin' => $datarray['site_admin'],
607 '$title' => $datarray['title'],
608 '$htmlversion' => $datarray['htmlversion'],
609 '$content_allowed' => $content_allowed,
612 // load the template for private message notifications
613 $tpl = get_markup_template('email_notify_text.tpl');
614 $email_text_body = replace_macros($tpl, [
615 '$banner' => $datarray['banner'],
616 '$product' => $datarray['product'],
617 '$preamble' => $datarray['preamble'],
618 '$sitename' => $datarray['sitename'],
619 '$siteurl' => $datarray['siteurl'],
620 '$source_name' => $datarray['source_name'],
621 '$source_link' => $datarray['source_link'],
622 '$source_photo' => $datarray['source_photo'],
623 '$username' => $datarray['username'],
624 '$tsitelink' => $datarray['tsitelink'],
625 '$titemlink' => $datarray['titemlink'],
626 '$thanks' => $datarray['thanks'],
627 '$site_admin' => $datarray['site_admin'],
628 '$title' => $datarray['title'],
629 '$textversion' => $datarray['textversion'],
630 '$content_allowed' => $content_allowed,
634 // use the Emailer class to send the message
635 return Emailer::send(
637 'uid' => $params['uid'],
638 'fromName' => $sender_name,
639 'fromEmail' => $sender_email,
640 'replyTo' => $sender_email,
641 'toEmail' => $params['to_email'],
642 'messageSubject' => $datarray['subject'],
643 'htmlVersion' => $email_html_body,
644 'textVersion' => $email_text_body,
645 'additionalMailHeader' => $datarray['headers']]
654 * @brief Checks for users who should be notified
656 * @param int $itemid ID of the item for which the check should be done
658 function check_user_notification($itemid) {
659 // fetch all users in the thread
660 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
661 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
662 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
663 while ($user = DBA::fetch($users)) {
664 check_item_notification($itemid, $user['uid']);
670 * @brief Checks for item related notifications and sends them
672 * @param int $itemid ID of the item for which the check should be done
673 * @param int $uid User ID
674 * @param string $defaulttype (Optional) Forces a notification with this type.
676 function check_item_notification($itemid, $uid, $defaulttype = "") {
677 $notification_data = ["uid" => $uid, "profiles" => []];
678 Addon::callHooks('check_item_notification', $notification_data);
680 $profiles = $notification_data["profiles"];
682 $fields = ['nickname'];
683 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
684 if (!DBA::isResult($user)) {
688 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
689 if (!DBA::isResult($owner)) {
693 // This is our regular URL format
694 $profiles[] = $owner["url"];
696 // Notifications from Diaspora are often with an URL in the Diaspora format
697 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
701 foreach ($profiles AS $profile) {
702 // Check for invalid profile urls. 13 should be the shortest possible profile length:
704 // Additionally check for invalid urls that would return the normalised value "http:"
705 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
706 if (!in_array($profile, $profiles2))
707 $profiles2[] = $profile;
709 $profile = normalise_link($profile);
710 if (!in_array($profile, $profiles2))
711 $profiles2[] = $profile;
713 $profile = str_replace("http://", "https://", $profile);
714 if (!in_array($profile, $profiles2))
715 $profiles2[] = $profile;
719 $profiles = $profiles2;
721 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
725 while ($contact = DBA::fetch($ret)) {
726 $contacts[] = $contact['id'];
731 // Only act if it is a "real" post
732 // We need the additional check for the "local_profile" because of mixed situations on connector networks
733 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
734 'author-link', 'author-name', 'author-avatar', 'author-id',
735 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
736 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
737 $item = Item::selectFirst($fields, $condition);
738 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
742 // Generate the notification array
744 $params["uid"] = $uid;
745 $params["item"] = $item;
746 $params["parent"] = $item["parent"];
747 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
748 $params["otype"] = 'item';
749 $params["source_name"] = $item["author-name"];
750 $params["source_link"] = $item["author-link"];
751 $params["source_photo"] = $item["author-avatar"];
753 if ($item["parent-uri"] === $item["uri"]) {
754 // Send a notification for every new post?
755 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
757 if (!$send_notification) {
758 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
759 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
761 if (DBA::isResult($tags)) {
762 foreach ($tags AS $tag) {
763 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
764 $r = DBA::exists('contact', $condition);
766 $send_notification = true;
772 if ($send_notification) {
773 $params["type"] = NOTIFY_SHARE;
774 $params["verb"] = ACTIVITY_TAG;
778 // Is the user mentioned in this post?
781 foreach ($profiles AS $profile) {
782 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
786 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
787 $params["type"] = NOTIFY_TAGSELF;
788 $params["verb"] = ACTIVITY_TAG;
791 // Is it a post that the user had started?
792 $fields = ['ignored', 'mention'];
793 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
795 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
796 $params["type"] = NOTIFY_COMMENT;
797 $params["verb"] = ACTIVITY_POST;
800 // And now we check for participation of one of our contacts in the thread
801 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
803 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
804 $params["type"] = NOTIFY_COMMENT;
805 $params["verb"] = ACTIVITY_POST;
808 if (isset($params["type"])) {
809 notification($params);
814 * @brief Formats a notification message with the notification author
816 * Replace the name with {0} but ensure to make that only once. The {0} is used
817 * later and prints the name in bold.
819 * @param string $name
820 * @param string $message
821 * @return string Formatted message
823 function format_notification_message($name, $message) {
825 $pos = strpos($message, $name);
830 if ($pos !== false) {
831 $message = substr_replace($message, '{0}', $pos, strlen($name));