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.

656 lines
23 KiB

  1. <?php
  2. /**
  3. * @file src/Worker/OnePoll.php
  4. */
  5. namespace Friendica\Worker;
  6. use Friendica\Content\Text\BBCode;
  7. use Friendica\Core\Config;
  8. use Friendica\Core\PConfig;
  9. use Friendica\Database\DBM;
  10. use Friendica\Model\Contact;
  11. use Friendica\Model\Item;
  12. use Friendica\Protocol\Email;
  13. use Friendica\Protocol\PortableContact;
  14. use Friendica\Util\DateTimeFormat;
  15. use Friendica\Util\Network;
  16. use Friendica\Util\XML;
  17. use dba;
  18. require_once 'include/dba.php';
  19. class OnePoll
  20. {
  21. public static function execute($contact_id = 0, $command = '') {
  22. global $a;
  23. require_once 'include/items.php';
  24. logger('start');
  25. $manual_id = 0;
  26. $generation = 0;
  27. $hub_update = false;
  28. $force = false;
  29. $restart = false;
  30. if ($command == "force") {
  31. $force = true;
  32. }
  33. if (!$contact_id) {
  34. logger('no contact');
  35. return;
  36. }
  37. $d = DateTimeFormat::utcNow();
  38. $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
  39. if (!DBM::is_result($contact)) {
  40. logger('Contact not found or cannot be used.');
  41. return;
  42. }
  43. $importer_uid = $contact['uid'];
  44. // load current friends if possible.
  45. if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
  46. $r = q("SELECT count(*) AS total FROM glink
  47. WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
  48. intval($contact['id'])
  49. );
  50. if (DBM::is_result($r)) {
  51. if (!$r[0]['total']) {
  52. PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
  53. }
  54. }
  55. }
  56. // Diaspora users, archived users and followers are only checked if they still exist.
  57. if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
  58. $last_updated = PortableContact::lastUpdated($contact["url"], true);
  59. $updated = DateTimeFormat::utcNow();
  60. if ($last_updated) {
  61. logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
  62. // The last public item can be older than the last item we got
  63. if ($last_updated < $contact['last-item']) {
  64. $last_updated = $contact['last-item'];
  65. }
  66. $fields = ['last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated];
  67. self::updateContact($contact, $fields);
  68. Contact::unmarkForArchival($contact);
  69. } else {
  70. self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
  71. Contact::markForArchival($contact);
  72. logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
  73. }
  74. return;
  75. }
  76. $xml = false;
  77. $t = $contact['last-update'];
  78. if ($contact['subhub']) {
  79. $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
  80. $contact['priority'] = intval($poll_interval);
  81. $hub_update = false;
  82. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
  83. $hub_update = true;
  84. }
  85. } else {
  86. $hub_update = false;
  87. }
  88. $last_update = (($contact['last-update'] <= NULL_DATE)
  89. ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
  90. : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
  91. );
  92. // Update the contact entry
  93. if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
  94. if (!PortableContact::reachable($contact['url'])) {
  95. logger("Skipping probably dead contact ".$contact['url']);
  96. // set the last-update so we don't keep polling
  97. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  98. return;
  99. }
  100. if (!Contact::updateFromProbe($contact["id"])) {
  101. Contact::markForArchival($contact);
  102. logger('Contact is marked dead');
  103. // set the last-update so we don't keep polling
  104. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  105. return;
  106. } else {
  107. Contact::unmarkForArchival($contact);
  108. }
  109. }
  110. if ($importer_uid == 0) {
  111. logger('Ignore public contacts');
  112. // set the last-update so we don't keep polling
  113. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  114. return;
  115. }
  116. $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
  117. intval($importer_uid)
  118. );
  119. if (!DBM::is_result($r)) {
  120. logger('No self contact for user '.$importer_uid);
  121. // set the last-update so we don't keep polling
  122. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  123. return;
  124. }
  125. $importer = $r[0];
  126. $url = '';
  127. logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
  128. if ($contact['network'] === NETWORK_DFRN) {
  129. $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
  130. if (intval($contact['duplex']) && $contact['dfrn-id']) {
  131. $idtosend = '0:' . $orig_id;
  132. }
  133. if (intval($contact['duplex']) && $contact['issued-id']) {
  134. $idtosend = '1:' . $orig_id;
  135. }
  136. // they have permission to write to us. We already filtered this in the contact query.
  137. $perm = 'rw';
  138. // But this may be our first communication, so set the writable flag if it isn't set already.
  139. if (!intval($contact['writable'])) {
  140. $fields = ['writable' => true];
  141. dba::update('contact', $fields, ['id' => $contact['id']]);
  142. }
  143. $url = $contact['poll'] . '?dfrn_id=' . $idtosend
  144. . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
  145. . '&type=data&last_update=' . $last_update
  146. . '&perm=' . $perm ;
  147. $ret = Network::curl($url);
  148. if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
  149. // set the last-update so we don't keep polling
  150. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  151. Contact::markForArchival($contact);
  152. return;
  153. }
  154. $handshake_xml = $ret['body'];
  155. $html_code = $a->get_curl_code();
  156. logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
  157. if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
  158. logger("$url appears to be dead - marking for death ");
  159. // dead connection - might be a transient event, or this might
  160. // mean the software was uninstalled or the domain expired.
  161. // Will keep trying for one month.
  162. Contact::markForArchival($contact);
  163. // set the last-update so we don't keep polling
  164. $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
  165. self::updateContact($contact, $fields);
  166. return;
  167. }
  168. if (!strstr($handshake_xml, '<')) {
  169. logger('response from ' . $url . ' did not contain XML.');
  170. Contact::markForArchival($contact);
  171. $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
  172. self::updateContact($contact, $fields);
  173. return;
  174. }
  175. $res = XML::parseString($handshake_xml);
  176. if (intval($res->status) == 1) {
  177. logger("$url replied status 1 - marking for death ");
  178. // we may not be friends anymore. Will keep trying for one month.
  179. // set the last-update so we don't keep polling
  180. $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
  181. self::updateContact($contact, $fields);
  182. Contact::markForArchival($contact);
  183. } elseif ($contact['term-date'] > NULL_DATE) {
  184. logger("$url back from the dead - removing mark for death");
  185. Contact::unmarkForArchival($contact);
  186. }
  187. if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
  188. // set the last-update so we don't keep polling
  189. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  190. return;
  191. }
  192. if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
  193. $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
  194. dba::update('contact', $fields, ['id' => $contact['id']]);
  195. }
  196. $postvars = [];
  197. $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
  198. $challenge = hex2bin((string) $res->challenge);
  199. $final_dfrn_id = '';
  200. if ($contact['duplex'] && strlen($contact['prvkey'])) {
  201. openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
  202. openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
  203. } else {
  204. openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
  205. openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
  206. }
  207. $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
  208. if (strpos($final_dfrn_id, ':') == 1) {
  209. $final_dfrn_id = substr($final_dfrn_id, 2);
  210. }
  211. if ($final_dfrn_id != $orig_id) {
  212. // did not decode properly - cannot trust this site
  213. logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
  214. // set the last-update so we don't keep polling
  215. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  216. Contact::markForArchival($contact);
  217. return;
  218. }
  219. $postvars['dfrn_id'] = $idtosend;
  220. $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
  221. $postvars['perm'] = 'rw';
  222. $xml = Network::post($contact['poll'], $postvars);
  223. } elseif (($contact['network'] === NETWORK_OSTATUS)
  224. || ($contact['network'] === NETWORK_DIASPORA)
  225. || ($contact['network'] === NETWORK_FEED)) {
  226. // Upgrading DB fields from an older Friendica version
  227. // Will only do this once per notify-enabled OStatus contact
  228. // or if relationship changes
  229. $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
  230. // Contacts from OStatus are always writable
  231. if ($contact['network'] === NETWORK_OSTATUS) {
  232. $stat_writeable = 1;
  233. }
  234. if ($stat_writeable != $contact['writable']) {
  235. $fields = ['writable' => $stat_writeable];
  236. dba::update('contact', $fields, ['id' => $contact['id']]);
  237. }
  238. // Are we allowed to import from this person?
  239. if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
  240. // set the last-update so we don't keep polling
  241. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  242. return;
  243. }
  244. $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
  245. $ret = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
  246. unlink($cookiejar);
  247. if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
  248. // set the last-update so we don't keep polling
  249. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  250. Contact::markForArchival($contact);
  251. return;
  252. }
  253. $xml = $ret['body'];
  254. } elseif ($contact['network'] === NETWORK_MAIL) {
  255. logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
  256. $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
  257. if ($mail_disabled) {
  258. // set the last-update so we don't keep polling
  259. dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  260. Contact::markForArchival($contact);
  261. return;
  262. }
  263. logger("Mail: Enabled", LOGGER_DEBUG);
  264. $mbox = null;
  265. $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
  266. $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
  267. $mailconf = dba::selectFirst('mailacct', [], $condition);
  268. if (DBM::is_result($user) && DBM::is_result($mailconf)) {
  269. $mailbox = Email::constructMailboxName($mailconf);
  270. $password = '';
  271. openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
  272. $mbox = Email::connect($mailbox, $mailconf['user'], $password);
  273. unset($password);
  274. logger("Mail: Connect to " . $mailconf['user']);
  275. if ($mbox) {
  276. $fields = ['last_check' => DateTimeFormat::utcNow()];
  277. dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
  278. logger("Mail: Connected to " . $mailconf['user']);
  279. } else {
  280. logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
  281. }
  282. }
  283. if ($mbox) {
  284. $msgs = Email::poll($mbox, $contact['addr']);
  285. if (count($msgs)) {
  286. logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
  287. $metas = Email::messageMeta($mbox, implode(',', $msgs));
  288. if (count($metas) != count($msgs)) {
  289. logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
  290. } else {
  291. $msgs = array_combine($msgs, $metas);
  292. foreach ($msgs as $msg_uid => $meta) {
  293. logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
  294. $datarray = [];
  295. $datarray['verb'] = ACTIVITY_POST;
  296. $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
  297. // $meta = Email::messageMeta($mbox, $msg_uid);
  298. $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
  299. // Have we seen it before?
  300. $fields = ['deleted', 'id'];
  301. $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
  302. $item = dba::selectFirst('item', $fields, $condition);
  303. if (DBM::is_result($item)) {
  304. logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
  305. // Only delete when mails aren't automatically moved or deleted
  306. if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
  307. if ($meta->deleted && ! $item['deleted']) {
  308. $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
  309. Item::update($fields, ['id' => $item['id']]);
  310. }
  311. switch ($mailconf['action']) {
  312. case 0:
  313. logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
  314. break;
  315. case 1:
  316. logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
  317. imap_delete($mbox, $msg_uid, FT_UID);
  318. break;
  319. case 2:
  320. logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
  321. imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
  322. break;
  323. case 3:
  324. logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
  325. imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
  326. if ($mailconf['movetofolder'] != "") {
  327. imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
  328. }
  329. break;
  330. }
  331. continue;
  332. }
  333. // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
  334. $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
  335. if (!trim($raw_refs)) {
  336. $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
  337. }
  338. $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
  339. if ($raw_refs) {
  340. $refs_arr = explode(' ', $raw_refs);
  341. if (count($refs_arr)) {
  342. for ($x = 0; $x < count($refs_arr); $x ++) {
  343. $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''],dbesc($refs_arr[$x]))) . "'";
  344. }
  345. }
  346. $qstr = implode(',', $refs_arr);
  347. $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
  348. intval($importer_uid)
  349. );
  350. if (DBM::is_result($r)) {
  351. $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
  352. }
  353. }
  354. // Decoding the header
  355. $subject = imap_mime_header_decode($meta->subject);
  356. $datarray['title'] = "";
  357. foreach ($subject as $subpart) {
  358. if ($subpart->charset != "default") {
  359. $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
  360. } else {
  361. $datarray['title'] .= $subpart->text;
  362. }
  363. }
  364. $datarray['title'] = notags(trim($datarray['title']));
  365. //$datarray['title'] = notags(trim($meta->subject));
  366. $datarray['created'] = DateTimeFormat::utc($meta->date);
  367. // Is it a reply?
  368. $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
  369. (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
  370. ($raw_refs != ""));
  371. // Remove Reply-signs in the subject
  372. $datarray['title'] = self::RemoveReply($datarray['title']);
  373. // If it seems to be a reply but a header couldn't be found take the last message with matching subject
  374. if (empty($datarray['parent-uri']) && $reply) {
  375. $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
  376. dbesc(protect_sprintf($datarray['title'])),
  377. intval($importer_uid),
  378. dbesc(NETWORK_MAIL));
  379. if (DBM::is_result($r)) {
  380. $datarray['parent-uri'] = $r[0]['parent-uri'];
  381. }
  382. }
  383. if (empty($datarray['parent-uri'])) {
  384. $datarray['parent-uri'] = $datarray['uri'];
  385. }
  386. $r = Email::getMessage($mbox, $msg_uid, $reply);
  387. if (!$r) {
  388. logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
  389. continue;
  390. }
  391. $datarray['body'] = escape_tags($r['body']);
  392. $datarray['body'] = BBCode::limitBodySize($datarray['body']);
  393. logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
  394. /// @TODO Adding a gravatar for the original author would be cool
  395. $from = imap_mime_header_decode($meta->from);
  396. $fromdecoded = "";
  397. foreach ($from as $frompart) {
  398. if ($frompart->charset != "default") {
  399. $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
  400. } else {
  401. $fromdecoded .= $frompart->text;
  402. }
  403. }
  404. $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
  405. $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
  406. if (isset($fromarr[0]->personal)) {
  407. $fromname = $fromarr[0]->personal;
  408. } else {
  409. $fromname = $frommail;
  410. }
  411. $datarray['author-name'] = $fromname;
  412. $datarray['author-link'] = "mailto:".$frommail;
  413. $datarray['author-avatar'] = $contact['photo'];
  414. $datarray['owner-name'] = $contact['name'];
  415. $datarray['owner-link'] = "mailto:".$contact['addr'];
  416. $datarray['owner-avatar'] = $contact['photo'];
  417. $datarray['uid'] = $importer_uid;
  418. $datarray['contact-id'] = $contact['id'];
  419. if ($datarray['parent-uri'] === $datarray['uri']) {
  420. $datarray['private'] = 1;
  421. }
  422. if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
  423. $datarray['private'] = 1;
  424. $datarray['allow_cid'] = '<' . $contact['id'] . '>';
  425. }
  426. $stored_item = Item::insert($datarray);
  427. switch ($mailconf['action']) {
  428. case 0:
  429. logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
  430. break;
  431. case 1:
  432. logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
  433. imap_delete($mbox, $msg_uid, FT_UID);
  434. break;
  435. case 2:
  436. logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
  437. imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
  438. break;
  439. case 3:
  440. logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
  441. imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
  442. if ($mailconf['movetofolder'] != "") {
  443. imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
  444. }
  445. break;
  446. }
  447. }
  448. }
  449. } else {
  450. logger("Mail: no mails for ".$mailconf['user']);
  451. }
  452. logger("Mail: closing connection for ".$mailconf['user']);
  453. imap_close($mbox);
  454. }
  455. }
  456. if ($xml) {
  457. logger('received xml : ' . $xml, LOGGER_DATA);
  458. if (!strstr($xml, '<')) {
  459. logger('post_handshake: response from ' . $url . ' did not contain XML.');
  460. $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
  461. self::updateContact($contact, $fields);
  462. Contact::markForArchival($contact);
  463. return;
  464. }
  465. logger("Consume feed of contact ".$contact['id']);
  466. consume_feed($xml, $importer, $contact, $hub, 1, 1);
  467. // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
  468. consume_feed($xml, $importer, $contact, $hub, 1, 2);
  469. $hubmode = 'subscribe';
  470. if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
  471. $hubmode = 'unsubscribe';
  472. }
  473. if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
  474. $hub_update = true;
  475. }
  476. if ($force) {
  477. $hub_update = true;
  478. }
  479. logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
  480. if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
  481. logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
  482. $hubs = explode(',', $hub);
  483. if (count($hubs)) {
  484. foreach ($hubs as $h) {
  485. $h = trim($h);
  486. if (!strlen($h)) {
  487. continue;
  488. }
  489. subscribe_to_hub($h, $importer, $contact, $hubmode);
  490. }
  491. }
  492. }
  493. $updated = DateTimeFormat::utcNow();
  494. self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
  495. dba::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
  496. Contact::unmarkForArchival($contact);
  497. } elseif (in_array($contact["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED])) {
  498. $updated = DateTimeFormat::utcNow();
  499. self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
  500. dba::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
  501. Contact::markForArchival($contact);
  502. } else {
  503. $updated = DateTimeFormat::utcNow();
  504. dba::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
  505. }
  506. return;
  507. }
  508. private static function RemoveReply($subject) {
  509. while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
  510. $subject = trim(substr($subject, 4));
  511. }
  512. return $subject;
  513. }
  514. /**
  515. * @brief Updates a personal contact entry and the public contact entry
  516. *
  517. * @param array $contact The personal contact entry
  518. * @param array $fields The fields that are updated
  519. */
  520. private static function updateContact($contact, $fields) {
  521. dba::update('contact', $fields, ['id' => $contact['id']]);
  522. dba::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
  523. }
  524. }