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.
 
 
 
 
 
 

541 lines
15 KiB

  1. <?php
  2. require_once("boot.php");
  3. require_once('include/queue_fn.php');
  4. require_once('include/html2plain.php');
  5. function delivery_run($argv, $argc){
  6. global $a, $db;
  7. if(is_null($a)){
  8. $a = new App;
  9. }
  10. if(is_null($db)) {
  11. @include(".htconfig.php");
  12. require_once("dba.php");
  13. $db = new dba($db_host, $db_user, $db_pass, $db_data);
  14. unset($db_host, $db_user, $db_pass, $db_data);
  15. }
  16. require_once("session.php");
  17. require_once("datetime.php");
  18. require_once('include/items.php');
  19. require_once('include/bbcode.php');
  20. require_once('include/diaspora.php');
  21. require_once('include/email.php');
  22. load_config('config');
  23. load_config('system');
  24. load_hooks();
  25. if($argc < 3)
  26. return;
  27. $a->set_baseurl(get_config('system','url'));
  28. logger('delivery: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
  29. $cmd = $argv[1];
  30. $item_id = intval($argv[2]);
  31. $contact_id = intval($argv[3]);
  32. // Some other process may have delivered this item already.
  33. $r = q("select * from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
  34. dbesc($cmd),
  35. dbesc($item_id),
  36. dbesc($contact_id)
  37. );
  38. if(! count($r)) {
  39. return;
  40. }
  41. $maxsysload = intval(get_config('system','maxloadavg'));
  42. if($maxsysload < 1)
  43. $maxsysload = 50;
  44. if(function_exists('sys_getloadavg')) {
  45. $load = sys_getloadavg();
  46. if(intval($load[0]) > $maxsysload) {
  47. logger('system: load ' . $load . ' too high. Delivery deferred to next queue run.');
  48. return;
  49. }
  50. }
  51. // It's ours to deliver. Remove it from the queue.
  52. q("delete from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
  53. dbesc($cmd),
  54. dbesc($item_id),
  55. dbesc($contact_id)
  56. );
  57. if((! $item_id) || (! $contact_id))
  58. return;
  59. $expire = false;
  60. $top_level = false;
  61. $recipients = array();
  62. $url_recipients = array();
  63. $normal_mode = true;
  64. $recipients[] = $contact_id;
  65. if($cmd === 'expire') {
  66. $normal_mode = false;
  67. $expire = true;
  68. $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
  69. AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
  70. intval($item_id)
  71. );
  72. $uid = $item_id;
  73. $item_id = 0;
  74. if(! count($items))
  75. return;
  76. }
  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((! count($r)) || (! intval($r[0]['parent']))) {
  83. return;
  84. }
  85. $target_item = $r[0];
  86. $parent_id = intval($r[0]['parent']);
  87. $uid = $r[0]['uid'];
  88. $updated = $r[0]['edited'];
  89. if(! $parent_id)
  90. return;
  91. $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
  92. FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
  93. intval($parent_id)
  94. );
  95. if(! count($items)) {
  96. return;
  97. }
  98. $icontacts = null;
  99. $contacts_arr = array();
  100. foreach($items as $item)
  101. if(! in_array($item['contact-id'],$contacts_arr))
  102. $contacts_arr[] = intval($item['contact-id']);
  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. return;
  111. // avoid race condition with deleting entries
  112. if($items[0]['deleted']) {
  113. foreach($items as $item)
  114. $item['deleted'] = 1;
  115. }
  116. if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
  117. logger('delivery: top level post');
  118. $top_level = true;
  119. }
  120. }
  121. $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
  122. `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
  123. `user`.`page-flags`, `user`.`prvnets`
  124. FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
  125. WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
  126. intval($uid)
  127. );
  128. if(! count($r))
  129. return;
  130. $owner = $r[0];
  131. $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
  132. $public_message = true;
  133. // fill this in with a single salmon slap if applicable
  134. $slap = '';
  135. require_once('include/group.php');
  136. $parent = $items[0];
  137. // This is IMPORTANT!!!!
  138. // We will only send a "notify owner to relay" or followup message if the referenced post
  139. // originated on our system by virtue of having our hostname somewhere
  140. // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
  141. // if $parent['wall'] == 1 we will already have the parent message in our array
  142. // and we will relay the whole lot.
  143. // expire sends an entire group of expire messages and cannot be forwarded.
  144. // However the conversation owner will be a part of the conversation and will
  145. // be notified during this run.
  146. // Other DFRN conversation members will be alerted during polled updates.
  147. // Diaspora members currently are not notified of expirations, and other networks have
  148. // either limited or no ability to process deletions. We should at least fix Diaspora
  149. // by stringing togther an array of retractions and sending them onward.
  150. $localhost = $a->get_hostname();
  151. if(strpos($localhost,':'))
  152. $localhost = substr($localhost,0,strpos($localhost,':'));
  153. /**
  154. *
  155. * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
  156. * have been known to cause runaway conditions which affected several servers, along with
  157. * permissions issues.
  158. *
  159. */
  160. if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
  161. logger('relay denied for delivery agent.');
  162. /* no relay allowed for direct contact delivery */
  163. return;
  164. }
  165. if((strlen($parent['allow_cid']))
  166. || (strlen($parent['allow_gid']))
  167. || (strlen($parent['deny_cid']))
  168. || (strlen($parent['deny_gid']))) {
  169. $public_message = false; // private recipients, not public
  170. }
  171. $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
  172. intval($contact_id)
  173. );
  174. if(count($r))
  175. $contact = $r[0];
  176. $hubxml = feed_hublinks();
  177. logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
  178. require_once('include/salmon.php');
  179. if($contact['self'])
  180. return;
  181. $deliver_status = 0;
  182. switch($contact['network']) {
  183. case NETWORK_DFRN :
  184. logger('notifier: dfrndelivery: ' . $contact['name']);
  185. $feed_template = get_markup_template('atom_feed.tpl');
  186. $mail_template = get_markup_template('atom_mail.tpl');
  187. $atom = '';
  188. $birthday = feed_birthday($owner['uid'],$owner['timezone']);
  189. if(strlen($birthday))
  190. $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
  191. $atom .= replace_macros($feed_template, array(
  192. '$version' => xmlify(FRIENDICA_VERSION),
  193. '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
  194. '$feed_title' => xmlify($owner['name']),
  195. '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
  196. '$hub' => $hubxml,
  197. '$salmon' => '', // private feed, we don't use salmon here
  198. '$name' => xmlify($owner['name']),
  199. '$profile_page' => xmlify($owner['url']),
  200. '$photo' => xmlify($owner['photo']),
  201. '$thumb' => xmlify($owner['thumb']),
  202. '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
  203. '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
  204. '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
  205. '$birthday' => $birthday,
  206. '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
  207. ));
  208. foreach($items as $item) {
  209. if(! $item['parent'])
  210. continue;
  211. // private emails may be in included in public conversations. Filter them.
  212. if(($public_message) && $item['private'])
  213. continue;
  214. $item_contact = get_item_contact($item,$icontacts);
  215. if(! $item_contact)
  216. continue;
  217. if($normal_mode) {
  218. if($item_id == $item['id'] || $item['id'] == $item['parent'])
  219. $atom .= atom_entry($item,'text',null,$owner,true);
  220. }
  221. else
  222. $atom .= atom_entry($item,'text',null,$owner,true);
  223. }
  224. $atom .= '</feed>' . "\r\n";
  225. logger('notifier: ' . $atom, LOGGER_DATA);
  226. $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
  227. // perform local delivery if we are on the same site
  228. if(link_compare($basepath,$a->get_baseurl())) {
  229. $nickname = basename($contact['url']);
  230. if($contact['issued-id'])
  231. $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
  232. else
  233. $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
  234. $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
  235. `contact`.`pubkey` AS `cpubkey`,
  236. `contact`.`prvkey` AS `cprvkey`,
  237. `contact`.`thumb` AS `thumb`,
  238. `contact`.`url` as `url`,
  239. `contact`.`name` as `senderName`,
  240. `user`.*
  241. FROM `contact`
  242. LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
  243. WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
  244. AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
  245. $sql_extra
  246. AND `user`.`account_expired` = 0 LIMIT 1",
  247. dbesc(NETWORK_DFRN),
  248. dbesc($nickname)
  249. );
  250. if(count($x)) {
  251. if($owner['page-flags'] == PAGE_COMMUNITY && ! $x[0]['writable']) {
  252. q("update contact set writable = 1 where id = %d limit 1",
  253. intval($x[0]['id'])
  254. );
  255. $x[0]['writable'] = 1;
  256. }
  257. $ssl_policy = get_config('system','ssl_policy');
  258. fix_contact_ssl_policy($x[0],$ssl_policy);
  259. // If we are setup as a soapbox we aren't accepting input from this person
  260. if($x[0]['page-flags'] == PAGE_SOAPBOX)
  261. break;
  262. require_once('library/simplepie/simplepie.inc');
  263. logger('mod-delivery: local delivery');
  264. local_delivery($x[0],$atom);
  265. break;
  266. }
  267. }
  268. $deliver_status = dfrn_deliver($owner,$contact,$atom);
  269. logger('notifier: dfrn_delivery returns ' . $deliver_status);
  270. if($deliver_status == (-1)) {
  271. logger('notifier: delivery failed: queuing message');
  272. add_to_queue($contact['id'],NETWORK_DFRN,$atom);
  273. }
  274. break;
  275. case NETWORK_OSTATUS :
  276. // Do not send to otatus if we are not configured to send to public networks
  277. if($owner['prvnets'])
  278. break;
  279. if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
  280. break;
  281. // only send salmon if public - e.g. if it's ok to notify
  282. // a public hub, it's ok to send a salmon
  283. if(($public_message) && (! $expire)) {
  284. $slaps = array();
  285. foreach($items as $item) {
  286. if(! $item['parent'])
  287. continue;
  288. // private emails may be in included in public conversations. Filter them.
  289. if(($public_message) && $item['private'])
  290. continue;
  291. $item_contact = get_item_contact($item,$icontacts);
  292. if(! $item_contact)
  293. continue;
  294. if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
  295. $slaps[] = atom_entry($item,'html',null,$owner,true);
  296. }
  297. logger('notifier: slapdelivery: ' . $contact['name']);
  298. foreach($slaps as $slappy) {
  299. if($contact['notify']) {
  300. $deliver_status = slapper($owner,$contact['notify'],$slappy);
  301. if($deliver_status == (-1)) {
  302. // queue message for redelivery
  303. add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
  304. }
  305. }
  306. }
  307. }
  308. break;
  309. case NETWORK_MAIL :
  310. case NETWORK_MAIL2:
  311. if(get_config('system','dfrn_only'))
  312. break;
  313. // WARNING: does not currently convert to RFC2047 header encodings, etc.
  314. $addr = $contact['addr'];
  315. if(! strlen($addr))
  316. break;
  317. if($cmd === 'wall-new' || $cmd === 'comment-new') {
  318. $it = null;
  319. if($cmd === 'wall-new')
  320. $it = $items[0];
  321. else {
  322. $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  323. intval($argv[2]),
  324. intval($uid)
  325. );
  326. if(count($r))
  327. $it = $r[0];
  328. }
  329. if(! $it)
  330. break;
  331. $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  332. intval($uid)
  333. );
  334. if(! count($local_user))
  335. break;
  336. $reply_to = '';
  337. $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
  338. intval($uid)
  339. );
  340. if($r1 && $r1[0]['reply_to'])
  341. $reply_to = $r1[0]['reply_to'];
  342. $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
  343. // only expose our real email address to true friends
  344. if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
  345. $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
  346. else
  347. $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
  348. if($reply_to)
  349. $headers .= 'Reply-to: ' . $reply_to . "\n";
  350. // for testing purposes: Collect exported mails
  351. // $file = tempnam("/tmp/friendica/", "mail-out-");
  352. // file_put_contents($file, json_encode($it));
  353. $headers .= 'Message-Id: <' . iri2msgid($it['uri']). '>' . "\n";
  354. //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
  355. //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
  356. //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
  357. if($it['uri'] !== $it['parent-uri']) {
  358. $headers .= 'References: <' . iri2msgid($it['parent-uri']) . '>' . "\n";
  359. if(!strlen($it['title'])) {
  360. $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
  361. dbesc($it['parent-uri']));
  362. if(count($r) AND ($r[0]['title'] != ''))
  363. $subject = $r[0]['title'];
  364. }
  365. if(strncasecmp($subject,'RE:',3))
  366. $subject = 'Re: '.$subject;
  367. }
  368. email_send($addr, $subject, $headers, $it);
  369. }
  370. break;
  371. case NETWORK_DIASPORA :
  372. if($public_message)
  373. $loc = 'public batch ' . $contact['batch'];
  374. else
  375. $loc = $contact['name'];
  376. logger('delivery: diaspora batch deliver: ' . $loc);
  377. if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
  378. break;
  379. if((! $contact['pubkey']) && (! $public_message))
  380. break;
  381. if($target_item['verb'] === ACTIVITY_DISLIKE) {
  382. // unsupported
  383. break;
  384. }
  385. elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
  386. logger('delivery: diaspora retract: ' . $loc);
  387. // diaspora delete,
  388. diaspora_send_retraction($target_item,$owner,$contact,$public_message);
  389. break;
  390. }
  391. elseif($target_item['parent'] != $target_item['id']) {
  392. logger('delivery: diaspora relay: ' . $loc);
  393. // we are the relay - send comments, likes and unlikes to our conversants
  394. diaspora_send_relay($target_item,$owner,$contact,$public_message);
  395. break;
  396. }
  397. elseif(($top_level) && (! $walltowall)) {
  398. // currently no workable solution for sending walltowall
  399. logger('delivery: diaspora status: ' . $loc);
  400. diaspora_send_status($target_item,$owner,$contact,$public_message);
  401. break;
  402. }
  403. logger('delivery: diaspora unknown mode: ' . $contact['name']);
  404. break;
  405. case NETWORK_FEED :
  406. case NETWORK_FACEBOOK :
  407. if(get_config('system','dfrn_only'))
  408. break;
  409. default:
  410. break;
  411. }
  412. return;
  413. }
  414. if (array_search(__file__,get_included_files())===0){
  415. delivery_run($argv,$argc);
  416. killme();
  417. }