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.
 
 
 
 
 
 

572 lines
17 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("include/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("include/session.php");
  17. require_once("include/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[0] . ' 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",
  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. $target_item = $r[0];
  86. $parent_id = intval($r[0]['parent']);
  87. $uid = $r[0]['uid'];
  88. $updated = $r[0]['edited'];
  89. // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
  90. if(! $parent_id)
  91. continue;
  92. $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
  93. FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
  94. intval($parent_id)
  95. );
  96. if(! count($items))
  97. continue;
  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. continue;
  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` INNER 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. continue;
  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. $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
  154. intval($contact_id)
  155. );
  156. if(count($r))
  157. $contact = $r[0];
  158. /**
  159. *
  160. * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
  161. * have been known to cause runaway conditions which affected several servers, along with
  162. * permissions issues.
  163. *
  164. */
  165. if(!$top_level && ($parent["network"] != NETWORK_OSTATUS) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
  166. logger('relay denied for delivery agent.');
  167. /* no relay allowed for direct contact delivery */
  168. continue;
  169. }
  170. if((strlen($parent['allow_cid']))
  171. || (strlen($parent['allow_gid']))
  172. || (strlen($parent['deny_cid']))
  173. || (strlen($parent['deny_gid']))) {
  174. $public_message = false; // private recipients, not public
  175. }
  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. continue;
  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'] == 1)
  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,(($top_level) ? $contact['id'] : 0));
  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. INNER 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 AND `user`.`account_removed` = 0 LIMIT 1",
  247. dbesc(NETWORK_DFRN),
  248. dbesc($nickname)
  249. );
  250. if($x && count($x)) {
  251. $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
  252. if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
  253. q("update contact set writable = 1 where id = %d",
  254. intval($x[0]['id'])
  255. );
  256. $x[0]['writable'] = 1;
  257. }
  258. $ssl_policy = get_config('system','ssl_policy');
  259. fix_contact_ssl_policy($x[0],$ssl_policy);
  260. // If we are setup as a soapbox we aren't accepting input from this person
  261. if($x[0]['page-flags'] == PAGE_SOAPBOX)
  262. break;
  263. require_once('library/simplepie/simplepie.inc');
  264. logger('mod-delivery: local delivery');
  265. local_delivery($x[0],$atom);
  266. break;
  267. }
  268. }
  269. if(! was_recently_delayed($contact['id']))
  270. $deliver_status = dfrn_deliver($owner,$contact,$atom);
  271. else
  272. $deliver_status = (-1);
  273. logger('notifier: dfrn_delivery returns ' . $deliver_status);
  274. if($deliver_status == (-1)) {
  275. logger('notifier: delivery failed: queuing message');
  276. add_to_queue($contact['id'],NETWORK_DFRN,$atom);
  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. if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
  284. break;
  285. // only send salmon if public - e.g. if it's ok to notify
  286. // a public hub, it's ok to send a salmon
  287. if(($public_message) && (! $expire)) {
  288. $slaps = array();
  289. foreach($items as $item) {
  290. if(! $item['parent'])
  291. continue;
  292. // private emails may be in included in public conversations. Filter them.
  293. if(($public_message) && $item['private'] == 1)
  294. continue;
  295. $item_contact = get_item_contact($item,$icontacts);
  296. if(! $item_contact)
  297. continue;
  298. // For OStatus don't notify all contacts in the thread
  299. if (!$top_level AND ($parent["network"] == NETWORK_OSTATUS) AND ($item["id"] != $item_id))
  300. continue;
  301. if(($top_level OR ($parent["network"] == NETWORK_OSTATUS)) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
  302. $slaps[] = atom_entry($item,'html',null,$owner,true);
  303. }
  304. logger('slapdelivery item '.$item_id.' to ' . $contact['name']);
  305. foreach($slaps as $slappy) {
  306. if($contact['notify']) {
  307. if(! was_recently_delayed($contact['id']))
  308. $deliver_status = slapper($owner,$contact['notify'],$slappy);
  309. else
  310. $deliver_status = (-1);
  311. if($deliver_status == (-1)) {
  312. // queue message for redelivery
  313. add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
  314. }
  315. }
  316. }
  317. }
  318. break;
  319. case NETWORK_MAIL :
  320. case NETWORK_MAIL2:
  321. if(get_config('system','dfrn_only'))
  322. break;
  323. // WARNING: does not currently convert to RFC2047 header encodings, etc.
  324. $addr = $contact['addr'];
  325. if(! strlen($addr))
  326. break;
  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(count($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. } else
  361. $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
  362. //if($reply_to)
  363. // $headers .= 'Reply-to: ' . $reply_to . "\n";
  364. $headers .= 'Message-Id: <' . iri2msgid($it['uri']). '>' . "\n";
  365. //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
  366. //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
  367. //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
  368. if($it['uri'] !== $it['parent-uri']) {
  369. $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
  370. // If Threading is enabled, write down the correct parent
  371. if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
  372. $headers .= " <".iri2msgid($it["thr-parent"]).">";
  373. $headers .= "\n";
  374. if(!$it['title']) {
  375. $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  376. dbesc($it['parent-uri']),
  377. intval($uid));
  378. if(count($r) AND ($r[0]['title'] != ''))
  379. $subject = $r[0]['title'];
  380. else {
  381. $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
  382. dbesc($it['parent-uri']),
  383. intval($uid));
  384. if(count($r) AND ($r[0]['title'] != ''))
  385. $subject = $r[0]['title'];
  386. }
  387. }
  388. if(strncasecmp($subject,'RE:',3))
  389. $subject = 'Re: '.$subject;
  390. }
  391. email_send($addr, $subject, $headers, $it);
  392. }
  393. break;
  394. case NETWORK_DIASPORA :
  395. if($public_message)
  396. $loc = 'public batch ' . $contact['batch'];
  397. else
  398. $loc = $contact['name'];
  399. logger('delivery: diaspora batch deliver: ' . $loc);
  400. if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
  401. break;
  402. if((! $contact['pubkey']) && (! $public_message))
  403. break;
  404. if($target_item['verb'] === ACTIVITY_DISLIKE) {
  405. // unsupported
  406. break;
  407. }
  408. elseif(($target_item['deleted']) && ($target_item['uri'] === $target_item['parent-uri'])) {
  409. // top-level retraction
  410. logger('delivery: diaspora retract: ' . $loc);
  411. diaspora_send_retraction($target_item,$owner,$contact,$public_message);
  412. break;
  413. }
  414. elseif($target_item['uri'] !== $target_item['parent-uri']) {
  415. // we are the relay - send comments, likes and relayable_retractions to our conversants
  416. logger('delivery: diaspora relay: ' . $loc);
  417. diaspora_send_relay($target_item,$owner,$contact,$public_message);
  418. break;
  419. }
  420. elseif(($top_level) && (! $walltowall)) {
  421. // currently no workable solution for sending walltowall
  422. logger('delivery: diaspora status: ' . $loc);
  423. diaspora_send_status($target_item,$owner,$contact,$public_message);
  424. break;
  425. }
  426. logger('delivery: diaspora unknown mode: ' . $contact['name']);
  427. break;
  428. case NETWORK_FEED :
  429. case NETWORK_FACEBOOK :
  430. if(get_config('system','dfrn_only'))
  431. break;
  432. case NETWORK_PUMPIO :
  433. if(get_config('system','dfrn_only'))
  434. break;
  435. default:
  436. break;
  437. }
  438. }
  439. return;
  440. }
  441. if (array_search(__file__,get_included_files())===0){
  442. delivery_run($_SERVER["argv"],$_SERVER["argc"]);
  443. killme();
  444. }