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('notifier: 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('notifier: 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 = [];
179 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
182 self::activityPubDelivery($a, $cmd, $item_id, $uid, $target_item, $parent);
184 $fields = ['network', 'author-id', 'owner-id'];
185 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
186 $thr_parent = Item::selectFirst($fields, $condition);
188 Logger::log('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], Logger::DEBUG);
190 // This is IMPORTANT!!!!
192 // We will only send a "notify owner to relay" or followup message if the referenced post
193 // originated on our system by virtue of having our hostname somewhere
194 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
196 // if $parent['wall'] == 1 we will already have the parent message in our array
197 // and we will relay the whole lot.
199 $localhost = str_replace('www.','',$a->getHostName());
200 if (strpos($localhost,':')) {
201 $localhost = substr($localhost,0,strpos($localhost,':'));
205 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
206 * have been known to cause runaway conditions which affected several servers, along with
207 * permissions issues.
211 $relay_to_owner = false;
213 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
214 $relay_to_owner = true;
218 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
219 $relay_to_owner = true;
222 // until the 'origin' flag has been in use for several months
223 // we will just use it as a fallback test
224 // later we will be able to use it as the primary test of whether or not to relay.
226 if (!$target_item['origin']) {
227 $relay_to_owner = false;
229 if ($parent['origin']) {
230 $relay_to_owner = false;
233 // Special treatment for forum posts
234 if (self::isForumPost($target_item, $owner)) {
235 $relay_to_owner = true;
236 $direct_forum_delivery = true;
239 // Avoid that comments in a forum thread are sent to OStatus
240 if (self::isForumPost($parent, $owner)) {
241 $direct_forum_delivery = true;
244 if ($relay_to_owner) {
245 // local followup to remote post
247 $public_message = false; // not public
248 $conversant_str = DBA::escape($parent['contact-id']);
249 $recipients = [$parent['contact-id']];
250 $recipients_followup = [$parent['contact-id']];
252 Logger::log('notifier: followup '.$target_item["guid"].' to '.$conversant_str, Logger::DEBUG);
254 //if (!$target_item['private'] && $target_item['wall'] &&
255 if (!$target_item['private'] &&
256 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
257 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
260 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
263 if ($parent["network"] == Protocol::OSTATUS) {
264 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
265 // Currently it is work at progress
266 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
268 DBA::escape(Protocol::DFRN)
270 if (DBA::isResult($r)) {
271 foreach ($r as $rr) {
272 $recipients_followup[] = $rr['id'];
278 if ($direct_forum_delivery) {
279 $push_notify = false;
282 Logger::log("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), Logger::DEBUG);
286 Logger::log('Distributing directly '.$target_item["guid"], Logger::DEBUG);
288 // don't send deletions onward for other people's stuff
290 if ($target_item['deleted'] && !intval($target_item['wall'])) {
291 Logger::log('notifier: ignoring delete notification for non-wall item');
295 if (strlen($parent['allow_cid'])
296 || strlen($parent['allow_gid'])
297 || strlen($parent['deny_cid'])
298 || strlen($parent['deny_gid'])) {
299 $public_message = false; // private recipients, not public
302 $allow_people = expand_acl($parent['allow_cid']);
303 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
304 $deny_people = expand_acl($parent['deny_cid']);
305 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
307 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
308 // a delivery fork. private groups (forum_mode == 2) do not uplink
310 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
311 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
314 foreach ($items as $item) {
315 $recipients[] = $item['contact-id'];
316 $conversants[] = $item['contact-id'];
317 // pull out additional tagged people to notify (if public message)
318 if ($public_message && strlen($item['inform'])) {
319 $people = explode(',',$item['inform']);
320 foreach ($people as $person) {
321 if (substr($person,0,4) === 'cid:') {
322 $recipients[] = intval(substr($person,4));
323 $conversants[] = intval(substr($person,4));
325 $url_recipients[] = substr($person,4);
331 if (count($url_recipients)) {
332 Logger::log('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
335 $conversants = array_unique($conversants);
337 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
338 $deny = array_unique(array_merge($deny_people,$deny_groups));
339 $recipients = array_diff($recipients,$deny);
341 $conversant_str = DBA::escape(implode(', ',$conversants));
344 // If the thread parent is OStatus then do some magic to distribute the messages.
345 // We have not only to look at the parent, since it could be a Friendica thread.
346 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
347 $diaspora_delivery = false;
349 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
351 // Send a salmon to the parent author
352 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
353 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
354 Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
355 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
358 // Send a salmon to the parent owner
359 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
360 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
361 Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
362 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
365 // Send a salmon notification to every person we mentioned in the post
366 $arr = explode(',',$target_item['tag']);
367 foreach ($arr as $x) {
368 //Logger::log('Checking tag '.$x, Logger::DEBUG);
370 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
371 $probed_contact = Probe::uri($matches[1]);
372 if ($probed_contact["notify"] != "") {
373 Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
374 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
379 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
380 $networks = [Protocol::OSTATUS, Protocol::DFRN];
382 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
385 $public_message = false;
388 // If this is a public message and pubmail is set on the parent, include all your email contacts
389 if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
390 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
391 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
392 && intval($target_item['pubmail'])) {
393 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
395 DBA::escape(Protocol::MAIL)
397 if (DBA::isResult($r)) {
398 foreach ($r as $rr) {
399 $recipients[] = $rr['id'];
405 if (($cmd == Delivery::RELOCATION)) {
406 $r = $recipients_relocate;
409 $recipients = $recipients_followup;
411 $condition = ['id' => $recipients, 'self' => false,
412 'blocked' => false, 'pending' => false, 'archive' => false];
413 if (!empty($networks)) {
414 $condition['network'] = $networks;
416 $contacts = DBA::select('contact', ['id', 'url', 'network'], $condition);
417 $r = DBA::toArray($contacts);
421 if (DBA::isResult($r)) {
422 foreach ($r as $contact) {
423 Logger::log("Deliver ".$item_id." to ".$contact['url']." via network ".$contact['network'], Logger::DEBUG);
425 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
426 'Delivery', $cmd, $item_id, (int)$contact['id']);
430 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
431 // They are especially used for notifications to OStatus users that don't follow us.
432 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
433 $slap = OStatus::salmon($target_item, $owner);
434 foreach ($url_recipients as $url) {
436 Logger::log('notifier: urldelivery: ' . $url);
437 $deliver_status = Salmon::slapper($owner, $url, $slap);
438 /// @TODO Redeliver/queue these items on failure, though there is no contact record
443 if ($public_message) {
446 if ($diaspora_delivery) {
447 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
448 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
449 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
450 DBA::escape(Protocol::DIASPORA),
451 intval($owner['uid']),
452 intval(Contact::SHARING)
455 // Fetch the participation list
456 // The function will ensure that there are no duplicates
457 $r1 = Diaspora::participantsForThread($item_id, $r1);
459 // Add the relay to the list, avoid duplicates
461 $r1 = Diaspora::relayList($item_id, $r1);
465 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
466 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
468 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
470 $r = array_merge($r2, $r1);
472 if (DBA::isResult($r)) {
473 Logger::log('pubdeliver '.$target_item["guid"].': '.print_r($r,true), Logger::DEBUG);
475 foreach ($r as $rr) {
476 // except for Diaspora batch jobs
477 // Don't deliver to folks who have already been delivered to
479 if (($rr['network'] !== Protocol::DIASPORA) && (in_array($rr['id'], $conversants))) {
480 Logger::log('notifier: already delivered id=' . $rr['id']);
484 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
485 Logger::log('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
486 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
487 'Delivery', $cmd, $item_id, (int)$rr['id']);
495 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
497 Logger::log('Activating internal PuSH for item '.$item_id, Logger::DEBUG);
499 // Handling the pubsubhubbub requests
500 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
503 Logger::log('notifier: calling hooks for ' . $cmd . ' ' . $item_id, Logger::DEBUG);
506 Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
509 Addon::callHooks('notifier_end',$target_item);
514 private static function activityPubDelivery($a, $cmd, $item_id, $uid, $target_item, $parent)
519 if ($target_item['origin']) {
520 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
521 Logger::log('Origin item ' . $item_id . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
522 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
523 Logger::log('Remote item ' . $item_id . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
526 // Remote items are transmitted via the personal inboxes.
527 // Doing so ensures that the dedicated receiver will get the message.
529 Logger::log('Remote item ' . $item_id . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
532 if ($parent['origin']) {
533 $parent_inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, $personal);
534 $inboxes = array_merge($inboxes, $parent_inboxes);
537 if (empty($inboxes)) {
538 Logger::log('No inboxes found for item ' . $item_id . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
542 // Fill the item cache
543 ActivityPub\Transmitter::createCachedActivityFromItem($item_id, true);
545 foreach ($inboxes as $inbox) {
546 Logger::log('Deliver ' . $item_id .' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
548 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
549 'APDelivery', $cmd, $item_id, $inbox, $uid);
553 private static function isForumPost($item, $owner) {
554 if (($item['author-id'] == $item['owner-id']) ||
555 ($owner['id'] == $item['contact-id']) ||
556 ($item['uri'] != $item['parent-uri'])) {
560 $fields = ['forum', 'prv'];
561 $condition = ['id' => $item['contact-id']];
562 $contact = DBA::selectFirst('contact', $fields, $condition);
563 if (!DBA::isResult($contact)) {
564 // Should never happen
568 // Is the post from a forum?
569 return ($contact['forum'] || $contact['prv']);