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.

538 lines
16KB

  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/dfrn.php';
  10. function delivery_run(&$argv, &$argc){
  11. global $a;
  12. require_once 'include/datetime.php';
  13. require_once 'include/items.php';
  14. require_once 'include/bbcode.php';
  15. require_once 'include/email.php';
  16. if ($argc < 3) {
  17. return;
  18. }
  19. logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
  20. $cmd = $argv[1];
  21. $item_id = intval($argv[2]);
  22. for ($x = 3; $x < $argc; $x ++) {
  23. $contact_id = intval($argv[$x]);
  24. if (!$item_id || !$contact_id) {
  25. continue;
  26. }
  27. $expire = false;
  28. $mail = false;
  29. $fsuggest = false;
  30. $relocate = false;
  31. $top_level = false;
  32. $recipients = array();
  33. $url_recipients = array();
  34. $followup = false;
  35. $normal_mode = true;
  36. $recipients[] = $contact_id;
  37. if ($cmd === 'mail') {
  38. $normal_mode = false;
  39. $mail = true;
  40. $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
  41. intval($item_id)
  42. );
  43. if (!count($message)) {
  44. return;
  45. }
  46. $uid = $message[0]['uid'];
  47. $recipients[] = $message[0]['contact-id'];
  48. $item = $message[0];
  49. } elseif ($cmd === 'expire') {
  50. $normal_mode = false;
  51. $expire = true;
  52. $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
  53. AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
  54. intval($item_id)
  55. );
  56. $uid = $item_id;
  57. $item_id = 0;
  58. if (!count($items)) {
  59. continue;
  60. }
  61. } elseif ($cmd === 'suggest') {
  62. $normal_mode = false;
  63. $fsuggest = true;
  64. $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
  65. intval($item_id)
  66. );
  67. if (!count($suggest)) {
  68. return;
  69. }
  70. $uid = $suggest[0]['uid'];
  71. $recipients[] = $suggest[0]['cid'];
  72. $item = $suggest[0];
  73. } elseif ($cmd === 'relocate') {
  74. $normal_mode = false;
  75. $relocate = true;
  76. $uid = $item_id;
  77. } else {
  78. // find ancestors
  79. $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
  80. intval($item_id)
  81. );
  82. if ((!dbm::is_result($r)) || (!intval($r[0]['parent']))) {
  83. continue;
  84. }
  85. $target_item = $r[0];
  86. $parent_id = intval($r[0]['parent']);
  87. $uid = $r[0]['uid'];
  88. $updated = $r[0]['edited'];
  89. $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
  90. FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
  91. intval($parent_id)
  92. );
  93. if (!count($items)) {
  94. continue;
  95. }
  96. $icontacts = null;
  97. $contacts_arr = array();
  98. foreach ($items as $item) {
  99. if (!in_array($item['contact-id'],$contacts_arr)) {
  100. $contacts_arr[] = intval($item['contact-id']);
  101. }
  102. }
  103. if (count($contacts_arr)) {
  104. $str_contacts = implode(',',$contacts_arr);
  105. $icontacts = q("SELECT * FROM `contact`
  106. WHERE `id` IN ( $str_contacts ) "
  107. );
  108. }
  109. if ( !($icontacts && count($icontacts))) {
  110. continue;
  111. }
  112. // avoid race condition with deleting entries
  113. if ($items[0]['deleted']) {
  114. foreach ($items as $item) {
  115. $item['deleted'] = 1;
  116. }
  117. }
  118. // When commenting too fast after delivery, a post wasn't recognized as top level post.
  119. // The count then showed more than one entry. The additional check should help.
  120. // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
  121. if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
  122. logger('delivery: top level post');
  123. $top_level = true;
  124. }
  125. }
  126. $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
  127. `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
  128. `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
  129. FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  130. WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
  131. intval($uid)
  132. );
  133. if (!dbm::is_result($r)) {
  134. continue;
  135. }
  136. $owner = $r[0];
  137. $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
  138. $public_message = true;
  139. if (!($mail || $fsuggest || $relocate)) {
  140. require_once 'include/group.php';
  141. $parent = $items[0];
  142. // This is IMPORTANT!!!!
  143. // We will only send a "notify owner to relay" or followup message if the referenced post
  144. // originated on our system by virtue of having our hostname somewhere
  145. // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
  146. // if $parent['wall'] == 1 we will already have the parent message in our array
  147. // and we will relay the whole lot.
  148. // expire sends an entire group of expire messages and cannot be forwarded.
  149. // However the conversation owner will be a part of the conversation and will
  150. // be notified during this run.
  151. // Other DFRN conversation members will be alerted during polled updates.
  152. // Diaspora members currently are not notified of expirations, and other networks have
  153. // either limited or no ability to process deletions. We should at least fix Diaspora
  154. // by stringing togther an array of retractions and sending them onward.
  155. $localhost = $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 line. 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) && !$expire && stristr($target_item['uri'],$localhost)) {
  168. $relay_to_owner = true;
  169. }
  170. if ($relay_to_owner) {
  171. logger('followup '.$target_item["guid"], LOGGER_DEBUG);
  172. // local followup to remote post
  173. $followup = true;
  174. }
  175. if ((strlen($parent['allow_cid']))
  176. || (strlen($parent['allow_gid']))
  177. || (strlen($parent['deny_cid']))
  178. || (strlen($parent['deny_gid']))
  179. || $parent["private"]) {
  180. $public_message = false; // private recipients, not public
  181. }
  182. }
  183. $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
  184. intval($contact_id)
  185. );
  186. if (dbm::is_result($r)) {
  187. $contact = $r[0];
  188. }
  189. if ($contact['self']) {
  190. continue;
  191. }
  192. $deliver_status = 0;
  193. logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
  194. switch($contact['network']) {
  195. case NETWORK_DFRN:
  196. logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
  197. if ($mail) {
  198. $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
  199. $atom = dfrn::mail($item, $owner);
  200. } elseif ($fsuggest) {
  201. $atom = dfrn::fsuggest($item, $owner);
  202. q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
  203. } elseif ($relocate) {
  204. $atom = dfrn::relocate($owner, $uid);
  205. } elseif ($followup) {
  206. $msgitems = array();
  207. foreach ($items as $item) { // there is only one item
  208. if (!$item['parent']) {
  209. continue;
  210. }
  211. if ($item['id'] == $item_id) {
  212. logger('followup: item: '. print_r($item,true), LOGGER_DATA);
  213. $msgitems[] = $item;
  214. }
  215. }
  216. $atom = dfrn::entries($msgitems,$owner);
  217. } else {
  218. $msgitems = array();
  219. foreach ($items as $item) {
  220. if (!$item['parent']) {
  221. continue;
  222. }
  223. // private emails may be in included in public conversations. Filter them.
  224. if ($public_message && $item['private']) {
  225. continue;
  226. }
  227. $item_contact = get_item_contact($item,$icontacts);
  228. if (!$item_contact) {
  229. continue;
  230. }
  231. if ($normal_mode) {
  232. if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
  233. $item["entry:comment-allow"] = true;
  234. $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
  235. $msgitems[] = $item;
  236. }
  237. } else {
  238. $item["entry:comment-allow"] = true;
  239. $msgitems[] = $item;
  240. }
  241. }
  242. $atom = dfrn::entries($msgitems,$owner);
  243. }
  244. logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
  245. logger('notifier: '.$atom, LOGGER_DATA);
  246. $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
  247. // perform local delivery if we are on the same site
  248. if (link_compare($basepath,App::get_baseurl())) {
  249. $nickname = basename($contact['url']);
  250. if ($contact['issued-id']) {
  251. $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
  252. } else {
  253. $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
  254. }
  255. $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
  256. `contact`.`pubkey` AS `cpubkey`,
  257. `contact`.`prvkey` AS `cprvkey`,
  258. `contact`.`thumb` AS `thumb`,
  259. `contact`.`url` as `url`,
  260. `contact`.`name` as `senderName`,
  261. `user`.*
  262. FROM `contact`
  263. INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
  264. WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
  265. AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
  266. $sql_extra
  267. AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
  268. dbesc(NETWORK_DFRN),
  269. dbesc($nickname)
  270. );
  271. if ($x && count($x)) {
  272. $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
  273. if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
  274. q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
  275. intval($x[0]['id'])
  276. );
  277. $x[0]['writable'] = 1;
  278. }
  279. $ssl_policy = get_config('system','ssl_policy');
  280. fix_contact_ssl_policy($x[0],$ssl_policy);
  281. // If we are setup as a soapbox we aren't accepting top level posts from this person
  282. if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
  283. break;
  284. }
  285. logger('mod-delivery: local delivery');
  286. dfrn::import($atom, $x[0]);
  287. break;
  288. }
  289. }
  290. if (!was_recently_delayed($contact['id'])) {
  291. $deliver_status = dfrn::deliver($owner,$contact,$atom);
  292. } else {
  293. $deliver_status = (-1);
  294. }
  295. logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
  296. if ($deliver_status < 0) {
  297. logger('notifier: delivery failed: queuing message');
  298. add_to_queue($contact['id'],NETWORK_DFRN,$atom);
  299. // The message could not be delivered. We mark the contact as "dead"
  300. mark_for_death($contact);
  301. } else {
  302. // We successfully delivered a message, the contact is alive
  303. unmark_for_death($contact);
  304. }
  305. break;
  306. case NETWORK_OSTATUS:
  307. // Do not send to otatus if we are not configured to send to public networks
  308. if ($owner['prvnets']) {
  309. break;
  310. }
  311. if (get_config('system','ostatus_disabled') || get_config('system','dfrn_only')) {
  312. break;
  313. }
  314. // There is currently no code here to distribute anything to OStatus.
  315. // This is done in "notifier.php" (See "url_recipients" and "push_notify")
  316. break;
  317. case NETWORK_MAIL:
  318. case NETWORK_MAIL2:
  319. if (get_config('system','dfrn_only')) {
  320. break;
  321. }
  322. // WARNING: does not currently convert to RFC2047 header encodings, etc.
  323. $addr = $contact['addr'];
  324. if (!strlen($addr)) {
  325. break;
  326. }
  327. if ($cmd === 'wall-new' || $cmd === 'comment-new') {
  328. $it = null;
  329. if ($cmd === 'wall-new') {
  330. $it = $items[0];
  331. } else {
  332. $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  333. intval($argv[2]),
  334. intval($uid)
  335. );
  336. if (dbm::is_result($r))
  337. $it = $r[0];
  338. }
  339. if (!$it)
  340. break;
  341. $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  342. intval($uid)
  343. );
  344. if (!count($local_user))
  345. break;
  346. $reply_to = '';
  347. $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
  348. intval($uid)
  349. );
  350. if ($r1 && $r1[0]['reply_to'])
  351. $reply_to = $r1[0]['reply_to'];
  352. $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
  353. // only expose our real email address to true friends
  354. if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
  355. if ($reply_to) {
  356. $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
  357. $headers .= 'Sender: '.$local_user[0]['email']."\n";
  358. } else {
  359. $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
  360. }
  361. } else {
  362. $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
  363. }
  364. //if ($reply_to)
  365. // $headers .= 'Reply-to: '.$reply_to . "\n";
  366. $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
  367. //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
  368. //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
  369. //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
  370. if ($it['uri'] !== $it['parent-uri']) {
  371. $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
  372. // If Threading is enabled, write down the correct parent
  373. if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"]))
  374. $headers .= " <".iri2msgid($it["thr-parent"]).">";
  375. $headers .= "\n";
  376. if (!$it['title']) {
  377. $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  378. dbesc($it['parent-uri']),
  379. intval($uid));
  380. if (dbm::is_result($r) && ($r[0]['title'] != '')) {
  381. $subject = $r[0]['title'];
  382. } else {
  383. $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
  384. dbesc($it['parent-uri']),
  385. intval($uid));
  386. if (dbm::is_result($r) && ($r[0]['title'] != ''))
  387. $subject = $r[0]['title'];
  388. }
  389. }
  390. if (strncasecmp($subject,'RE:',3))
  391. $subject = 'Re: '.$subject;
  392. }
  393. email_send($addr, $subject, $headers, $it);
  394. }
  395. break;
  396. case NETWORK_DIASPORA:
  397. if ($public_message)
  398. $loc = 'public batch '.$contact['batch'];
  399. else
  400. $loc = $contact['name'];
  401. logger('delivery: diaspora batch deliver: '.$loc);
  402. if (get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
  403. break;
  404. if ($mail) {
  405. Diaspora::send_mail($item,$owner,$contact);
  406. break;
  407. }
  408. if (!$normal_mode)
  409. break;
  410. if (!$contact['pubkey'] && !$public_message)
  411. break;
  412. if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
  413. // top-level retraction
  414. logger('diaspora retract: '.$loc);
  415. Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
  416. break;
  417. } elseif ($followup) {
  418. // send comments and likes to owner to relay
  419. logger('diaspora followup: '.$loc);
  420. Diaspora::send_followup($target_item,$owner,$contact,$public_message);
  421. break;
  422. } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
  423. // we are the relay - send comments, likes and relayable_retractions to our conversants
  424. logger('diaspora relay: '.$loc);
  425. Diaspora::send_relay($target_item,$owner,$contact,$public_message);
  426. break;
  427. } elseif ($top_level && !$walltowall) {
  428. // currently no workable solution for sending walltowall
  429. logger('diaspora status: '.$loc);
  430. Diaspora::send_status($target_item,$owner,$contact,$public_message);
  431. break;
  432. }
  433. logger('delivery: diaspora unknown mode: '.$contact['name']);
  434. break;
  435. default:
  436. break;
  437. }
  438. }
  439. return;
  440. }