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.

527 lines
18 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\Addon;
  8. use Friendica\Core\Config;
  9. use Friendica\Core\Protocol;
  10. use Friendica\Core\Worker;
  11. use Friendica\Database\DBA;
  12. use Friendica\Model\Contact;
  13. use Friendica\Model\Group;
  14. use Friendica\Model\Item;
  15. use Friendica\Model\PushSubscriber;
  16. use Friendica\Model\User;
  17. use Friendica\Network\Probe;
  18. use Friendica\Protocol\ActivityPub;
  19. use Friendica\Protocol\Diaspora;
  20. use Friendica\Protocol\OStatus;
  21. use Friendica\Protocol\Salmon;
  22. require_once 'include/dba.php';
  23. require_once 'include/items.php';
  24. /*
  25. * The notifier is typically called with:
  26. *
  27. * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
  28. *
  29. * where COMMAND is one of the following:
  30. *
  31. * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
  32. * comment-import (in diaspora.php, items.php)
  33. * comment-new (in item.php)
  34. * drop (in diaspora.php, items.php, photos.php)
  35. * edit_post (in item.php)
  36. * event (in events.php)
  37. * like (in like.php, poke.php)
  38. * mail (in message.php)
  39. * suggest (in fsuggest.php)
  40. * tag (in photos.php, poke.php, tagger.php)
  41. * tgroup (in items.php)
  42. * wall-new (in photos.php, item.php)
  43. * removeme (in Contact.php)
  44. * relocate (in uimport.php)
  45. *
  46. * and ITEM_ID is the id of the item in the database that needs to be sent to others.
  47. */
  48. class Notifier
  49. {
  50. public static function execute($cmd, $item_id)
  51. {
  52. $a = BaseObject::getApp();
  53. logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
  54. $top_level = false;
  55. $recipients = [];
  56. $url_recipients = [];
  57. $normal_mode = true;
  58. $recipients_relocate = [];
  59. if ($cmd == Delivery::MAIL) {
  60. $normal_mode = false;
  61. $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
  62. if (!DBA::isResult($message)) {
  63. return;
  64. }
  65. $uid = $message['uid'];
  66. $recipients[] = $message['contact-id'];
  67. } elseif ($cmd == Delivery::SUGGESTION) {
  68. $normal_mode = false;
  69. $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
  70. if (!DBA::isResult($suggest)) {
  71. return;
  72. }
  73. $uid = $suggest['uid'];
  74. $recipients[] = $suggest['cid'];
  75. } elseif ($cmd == Delivery::REMOVAL) {
  76. $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
  77. `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
  78. `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
  79. FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  80. WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
  81. intval($item_id));
  82. if (!$r) {
  83. return;
  84. }
  85. $user = $r[0];
  86. $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
  87. if (!$r) {
  88. return;
  89. }
  90. foreach ($r as $contact) {
  91. Contact::terminateFriendship($user, $contact, true);
  92. }
  93. return;
  94. } elseif ($cmd == Delivery::RELOCATION) {
  95. $normal_mode = false;
  96. $uid = $item_id;
  97. $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
  98. intval($uid), Protocol::DFRN, Protocol::DIASPORA);
  99. } else {
  100. // find ancestors
  101. $condition = ['id' => $item_id, 'visible' => true, 'moderated' => false];
  102. $target_item = Item::selectFirst([], $condition);
  103. if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
  104. return;
  105. }
  106. $parent_id = intval($target_item['parent']);
  107. $uid = $target_item['contact-uid'];
  108. $updated = $target_item['edited'];
  109. $condition = ['parent' => $parent_id, 'visible' => true, 'moderated' => false];
  110. $params = ['order' => ['id']];
  111. $ret = Item::select([], $condition, $params);
  112. if (!DBA::isResult($ret)) {
  113. return;
  114. }
  115. $items = Item::inArray($ret);
  116. // avoid race condition with deleting entries
  117. if ($items[0]['deleted']) {
  118. foreach ($items as $item) {
  119. $item['deleted'] = 1;
  120. }
  121. }
  122. if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
  123. logger('notifier: top level post');
  124. $top_level = true;
  125. }
  126. }
  127. $owner = User::getOwnerDataById($uid);
  128. if (!$owner) {
  129. return;
  130. }
  131. $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
  132. // Should the post be transmitted to Diaspora?
  133. $diaspora_delivery = true;
  134. // If this is a public conversation, notify the feed hub
  135. $public_message = true;
  136. // Do a PuSH
  137. $push_notify = false;
  138. // Deliver directly to a forum, don't PuSH
  139. $direct_forum_delivery = false;
  140. $followup = false;
  141. $recipients_followup = [];
  142. $conversants = [];
  143. if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
  144. $parent = $items[0];
  145. $fields = ['network', 'author-id', 'owner-id'];
  146. $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
  147. $thr_parent = Item::selectFirst($fields, $condition);
  148. logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
  149. // This is IMPORTANT!!!!
  150. // We will only send a "notify owner to relay" or followup message if the referenced post
  151. // originated on our system by virtue of having our hostname somewhere
  152. // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
  153. // if $parent['wall'] == 1 we will already have the parent message in our array
  154. // and we will relay the whole lot.
  155. $localhost = str_replace('www.','',$a->get_hostname());
  156. if (strpos($localhost,':')) {
  157. $localhost = substr($localhost,0,strpos($localhost,':'));
  158. }
  159. /**
  160. *
  161. * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
  162. * have been known to cause runaway conditions which affected several servers, along with
  163. * permissions issues.
  164. *
  165. */
  166. $relay_to_owner = false;
  167. if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
  168. $relay_to_owner = true;
  169. }
  170. if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
  171. $relay_to_owner = true;
  172. }
  173. // until the 'origin' flag has been in use for several months
  174. // we will just use it as a fallback test
  175. // later we will be able to use it as the primary test of whether or not to relay.
  176. if (!$target_item['origin']) {
  177. $relay_to_owner = false;
  178. }
  179. if ($parent['origin']) {
  180. $relay_to_owner = false;
  181. }
  182. // Special treatment for forum posts
  183. if (self::isForumPost($target_item, $owner)) {
  184. $relay_to_owner = true;
  185. $direct_forum_delivery = true;
  186. }
  187. // Avoid that comments in a forum thread are sent to OStatus
  188. if (self::isForumPost($parent, $owner)) {
  189. $direct_forum_delivery = true;
  190. }
  191. if ($relay_to_owner) {
  192. // local followup to remote post
  193. $followup = true;
  194. $public_message = false; // not public
  195. $conversant_str = DBA::escape($parent['contact-id']);
  196. $recipients = [$parent['contact-id']];
  197. $recipients_followup = [$parent['contact-id']];
  198. logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
  199. //if (!$target_item['private'] && $target_item['wall'] &&
  200. if (!$target_item['private'] &&
  201. (strlen($target_item['allow_cid'].$target_item['allow_gid'].
  202. $target_item['deny_cid'].$target_item['deny_gid']) == 0))
  203. $push_notify = true;
  204. if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
  205. $push_notify = true;
  206. if ($parent["network"] == Protocol::OSTATUS) {
  207. // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
  208. // Currently it is work at progress
  209. $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
  210. intval($uid),
  211. DBA::escape(Protocol::DFRN)
  212. );
  213. if (DBA::isResult($r)) {
  214. foreach ($r as $rr) {
  215. $recipients_followup[] = $rr['id'];
  216. }
  217. }
  218. }
  219. }
  220. if ($direct_forum_delivery) {
  221. $push_notify = false;
  222. }
  223. logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
  224. } else {
  225. $followup = false;
  226. logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
  227. // don't send deletions onward for other people's stuff
  228. if ($target_item['deleted'] && !intval($target_item['wall'])) {
  229. logger('notifier: ignoring delete notification for non-wall item');
  230. return;
  231. }
  232. if (strlen($parent['allow_cid'])
  233. || strlen($parent['allow_gid'])
  234. || strlen($parent['deny_cid'])
  235. || strlen($parent['deny_gid'])) {
  236. $public_message = false; // private recipients, not public
  237. }
  238. $allow_people = expand_acl($parent['allow_cid']);
  239. $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
  240. $deny_people = expand_acl($parent['deny_cid']);
  241. $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
  242. // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
  243. // a delivery fork. private groups (forum_mode == 2) do not uplink
  244. if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
  245. Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
  246. }
  247. foreach ($items as $item) {
  248. $recipients[] = $item['contact-id'];
  249. $conversants[] = $item['contact-id'];
  250. // pull out additional tagged people to notify (if public message)
  251. if ($public_message && strlen($item['inform'])) {
  252. $people = explode(',',$item['inform']);
  253. foreach ($people as $person) {
  254. if (substr($person,0,4) === 'cid:') {
  255. $recipients[] = intval(substr($person,4));
  256. $conversants[] = intval(substr($person,4));
  257. } else {
  258. $url_recipients[] = substr($person,4);
  259. }
  260. }
  261. }
  262. }
  263. if (count($url_recipients)) {
  264. logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
  265. }
  266. $conversants = array_unique($conversants);
  267. $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
  268. $deny = array_unique(array_merge($deny_people,$deny_groups));
  269. $recipients = array_diff($recipients,$deny);
  270. $conversant_str = DBA::escape(implode(', ',$conversants));
  271. }
  272. // If the thread parent is OStatus then do some magic to distribute the messages.
  273. // We have not only to look at the parent, since it could be a Friendica thread.
  274. if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
  275. $diaspora_delivery = false;
  276. logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
  277. // Send a salmon to the parent author
  278. $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
  279. if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
  280. logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
  281. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  282. }
  283. // Send a salmon to the parent owner
  284. $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
  285. if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
  286. logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
  287. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  288. }
  289. // Send a salmon notification to every person we mentioned in the post
  290. $arr = explode(',',$target_item['tag']);
  291. foreach ($arr as $x) {
  292. //logger('Checking tag '.$x, LOGGER_DEBUG);
  293. $matches = null;
  294. if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
  295. $probed_contact = Probe::uri($matches[1]);
  296. if ($probed_contact["notify"] != "") {
  297. logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
  298. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  299. }
  300. }
  301. }
  302. // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
  303. $networks = [Protocol::OSTATUS, Protocol::DFRN];
  304. } else {
  305. $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
  306. }
  307. } else {
  308. $public_message = false;
  309. }
  310. // If this is a public message and pubmail is set on the parent, include all your email contacts
  311. if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
  312. if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
  313. && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
  314. && intval($target_item['pubmail'])) {
  315. $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
  316. intval($uid),
  317. DBA::escape(Protocol::MAIL)
  318. );
  319. if (DBA::isResult($r)) {
  320. foreach ($r as $rr) {
  321. $recipients[] = $rr['id'];
  322. }
  323. }
  324. }
  325. }
  326. if (($cmd == Delivery::RELOCATION)) {
  327. $r = $recipients_relocate;
  328. } else {
  329. if ($followup) {
  330. $recipients = $recipients_followup;
  331. }
  332. $condition = ['id' => $recipients, 'self' => false,
  333. 'blocked' => false, 'pending' => false, 'archive' => false];
  334. if (!empty($networks)) {
  335. $condition['network'] = $networks;
  336. }
  337. $contacts = DBA::select('contact', ['id', 'url', 'network'], $condition);
  338. $r = DBA::toArray($contacts);
  339. }
  340. // delivery loop
  341. if (DBA::isResult($r)) {
  342. foreach ($r as $contact) {
  343. logger("Deliver ".$item_id." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
  344. Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
  345. 'Delivery', $cmd, $item_id, (int)$contact['id']);
  346. }
  347. }
  348. $inboxes = ActivityPub::fetchTargetInboxes($target_item);
  349. foreach ($inboxes as $inbox) {
  350. logger('Deliver ' . $item_id .' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
  351. Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
  352. 'APDelivery', $cmd, $item_id, $inbox);
  353. }
  354. // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
  355. // They are especially used for notifications to OStatus users that don't follow us.
  356. if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
  357. $slap = OStatus::salmon($target_item, $owner);
  358. foreach ($url_recipients as $url) {
  359. if ($url) {
  360. logger('notifier: urldelivery: ' . $url);
  361. $deliver_status = Salmon::slapper($owner, $url, $slap);
  362. /// @TODO Redeliver/queue these items on failure, though there is no contact record
  363. }
  364. }
  365. }
  366. if ($public_message) {
  367. $r1 = [];
  368. if ($diaspora_delivery) {
  369. $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
  370. FROM `contact` WHERE `network` = '%s' AND `batch` != ''
  371. AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
  372. DBA::escape(Protocol::DIASPORA),
  373. intval($owner['uid']),
  374. intval(Contact::SHARING)
  375. );
  376. // Fetch the participation list
  377. // The function will ensure that there are no duplicates
  378. $r1 = Diaspora::participantsForThread($item_id, $r1);
  379. // Add the relay to the list, avoid duplicates
  380. if (!$followup) {
  381. $r1 = Diaspora::relayList($item_id, $r1);
  382. }
  383. }
  384. $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
  385. 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
  386. $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
  387. $r = array_merge($r2, $r1);
  388. if (DBA::isResult($r)) {
  389. logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
  390. foreach ($r as $rr) {
  391. // except for Diaspora batch jobs
  392. // Don't deliver to folks who have already been delivered to
  393. if (($rr['network'] !== Protocol::DIASPORA) && (in_array($rr['id'], $conversants))) {
  394. logger('notifier: already delivered id=' . $rr['id']);
  395. continue;
  396. }
  397. if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
  398. logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
  399. Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
  400. 'Delivery', $cmd, $item_id, (int)$rr['id']);
  401. }
  402. }
  403. }
  404. $push_notify = true;
  405. }
  406. // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
  407. if ($push_notify) {
  408. logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
  409. // Handling the pubsubhubbub requests
  410. PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
  411. }
  412. logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
  413. if ($normal_mode) {
  414. Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
  415. }
  416. Addon::callHooks('notifier_end',$target_item);
  417. return;
  418. }
  419. private static function isForumPost($item, $owner) {
  420. if (($item['author-id'] == $item['owner-id']) ||
  421. ($owner['id'] == $item['contact-id']) ||
  422. ($item['uri'] != $item['parent-uri'])) {
  423. return false;
  424. }
  425. $fields = ['forum', 'prv'];
  426. $condition = ['id' => $item['contact-id']];
  427. $contact = DBA::selectFirst('contact', $fields, $condition);
  428. if (!DBA::isResult($contact)) {
  429. // Should never happen
  430. return false;
  431. }
  432. // Is the post from a forum?
  433. return ($contact['forum'] || $contact['prv']);
  434. }
  435. }