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.

552 lines
16 KiB

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