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.

619 lines
19KB

  1. <?php
  2. use Friendica\App;
  3. use Friendica\Core\Config;
  4. require_once 'include/queue_fn.php';
  5. require_once 'include/html2plain.php';
  6. require_once 'include/probe.php';
  7. require_once 'include/diaspora.php';
  8. require_once 'include/ostatus.php';
  9. require_once 'include/salmon.php';
  10. /*
  11. * This file was at one time responsible for doing all deliveries, but this caused
  12. * big problems when the process was killed or stalled during the delivery process.
  13. * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
  14. */
  15. /*
  16. * The notifier is typically called with:
  17. *
  18. * proc_run(PRIORITY_HIGH, "include/notifier.php", COMMAND, ITEM_ID);
  19. *
  20. * where COMMAND is one of the following:
  21. *
  22. * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
  23. * comment-import (in diaspora.php, items.php)
  24. * comment-new (in item.php)
  25. * drop (in diaspora.php, items.php, photos.php)
  26. * edit_post (in item.php)
  27. * event (in events.php)
  28. * expire (in items.php)
  29. * like (in like.php, poke.php)
  30. * mail (in message.php)
  31. * suggest (in fsuggest.php)
  32. * tag (in photos.php, poke.php, tagger.php)
  33. * tgroup (in items.php)
  34. * wall-new (in photos.php, item.php)
  35. * removeme (in Contact.php)
  36. * relocate (in uimport.php)
  37. *
  38. * and ITEM_ID is the id of the item in the database that needs to be sent to others.
  39. */
  40. function notifier_run(&$argv, &$argc){
  41. global $a;
  42. require_once 'include/datetime.php';
  43. require_once 'include/items.php';
  44. require_once 'include/bbcode.php';
  45. require_once 'include/email.php';
  46. if ($argc < 3) {
  47. return;
  48. }
  49. // Inherit the priority
  50. $queue = dba::select('workerqueue', array('priority'), array('pid' => getmypid()), array('limit' => 1));
  51. if (dbm::is_result($queue)) {
  52. $priority = (int)$queue['priority'];
  53. logger('inherited priority: '.$priority);
  54. } else {
  55. // Normally this shouldn't happen.
  56. $priority = PRIORITY_HIGH;
  57. logger('no inherited priority! Something is wrong.');
  58. }
  59. logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
  60. $cmd = $argv[1];
  61. switch($cmd) {
  62. case 'mail':
  63. default:
  64. $item_id = intval($argv[2]);
  65. if (! $item_id) {
  66. return;
  67. }
  68. break;
  69. }
  70. $expire = false;
  71. $mail = false;
  72. $fsuggest = false;
  73. $relocate = false;
  74. $top_level = false;
  75. $recipients = array();
  76. $url_recipients = array();
  77. $normal_mode = true;
  78. if ($cmd === 'mail') {
  79. $normal_mode = false;
  80. $mail = true;
  81. $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
  82. intval($item_id)
  83. );
  84. if (! count($message)) {
  85. return;
  86. }
  87. $uid = $message[0]['uid'];
  88. $recipients[] = $message[0]['contact-id'];
  89. $item = $message[0];
  90. } elseif ($cmd === 'expire') {
  91. $normal_mode = false;
  92. $expire = true;
  93. $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
  94. AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
  95. intval($item_id)
  96. );
  97. $uid = $item_id;
  98. $item_id = 0;
  99. if (! count($items)) {
  100. return;
  101. }
  102. } elseif ($cmd === 'suggest') {
  103. $normal_mode = false;
  104. $fsuggest = true;
  105. $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
  106. intval($item_id)
  107. );
  108. if (! count($suggest)) {
  109. return;
  110. }
  111. $uid = $suggest[0]['uid'];
  112. $recipients[] = $suggest[0]['cid'];
  113. $item = $suggest[0];
  114. } elseif ($cmd === 'removeme') {
  115. $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
  116. `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
  117. `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
  118. FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  119. WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
  120. intval($item_id));
  121. if (!$r)
  122. return;
  123. $user = $r[0];
  124. $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($item_id));
  125. if (!$r)
  126. return;
  127. $self = $r[0];
  128. $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
  129. if (!$r) {
  130. return;
  131. }
  132. require_once 'include/Contact.php';
  133. foreach ($r as $contact) {
  134. terminate_friendship($user, $self, $contact);
  135. }
  136. return;
  137. } elseif ($cmd === 'relocate') {
  138. $normal_mode = false;
  139. $relocate = true;
  140. $uid = $item_id;
  141. $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
  142. } else {
  143. // find ancestors
  144. $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
  145. intval($item_id)
  146. );
  147. if ((! dbm::is_result($r)) || (! intval($r[0]['parent']))) {
  148. return;
  149. }
  150. $target_item = $r[0];
  151. $parent_id = intval($r[0]['parent']);
  152. $uid = $r[0]['uid'];
  153. $updated = $r[0]['edited'];
  154. $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
  155. FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
  156. intval($parent_id)
  157. );
  158. if (! count($items)) {
  159. return;
  160. }
  161. // avoid race condition with deleting entries
  162. if ($items[0]['deleted']) {
  163. foreach ($items as $item) {
  164. $item['deleted'] = 1;
  165. }
  166. }
  167. if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
  168. logger('notifier: top level post');
  169. $top_level = true;
  170. }
  171. }
  172. $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
  173. `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
  174. `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
  175. FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  176. WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
  177. intval($uid)
  178. );
  179. if (! dbm::is_result($r)) {
  180. return;
  181. }
  182. $owner = $r[0];
  183. $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
  184. $hub = get_config('system','huburl');
  185. // Should the post be transmitted to Diaspora?
  186. $diaspora_delivery = true;
  187. // If this is a public conversation, notify the feed hub
  188. $public_message = true;
  189. // Do a PuSH
  190. $push_notify = false;
  191. // fill this in with a single salmon slap if applicable
  192. $slap = '';
  193. if (! ($mail || $fsuggest || $relocate)) {
  194. $slap = ostatus::salmon($target_item,$owner);
  195. require_once 'include/group.php';
  196. $parent = $items[0];
  197. $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
  198. dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
  199. logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
  200. // This is IMPORTANT!!!!
  201. // We will only send a "notify owner to relay" or followup message if the referenced post
  202. // originated on our system by virtue of having our hostname somewhere
  203. // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
  204. // if $parent['wall'] == 1 we will already have the parent message in our array
  205. // and we will relay the whole lot.
  206. // expire sends an entire group of expire messages and cannot be forwarded.
  207. // However the conversation owner will be a part of the conversation and will
  208. // be notified during this run.
  209. // Other DFRN conversation members will be alerted during polled updates.
  210. // Diaspora members currently are not notified of expirations, and other networks have
  211. // either limited or no ability to process deletions. We should at least fix Diaspora
  212. // by stringing togther an array of retractions and sending them onward.
  213. $localhost = str_replace('www.','',$a->get_hostname());
  214. if (strpos($localhost,':')) {
  215. $localhost = substr($localhost,0,strpos($localhost,':'));
  216. }
  217. /**
  218. *
  219. * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
  220. * have been known to cause runaway conditions which affected several servers, along with
  221. * permissions issues.
  222. *
  223. */
  224. $relay_to_owner = false;
  225. if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
  226. $relay_to_owner = true;
  227. }
  228. if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
  229. $relay_to_owner = true;
  230. }
  231. // until the 'origin' flag has been in use for several months
  232. // we will just use it as a fallback test
  233. // later we will be able to use it as the primary test of whether or not to relay.
  234. if (! $target_item['origin']) {
  235. $relay_to_owner = false;
  236. }
  237. if ($parent['origin']) {
  238. $relay_to_owner = false;
  239. }
  240. if ($relay_to_owner) {
  241. logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
  242. // local followup to remote post
  243. $followup = true;
  244. $public_message = false; // not public
  245. $conversant_str = dbesc($parent['contact-id']);
  246. $recipients = array($parent['contact-id']);
  247. $recipients_followup = array($parent['contact-id']);
  248. //if (!$target_item['private'] && $target_item['wall'] &&
  249. if (!$target_item['private'] &&
  250. (strlen($target_item['allow_cid'].$target_item['allow_gid'].
  251. $target_item['deny_cid'].$target_item['deny_gid']) == 0))
  252. $push_notify = true;
  253. if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
  254. $push_notify = true;
  255. if ($parent["network"] == NETWORK_OSTATUS) {
  256. // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
  257. // Currently it is work at progress
  258. $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
  259. intval($uid),
  260. dbesc(NETWORK_DFRN)
  261. );
  262. if (dbm::is_result($r)) {
  263. foreach ($r as $rr) {
  264. $recipients_followup[] = $rr['id'];
  265. }
  266. }
  267. }
  268. }
  269. logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
  270. } else {
  271. $followup = false;
  272. logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
  273. // don't send deletions onward for other people's stuff
  274. if ($target_item['deleted'] && (! intval($target_item['wall']))) {
  275. logger('notifier: ignoring delete notification for non-wall item');
  276. return;
  277. }
  278. if ((strlen($parent['allow_cid']))
  279. || (strlen($parent['allow_gid']))
  280. || (strlen($parent['deny_cid']))
  281. || (strlen($parent['deny_gid']))) {
  282. $public_message = false; // private recipients, not public
  283. }
  284. $allow_people = expand_acl($parent['allow_cid']);
  285. $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
  286. $deny_people = expand_acl($parent['deny_cid']);
  287. $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
  288. // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
  289. // a delivery fork. private groups (forum_mode == 2) do not uplink
  290. if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
  291. proc_run($priority, 'include/notifier.php', 'uplink', $item_id);
  292. }
  293. $conversants = array();
  294. foreach ($items as $item) {
  295. $recipients[] = $item['contact-id'];
  296. $conversants[] = $item['contact-id'];
  297. // pull out additional tagged people to notify (if public message)
  298. if ($public_message && strlen($item['inform'])) {
  299. $people = explode(',',$item['inform']);
  300. foreach ($people as $person) {
  301. if (substr($person,0,4) === 'cid:') {
  302. $recipients[] = intval(substr($person,4));
  303. $conversants[] = intval(substr($person,4));
  304. } else {
  305. $url_recipients[] = substr($person,4);
  306. }
  307. }
  308. }
  309. }
  310. if (count($url_recipients))
  311. logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
  312. $conversants = array_unique($conversants);
  313. $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
  314. $deny = array_unique(array_merge($deny_people,$deny_groups));
  315. $recipients = array_diff($recipients,$deny);
  316. $conversant_str = dbesc(implode(', ',$conversants));
  317. }
  318. // If the thread parent is OStatus then do some magic to distribute the messages.
  319. // We have not only to look at the parent, since it could be a Friendica thread.
  320. if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
  321. $diaspora_delivery = false;
  322. logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
  323. // Send a salmon to the parent author
  324. $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
  325. dbesc(normalise_link($thr_parent[0]['author-link'])),
  326. intval($uid));
  327. if (dbm::is_result($r)) {
  328. $probed_contact = $r[0];
  329. } else {
  330. $probed_contact = probe_url($thr_parent[0]['author-link']);
  331. }
  332. if ($probed_contact["notify"] != "") {
  333. logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
  334. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  335. }
  336. // Send a salmon to the parent owner
  337. $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
  338. dbesc(normalise_link($thr_parent[0]['owner-link'])),
  339. intval($uid));
  340. if (dbm::is_result($r)) {
  341. $probed_contact = $r[0];
  342. } else {
  343. $probed_contact = probe_url($thr_parent[0]['owner-link']);
  344. }
  345. if ($probed_contact["notify"] != "") {
  346. logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
  347. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  348. }
  349. // Send a salmon notification to every person we mentioned in the post
  350. $arr = explode(',',$target_item['tag']);
  351. foreach ($arr as $x) {
  352. //logger('Checking tag '.$x, LOGGER_DEBUG);
  353. $matches = null;
  354. if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
  355. $probed_contact = probe_url($matches[1]);
  356. if ($probed_contact["notify"] != "") {
  357. logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
  358. $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
  359. }
  360. }
  361. }
  362. // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
  363. $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
  364. } else {
  365. $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
  366. }
  367. } else {
  368. $public_message = false;
  369. }
  370. // If this is a public message and pubmail is set on the parent, include all your email contacts
  371. $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
  372. if (! $mail_disabled) {
  373. if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
  374. && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
  375. && (intval($target_item['pubmail']))) {
  376. $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
  377. intval($uid),
  378. dbesc(NETWORK_MAIL)
  379. );
  380. if (dbm::is_result($r)) {
  381. foreach ($r as $rr) {
  382. $recipients[] = $rr['id'];
  383. }
  384. }
  385. }
  386. }
  387. if ($followup) {
  388. $recip_str = implode(', ', $recipients_followup);
  389. } else {
  390. $recip_str = implode(', ', $recipients);
  391. }
  392. if ($relocate) {
  393. $r = $recipients_relocate;
  394. } else {
  395. $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
  396. WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
  397. dbesc($recip_str)
  398. );
  399. }
  400. // delivery loop
  401. if (dbm::is_result($r)) {
  402. foreach ($r as $contact) {
  403. if ($contact['self']) {
  404. continue;
  405. }
  406. logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
  407. proc_run(array('priority' => $priority, 'dont_fork' => true), 'include/delivery.php', $cmd, $item_id, $contact['id']);
  408. }
  409. }
  410. // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
  411. // They are especially used for notifications to OStatus users that don't follow us.
  412. if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
  413. if (!get_config('system','dfrn_only')) {
  414. foreach ($url_recipients as $url) {
  415. if ($url) {
  416. logger('notifier: urldelivery: ' . $url);
  417. $deliver_status = slapper($owner,$url,$slap);
  418. /// @TODO Redeliver/queue these items on failure, though there is no contact record
  419. }
  420. }
  421. }
  422. }
  423. if ($public_message) {
  424. $r0 = array();
  425. $r1 = array();
  426. if ($diaspora_delivery) {
  427. if (!$followup) {
  428. $r0 = Diaspora::relay_list();
  429. }
  430. $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
  431. FROM `contact` WHERE `network` = '%s'
  432. AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch` ORDER BY rand()",
  433. dbesc(NETWORK_DIASPORA),
  434. intval($owner['uid']),
  435. intval(CONTACT_IS_SHARING)
  436. );
  437. }
  438. $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
  439. WHERE `network` in ( '%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive`
  440. AND `rel` != %d order by rand() ",
  441. dbesc(NETWORK_DFRN),
  442. dbesc(NETWORK_MAIL2),
  443. intval($owner['uid']),
  444. intval(CONTACT_IS_SHARING)
  445. );
  446. $r = array_merge($r2,$r1,$r0);
  447. if (dbm::is_result($r)) {
  448. logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
  449. foreach ($r as $rr) {
  450. // except for Diaspora batch jobs
  451. // Don't deliver to folks who have already been delivered to
  452. if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
  453. logger('notifier: already delivered id=' . $rr['id']);
  454. continue;
  455. }
  456. if ((! $mail) && (! $fsuggest) && (! $followup)) {
  457. logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
  458. proc_run(array('priority' => $priority, 'dont_fork' => true), 'include/delivery.php', $cmd, $item_id, $rr['id']);
  459. }
  460. }
  461. }
  462. $push_notify = true;
  463. }
  464. // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
  465. if ($push_notify && strlen($hub)) {
  466. $hubs = explode(',', $hub);
  467. if (count($hubs)) {
  468. foreach ($hubs as $h) {
  469. $h = trim($h);
  470. if (! strlen($h)) {
  471. continue;
  472. }
  473. if ($h === '[internal]') {
  474. // Set push flag for PuSH subscribers to this topic,
  475. // they will be notified in queue.php
  476. q("UPDATE `push_subscriber` SET `push` = 1 ".
  477. "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
  478. logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
  479. } else {
  480. $params = 'hub.mode=publish&hub.url=' . urlencode( App::get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
  481. post_url($h,$params);
  482. logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
  483. }
  484. if (count($hubs) > 1) {
  485. sleep(7); // try and avoid multiple hubs responding at precisely the same time
  486. }
  487. }
  488. }
  489. // Handling the pubsubhubbub requests
  490. proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'include/pubsubpublish.php');
  491. }
  492. logger('notifier: calling hooks', LOGGER_DEBUG);
  493. if ($normal_mode) {
  494. call_hooks('notifier_normal',$target_item);
  495. }
  496. call_hooks('notifier_end',$target_item);
  497. return;
  498. }