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;
26 require_once 'include/items.php';
29 * The notifier is typically called with:
31 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
33 * where COMMAND is one of the following:
35 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
36 * comment-import (in diaspora.php, items.php)
37 * comment-new (in item.php)
38 * drop (in diaspora.php, items.php, photos.php)
39 * edit_post (in item.php)
40 * event (in events.php)
41 * like (in like.php, poke.php)
42 * mail (in message.php)
43 * suggest (in fsuggest.php)
44 * tag (in photos.php, poke.php, tagger.php)
45 * tgroup (in items.php)
46 * wall-new (in photos.php, item.php)
47 * removeme (in Contact.php)
48 * relocate (in uimport.php)
50 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
55 public static function execute($cmd, $target_id)
57 $a = BaseObject::getApp();
59 Logger::log('Invoked: ' . $cmd . ': ' . $target_id, Logger::DEBUG);
65 $delivery_contacts_stmt = null;
69 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) {
77 $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $target_id]);
78 if (!DBA::isResult($suggest)) {
81 $uid = $suggest['uid'];
82 $recipients[] = $suggest['cid'];
83 } elseif ($cmd == Delivery::REMOVAL) {
84 return self::notifySelfRemoval($target_id, $a->queue['priority'], $a->queue['created']);
85 } elseif ($cmd == Delivery::RELOCATION) {
88 $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
89 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
92 $condition = ['id' => $target_id, 'visible' => true, 'moderated' => false];
93 $target_item = Item::selectFirst([], $condition);
95 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
99 if (!empty($target_item['contact-uid'])) {
100 $uid = $target_item['contact-uid'];
101 } elseif (!empty($target_item['uid'])) {
102 $uid = $target_item['uid'];
104 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
108 $condition = ['parent' => $target_item['parent'], 'visible' => true, 'moderated' => false];
109 $params = ['order' => ['id']];
110 $items_stmt = Item::select([], $condition, $params);
111 if (!DBA::isResult($items_stmt)) {
115 $items = Item::inArray($items_stmt);
117 // avoid race condition with deleting entries
118 if ($items[0]['deleted']) {
119 foreach ($items as $item) {
120 $item['deleted'] = 1;
124 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
125 Logger::log('Top level post');
130 $owner = User::getOwnerDataById($uid);
135 // Should the post be transmitted to Diaspora?
136 $diaspora_delivery = true;
138 // If this is a public conversation, notify the feed hub
139 $public_message = true;
142 $push_notify = false;
144 // Deliver directly to a forum, don't PuSH
145 $direct_forum_delivery = false;
148 $recipients_followup = [];
150 if (!empty($target_item) && !empty($items)) {
153 self::activityPubDelivery($cmd, $target_item, $parent, $a->queue['priority'], $a->query_string['created']);
155 $fields = ['network', 'author-id', 'owner-id'];
156 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
157 $thr_parent = Item::selectFirst($fields, $condition);
159 Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
161 // This is IMPORTANT!!!!
163 // We will only send a "notify owner to relay" or followup message if the referenced post
164 // originated on our system by virtue of having our hostname somewhere
165 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
167 // if $parent['wall'] == 1 we will already have the parent message in our array
168 // and we will relay the whole lot.
170 $localhost = str_replace('www.','',$a->getHostName());
171 if (strpos($localhost,':')) {
172 $localhost = substr($localhost,0,strpos($localhost,':'));
176 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
177 * have been known to cause runaway conditions which affected several servers, along with
178 * permissions issues.
182 $relay_to_owner = false;
184 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
185 $relay_to_owner = true;
189 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
190 $relay_to_owner = true;
193 // until the 'origin' flag has been in use for several months
194 // we will just use it as a fallback test
195 // later we will be able to use it as the primary test of whether or not to relay.
197 if (!$target_item['origin']) {
198 $relay_to_owner = false;
200 if ($parent['origin']) {
201 $relay_to_owner = false;
204 // Special treatment for forum posts
205 if (self::isForumPost($target_item, $owner)) {
206 $relay_to_owner = true;
207 $direct_forum_delivery = true;
210 // Avoid that comments in a forum thread are sent to OStatus
211 if (self::isForumPost($parent, $owner)) {
212 $direct_forum_delivery = true;
215 if ($relay_to_owner) {
216 // local followup to remote post
218 $public_message = false; // not public
219 $recipients = [$parent['contact-id']];
220 $recipients_followup = [$parent['contact-id']];
222 Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
224 //if (!$target_item['private'] && $target_item['wall'] &&
225 if (!$target_item['private'] &&
226 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
227 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
230 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
233 if ($parent["network"] == Protocol::OSTATUS) {
234 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
235 // Currently it is work at progress
236 $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
237 $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
238 while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
239 $recipients_followup[] = $followup_contact['id'];
241 DBA::close($followup_contacts_stmt);
245 if ($direct_forum_delivery) {
246 $push_notify = false;
249 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
253 Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
255 // don't send deletions onward for other people's stuff
257 if ($target_item['deleted'] && !intval($target_item['wall'])) {
258 Logger::log('Ignoring delete notification for non-wall item');
262 if (strlen($parent['allow_cid'])
263 || strlen($parent['allow_gid'])
264 || strlen($parent['deny_cid'])
265 || strlen($parent['deny_gid'])) {
266 $public_message = false; // private recipients, not public
269 $allow_people = expand_acl($parent['allow_cid']);
270 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
271 $deny_people = expand_acl($parent['deny_cid']);
272 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
274 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
275 // a delivery fork. private groups (forum_mode == 2) do not uplink
277 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
278 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $target_id);
281 foreach ($items as $item) {
282 $recipients[] = $item['contact-id'];
283 // pull out additional tagged people to notify (if public message)
284 if ($public_message && strlen($item['inform'])) {
285 $people = explode(',',$item['inform']);
286 foreach ($people as $person) {
287 if (substr($person,0,4) === 'cid:') {
288 $recipients[] = intval(substr($person,4));
290 $url_recipients[] = substr($person,4);
296 if (count($url_recipients)) {
297 Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_encode($url_recipients));
300 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
301 $deny = array_unique(array_merge($deny_people, $deny_groups));
302 $recipients = array_diff($recipients, $deny);
304 // If this is a public message and pubmail is set on the parent, include all your email contacts
306 function_exists('imap_open')
307 && !Config::get('system','imap_disabled')
309 && intval($target_item['pubmail'])
311 $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
312 while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
313 $recipients[] = $mail_contact['id'];
315 DBA::close($mail_contacts_stmt);
319 // If the thread parent is OStatus then do some magic to distribute the messages.
320 // We have not only to look at the parent, since it could be a Friendica thread.
321 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
322 $diaspora_delivery = false;
324 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
326 // Send a salmon to the parent author
327 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
328 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
329 Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
330 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
333 // Send a salmon to the parent owner
334 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
335 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
336 Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
337 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
340 // Send a salmon notification to every person we mentioned in the post
341 $arr = explode(',',$target_item['tag']);
342 foreach ($arr as $x) {
343 //Logger::log('Checking tag '.$x, Logger::DEBUG);
345 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
346 $probed_contact = Probe::uri($matches[1]);
347 if ($probed_contact["notify"] != "") {
348 Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
349 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
354 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
355 $networks = [Protocol::OSTATUS, Protocol::DFRN];
357 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
360 $public_message = false;
363 if (empty($delivery_contacts_stmt)) {
365 $recipients = $recipients_followup;
367 $condition = ['id' => $recipients, 'self' => false,
368 'blocked' => false, 'pending' => false, 'archive' => false];
369 if (!empty($networks)) {
370 $condition['network'] = $networks;
372 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
376 $batch_delivery = false;
378 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
381 if ($diaspora_delivery) {
382 $batch_delivery = true;
384 $relay_list_stmt = DBA::p(
387 ANY_VALUE(`id`) AS `id`,
388 ANY_VALUE(`name`) AS `name`,
389 ANY_VALUE(`network`) AS `network`
403 $relay_list = DBA::toArray($relay_list_stmt);
405 // Fetch the participation list
406 // The function will ensure that there are no duplicates
407 $relay_list = Diaspora::participantsForThread($target_id, $relay_list);
409 // Add the relay to the list, avoid duplicates.
410 // Don't send community posts to the relay. Forum posts via the Diaspora protocol are looking ugly.
411 if (!$followup && !self::isForumPost($target_item, $owner)) {
412 $relay_list = Diaspora::relayList($target_id, $relay_list);
416 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
417 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
419 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
421 $r = array_merge($r2, $relay_list);
423 if (DBA::isResult($r)) {
424 foreach ($r as $rr) {
425 $conversants[] = $rr['id'];
426 Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $target_id . ') to ' . json_encode($rr), Logger::DEBUG);
428 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
429 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
430 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
431 if ($rr['network'] == Protocol::DIASPORA) {
432 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
434 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
436 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$rr['id']);
444 while ($contact = DBA::fetch($delivery_contacts_stmt)) {
445 // Don't deliver to Diaspora if it already had been done as batch delivery
446 if (($contact['network'] == Protocol::DIASPORA) && $batch_delivery) {
447 Logger::log('Already delivered id ' . $target_id . ' via batch to ' . json_encode($contact), Logger::DEBUG);
451 // Don't deliver to folks who have already been delivered to
452 if (in_array($contact['id'], $conversants)) {
453 Logger::log('Already delivered id ' . $target_id. ' to ' . json_encode($contact), Logger::DEBUG);
457 Logger::log('Delivery of item ' . $target_id . ' to ' . json_encode($contact), Logger::DEBUG);
459 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
460 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
461 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
462 if ($contact['network'] == Protocol::DIASPORA) {
463 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
465 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
467 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$contact['id']);
469 DBA::close($delivery_contacts_stmt);
472 $url_recipients = array_filter($url_recipients);
473 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
474 // They are especially used for notifications to OStatus users that don't follow us.
475 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
476 $slap = OStatus::salmon($target_item, $owner);
477 foreach ($url_recipients as $url) {
478 Logger::log('Salmon delivery of item ' . $target_id . ' to ' . $url);
479 /// @TODO Redeliver/queue these items on failure, though there is no contact record
480 Salmon::slapper($owner, $url, $slap);
484 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
486 Logger::log('Activating internal PuSH for item '.$target_id, Logger::DEBUG);
488 // Handling the pubsubhubbub requests
489 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
492 if (!empty($target_item)) {
493 Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
495 Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
497 Hook::callAll('notifier_end', $target_item);
504 * @param int $self_user_id
505 * @param int $priority The priority the Notifier queue item was created with
506 * @param string $created The date the Notifier queue item was created on
509 private static function notifySelfRemoval($self_user_id, $priority, $created)
511 $owner = User::getOwnerDataById($self_user_id);
516 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
517 if (!DBA::isResult($contacts_stmt)) {
521 while($contact = DBA::fetch($contacts_stmt)) {
522 Contact::terminateFriendship($owner, $contact, true);
524 DBA::close($contacts_stmt);
526 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
527 foreach ($inboxes as $inbox) {
528 Logger::log('Account removal for user ' . $self_user_id . ' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
529 Worker::add(['priority' => PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
530 'APDelivery', Delivery::REMOVAL, '', $inbox, $self_user_id);
538 * @param array $target_item
539 * @param array $parent
540 * @param int $priority The priority the Notifier queue item was created with
541 * @param string $created The date the Notifier queue item was created on
543 private static function activityPubDelivery($cmd, array $target_item, array $parent, $priority, $created)
547 if ($target_item['origin']) {
548 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $target_item['contact-uid']);
549 Logger::log('Origin item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
550 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
551 Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
553 } elseif ($parent['origin']) {
554 // Remote items are transmitted via the personal inboxes.
555 // Doing so ensures that the dedicated receiver will get the message.
556 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $target_item['contact-uid'], true, $target_item['id']);
557 Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
560 if (empty($inboxes)) {
561 Logger::log('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
565 // Fill the item cache
566 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
568 foreach ($inboxes as $inbox) {
569 Logger::log('Deliver ' . $target_item['id'] .' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
571 Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
572 'APDelivery', $cmd, $target_item['id'], $inbox, $target_item['contact-uid']);
576 private static function isForumPost(array $item, array $owner)
578 if (($item['author-id'] == $item['owner-id']) ||
579 ($owner['id'] == $item['contact-id']) ||
580 ($item['uri'] != $item['parent-uri'])) {
584 $fields = ['forum', 'prv'];
585 $condition = ['id' => $item['contact-id']];
586 $contact = DBA::selectFirst('contact', $fields, $condition);
587 if (!DBA::isResult($contact)) {
588 // Should never happen
592 // Is the post from a forum?
593 return ($contact['forum'] || $contact['prv']);