3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Conversation;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Model\PushSubscriber;
20 use Friendica\Model\User;
21 use Friendica\Network\Probe;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Protocol\Salmon;
27 require_once 'include/dba.php';
28 require_once 'include/items.php';
31 * The notifier is typically called with:
33 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
35 * where COMMAND is one of the following:
37 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
38 * comment-import (in diaspora.php, items.php)
39 * comment-new (in item.php)
40 * drop (in diaspora.php, items.php, photos.php)
41 * edit_post (in item.php)
42 * event (in events.php)
43 * like (in like.php, poke.php)
44 * mail (in message.php)
45 * suggest (in fsuggest.php)
46 * tag (in photos.php, poke.php, tagger.php)
47 * tgroup (in items.php)
48 * wall-new (in photos.php, item.php)
49 * removeme (in Contact.php)
50 * relocate (in uimport.php)
52 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
57 public static function execute($cmd, $item_id)
59 $a = BaseObject::getApp();
61 Logger::log('Invoked: ' . $cmd . ': ' . $item_id, Logger::DEBUG);
68 $recipients_relocate = [];
70 if ($cmd == Delivery::MAIL) {
72 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
73 if (!DBA::isResult($message)) {
76 $uid = $message['uid'];
77 $recipients[] = $message['contact-id'];
78 } elseif ($cmd == Delivery::SUGGESTION) {
80 $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
81 if (!DBA::isResult($suggest)) {
84 $uid = $suggest['uid'];
85 $recipients[] = $suggest['cid'];
86 } elseif ($cmd == Delivery::REMOVAL) {
87 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
88 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
89 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
90 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
91 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
98 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
102 foreach ($r as $contact) {
103 Contact::terminateFriendship($user, $contact, true);
106 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
107 foreach ($inboxes as $inbox) {
108 Logger::log('Account removal for user ' . $item_id . ' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
109 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
110 'APDelivery', Delivery::REMOVAL, '', $inbox, $item_id);
114 } elseif ($cmd == Delivery::RELOCATION) {
115 $normal_mode = false;
118 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
119 intval($uid), Protocol::DFRN, Protocol::DIASPORA);
122 $condition = ['id' => $item_id, 'visible' => true, 'moderated' => false];
123 $target_item = Item::selectFirst([], $condition);
125 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
129 $parent_id = intval($target_item['parent']);
130 $uid = $target_item['contact-uid'];
131 $updated = $target_item['edited'];
133 $condition = ['parent' => $parent_id, 'visible' => true, 'moderated' => false];
134 $params = ['order' => ['id']];
135 $ret = Item::select([], $condition, $params);
137 if (!DBA::isResult($ret)) {
141 $items = Item::inArray($ret);
143 // avoid race condition with deleting entries
144 if ($items[0]['deleted']) {
145 foreach ($items as $item) {
146 $item['deleted'] = 1;
150 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
151 Logger::log('Top level post');
156 $owner = User::getOwnerDataById($uid);
161 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
163 // Should the post be transmitted to Diaspora?
164 $diaspora_delivery = true;
166 // If this is a public conversation, notify the feed hub
167 $public_message = true;
170 $push_notify = false;
172 // Deliver directly to a forum, don't PuSH
173 $direct_forum_delivery = false;
176 $recipients_followup = [];
178 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
181 self::activityPubDelivery($a, $cmd, $item_id, $uid, $target_item, $parent);
183 $fields = ['network', 'author-id', 'owner-id'];
184 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
185 $thr_parent = Item::selectFirst($fields, $condition);
187 Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
189 // This is IMPORTANT!!!!
191 // We will only send a "notify owner to relay" or followup message if the referenced post
192 // originated on our system by virtue of having our hostname somewhere
193 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
195 // if $parent['wall'] == 1 we will already have the parent message in our array
196 // and we will relay the whole lot.
198 $localhost = str_replace('www.','',$a->getHostName());
199 if (strpos($localhost,':')) {
200 $localhost = substr($localhost,0,strpos($localhost,':'));
204 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
205 * have been known to cause runaway conditions which affected several servers, along with
206 * permissions issues.
210 $relay_to_owner = false;
212 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
213 $relay_to_owner = true;
217 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
218 $relay_to_owner = true;
221 // until the 'origin' flag has been in use for several months
222 // we will just use it as a fallback test
223 // later we will be able to use it as the primary test of whether or not to relay.
225 if (!$target_item['origin']) {
226 $relay_to_owner = false;
228 if ($parent['origin']) {
229 $relay_to_owner = false;
232 // Special treatment for forum posts
233 if (self::isForumPost($target_item, $owner)) {
234 $relay_to_owner = true;
235 $direct_forum_delivery = true;
238 // Avoid that comments in a forum thread are sent to OStatus
239 if (self::isForumPost($parent, $owner)) {
240 $direct_forum_delivery = true;
243 if ($relay_to_owner) {
244 // local followup to remote post
246 $public_message = false; // not public
247 $recipients = [$parent['contact-id']];
248 $recipients_followup = [$parent['contact-id']];
250 Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
252 //if (!$target_item['private'] && $target_item['wall'] &&
253 if (!$target_item['private'] &&
254 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
255 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
258 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
261 if ($parent["network"] == Protocol::OSTATUS) {
262 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
263 // Currently it is work at progress
264 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
266 DBA::escape(Protocol::DFRN)
268 if (DBA::isResult($r)) {
269 foreach ($r as $rr) {
270 $recipients_followup[] = $rr['id'];
276 if ($direct_forum_delivery) {
277 $push_notify = false;
280 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
284 Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
286 // don't send deletions onward for other people's stuff
288 if ($target_item['deleted'] && !intval($target_item['wall'])) {
289 Logger::log('Ignoring delete notification for non-wall item');
293 if (strlen($parent['allow_cid'])
294 || strlen($parent['allow_gid'])
295 || strlen($parent['deny_cid'])
296 || strlen($parent['deny_gid'])) {
297 $public_message = false; // private recipients, not public
300 $allow_people = expand_acl($parent['allow_cid']);
301 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
302 $deny_people = expand_acl($parent['deny_cid']);
303 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
305 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
306 // a delivery fork. private groups (forum_mode == 2) do not uplink
308 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
309 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
312 foreach ($items as $item) {
313 $recipients[] = $item['contact-id'];
314 // pull out additional tagged people to notify (if public message)
315 if ($public_message && strlen($item['inform'])) {
316 $people = explode(',',$item['inform']);
317 foreach ($people as $person) {
318 if (substr($person,0,4) === 'cid:') {
319 $recipients[] = intval(substr($person,4));
321 $url_recipients[] = substr($person,4);
327 if (count($url_recipients)) {
328 Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_decode($url_recipients));
331 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
332 $deny = array_unique(array_merge($deny_people, $deny_groups));
333 $recipients = array_diff($recipients, $deny);
336 // If the thread parent is OStatus then do some magic to distribute the messages.
337 // We have not only to look at the parent, since it could be a Friendica thread.
338 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
339 $diaspora_delivery = false;
341 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
343 // Send a salmon to the parent author
344 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
345 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
346 Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
347 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
350 // Send a salmon to the parent owner
351 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
352 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
353 Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
354 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
357 // Send a salmon notification to every person we mentioned in the post
358 $arr = explode(',',$target_item['tag']);
359 foreach ($arr as $x) {
360 //Logger::log('Checking tag '.$x, Logger::DEBUG);
362 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
363 $probed_contact = Probe::uri($matches[1]);
364 if ($probed_contact["notify"] != "") {
365 Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
366 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
371 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
372 $networks = [Protocol::OSTATUS, Protocol::DFRN];
374 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
377 $public_message = false;
380 // If this is a public message and pubmail is set on the parent, include all your email contacts
381 if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
382 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
383 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
384 && intval($target_item['pubmail'])) {
385 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
387 DBA::escape(Protocol::MAIL)
389 if (DBA::isResult($r)) {
390 foreach ($r as $rr) {
391 $recipients[] = $rr['id'];
397 if (($cmd == Delivery::RELOCATION)) {
398 $contacts = $recipients_relocate;
401 $recipients = $recipients_followup;
403 $condition = ['id' => $recipients, 'self' => false,
404 'blocked' => false, 'pending' => false, 'archive' => false];
405 if (!empty($networks)) {
406 $condition['network'] = $networks;
408 $result = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
409 $contacts = DBA::toArray($result);
413 $batch_delivery = false;
415 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
418 if ($diaspora_delivery) {
419 $batch_delivery = true;
421 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
422 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
423 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
424 DBA::escape(Protocol::DIASPORA),
425 intval($owner['uid']),
426 intval(Contact::SHARING)
429 // Fetch the participation list
430 // The function will ensure that there are no duplicates
431 $r1 = Diaspora::participantsForThread($item_id, $r1);
433 // Add the relay to the list, avoid duplicates
435 $r1 = Diaspora::relayList($item_id, $r1);
439 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
440 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
442 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
444 $r = array_merge($r2, $r1);
446 if (DBA::isResult($r)) {
447 foreach ($r as $rr) {
448 $conversants[] = $rr['id'];
449 Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $item_id . ') to ' . json_encode($rr), Logger::DEBUG);
450 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
451 'Delivery', $cmd, $item_id, (int)$rr['id']);
459 if (DBA::isResult($contacts)) {
460 foreach ($contacts as $contact) {
461 // Don't deliver to Diaspora if it already had been done as batch delivery
462 if (($contact['network'] == Protocol::DIASPORA) && $batch_delivery) {
463 Logger::log('Already delivered id ' . $item_id . ' via batch to ' . json_encode($contact), Logger::DEBUG);
467 // Don't deliver to folks who have already been delivered to
468 if (in_array($contact['id'], $conversants)) {
469 Logger::log('Already delivered id ' . $item_id. ' to ' . json_encode($contact), Logger::DEBUG);
473 Logger::log('Delivery of item ' . $item_id . ' to ' . json_encode($contact), Logger::DEBUG);
474 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
475 'Delivery', $cmd, $item_id, (int)$contact['id']);
479 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
480 // They are especially used for notifications to OStatus users that don't follow us.
481 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
482 $slap = OStatus::salmon($target_item, $owner);
483 foreach ($url_recipients as $url) {
485 Logger::log('Salmon delivery of item ' . $item_id . ' to ' . $url);
486 $deliver_status = Salmon::slapper($owner, $url, $slap);
487 /// @TODO Redeliver/queue these items on failure, though there is no contact record
492 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
494 Logger::log('Activating internal PuSH for item '.$item_id, Logger::DEBUG);
496 // Handling the pubsubhubbub requests
497 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
500 Logger::log('Calling hooks for ' . $cmd . ' ' . $item_id, Logger::DEBUG);
503 Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
506 Addon::callHooks('notifier_end',$target_item);
511 private static function activityPubDelivery($a, $cmd, $item_id, $uid, $target_item, $parent)
516 if ($target_item['origin']) {
517 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
518 Logger::log('Origin item ' . $item_id . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
519 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
520 Logger::log('Remote item ' . $item_id . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
523 // Remote items are transmitted via the personal inboxes.
524 // Doing so ensures that the dedicated receiver will get the message.
526 Logger::log('Remote item ' . $item_id . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
529 if ($parent['origin']) {
530 $parent_inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, $personal);
531 $inboxes = array_merge($inboxes, $parent_inboxes);
534 if (empty($inboxes)) {
535 Logger::log('No inboxes found for item ' . $item_id . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
539 // Fill the item cache
540 ActivityPub\Transmitter::createCachedActivityFromItem($item_id, true);
542 foreach ($inboxes as $inbox) {
543 Logger::log('Deliver ' . $item_id .' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
545 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
546 'APDelivery', $cmd, $item_id, $inbox, $uid);
550 private static function isForumPost($item, $owner) {
551 if (($item['author-id'] == $item['owner-id']) ||
552 ($owner['id'] == $item['contact-id']) ||
553 ($item['uri'] != $item['parent-uri'])) {
557 $fields = ['forum', 'prv'];
558 $condition = ['id' => $item['contact-id']];
559 $contact = DBA::selectFirst('contact', $fields, $condition);
560 if (!DBA::isResult($contact)) {
561 // Should never happen
565 // Is the post from a forum?
566 return ($contact['forum'] || $contact['prv']);