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.

520 lines
15 KiB

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