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\APContact;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Conversation;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Model\ItemDeliveryData;
20 use Friendica\Model\PushSubscriber;
21 use Friendica\Model\User;
22 use Friendica\Network\Probe;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Protocol\OStatus;
26 use Friendica\Protocol\Salmon;
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, $target_id)
59 $a = BaseObject::getApp();
61 Logger::log('Invoked: ' . $cmd . ': ' . $target_id, Logger::DEBUG);
67 $delivery_contacts_stmt = null;
70 $delivery_queue_count = 0;
72 if ($cmd == Delivery::MAIL) {
73 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
74 if (!DBA::isResult($message)) {
77 $uid = $message['uid'];
78 $recipients[] = $message['contact-id'];
79 } elseif ($cmd == Delivery::SUGGESTION) {
80 $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $target_id]);
81 if (!DBA::isResult($suggest)) {
84 $uid = $suggest['uid'];
85 $recipients[] = $suggest['cid'];
86 } elseif ($cmd == Delivery::REMOVAL) {
87 return self::notifySelfRemoval($target_id, $a->queue['priority'], $a->queue['created']);
88 } elseif ($cmd == Delivery::RELOCATION) {
91 $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
92 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
95 $condition = ['id' => $target_id, 'visible' => true, 'moderated' => false];
96 $target_item = Item::selectFirst([], $condition);
98 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
102 if (!empty($target_item['contact-uid'])) {
103 $uid = $target_item['contact-uid'];
104 } elseif (!empty($target_item['uid'])) {
105 $uid = $target_item['uid'];
107 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
111 $condition = ['parent' => $target_item['parent'], 'visible' => true, 'moderated' => false];
112 $params = ['order' => ['id']];
113 $items_stmt = Item::select([], $condition, $params);
114 if (!DBA::isResult($items_stmt)) {
118 $items = Item::inArray($items_stmt);
120 // avoid race condition with deleting entries
121 if ($items[0]['deleted']) {
122 foreach ($items as $item) {
123 $item['deleted'] = 1;
127 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
128 Logger::log('Top level post');
133 $owner = User::getOwnerDataById($uid);
138 // Should the post be transmitted to Diaspora?
139 $diaspora_delivery = true;
141 // If this is a public conversation, notify the feed hub
142 $public_message = true;
145 $push_notify = false;
147 // Deliver directly to a forum, don't PuSH
148 $direct_forum_delivery = false;
151 $recipients_followup = [];
153 if (!empty($target_item) && !empty($items)) {
156 $delivery_queue_count += self::activityPubDelivery($cmd, $target_item, $parent, $a->queue['priority'], $a->queue['created']);
158 $fields = ['network', 'author-id', 'owner-id'];
159 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
160 $thr_parent = Item::selectFirst($fields, $condition);
162 Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
164 // This is IMPORTANT!!!!
166 // We will only send a "notify owner to relay" or followup message if the referenced post
167 // originated on our system by virtue of having our hostname somewhere
168 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
170 // if $parent['wall'] == 1 we will already have the parent message in our array
171 // and we will relay the whole lot.
173 $localhost = str_replace('www.','',$a->getHostName());
174 if (strpos($localhost,':')) {
175 $localhost = substr($localhost,0,strpos($localhost,':'));
179 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
180 * have been known to cause runaway conditions which affected several servers, along with
181 * permissions issues.
185 $relay_to_owner = false;
187 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
188 $relay_to_owner = true;
192 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
193 $relay_to_owner = true;
196 // until the 'origin' flag has been in use for several months
197 // we will just use it as a fallback test
198 // later we will be able to use it as the primary test of whether or not to relay.
200 if (!$target_item['origin']) {
201 $relay_to_owner = false;
203 if ($parent['origin']) {
204 $relay_to_owner = false;
207 // Special treatment for forum posts
208 if (self::isForumPost($target_item, $owner)) {
209 $relay_to_owner = true;
210 $direct_forum_delivery = true;
213 // Avoid that comments in a forum thread are sent to OStatus
214 if (self::isForumPost($parent, $owner)) {
215 $direct_forum_delivery = true;
218 if ($relay_to_owner) {
219 // local followup to remote post
221 $public_message = false; // not public
222 $recipients = [$parent['contact-id']];
223 $recipients_followup = [$parent['contact-id']];
225 Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
227 //if (!$target_item['private'] && $target_item['wall'] &&
228 if (!$target_item['private'] &&
229 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
230 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
233 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
236 if ($parent["network"] == Protocol::OSTATUS) {
237 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
238 // Currently it is work at progress
239 $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
240 $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
241 while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
242 $recipients_followup[] = $followup_contact['id'];
244 DBA::close($followup_contacts_stmt);
248 if ($direct_forum_delivery) {
249 $push_notify = false;
252 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
256 Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
258 // don't send deletions onward for other people's stuff
260 if ($target_item['deleted'] && !intval($target_item['wall'])) {
261 Logger::log('Ignoring delete notification for non-wall item');
265 if (strlen($parent['allow_cid'])
266 || strlen($parent['allow_gid'])
267 || strlen($parent['deny_cid'])
268 || strlen($parent['deny_gid'])) {
269 $public_message = false; // private recipients, not public
272 $allow_people = expand_acl($parent['allow_cid']);
273 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
274 $deny_people = expand_acl($parent['deny_cid']);
275 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
277 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
278 // a delivery fork. private groups (forum_mode == 2) do not uplink
280 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
281 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $target_id);
284 foreach ($items as $item) {
285 $recipients[] = $item['contact-id'];
286 // pull out additional tagged people to notify (if public message)
287 if ($public_message && strlen($item['inform'])) {
288 $people = explode(',',$item['inform']);
289 foreach ($people as $person) {
290 if (substr($person,0,4) === 'cid:') {
291 $recipients[] = intval(substr($person,4));
293 $url_recipients[] = substr($person,4);
299 if (count($url_recipients)) {
300 Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_encode($url_recipients));
303 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
304 $deny = array_unique(array_merge($deny_people, $deny_groups));
305 $recipients = array_diff($recipients, $deny);
307 // If this is a public message and pubmail is set on the parent, include all your email contacts
309 function_exists('imap_open')
310 && !Config::get('system','imap_disabled')
312 && intval($target_item['pubmail'])
314 $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
315 while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
316 $recipients[] = $mail_contact['id'];
318 DBA::close($mail_contacts_stmt);
322 // If the thread parent is OStatus then do some magic to distribute the messages.
323 // We have not only to look at the parent, since it could be a Friendica thread.
324 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
325 $diaspora_delivery = false;
327 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
329 // Send a salmon to the parent author
330 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
331 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
332 Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
333 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
336 // Send a salmon to the parent owner
337 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
338 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
339 Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
340 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
343 // Send a salmon notification to every person we mentioned in the post
344 $arr = explode(',',$target_item['tag']);
345 foreach ($arr as $x) {
346 //Logger::log('Checking tag '.$x, Logger::DEBUG);
348 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
349 $probed_contact = Probe::uri($matches[1]);
350 if ($probed_contact["notify"] != "") {
351 Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
352 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
357 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
358 $networks = [Protocol::OSTATUS, Protocol::DFRN];
360 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
363 $public_message = false;
366 if (empty($delivery_contacts_stmt)) {
368 $recipients = $recipients_followup;
370 $condition = ['id' => $recipients, 'self' => false,
371 'blocked' => false, 'pending' => false, 'archive' => false];
372 if (!empty($networks)) {
373 $condition['network'] = $networks;
375 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
379 $batch_delivery = false;
381 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
384 if ($diaspora_delivery) {
385 $batch_delivery = true;
387 $relay_list_stmt = DBA::p(
390 ANY_VALUE(`id`) AS `id`,
391 ANY_VALUE(`name`) AS `name`,
392 ANY_VALUE(`network`) AS `network`
406 $relay_list = DBA::toArray($relay_list_stmt);
408 // Fetch the participation list
409 // The function will ensure that there are no duplicates
410 $relay_list = Diaspora::participantsForThread($target_id, $relay_list);
412 // Add the relay to the list, avoid duplicates.
413 // Don't send community posts to the relay. Forum posts via the Diaspora protocol are looking ugly.
414 if (!$followup && !self::isForumPost($target_item, $owner)) {
415 $relay_list = Diaspora::relayList($target_id, $relay_list);
419 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
420 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
422 $r2 = DBA::toArray(DBA::select('contact', ['id', 'url', 'name', 'network'], $condition));
424 $r = array_merge($r2, $relay_list);
426 if (DBA::isResult($r)) {
427 foreach ($r as $rr) {
428 if (Config::get('debug', 'total_ap_delivery') && !empty($rr['url']) && ($rr['network'] == Protocol::DFRN) && !empty(APContact::getByURL($rr['url'], false))) {
429 Logger::log('Skipping contact ' . $rr['url'] . ' since it will be delivered via AP', Logger::DEBUG);
433 $conversants[] = $rr['id'];
435 $delivery_queue_count++;
437 Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $target_id . ') to ' . json_encode($rr), Logger::DEBUG);
439 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
440 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
441 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
442 if ($rr['network'] == Protocol::DIASPORA) {
443 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
445 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
447 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$rr['id']);
455 while ($contact = DBA::fetch($delivery_contacts_stmt)) {
456 if (Config::get('debug', 'total_ap_delivery') && ($contact['network'] == Protocol::DFRN) && !empty(APContact::getByURL($contact['url'], false))) {
457 Logger::log('Skipping contact ' . $contact['url'] . ' since it will be delivered via AP', Logger::DEBUG);
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 ' . $target_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 ' . $target_id. ' to ' . json_encode($contact), Logger::DEBUG);
473 $delivery_queue_count++;
475 Logger::log('Delivery of item ' . $target_id . ' to ' . json_encode($contact), Logger::DEBUG);
477 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
478 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
479 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
480 if ($contact['network'] == Protocol::DIASPORA) {
481 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
483 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
485 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$contact['id']);
487 DBA::close($delivery_contacts_stmt);
490 $url_recipients = array_filter($url_recipients);
491 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
492 // They are especially used for notifications to OStatus users that don't follow us.
493 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
494 $delivery_queue_count += count($url_recipients);
495 $slap = OStatus::salmon($target_item, $owner);
496 foreach ($url_recipients as $url) {
497 Logger::log('Salmon delivery of item ' . $target_id . ' to ' . $url);
498 /// @TODO Redeliver/queue these items on failure, though there is no contact record
499 Salmon::slapper($owner, $url, $slap);
500 ItemDeliveryData::incrementQueueDone($target_id);
504 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
506 Logger::log('Activating internal PuSH for item '.$target_id, Logger::DEBUG);
508 // Handling the pubsubhubbub requests
509 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
512 if (!empty($target_item)) {
513 Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
515 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
516 ItemDeliveryData::update($target_item['id'], ['queue_count' => $delivery_queue_count]);
519 Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
521 Hook::callAll('notifier_end', $target_item);
528 * @param int $self_user_id
529 * @param int $priority The priority the Notifier queue item was created with
530 * @param string $created The date the Notifier queue item was created on
532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
533 * @throws \ImagickException
535 private static function notifySelfRemoval($self_user_id, $priority, $created)
537 $owner = User::getOwnerDataById($self_user_id);
542 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
543 if (!DBA::isResult($contacts_stmt)) {
547 while($contact = DBA::fetch($contacts_stmt)) {
548 Contact::terminateFriendship($owner, $contact, true);
550 DBA::close($contacts_stmt);
552 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
553 foreach ($inboxes as $inbox) {
554 Logger::log('Account removal for user ' . $self_user_id . ' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
555 Worker::add(['priority' => PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
556 'APDelivery', Delivery::REMOVAL, '', $inbox, $self_user_id);
564 * @param array $target_item
565 * @param array $parent
566 * @param int $priority The priority the Notifier queue item was created with
567 * @param string $created The date the Notifier queue item was created on
568 * @return int The number of delivery tasks created
569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
570 * @throws \ImagickException
572 private static function activityPubDelivery($cmd, array $target_item, array $parent, $priority, $created)
576 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
578 if ($target_item['origin']) {
579 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
580 Logger::log('Origin item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
581 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
582 Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
584 } elseif ($parent['origin']) {
585 // Remote items are transmitted via the personal inboxes.
586 // Doing so ensures that the dedicated receiver will get the message.
587 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, true, $target_item['id']);
588 Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
591 if (empty($inboxes)) {
592 Logger::log('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
596 // Fill the item cache
597 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
599 foreach ($inboxes as $inbox) {
600 Logger::log('Deliver ' . $target_item['id'] .' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
602 Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
603 'APDelivery', $cmd, $target_item['id'], $inbox, $uid);
606 return count($inboxes);
609 private static function isForumPost(array $item, array $owner)
611 if (($item['author-id'] == $item['owner-id']) ||
612 ($owner['id'] == $item['contact-id']) ||
613 ($item['uri'] != $item['parent-uri'])) {
617 return self::isForum($item['contact-id']);
620 private static function isForum($contactid)
622 $fields = ['forum', 'prv'];
623 $condition = ['id' => $contactid];
624 $contact = DBA::selectFirst('contact', $fields, $condition);
625 if (!DBA::isResult($contact)) {
626 // Should never happen
631 return ($contact['forum'] || $contact['prv']);