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;
20 * @brief Creates a notification entry and possibly sends a mail
22 * @param array $params Array with the elements:
23 * uid, item, parent, type, otype, verb, event,
24 * link, subject, body, to_name, to_email, source_name,
25 * source_link, activity, preamble, notify_flags,
26 * language, show_in_notification_page
28 function notification($params)
32 // Temporary logging for finding the origin
33 if (!isset($params['language']) || !isset($params['uid'])) {
34 Logger::log('Missing parameters.' . System::callstack());
37 // Ensure that the important fields are set at any time
38 $fields = ['notify-flags', 'language', 'username', 'email'];
39 $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
41 if (!DBA::isResult($user)) {
42 Logger::log('Unknown user ' . $params['uid']);
46 $params['notify_flags'] = defaults($params, 'notify_flags', $user['notify-flags']);
47 $params['language'] = defaults($params, 'language' , $user['language']);
48 $params['to_name'] = defaults($params, 'to_name' , $user['username']);
49 $params['to_email'] = defaults($params, 'to_email' , $user['email']);
51 // from here on everything is in the recipients language
52 L10n::pushLang($params['language']);
54 $banner = L10n::t('Friendica Notification');
55 $product = FRIENDICA_PLATFORM;
56 $siteurl = System::baseUrl(true);
57 $thanks = L10n::t('Thank You,');
58 $sitename = Config::get('config', 'sitename');
59 if (Config::get('config', 'admin_name')) {
60 $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
62 $site_admin = L10n::t('%s Administrator', $sitename);
65 $sender_name = $sitename;
66 $hostname = $a->getHostName();
67 if (strpos($hostname, ':')) {
68 $hostname = substr($hostname, 0, strpos($hostname, ':'));
71 $sender_email = $a->getSenderEmailAddress();
73 if ($params['type'] != SYSTEM_EMAIL) {
74 $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
75 ['uid' => $params['uid']]);
77 // There is no need to create notifications for forum accounts
78 if (!DBA::isResult($user) || in_array($user["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
81 $nickname = $user["nickname"];
86 // with $params['show_in_notification_page'] == false, the notification isn't inserted into
87 // the database, and an email is sent if applicable.
88 // default, if not specified: true
89 $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
91 $additional_mail_header = "";
92 $additional_mail_header .= "Precedence: list\n";
93 $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
94 $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
95 $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
96 $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
97 $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
98 $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
100 if (array_key_exists('item', $params)) {
101 $title = $params['item']['title'];
102 $body = $params['item']['body'];
107 if (isset($params['item']['id'])) {
108 $item_id = $params['item']['id'];
113 if (isset($params['parent'])) {
114 $parent_id = $params['parent'];
121 if ($params['type'] == NOTIFY_MAIL) {
122 $itemlink = $siteurl.'/message/'.$params['item']['id'];
123 $params["link"] = $itemlink;
125 $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
127 $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
128 $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]');
130 $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
131 $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
132 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
135 if ($params['type'] == NOTIFY_COMMENT) {
136 $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
137 if (DBA::isResult($thread) && $thread["ignored"]) {
138 Logger::log("Thread ".$parent_id." will be ignored", Logger::DEBUG);
143 // Check to see if there was already a tag notify or comment notify for this post.
144 // If so don't create a second notification
145 $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
146 'link' => $params['link'], 'uid' => $params['uid']];
147 if (DBA::exists('notify', $condition)) {
152 // if it's a post figure out who's post it is.
156 if ($params['otype'] === 'item' && $parent_id) {
157 $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id]);
160 $item_post_type = item_post_type($item);
161 $itemlink = $item['plink'];
164 $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
165 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
170 // "George Bull's post"
172 $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
173 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
175 $item['author-name'],
181 if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
182 $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
183 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
189 // Some mail softwares relies on subject field for threading.
190 // So, we cannot have different subjects for notifications of the same thread.
191 // Before this we have the name of the replier on the subject rendering
192 // differents subjects for messages on the same thread.
194 $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
196 $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
197 $epreamble = $dest_str;
199 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
200 $tsitelink = sprintf($sitelink, $siteurl);
201 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
202 $itemlink = $params['link'];
205 if ($params['type'] == NOTIFY_WALL) {
206 $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
208 $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
209 $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
210 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
214 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
215 $tsitelink = sprintf($sitelink, $siteurl);
216 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
217 $itemlink = $params['link'];
220 if ($params['type'] == NOTIFY_TAGSELF) {
221 $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
223 $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
224 $epreamble = L10n::t('%1$s [url=%2$s]tagged you[/url].',
225 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
229 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
230 $tsitelink = sprintf($sitelink, $siteurl);
231 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
232 $itemlink = $params['link'];
235 if ($params['type'] == NOTIFY_SHARE) {
236 $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
238 $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
239 $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
240 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
244 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
245 $tsitelink = sprintf($sitelink, $siteurl);
246 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
247 $itemlink = $params['link'];
250 if ($params['type'] == NOTIFY_POKE) {
251 $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
253 $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
254 $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
255 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
259 $subject = str_replace('poked', L10n::t($params['activity']), $subject);
260 $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
261 $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
263 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
264 $tsitelink = sprintf($sitelink, $siteurl);
265 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
266 $itemlink = $params['link'];
269 if ($params['type'] == NOTIFY_TAGSHARE) {
270 $itemlink = $params['link'];
271 $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
273 $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
274 $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
275 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
279 $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
280 $tsitelink = sprintf($sitelink, $siteurl);
281 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
284 if ($params['type'] == NOTIFY_INTRO) {
285 $itemlink = $params['link'];
286 $subject = L10n::t('[Friendica:Notify] Introduction received');
288 $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
289 $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
291 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
294 $body = L10n::t('You may visit their profile at %s', $params['source_link']);
296 $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
297 $tsitelink = sprintf($sitelink, $siteurl);
298 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
300 switch ($params['verb']) {
301 case ACTIVITY_FRIEND:
302 // someone started to share with user (mostly OStatus)
303 $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
305 $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
306 $epreamble = L10n::t('%1$s is sharing with you at %2$s',
307 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
311 case ACTIVITY_FOLLOW:
312 // someone started to follow the user (mostly OStatus)
313 $subject = L10n::t('[Friendica:Notify] You have a new follower');
315 $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
316 $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
317 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
322 // ACTIVITY_REQ_FRIEND is default activity for notifications
327 if ($params['type'] == NOTIFY_SUGGEST) {
328 $itemlink = $params['link'];
329 $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
331 $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
332 $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
334 '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
335 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
338 $body = L10n::t('Name:').' '.$params['item']['name']."\n";
339 $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
340 $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
342 $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
343 $tsitelink = sprintf($sitelink, $siteurl);
344 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
347 if ($params['type'] == NOTIFY_CONFIRM) {
348 if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
349 $itemlink = $params['link'];
350 $subject = L10n::t('[Friendica:Notify] Connection accepted');
352 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
353 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
355 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
358 $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
360 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
361 $tsitelink = sprintf($sitelink, $siteurl);
362 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
363 } else { // ACTIVITY_FOLLOW
364 $itemlink = $params['link'];
365 $subject = L10n::t('[Friendica:Notify] Connection accepted');
367 $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
368 $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
370 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
373 $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']);
375 $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
377 $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
378 $tsitelink = sprintf($sitelink, $siteurl);
379 $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
383 if ($params['type'] == NOTIFY_SYSTEM) {
384 switch($params['event']) {
385 case "SYSTEM_REGISTER_REQUEST":
386 $itemlink = $params['link'];
387 $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
389 $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
390 $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
392 '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
395 $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
396 $params['source_name'],
397 $siteurl, $params['source_mail'],
398 $params['source_nick']
401 $sitelink = L10n::t('Please visit %s to approve or reject the request.');
402 $tsitelink = sprintf($sitelink, $params['link']);
403 $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
405 case "SYSTEM_DB_UPDATE_FAIL":
410 if ($params['type'] == SYSTEM_EMAIL) {
411 // not part of the notifications.
412 // it just send a mail to the user.
413 // It will be used by the system to send emails to users (like
414 // password reset, invitations and so) using one look (but without
415 // add a notification to the user, with could be inexistent)
416 $subject = $params['subject'];
418 $preamble = $params['preamble'];
420 $body = $params['body'];
426 $show_in_notification_page = false;
429 $subject .= " (".$nickname."@".$hostname.")";
433 'subject' => $subject,
434 'preamble' => $preamble,
435 'epreamble' => $epreamble,
437 'sitelink' => $sitelink,
438 'tsitelink' => $tsitelink,
439 'hsitelink' => $hsitelink,
440 'itemlink' => $itemlink
443 Addon::callHooks('enotify', $h);
445 $subject = $h['subject'];
447 $preamble = $h['preamble'];
448 $epreamble = $h['epreamble'];
452 $tsitelink = $h['tsitelink'];
453 $hsitelink = $h['hsitelink'];
454 $itemlink = $h['itemlink'];
456 if ($show_in_notification_page) {
457 Logger::log("adding notification entry", Logger::DEBUG);
460 $hash = random_string();
461 if (DBA::exists('notify', ['hash' => $hash])) {
464 } while ($dups == true);
466 /// @TODO One statement is enough
468 $datarray['hash'] = $hash;
469 $datarray['name'] = $params['source_name'];
470 $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
471 $datarray['url'] = $params['source_link'];
472 $datarray['photo'] = $params['source_photo'];
473 $datarray['date'] = DateTimeFormat::utcNow();
474 $datarray['uid'] = $params['uid'];
475 $datarray['link'] = $itemlink;
476 $datarray['iid'] = $item_id;
477 $datarray['parent'] = $parent_id;
478 $datarray['type'] = $params['type'];
479 $datarray['verb'] = $params['verb'];
480 $datarray['otype'] = $params['otype'];
481 $datarray['abort'] = false;
483 Addon::callHooks('enotify_store', $datarray);
485 if ($datarray['abort']) {
490 // create notification entry in DB
491 $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
492 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
493 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
494 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
495 'name_cache' => $datarray["name_cache"]];
496 DBA::insert('notify', $fields);
498 $notify_id = DBA::lastInsertId();
500 // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
501 // After we've stored everything, look again to see if there are any duplicates and if so remove them
502 $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
503 intval(NOTIFY_TAGSELF),
504 intval(NOTIFY_COMMENT),
505 DBA::escape($params['link']),
506 intval($params['uid'])
508 if ($p && (count($p) > 1)) {
509 for ($d = 1; $d < count($p); $d ++) {
510 DBA::delete('notify', ['id' => $p[$d]['id']]);
513 // only continue on if we stored the first one
514 if ($notify_id != $p[0]['id']) {
520 $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
521 $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
522 $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
524 $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
525 $condition = ['id' => $notify_id, 'uid' => $params['uid']];
526 DBA::update('notify', $fields, $condition);
529 // send email notification if notification preferences permit
530 if ((intval($params['notify_flags']) & intval($params['type']))
531 || $params['type'] == NOTIFY_SYSTEM
532 || $params['type'] == SYSTEM_EMAIL) {
534 Logger::log('sending notification email');
536 if (isset($params['parent']) && (intval($params['parent']) != 0)) {
537 $id_for_parent = $params['parent']."@".$hostname;
539 // Is this the first email notification for this parent item and user?
540 if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
541 Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
543 $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
544 'receiver-uid' => $params['uid'], 'parent-item' => 0];
545 DBA::insert('notify-threads', $fields);
547 $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
548 $log_msg = "include/enotify: No previous notification found for this parent:\n".
549 " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
550 Logger::log($log_msg, Logger::DEBUG);
552 // If not, just "follow" the thread.
553 $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
554 Logger::log("There's already a notification for this parent.", Logger::DEBUG);
558 $textversion = BBCode::toPlaintext($body);
559 $htmlversion = BBCode::convert($body);
562 $datarray['banner'] = $banner;
563 $datarray['product'] = $product;
564 $datarray['preamble'] = $preamble;
565 $datarray['sitename'] = $sitename;
566 $datarray['siteurl'] = $siteurl;
567 $datarray['type'] = $params['type'];
568 $datarray['parent'] = $parent_id;
569 $datarray['source_name'] = defaults($params, 'source_name', '');
570 $datarray['source_link'] = defaults($params, 'source_link', '');
571 $datarray['source_photo'] = defaults($params, 'source_photo', '');
572 $datarray['uid'] = $params['uid'];
573 $datarray['username'] = defaults($params, 'to_name', '');
574 $datarray['hsitelink'] = $hsitelink;
575 $datarray['tsitelink'] = $tsitelink;
576 $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
577 $datarray['titemlink'] = $itemlink;
578 $datarray['thanks'] = $thanks;
579 $datarray['site_admin'] = $site_admin;
580 $datarray['title'] = stripslashes($title);
581 $datarray['htmlversion'] = $htmlversion;
582 $datarray['textversion'] = $textversion;
583 $datarray['subject'] = $subject;
584 $datarray['headers'] = $additional_mail_header;
586 Addon::callHooks('enotify_mail', $datarray);
588 // check whether sending post content in email notifications is allowed
589 // always true for SYSTEM_EMAIL
590 $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
592 // load the template for private message notifications
593 $tpl = get_markup_template('email_notify_html.tpl');
594 $email_html_body = Renderer::replaceMacros($tpl, [
595 '$banner' => $datarray['banner'],
596 '$product' => $datarray['product'],
597 '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
598 '$sitename' => $datarray['sitename'],
599 '$siteurl' => $datarray['siteurl'],
600 '$source_name' => $datarray['source_name'],
601 '$source_link' => $datarray['source_link'],
602 '$source_photo' => $datarray['source_photo'],
603 '$username' => $datarray['username'],
604 '$hsitelink' => $datarray['hsitelink'],
605 '$hitemlink' => $datarray['hitemlink'],
606 '$thanks' => $datarray['thanks'],
607 '$site_admin' => $datarray['site_admin'],
608 '$title' => $datarray['title'],
609 '$htmlversion' => $datarray['htmlversion'],
610 '$content_allowed' => $content_allowed,
613 // load the template for private message notifications
614 $tpl = get_markup_template('email_notify_text.tpl');
615 $email_text_body = Renderer::replaceMacros($tpl, [
616 '$banner' => $datarray['banner'],
617 '$product' => $datarray['product'],
618 '$preamble' => $datarray['preamble'],
619 '$sitename' => $datarray['sitename'],
620 '$siteurl' => $datarray['siteurl'],
621 '$source_name' => $datarray['source_name'],
622 '$source_link' => $datarray['source_link'],
623 '$source_photo' => $datarray['source_photo'],
624 '$username' => $datarray['username'],
625 '$tsitelink' => $datarray['tsitelink'],
626 '$titemlink' => $datarray['titemlink'],
627 '$thanks' => $datarray['thanks'],
628 '$site_admin' => $datarray['site_admin'],
629 '$title' => $datarray['title'],
630 '$textversion' => $datarray['textversion'],
631 '$content_allowed' => $content_allowed,
635 // use the Emailer class to send the message
636 return Emailer::send(
638 'uid' => $params['uid'],
639 'fromName' => $sender_name,
640 'fromEmail' => $sender_email,
641 'replyTo' => $sender_email,
642 'toEmail' => $params['to_email'],
643 'messageSubject' => $datarray['subject'],
644 'htmlVersion' => $email_html_body,
645 'textVersion' => $email_text_body,
646 'additionalMailHeader' => $datarray['headers']]
655 * @brief Checks for users who should be notified
657 * @param int $itemid ID of the item for which the check should be done
659 function check_user_notification($itemid) {
660 // fetch all users in the thread
661 $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
662 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
663 WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
664 while ($user = DBA::fetch($users)) {
665 check_item_notification($itemid, $user['uid']);
671 * @brief Checks for item related notifications and sends them
673 * @param int $itemid ID of the item for which the check should be done
674 * @param int $uid User ID
675 * @param string $defaulttype (Optional) Forces a notification with this type.
677 function check_item_notification($itemid, $uid, $defaulttype = "") {
678 $notification_data = ["uid" => $uid, "profiles" => []];
679 Addon::callHooks('check_item_notification', $notification_data);
681 $profiles = $notification_data["profiles"];
683 $fields = ['nickname'];
684 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
685 if (!DBA::isResult($user)) {
689 $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
690 if (!DBA::isResult($owner)) {
694 // This is our regular URL format
695 $profiles[] = $owner["url"];
697 // Notifications from Diaspora are often with an URL in the Diaspora format
698 $profiles[] = System::baseUrl()."/u/".$user["nickname"];
702 foreach ($profiles AS $profile) {
703 // Check for invalid profile urls. 13 should be the shortest possible profile length:
705 // Additionally check for invalid urls that would return the normalised value "http:"
706 if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
707 if (!in_array($profile, $profiles2))
708 $profiles2[] = $profile;
710 $profile = normalise_link($profile);
711 if (!in_array($profile, $profiles2))
712 $profiles2[] = $profile;
714 $profile = str_replace("http://", "https://", $profile);
715 if (!in_array($profile, $profiles2))
716 $profiles2[] = $profile;
720 $profiles = $profiles2;
722 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
726 while ($contact = DBA::fetch($ret)) {
727 $contacts[] = $contact['id'];
732 // Only act if it is a "real" post
733 // We need the additional check for the "local_profile" because of mixed situations on connector networks
734 $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
735 'author-link', 'author-name', 'author-avatar', 'author-id',
736 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
737 $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
738 $item = Item::selectFirst($fields, $condition);
739 if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
743 // Generate the notification array
745 $params["uid"] = $uid;
746 $params["item"] = $item;
747 $params["parent"] = $item["parent"];
748 $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
749 $params["otype"] = 'item';
750 $params["source_name"] = $item["author-name"];
751 $params["source_link"] = $item["author-link"];
752 $params["source_photo"] = $item["author-avatar"];
754 if ($item["parent-uri"] === $item["uri"]) {
755 // Send a notification for every new post?
756 $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
758 if (!$send_notification) {
759 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
760 intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
762 if (DBA::isResult($tags)) {
763 foreach ($tags AS $tag) {
764 $condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
765 $r = DBA::exists('contact', $condition);
767 $send_notification = true;
773 if ($send_notification) {
774 $params["type"] = NOTIFY_SHARE;
775 $params["verb"] = ACTIVITY_TAG;
779 // Is the user mentioned in this post?
782 foreach ($profiles AS $profile) {
783 if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
787 if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
788 $params["type"] = NOTIFY_TAGSELF;
789 $params["verb"] = ACTIVITY_TAG;
792 // Is it a post that the user had started?
793 $fields = ['ignored', 'mention'];
794 $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"]]);
796 if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
797 $params["type"] = NOTIFY_COMMENT;
798 $params["verb"] = ACTIVITY_POST;
801 // And now we check for participation of one of our contacts in the thread
802 $condition = ['parent' => $item["parent"], 'author-id' => $contacts];
804 if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
805 $params["type"] = NOTIFY_COMMENT;
806 $params["verb"] = ACTIVITY_POST;
809 if (isset($params["type"])) {
810 notification($params);
815 * @brief Formats a notification message with the notification author
817 * Replace the name with {0} but ensure to make that only once. The {0} is used
818 * later and prints the name in bold.
820 * @param string $name
821 * @param string $message
822 * @return string Formatted message
824 function format_notification_message($name, $message) {
826 $pos = strpos($message, $name);
831 if ($pos !== false) {
832 $message = substr_replace($message, '{0}', $pos, strlen($name));