Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

645 lines
24 KiB

4 years ago
  1. <?php
  2. /**
  3. * @file src/Worker/Notifier.php
  4. */
  5. namespace Friendica\Worker;
  6. use Friendica\BaseObject;
  7. use Friendica\Core\Config;
  8. use Friendica\Core\Hook;
  9. use Friendica\Core\Logger;
  10. use Friendica\Core\Protocol;
  11. use Friendica\Core\Worker;
  12. use Friendica\Database\DBA;
  13. use Friendica\Model\APContact;
  14. use Friendica\Model\Contact;
  15. use Friendica\Model\Conversation;
  16. use Friendica\Model\Group;
  17. use Friendica\Model\Item;
  18. use Friendica\Model\ItemDeliveryData;
  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;
  26. require_once 'include/items.php';
  27. /*
  28. * The notifier is typically called with:
  29. *
  30. * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
  31. *
  32. * where COMMAND is one of the constants that are defined in Worker/Delivery.php
  33. * and ITEM_ID is the id of the item in the database that needs to be sent to others.
  34. */
  35. class Notifier
  36. {
  37. public static function execute($cmd, $target_id)
  38. {
  39. $a = BaseObject::getApp();
  40. Logger::log('Invoked: ' . $cmd . ': ' . $target_id, Logger::DEBUG);
  41. $top_level = false;
  42. $recipients = [];
  43. $url_recipients = [];
  44. $delivery_contacts_stmt = null;
  45. $target_item = [];
  46. $items = [];
  47. $delivery_queue_count = 0;
  48. if ($cmd == Delivery::MAIL) {
  49. $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
  50. if (!DBA::isResult($message)) {
  51. return;
  52. }
  53. $uid = $message['uid'];
  54. $recipients[] = $message['contact-id'];
  55. $mail = ActivityPub\Transmitter::ItemArrayFromMail($target_id);
  56. $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($mail, $uid, true);
  57. foreach ($inboxes as $inbox) {
  58. Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_id, 'inbox' => $inbox]);
  59. Worker::add(['priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true],
  60. 'APDelivery', $cmd, $target_id, $inbox, $uid);
  61. }
  62. } elseif ($cmd == Delivery::SUGGESTION) {
  63. $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $target_id]);
  64. if (!DBA::isResult($suggest)) {
  65. return;
  66. }
  67. $uid = $suggest['uid'];
  68. $recipients[] = $suggest['cid'];
  69. } elseif ($cmd == Delivery::REMOVAL) {
  70. return self::notifySelfRemoval($target_id, $a->queue['priority'], $a->queue['created']);
  71. } elseif ($cmd == Delivery::RELOCATION) {
  72. $uid = $target_id;
  73. $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
  74. $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'batch'], $condition);
  75. } else {
  76. // find ancestors
  77. $condition = ['id' => $target_id, 'visible' => true, 'moderated' => false];
  78. $target_item = Item::selectFirst([], $condition);
  79. if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
  80. return;
  81. }
  82. if (!empty($target_item['contact-uid'])) {
  83. $uid = $target_item['contact-uid'];
  84. } elseif (!empty($target_item['uid'])) {
  85. $uid = $target_item['uid'];
  86. } else {
  87. Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
  88. return;
  89. }
  90. $condition = ['parent' => $target_item['parent'], 'visible' => true, 'moderated' => false];
  91. $params = ['order' => ['id']];
  92. $items_stmt = Item::select([], $condition, $params);
  93. if (!DBA::isResult($items_stmt)) {
  94. return;
  95. }
  96. $items = Item::inArray($items_stmt);
  97. // avoid race condition with deleting entries
  98. if ($items[0]['deleted']) {
  99. foreach ($items as $item) {
  100. $item['deleted'] = 1;
  101. }
  102. }
  103. if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
  104. Logger::log('Top level post');
  105. $top_level = true;
  106. }
  107. }
  108. $owner = User::getOwnerDataById($uid);
  109. if (!$owner) {
  110. return;
  111. }
  112. // Should the post be transmitted to Diaspora?
  113. $diaspora_delivery = true;
  114. // If this is a public conversation, notify the feed hub
  115. $public_message = true;
  116. // Do a PuSH
  117. $push_notify = false;
  118. // Deliver directly to a forum, don't PuSH
  119. $direct_forum_delivery = false;
  120. $followup = false;
  121. $recipients_followup = [];
  122. if (!empty($target_item) && !empty($items)) {
  123. $parent = $items[0];
  124. if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB)) {
  125. $delivery_queue_count += self::activityPubDelivery($cmd, $target_item, $parent, $a->queue['priority'], $a->queue['created'], $owner);
  126. }
  127. $fields = ['network', 'author-id', 'owner-id'];
  128. $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
  129. $thr_parent = Item::selectFirst($fields, $condition);
  130. Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
  131. // This is IMPORTANT!!!!
  132. // We will only send a "notify owner to relay" or followup message if the referenced post
  133. // originated on our system by virtue of having our hostname somewhere
  134. // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
  135. // if $parent['wall'] == 1 we will already have the parent message in our array
  136. // and we will relay the whole lot.
  137. $localhost = str_replace('www.','',$a->getHostName());
  138. if (strpos($localhost,':')) {
  139. $localhost = substr($localhost,0,strpos($localhost,':'));
  140. }
  141. /**
  142. *
  143. * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
  144. * have been known to cause runaway conditions which affected several servers, along with
  145. * permissions issues.
  146. *
  147. */
  148. $relay_to_owner = false;
  149. if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
  150. $relay_to_owner = true;
  151. }
  152. if (($cmd === Delivery::UPLINK) && (intval($parent['forum_mode']) == 1) && !$top_level) {
  153. $relay_to_owner = true;
  154. }
  155. // until the 'origin' flag has been in use for several months
  156. // we will just use it as a fallback test
  157. // later we will be able to use it as the primary test of whether or not to relay.
  158. if (!$target_item['origin']) {
  159. $relay_to_owner = false;
  160. }
  161. if ($parent['origin']) {
  162. $relay_to_owner = false;
  163. }
  164. // Special treatment for forum posts
  165. if (Item::isForumPost($target_item, $owner)) {
  166. $relay_to_owner = true;
  167. $direct_forum_delivery = true;
  168. }
  169. // Avoid that comments in a forum thread are sent to OStatus
  170. if (Item::isForumPost($parent, $owner)) {
  171. $direct_forum_delivery = true;
  172. }
  173. if ($relay_to_owner) {
  174. // local followup to remote post
  175. $followup = true;
  176. $public_message = false; // not public
  177. $recipients = [$parent['contact-id']];
  178. $recipients_followup = [$parent['contact-id']];
  179. Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
  180. //if (!$target_item['private'] && $target_item['wall'] &&
  181. if (!$target_item['private'] &&
  182. (strlen($target_item['allow_cid'].$target_item['allow_gid'].
  183. $target_item['deny_cid'].$target_item['deny_gid']) == 0))
  184. $push_notify = true;
  185. if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
  186. $push_notify = true;
  187. if ($parent["network"] == Protocol::OSTATUS) {
  188. // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
  189. // Currently it is work at progress
  190. $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
  191. $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
  192. while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
  193. $recipients_followup[] = $followup_contact['id'];
  194. }
  195. DBA::close($followup_contacts_stmt);
  196. }
  197. }
  198. if ($direct_forum_delivery) {
  199. $push_notify = false;
  200. }
  201. Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
  202. } else {
  203. $followup = false;
  204. Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
  205. // don't send deletions onward for other people's stuff
  206. if ($target_item['deleted'] && !intval($target_item['wall'])) {
  207. Logger::log('Ignoring delete notification for non-wall item');
  208. return;
  209. }
  210. if (strlen($parent['allow_cid'])
  211. || strlen($parent['allow_gid'])
  212. || strlen($parent['deny_cid'])
  213. || strlen($parent['deny_gid'])) {
  214. $public_message = false; // private recipients, not public
  215. }
  216. $allow_people = expand_acl($parent['allow_cid']);
  217. $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
  218. $deny_people = expand_acl($parent['deny_cid']);
  219. $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
  220. // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
  221. // a delivery fork. private groups (forum_mode == 2) do not uplink
  222. if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== Delivery::UPLINK)) {
  223. Worker::add($a->queue['priority'], 'Notifier', Delivery::UPLINK, $target_id);
  224. }
  225. foreach ($items as $item) {
  226. $recipients[] = $item['contact-id'];
  227. // pull out additional tagged people to notify (if public message)
  228. if ($public_message && strlen($item['inform'])) {
  229. $people = explode(',',$item['inform']);
  230. foreach ($people as $person) {
  231. if (substr($person,0,4) === 'cid:') {
  232. $recipients[] = intval(substr($person,4));
  233. } else {
  234. $url_recipients[] = substr($person,4);
  235. }
  236. }
  237. }
  238. }
  239. if (count($url_recipients)) {
  240. Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_encode($url_recipients));
  241. }
  242. $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
  243. $deny = array_unique(array_merge($deny_people, $deny_groups));
  244. $recipients = array_diff($recipients, $deny);
  245. // If this is a public message and pubmail is set on the parent, include all your email contacts
  246. if (
  247. function_exists('imap_open')
  248. && !Config::get('system','imap_disabled')
  249. && $public_message
  250. && intval($target_item['pubmail'])
  251. ) {
  252. $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
  253. while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
  254. $recipients[] = $mail_contact['id'];
  255. }
  256. DBA::close($mail_contacts_stmt);
  257. }
  258. }
  259. // If the thread parent is OStatus then do some magic to distribute the messages.
  260. // We have not only to look at the parent, since it could be a Friendica thread.
  261. if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
  262. $diaspora_delivery = false;
  263. Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
  264. // Send a salmon to the parent author
  265. $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
  266. if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
  267. Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
  268. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  269. }
  270. // Send a salmon to the parent owner
  271. $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
  272. if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
  273. Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
  274. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  275. }
  276. // Send a salmon notification to every person we mentioned in the post
  277. $arr = explode(',',$target_item['tag']);
  278. foreach ($arr as $x) {
  279. //Logger::log('Checking tag '.$x, Logger::DEBUG);
  280. $matches = null;
  281. if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
  282. $probed_contact = Probe::uri($matches[1]);
  283. if ($probed_contact["notify"] != "") {
  284. Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
  285. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  286. }
  287. }
  288. }
  289. // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
  290. $networks = [Protocol::OSTATUS, Protocol::DFRN];
  291. } else {
  292. $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
  293. }
  294. } else {
  295. $public_message = false;
  296. }
  297. if (empty($delivery_contacts_stmt)) {
  298. if ($followup) {
  299. $recipients = $recipients_followup;
  300. }
  301. $condition = ['id' => $recipients, 'self' => false,
  302. 'blocked' => false, 'pending' => false, 'archive' => false];
  303. if (!empty($networks)) {
  304. $condition['network'] = $networks;
  305. }
  306. $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'batch'], $condition);
  307. }
  308. $conversants = [];
  309. $batch_delivery = false;
  310. if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
  311. $relay_list = [];
  312. if ($diaspora_delivery) {
  313. $batch_delivery = true;
  314. $relay_list_stmt = DBA::p(
  315. "SELECT
  316. `batch`,
  317. ANY_VALUE(`id`) AS `id`,
  318. ANY_VALUE(`name`) AS `name`,
  319. ANY_VALUE(`network`) AS `network`,
  320. ANY_VALUE(`protocol`) AS `protocol`
  321. FROM `contact`
  322. WHERE `network` = ?
  323. AND `batch` != ''
  324. AND `uid` = ?
  325. AND `rel` != ?
  326. AND NOT `blocked`
  327. AND NOT `pending`
  328. AND NOT `archive`
  329. GROUP BY `batch`",
  330. Protocol::DIASPORA,
  331. $owner['uid'],
  332. Contact::SHARING
  333. );
  334. $relay_list = DBA::toArray($relay_list_stmt);
  335. // Fetch the participation list
  336. // The function will ensure that there are no duplicates
  337. $relay_list = Diaspora::participantsForThread($target_id, $relay_list);
  338. // Add the relay to the list, avoid duplicates.
  339. // Don't send community posts to the relay. Forum posts via the Diaspora protocol are looking ugly.
  340. if (!$followup && !Item::isForumPost($target_item, $owner)) {
  341. $relay_list = Diaspora::relayList($target_id, $relay_list);
  342. }
  343. }
  344. $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
  345. 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
  346. $r2 = DBA::toArray(DBA::select('contact', ['id', 'url', 'name', 'network', 'protocol'], $condition));
  347. $r = array_merge($r2, $relay_list);
  348. if (DBA::isResult($r)) {
  349. foreach ($r as $rr) {
  350. if (self::isRemovalActivity($cmd, $owner, $rr['network'])) {
  351. Logger::log('Skipping dropping for ' . $rr['url'] . ' since the network supports account removal commands.', Logger::DEBUG);
  352. continue;
  353. }
  354. if (in_array($rr['network'], [Protocol::DFRN, Protocol::DIASPORA]) && ($rr['protocol'] == Protocol::ACTIVITYPUB) &&
  355. !in_array($cmd, [Delivery::SUGGESTION, Delivery::REMOVAL, Delivery::RELOCATION, Delivery::POKE])) {
  356. Logger::info('Contact is Friendica AP, so skipping delivery via legacy DFRN', ['url' => $rr['url']]);
  357. continue;
  358. }
  359. if (Config::get('debug', 'total_ap_delivery') && !empty($rr['url']) && ($rr['network'] == Protocol::DFRN) && !empty(APContact::getByURL($rr['url'], false))) {
  360. Logger::log('Skipping contact ' . $rr['url'] . ' since it will be delivered via AP', Logger::DEBUG);
  361. continue;
  362. }
  363. $conversants[] = $rr['id'];
  364. $delivery_queue_count++;
  365. Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $target_id . ') to ' . json_encode($rr), Logger::DEBUG);
  366. // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
  367. // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
  368. // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
  369. // This is only important for high and medium priority tasks and not for Low priority jobs like deletions.
  370. if (($rr['network'] == Protocol::DIASPORA) && in_array($a->queue['priority'], [PRIORITY_HIGH, PRIORITY_MEDIUM])) {
  371. $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
  372. } else {
  373. $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
  374. }
  375. Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$rr['id']);
  376. }
  377. }
  378. $push_notify = true;
  379. }
  380. // delivery loop
  381. while ($contact = DBA::fetch($delivery_contacts_stmt)) {
  382. if (self::isRemovalActivity($cmd, $owner, $contact['network'])) {
  383. Logger::log('Skipping dropping for ' . $contact['url'] . ' since the network supports account removal commands.', Logger::DEBUG);
  384. continue;
  385. }
  386. if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && ($contact['protocol'] == Protocol::ACTIVITYPUB) &&
  387. !in_array($cmd, [Delivery::SUGGESTION, Delivery::REMOVAL, Delivery::RELOCATION, Delivery::POKE])) {
  388. Logger::info('Contact is Friendica AP, so skipping delivery via legacy DFRN', ['url' => $contact['url']]);
  389. continue;
  390. }
  391. if (Config::get('debug', 'total_ap_delivery') && ($contact['network'] == Protocol::DFRN) && !empty(APContact::getByURL($contact['url'], false))) {
  392. Logger::log('Skipping contact ' . $contact['url'] . ' since it will be delivered via AP', Logger::DEBUG);
  393. continue;
  394. }
  395. // Don't deliver to Diaspora if it already had been done as batch delivery
  396. if (($contact['network'] == Protocol::DIASPORA) && $batch_delivery) {
  397. Logger::log('Already delivered id ' . $target_id . ' via batch to ' . json_encode($contact), Logger::DEBUG);
  398. continue;
  399. }
  400. // Don't deliver to folks who have already been delivered to
  401. if (in_array($contact['id'], $conversants)) {
  402. Logger::log('Already delivered id ' . $target_id. ' to ' . json_encode($contact), Logger::DEBUG);
  403. continue;
  404. }
  405. $delivery_queue_count++;
  406. Logger::log('Delivery of item ' . $target_id . ' to ' . json_encode($contact), Logger::DEBUG);
  407. // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
  408. // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
  409. // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
  410. if ($contact['network'] == Protocol::DIASPORA) {
  411. $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
  412. } else {
  413. $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
  414. }
  415. Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$contact['id']);
  416. }
  417. DBA::close($delivery_contacts_stmt);
  418. $url_recipients = array_filter($url_recipients);
  419. // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
  420. // They are especially used for notifications to OStatus users that don't follow us.
  421. if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
  422. $delivery_queue_count += count($url_recipients);
  423. $slap = OStatus::salmon($target_item, $owner);
  424. foreach ($url_recipients as $url) {
  425. Logger::log('Salmon delivery of item ' . $target_id . ' to ' . $url);
  426. /// @TODO Redeliver/queue these items on failure, though there is no contact record
  427. Salmon::slapper($owner, $url, $slap);
  428. ItemDeliveryData::incrementQueueDone($target_id);
  429. }
  430. }
  431. // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
  432. if ($push_notify) {
  433. Logger::log('Activating internal PuSH for item '.$target_id, Logger::DEBUG);
  434. // Handling the pubsubhubbub requests
  435. PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
  436. }
  437. if (!empty($target_item)) {
  438. Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
  439. if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
  440. ItemDeliveryData::update($target_item['id'], ['queue_count' => $delivery_queue_count]);
  441. }
  442. Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
  443. Hook::callAll('notifier_end', $target_item);
  444. }
  445. return;
  446. }
  447. /**
  448. * Checks if the current action is a deletion command of a account removal activity
  449. * For Diaspora and ActivityPub we don't need to send single item deletion calls.
  450. * These protocols do have a dedicated command for deleting a whole account.
  451. *
  452. * @param string $cmd Notifier command
  453. * @param array $owner Sender of the post
  454. * @param string $network Receiver network
  455. * @return bool
  456. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  457. * @throws \ImagickException
  458. */
  459. private static function isRemovalActivity($cmd, $owner, $network)
  460. {
  461. return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
  462. }
  463. /**
  464. * @param int $self_user_id
  465. * @param int $priority The priority the Notifier queue item was created with
  466. * @param string $created The date the Notifier queue item was created on
  467. * @return bool
  468. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  469. * @throws \ImagickException
  470. */
  471. private static function notifySelfRemoval($self_user_id, $priority, $created)
  472. {
  473. $owner = User::getOwnerDataById($self_user_id);
  474. if (!$owner) {
  475. return false;
  476. }
  477. $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
  478. if (!DBA::isResult($contacts_stmt)) {
  479. return false;
  480. }
  481. while($contact = DBA::fetch($contacts_stmt)) {
  482. Contact::terminateFriendship($owner, $contact, true);
  483. }
  484. DBA::close($contacts_stmt);
  485. $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
  486. foreach ($inboxes as $inbox) {
  487. Logger::info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]);
  488. Worker::add(['priority' => PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
  489. 'APDelivery', Delivery::REMOVAL, '', $inbox, $self_user_id);
  490. }
  491. return true;
  492. }
  493. /**
  494. * @param string $cmd
  495. * @param array $target_item
  496. * @param array $parent
  497. * @param int $priority The priority the Notifier queue item was created with
  498. * @param string $created The date the Notifier queue item was created on
  499. * @return int The number of delivery tasks created
  500. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  501. * @throws \ImagickException
  502. */
  503. private static function activityPubDelivery($cmd, array $target_item, array $parent, $priority, $created, $owner)
  504. {
  505. $inboxes = [];
  506. $uid = $target_item['contact-uid'] ?: $target_item['uid'];
  507. if ($target_item['origin']) {
  508. $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
  509. Logger::log('Origin item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
  510. } elseif (Item::isForumPost($target_item, $owner)) {
  511. $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid, false, 0, true);
  512. Logger::log('Forum item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
  513. } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
  514. Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
  515. return 0;
  516. } elseif ($parent['origin']) {
  517. // Remote items are transmitted via the personal inboxes.
  518. // Doing so ensures that the dedicated receiver will get the message.
  519. $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, true, $target_item['id']);
  520. Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
  521. }
  522. if (empty($inboxes)) {
  523. Logger::log('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
  524. return 0;
  525. }
  526. // Fill the item cache
  527. ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
  528. foreach ($inboxes as $inbox) {
  529. Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
  530. Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
  531. 'APDelivery', $cmd, $target_item['id'], $inbox, $uid);
  532. }
  533. return count($inboxes);
  534. }
  535. }