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\Renderer;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Emailer;
18 use Friendica\Util\Strings;
21 * @brief Creates a notification entry and possibly sends a mail
23 * @param array $params Array with the elements:
24 * uid, item, parent, type, otype, verb, event,
25 * link, subject, body, to_name, to_email, source_name,
26 * source_link, activity, preamble, notify_flags,
27 * language, show_in_notification_page
29 function notification($params)
33 // Temporary logging for finding the origin
34 if (!isset($params['language']) || !isset($params['uid'])) {
35 Logger::log('Missing parameters.' . System::callstack());
38 // Ensure that the important fields are set at any time
39 $fields = ['notify-flags', 'language', 'username', 'email'];
40 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
42 if (!DBA::isResult($user)) {
43 Logger::log('Unknown user ' . $params['uid']);
47 $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
48 $params['language'] = defaults($params, 'language' , $user['language']);
49 $params['to_name'] = defaults($params, 'to_name' , $user['username']);
50 $params['to_email'] = defaults($params, 'to_email' , $user['email']);
52 // from here on everything is in the recipients language
53 L10n::pushLang($params['language']);
55 $banner = L10n::t('Friendica Notification');
56 $product = FRIENDICA_PLATFORM;
57 $siteurl = System::baseUrl(true);
58 $thanks = L10n::t('Thank You,');
59 $sitename = Config::get('config', 'sitename');
60 if (Config::get('config', 'admin_name')) {
61 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
63 $site_admin = L10n::t('%s Administrator', $sitename);
66 $sender_name = $sitename;
67 $hostname = $a->getHostName();
68 if (strpos($hostname, ':')) {
69 $hostname = substr($hostname, 0, strpos($hostname, ':'));
72 $sender_email = $a->getSenderEmailAddress();
74 if ($params['type'] != SYSTEM_EMAIL) {
75 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
76 ['uid' => $params['uid']]);
78 // There is no need to create notifications for forum accounts
79 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
82 $nickname = $user["nickname"];
87 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
88 // the database, and an email is sent if applicable.
89 // default, if not specified: true
90 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
92 $additional_mail_header = "";
93 $additional_mail_header .= "Precedence: list\n";
94 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
95 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
96 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
97 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
98 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
99 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
101 if (array_key_exists('item', $params)) {
102 $title = $params['item']['title'];
103 $body = $params['item']['body'];
108 if (isset($params['item']['id'])) {
109 $item_id = $params['item']['id'];
114 if (isset($params['parent'])) {
115 $parent_id = $params['parent'];
122 if ($params['type'] == NOTIFY_MAIL) {
123 $itemlink = $siteurl.'/message/'.$params['item']['id'];
124 $params["link"] = $itemlink;
126 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
128 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
129 $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]');
131 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
132 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
133 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
136 if ($params['type'] == NOTIFY_COMMENT) {
137 $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
138 if (DBA::isResult($thread) && $thread["ignored"]) {
139 Logger::log("Thread ".$parent_id." will be ignored", Logger::DEBUG);
144 // Check to see if there was already a tag notify or comment notify for this post.
145 // If so don't create a second notification
146 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
147 'link' => $params['link'], 'uid' => $params['uid']];
148 if (DBA::exists('notify', $condition)) {
153 // if it's a post figure out who's post it is.
157 if ($params['otype'] === 'item' && $parent_id) {
158 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
161 $item_post_type = Item::postType($item);
162 $itemlink = $item['plink'];
165 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
166 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
171 // "George Bull's post"
173 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
174 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
176 $item['author-name'],
182 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
183 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
184 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
190 // Some mail softwares relies on subject field for threading.
191 // So, we cannot have different subjects for notifications of the same thread.
192 // Before this we have the name of the replier on the subject rendering
193 // differents subjects for messages on the same thread.
195 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
197 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
198 $epreamble = $dest_str;
200 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
201 $tsitelink = sprintf($sitelink, $siteurl);
202 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
203 $itemlink = $params['link'];
206 if ($params['type'] == NOTIFY_WALL) {
207 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
209 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
210 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
211 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
215 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
216 $tsitelink = sprintf($sitelink, $siteurl);
217 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
218 $itemlink = $params['link'];
221 if ($params['type'] == NOTIFY_TAGSELF) {
222 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
224 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
225 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
226 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
230 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
231 $tsitelink = sprintf($sitelink, $siteurl);
232 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
233 $itemlink = $params['link'];
236 if ($params['type'] == NOTIFY_SHARE) {
237 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
239 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
240 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
241 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
245 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
246 $tsitelink = sprintf($sitelink, $siteurl);
247 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
248 $itemlink = $params['link'];
251 if ($params['type'] == NOTIFY_POKE) {
252 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
254 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
255 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
256 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
260 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
261 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
262 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
264 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
265 $tsitelink = sprintf($sitelink, $siteurl);
266 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
267 $itemlink = $params['link'];
270 if ($params['type'] == NOTIFY_TAGSHARE) {
271 $itemlink = $params['link'];
272 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
274 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
275 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
276 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
280 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
281 $tsitelink = sprintf($sitelink, $siteurl);
282 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
285 if ($params['type'] == NOTIFY_INTRO) {
286 $itemlink = $params['link'];
287 $subject = L10n::t('[Friendica:Notify] Introduction received');
289 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
290 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
292 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
295 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
297 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
298 $tsitelink = sprintf($sitelink, $siteurl);
299 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
301 switch ($params['verb']) {
302 case ACTIVITY_FRIEND:
303 // someone started to share with user (mostly OStatus)
304 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
306 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
307 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
308 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
312 case ACTIVITY_FOLLOW:
313 // someone started to follow the user (mostly OStatus)
314 $subject = L10n::t('[Friendica:Notify] You have a new follower');
316 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
317 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
318 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
323 // ACTIVITY_REQ_FRIEND is default activity for notifications
328 if ($params['type'] == NOTIFY_SUGGEST) {
329 $itemlink = $params['link'];
330 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
332 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
333 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
335 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
336 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
339 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
340 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
341 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
343 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
344 $tsitelink = sprintf($sitelink, $siteurl);
345 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
348 if ($params['type'] == NOTIFY_CONFIRM) {
349 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
350 $itemlink = $params['link'];
351 $subject = L10n::t('[Friendica:Notify] Connection accepted');
353 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
354 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
356 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
359 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
361 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
362 $tsitelink = sprintf($sitelink, $siteurl);
363 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
364 } else { // ACTIVITY_FOLLOW
365 $itemlink = $params['link'];
366 $subject = L10n::t('[Friendica:Notify] Connection accepted');
368 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
369 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
371 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
374 $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']);
376 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
378 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
379 $tsitelink = sprintf($sitelink, $siteurl);
380 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
384 if ($params['type'] == NOTIFY_SYSTEM) {
385 switch($params['event']) {
386 case "SYSTEM_REGISTER_REQUEST":
387 $itemlink = $params['link'];
388 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
390 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
391 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
393 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
396 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
397 $params['source_name'],
398 $siteurl, $params['source_mail'],
399 $params['source_nick']
402 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
403 $tsitelink = sprintf($sitelink, $params['link']);
404 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
406 case "SYSTEM_DB_UPDATE_FAIL":
411 if ($params['type'] == SYSTEM_EMAIL) {
412 // not part of the notifications.
413 // it just send a mail to the user.
414 // It will be used by the system to send emails to users (like
415 // password reset, invitations and so) using one look (but without
416 // add a notification to the user, with could be inexistent)
417 $subject = $params['subject'];
419 $preamble = $params['preamble'];
421 $body = $params['body'];
427 $show_in_notification_page = false;
430 $subject .= " (".$nickname."@".$hostname.")";
434 'subject' => $subject,
435 'preamble' => $preamble,
436 'epreamble' => $epreamble,
438 'sitelink' => $sitelink,
439 'tsitelink' => $tsitelink,
440 'hsitelink' => $hsitelink,
441 'itemlink' => $itemlink
444 Addon::callHooks('enotify', $h);
446 $subject = $h['subject'];
448 $preamble = $h['preamble'];
449 $epreamble = $h['epreamble'];
453 $tsitelink = $h['tsitelink'];
454 $hsitelink = $h['hsitelink'];
455 $itemlink = $h['itemlink'];
457 if ($show_in_notification_page) {
458 Logger::log("adding notification entry", Logger::DEBUG);
461 $hash = Strings::getRandomHex();
462 if (DBA::exists('notify', ['hash' => $hash])) {
465 } while ($dups == true);
467 /// @TODO One statement is enough
469 $datarray['hash'] = $hash;
470 $datarray['name'] = $params['source_name'];
471 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
472 $datarray['url'] = $params['source_link'];
473 $datarray['photo'] = $params['source_photo'];
474 $datarray['date'] = DateTimeFormat::utcNow();
475 $datarray['uid'] = $params['uid'];
476 $datarray['link'] = $itemlink;
477 $datarray['iid'] = $item_id;
478 $datarray['parent'] = $parent_id;
479 $datarray['type'] = $params['type'];
480 $datarray['verb'] = $params['verb'];
481 $datarray['otype'] = $params['otype'];
482 $datarray['abort'] = false;
484 Addon::callHooks('enotify_store', $datarray);
486 if ($datarray['abort']) {
491 // create notification entry in DB
492 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
493 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
494 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
495 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
496 'name_cache' => $datarray["name_cache"]];
497 DBA::insert('notify', $fields);
499 $notify_id = DBA::lastInsertId();
501 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
502 // After we've stored everything, look again to see if there are any duplicates and if so remove them
503 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
504 intval(NOTIFY_TAGSELF),
505 intval(NOTIFY_COMMENT),
506 DBA::escape($params['link']),
507 intval($params['uid'])
509 if ($p && (count($p) > 1)) {
510 for ($d = 1; $d < count($p); $d ++) {
511 DBA::delete('notify', ['id' => $p[$d]['id']]);
514 // only continue on if we stored the first one
515 if ($notify_id != $p[0]['id']) {
521 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
522 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
523 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
525 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
526 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
527 DBA::update('notify', $fields, $condition);
530 // send email notification if notification preferences permit
531 if ((intval($params['notify_flags']) & intval($params['type']))
532 || $params['type'] == NOTIFY_SYSTEM
533 || $params['type'] == SYSTEM_EMAIL) {
535 Logger::log('sending notification email');
537 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
538 $id_for_parent = $params['parent']."@".$hostname;
540 // Is this the first email notification for this parent item and user?
541 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
542 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
544 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
545 'receiver-uid' => $params['uid'], 'parent-item' => 0];
546 DBA::insert('notify-threads', $fields);
548 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
549 $log_msg = "include/enotify: No previous notification found for this parent:\n".
550 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
551 Logger::log($log_msg, Logger::DEBUG);
553 // If not, just "follow" the thread.
554 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
555 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
559 $textversion = BBCode::toPlaintext($body);
560 $htmlversion = BBCode::convert($body);
563 $datarray['banner'] = $banner;
564 $datarray['product'] = $product;
565 $datarray['preamble'] = $preamble;
566 $datarray['sitename'] = $sitename;
567 $datarray['siteurl'] = $siteurl;
568 $datarray['type'] = $params['type'];
569 $datarray['parent'] = $parent_id;
570 $datarray['source_name'] = defaults($params, 'source_name', '');
571 $datarray['source_link'] = defaults($params, 'source_link', '');
572 $datarray['source_photo'] = defaults($params, 'source_photo', '');
573 $datarray['uid'] = $params['uid'];
574 $datarray['username'] = defaults($params, 'to_name', '');
575 $datarray['hsitelink'] = $hsitelink;
576 $datarray['tsitelink'] = $tsitelink;
577 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
578 $datarray['titemlink'] = $itemlink;
579 $datarray['thanks'] = $thanks;
580 $datarray['site_admin'] = $site_admin;
581 $datarray['title'] = stripslashes($title);
582 $datarray['htmlversion'] = $htmlversion;
583 $datarray['textversion'] = $textversion;
584 $datarray['subject'] = $subject;
585 $datarray['headers'] = $additional_mail_header;
587 Addon::callHooks('enotify_mail', $datarray);
589 // check whether sending post content in email notifications is allowed
590 // always true for SYSTEM_EMAIL
591 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
593 // load the template for private message notifications
594 $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
595 $email_html_body = Renderer::replaceMacros($tpl, [
596 '$banner' => $datarray['banner'],
597 '$product' => $datarray['product'],
598 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
599 '$sitename' => $datarray['sitename'],
600 '$siteurl' => $datarray['siteurl'],
601 '$source_name' => $datarray['source_name'],
602 '$source_link' => $datarray['source_link'],
603 '$source_photo' => $datarray['source_photo'],
604 '$username' => $datarray['username'],
605 '$hsitelink' => $datarray['hsitelink'],
606 '$hitemlink' => $datarray['hitemlink'],
607 '$thanks' => $datarray['thanks'],
608 '$site_admin' => $datarray['site_admin'],
609 '$title' => $datarray['title'],
610 '$htmlversion' => $datarray['htmlversion'],
611 '$content_allowed' => $content_allowed,
614 // load the template for private message notifications
615 $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
616 $email_text_body = Renderer::replaceMacros($tpl, [
617 '$banner' => $datarray['banner'],
618 '$product' => $datarray['product'],
619 '$preamble' => $datarray['preamble'],
620 '$sitename' => $datarray['sitename'],
621 '$siteurl' => $datarray['siteurl'],
622 '$source_name' => $datarray['source_name'],
623 '$source_link' => $datarray['source_link'],
624 '$source_photo' => $datarray['source_photo'],
625 '$username' => $datarray['username'],
626 '$tsitelink' => $datarray['tsitelink'],
627 '$titemlink' => $datarray['titemlink'],
628 '$thanks' => $datarray['thanks'],
629 '$site_admin' => $datarray['site_admin'],
630 '$title' => $datarray['title'],
631 '$textversion' => $datarray['textversion'],
632 '$content_allowed' => $content_allowed,
636 // use the Emailer class to send the message
637 return Emailer::send(
639 'uid' => $params['uid'],
640 'fromName' => $sender_name,
641 'fromEmail' => $sender_email,
642 'replyTo' => $sender_email,
643 'toEmail' => $params['to_email'],
644 'messageSubject' => $datarray['subject'],
645 'htmlVersion' => $email_html_body,
646 'textVersion' => $email_text_body,
647 'additionalMailHeader' => $datarray['headers']]
656 * @brief Checks for users who should be notified
658 * @param int $itemid ID of the item for which the check should be done
660 function check_user_notification($itemid) {
661 // fetch all users in the thread
662 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
663 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
664 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
665 while ($user = DBA::fetch($users)) {
666 check_item_notification($itemid, $user['uid']);
672 * @brief Checks for item related notifications and sends them
674 * @param int $itemid ID of the item for which the check should be done
675 * @param int $uid User ID
676 * @param string $defaulttype (Optional) Forces a notification with this type.
678 function check_item_notification($itemid, $uid, $defaulttype = "") {
679 $notification_data = ["uid" => $uid, "profiles" => []];
680 Addon::callHooks('check_item_notification', $notification_data);
682 $profiles = $notification_data["profiles"];
684 $fields = ['nickname'];
685 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
686 if (!DBA::isResult($user)) {
690 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
691 if (!DBA::isResult($owner)) {
695 // This is our regular URL format
696 $profiles[] = $owner["url"];
698 // Notifications from Diaspora are often with an URL in the Diaspora format
699 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
703 foreach ($profiles AS $profile) {
704 // Check for invalid profile urls. 13 should be the shortest possible profile length:
706 // Additionally check for invalid urls that would return the normalised value "http:"
707 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
708 if (!in_array($profile, $profiles2))
709 $profiles2[] = $profile;
711 $profile = normalise_link($profile);
712 if (!in_array($profile, $profiles2))
713 $profiles2[] = $profile;
715 $profile = str_replace("http://", "https://", $profile);
716 if (!in_array($profile, $profiles2))
717 $profiles2[] = $profile;
721 $profiles = $profiles2;
723 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
727 while ($contact = DBA::fetch($ret)) {
728 $contacts[] = $contact['id'];
733 // Only act if it is a "real" post
734 // We need the additional check for the "local_profile" because of mixed situations on connector networks
735 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
736 'author-link', 'author-name', 'author-avatar', 'author-id',
737 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
738 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
739 $item = Item::selectFirst($fields, $condition);
740 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
744 // Generate the notification array
746 $params["uid"] = $uid;
747 $params["item"] = $item;
748 $params["parent"] = $item["parent"];
749 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
750 $params["otype"] = 'item';
751 $params["source_name"] = $item["author-name"];
752 $params["source_link"] = $item["author-link"];
753 $params["source_photo"] = $item["author-avatar"];
755 if ($item["parent-uri"] === $item["uri"]) {
756 // Send a notification for every new post?
757 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
759 if (!$send_notification) {
760 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
761 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
763 if (DBA::isResult($tags)) {
764 foreach ($tags AS $tag) {
765 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
766 $r = DBA::exists('contact', $condition);
768 $send_notification = true;
774 if ($send_notification) {
775 $params["type"] = NOTIFY_SHARE;
776 $params["verb"] = ACTIVITY_TAG;
780 // Is the user mentioned in this post?
783 foreach ($profiles AS $profile) {
784 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
788 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
789 $params["type"] = NOTIFY_TAGSELF;
790 $params["verb"] = ACTIVITY_TAG;
793 // Is it a post that the user had started?
794 $fields = ['ignored', 'mention'];
795 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
797 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
798 $params["type"] = NOTIFY_COMMENT;
799 $params["verb"] = ACTIVITY_POST;
802 // And now we check for participation of one of our contacts in the thread
803 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
805 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
806 $params["type"] = NOTIFY_COMMENT;
807 $params["verb"] = ACTIVITY_POST;
810 if (isset($params["type"])) {
811 notification($params);
816 * @brief Formats a notification message with the notification author
818 * Replace the name with {0} but ensure to make that only once. The {0} is used
819 * later and prints the name in bold.
821 * @param string $name
822 * @param string $message
823 * @return string Formatted message
825 function format_notification_message($name, $message) {
827 $pos = strpos($message, $name);
832 if ($pos !== false) {
833 $message = substr_replace($message, '{0}', $pos, strlen($name));