3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\Group;
17 use Friendica\Model\Item;
18 use Friendica\Model\PushSubscriber;
19 use Friendica\Model\User;
20 use Friendica\Network\Probe;
21 use Friendica\Protocol\ActivityPub;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\Salmon;
27 * The notifier is typically called with:
29 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
31 * where COMMAND is one of the following:
33 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
34 * comment-import (in diaspora.php, items.php)
35 * comment-new (in item.php)
36 * drop (in diaspora.php, items.php, photos.php)
37 * edit_post (in item.php)
38 * event (in events.php)
39 * like (in like.php, poke.php)
40 * mail (in message.php)
41 * suggest (in fsuggest.php)
42 * tag (in photos.php, poke.php, tagger.php)
43 * tgroup (in items.php)
44 * wall-new (in photos.php, item.php)
45 * removeme (in Contact.php)
46 * relocate (in uimport.php)
48 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
53 public static function execute($cmd, $target_id)
55 $a = BaseObject::getApp();
57 Logger::log('Invoked: ' . $cmd . ': ' . $target_id, Logger::DEBUG);
64 $recipients_relocate = [];
68 if ($cmd == Delivery::MAIL) {
70 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
71 if (!DBA::isResult($message)) {
74 $uid = $message['uid'];
75 $recipients[] = $message['contact-id'];
76 } elseif ($cmd == Delivery::SUGGESTION) {
78 $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $target_id]);
79 if (!DBA::isResult($suggest)) {
82 $uid = $suggest['uid'];
83 $recipients[] = $suggest['cid'];
84 } elseif ($cmd == Delivery::REMOVAL) {
85 return self::notifySelfRemoval($target_id, $a->queue['priority'], $a->queue['created']);
86 } elseif ($cmd == Delivery::RELOCATION) {
90 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
91 intval($uid), Protocol::DFRN, Protocol::DIASPORA);
94 $condition = ['id' => $target_id, 'visible' => true, 'moderated' => false];
95 $target_item = Item::selectFirst([], $condition);
97 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
101 if (!empty($target_item['contact-uid'])) {
102 $uid = $target_item['contact-uid'];
103 } elseif (!empty($target_item['uid'])) {
104 $uid = $target_item['uid'];
106 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
110 $condition = ['parent' => $target_item['parent'], 'visible' => true, 'moderated' => false];
111 $params = ['order' => ['id']];
112 $items_stmt = Item::select([], $condition, $params);
113 if (!DBA::isResult($items_stmt)) {
117 $items = Item::inArray($items_stmt);
119 // avoid race condition with deleting entries
120 if ($items[0]['deleted']) {
121 foreach ($items as $item) {
122 $item['deleted'] = 1;
126 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
127 Logger::log('Top level post');
132 $owner = User::getOwnerDataById($uid);
137 // Should the post be transmitted to Diaspora?
138 $diaspora_delivery = true;
140 // If this is a public conversation, notify the feed hub
141 $public_message = true;
144 $push_notify = false;
146 // Deliver directly to a forum, don't PuSH
147 $direct_forum_delivery = false;
150 $recipients_followup = [];
152 if (!empty($target_item) && !empty($items)) {
155 self::activityPubDelivery($cmd, $target_item, $parent, $a->queue['priority'], $a->query_string['created']);
157 $fields = ['network', 'author-id', 'owner-id'];
158 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
159 $thr_parent = Item::selectFirst($fields, $condition);
161 Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
163 // This is IMPORTANT!!!!
165 // We will only send a "notify owner to relay" or followup message if the referenced post
166 // originated on our system by virtue of having our hostname somewhere
167 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
169 // if $parent['wall'] == 1 we will already have the parent message in our array
170 // and we will relay the whole lot.
172 $localhost = str_replace('www.','',$a->getHostName());
173 if (strpos($localhost,':')) {
174 $localhost = substr($localhost,0,strpos($localhost,':'));
178 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
179 * have been known to cause runaway conditions which affected several servers, along with
180 * permissions issues.
184 $relay_to_owner = false;
186 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
187 $relay_to_owner = true;
191 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
192 $relay_to_owner = true;
195 // until the 'origin' flag has been in use for several months
196 // we will just use it as a fallback test
197 // later we will be able to use it as the primary test of whether or not to relay.
199 if (!$target_item['origin']) {
200 $relay_to_owner = false;
202 if ($parent['origin']) {
203 $relay_to_owner = false;
206 // Special treatment for forum posts
207 if (self::isForumPost($target_item, $owner)) {
208 $relay_to_owner = true;
209 $direct_forum_delivery = true;
212 // Avoid that comments in a forum thread are sent to OStatus
213 if (self::isForumPost($parent, $owner)) {
214 $direct_forum_delivery = true;
217 if ($relay_to_owner) {
218 // local followup to remote post
220 $public_message = false; // not public
221 $recipients = [$parent['contact-id']];
222 $recipients_followup = [$parent['contact-id']];
224 Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
226 //if (!$target_item['private'] && $target_item['wall'] &&
227 if (!$target_item['private'] &&
228 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
229 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
232 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
235 if ($parent["network"] == Protocol::OSTATUS) {
236 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
237 // Currently it is work at progress
238 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
240 DBA::escape(Protocol::DFRN)
242 if (DBA::isResult($r)) {
243 foreach ($r as $rr) {
244 $recipients_followup[] = $rr['id'];
250 if ($direct_forum_delivery) {
251 $push_notify = false;
254 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
258 Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
260 // don't send deletions onward for other people's stuff
262 if ($target_item['deleted'] && !intval($target_item['wall'])) {
263 Logger::log('Ignoring delete notification for non-wall item');
267 if (strlen($parent['allow_cid'])
268 || strlen($parent['allow_gid'])
269 || strlen($parent['deny_cid'])
270 || strlen($parent['deny_gid'])) {
271 $public_message = false; // private recipients, not public
274 $allow_people = expand_acl($parent['allow_cid']);
275 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
276 $deny_people = expand_acl($parent['deny_cid']);
277 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
279 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
280 // a delivery fork. private groups (forum_mode == 2) do not uplink
282 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
283 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $target_id);
286 foreach ($items as $item) {
287 $recipients[] = $item['contact-id'];
288 // pull out additional tagged people to notify (if public message)
289 if ($public_message && strlen($item['inform'])) {
290 $people = explode(',',$item['inform']);
291 foreach ($people as $person) {
292 if (substr($person,0,4) === 'cid:') {
293 $recipients[] = intval(substr($person,4));
295 $url_recipients[] = substr($person,4);
301 if (count($url_recipients)) {
302 Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_encode($url_recipients));
305 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
306 $deny = array_unique(array_merge($deny_people, $deny_groups));
307 $recipients = array_diff($recipients, $deny);
310 // If the thread parent is OStatus then do some magic to distribute the messages.
311 // We have not only to look at the parent, since it could be a Friendica thread.
312 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
313 $diaspora_delivery = false;
315 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
317 // Send a salmon to the parent author
318 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
319 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
320 Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
321 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
324 // Send a salmon to the parent owner
325 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
326 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
327 Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
328 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
331 // Send a salmon notification to every person we mentioned in the post
332 $arr = explode(',',$target_item['tag']);
333 foreach ($arr as $x) {
334 //Logger::log('Checking tag '.$x, Logger::DEBUG);
336 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
337 $probed_contact = Probe::uri($matches[1]);
338 if ($probed_contact["notify"] != "") {
339 Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
340 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
345 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
346 $networks = [Protocol::OSTATUS, Protocol::DFRN];
348 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
351 $public_message = false;
354 // If this is a public message and pubmail is set on the parent, include all your email contacts
355 if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
356 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
357 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
358 && intval($target_item['pubmail'])) {
359 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
361 DBA::escape(Protocol::MAIL)
363 if (DBA::isResult($r)) {
364 foreach ($r as $rr) {
365 $recipients[] = $rr['id'];
371 if ($cmd == Delivery::RELOCATION) {
372 $contacts = $recipients_relocate;
375 $recipients = $recipients_followup;
377 $condition = ['id' => $recipients, 'self' => false,
378 'blocked' => false, 'pending' => false, 'archive' => false];
379 if (!empty($networks)) {
380 $condition['network'] = $networks;
382 $result = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
383 $contacts = DBA::toArray($result);
387 $batch_delivery = false;
389 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
392 if ($diaspora_delivery) {
393 $batch_delivery = true;
395 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
396 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
397 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
398 DBA::escape(Protocol::DIASPORA),
399 intval($owner['uid']),
400 intval(Contact::SHARING)
403 // Fetch the participation list
404 // The function will ensure that there are no duplicates
405 $r1 = Diaspora::participantsForThread($target_id, $r1);
407 // Add the relay to the list, avoid duplicates.
408 // Don't send community posts to the relay. Forum posts via the Diaspora protocol are looking ugly.
409 if (!$followup && !self::isForumPost($target_item, $owner)) {
410 $r1 = Diaspora::relayList($target_id, $r1);
414 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
415 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
417 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
419 $r = array_merge($r2, $r1);
421 if (DBA::isResult($r)) {
422 foreach ($r as $rr) {
423 $conversants[] = $rr['id'];
424 Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $target_id . ') to ' . json_encode($rr), Logger::DEBUG);
426 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
427 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
428 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
429 if ($rr['network'] == Protocol::DIASPORA) {
430 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
432 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
434 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$rr['id']);
442 if (DBA::isResult($contacts)) {
443 foreach ($contacts as $contact) {
444 // Don't deliver to Diaspora if it already had been done as batch delivery
445 if (($contact['network'] == Protocol::DIASPORA) && $batch_delivery) {
446 Logger::log('Already delivered id ' . $target_id . ' via batch to ' . json_encode($contact), Logger::DEBUG);
450 // Don't deliver to folks who have already been delivered to
451 if (in_array($contact['id'], $conversants)) {
452 Logger::log('Already delivered id ' . $target_id. ' to ' . json_encode($contact), Logger::DEBUG);
456 Logger::log('Delivery of item ' . $target_id . ' to ' . json_encode($contact), Logger::DEBUG);
458 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
459 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
460 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
461 if ($contact['network'] == Protocol::DIASPORA) {
462 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
464 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
466 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$contact['id']);
470 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
471 // They are especially used for notifications to OStatus users that don't follow us.
472 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
473 $slap = OStatus::salmon($target_item, $owner);
474 foreach ($url_recipients as $url) {
476 Logger::log('Salmon delivery of item ' . $target_id . ' to ' . $url);
477 /// @TODO Redeliver/queue these items on failure, though there is no contact record
478 Salmon::slapper($owner, $url, $slap);
483 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
485 Logger::log('Activating internal PuSH for item '.$target_id, Logger::DEBUG);
487 // Handling the pubsubhubbub requests
488 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
491 Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
494 Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
497 Hook::callAll('notifier_end',$target_item);
503 * @param int $self_user_id
504 * @param int $priority The priority the Notifier queue item was created with
505 * @param string $created The date the Notifier queue item was created on
508 private static function notifySelfRemoval($self_user_id, $priority, $created)
510 $owner = User::getOwnerDataById($self_user_id);
515 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
516 if (!DBA::isResult($contacts_stmt)) {
520 while($contact = DBA::fetch($contacts_stmt)) {
521 Contact::terminateFriendship($owner, $contact, true);
524 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
525 foreach ($inboxes as $inbox) {
526 Logger::log('Account removal for user ' . $self_user_id . ' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
527 Worker::add(['priority' => PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
528 'APDelivery', Delivery::REMOVAL, '', $inbox, $self_user_id);
536 * @param array $target_item
537 * @param array $parent
538 * @param int $priority The priority the Notifier queue item was created with
539 * @param string $created The date the Notifier queue item was created on
541 private static function activityPubDelivery($cmd, array $target_item, array $parent, $priority, $created)
545 if ($target_item['origin']) {
546 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $target_item['contact-uid']);
547 Logger::log('Origin item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
548 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
549 Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
551 } elseif ($parent['origin']) {
552 // Remote items are transmitted via the personal inboxes.
553 // Doing so ensures that the dedicated receiver will get the message.
554 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $target_item['contact-uid'], true, $target_item['id']);
555 Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
558 if (empty($inboxes)) {
559 Logger::log('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
563 // Fill the item cache
564 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
566 foreach ($inboxes as $inbox) {
567 Logger::log('Deliver ' . $target_item['id'] .' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
569 Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
570 'APDelivery', $cmd, $target_item['id'], $inbox, $target_item['contact-uid']);
574 private static function isForumPost(array $item, array $owner)
576 if (($item['author-id'] == $item['owner-id']) ||
577 ($owner['id'] == $item['contact-id']) ||
578 ($item['uri'] != $item['parent-uri'])) {
582 $fields = ['forum', 'prv'];
583 $condition = ['id' => $item['contact-id']];
584 $contact = DBA::selectFirst('contact', $fields, $condition);
585 if (!DBA::isResult($contact)) {
586 // Should never happen
590 // Is the post from a forum?
591 return ($contact['forum'] || $contact['prv']);