3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Protocol\ActivityPub;
17 use Friendica\Protocol\Email;
18 use Friendica\Protocol\PortableContact;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\Strings;
22 use Friendica\Util\XML;
26 public static function execute($contact_id = 0, $command = '')
28 $a = BaseObject::getApp();
38 if ($command == "force") {
43 Logger::log('no contact');
47 $d = DateTimeFormat::utcNow();
49 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
50 if (!DBA::isResult($contact)) {
51 Logger::log('Contact not found or cannot be used.');
55 $importer_uid = $contact['uid'];
57 // Possibly switch the remote contact to AP
58 if ($contact['network'] === Protocol::OSTATUS) {
59 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
60 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
63 // We currently don't do anything with AP here
64 if ($contact['network'] === Protocol::ACTIVITYPUB) {
68 // load current friends if possible.
69 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
70 $r = q("SELECT count(*) AS total FROM glink
71 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
72 intval($contact['id'])
74 if (DBA::isResult($r)) {
75 if (!$r[0]['total']) {
76 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
81 // Diaspora users, archived users and followers are only checked if they still exist.
82 if ($contact['archive'] || ($contact["network"] == Protocol::DIASPORA) || ($contact["rel"] == Contact::FOLLOWER)) {
83 $last_updated = PortableContact::lastUpdated($contact["url"], true);
84 $updated = DateTimeFormat::utcNow();
87 Logger::log('Contact '.$contact['id'].' had last update on '.$last_updated, Logger::DEBUG);
89 // The last public item can be older than the last item we got
90 if ($last_updated < $contact['last-item']) {
91 $last_updated = $contact['last-item'];
94 $fields = ['last-item' => DateTimeFormat::utc($last_updated), 'last-update' => $updated, 'success_update' => $updated];
95 self::updateContact($contact, $fields);
96 Contact::unmarkForArchival($contact);
98 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
99 Contact::markForArchival($contact);
100 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
108 $t = $contact['last-update'];
110 if ($contact['subhub']) {
111 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
112 $contact['priority'] = intval($poll_interval);
115 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
122 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
123 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
124 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
127 // Update the contact entry
128 if (($contact['network'] === Protocol::OSTATUS) || ($contact['network'] === Protocol::DIASPORA) || ($contact['network'] === Protocol::DFRN)) {
129 if (!PortableContact::reachable($contact['url'])) {
130 Logger::log("Skipping probably dead contact ".$contact['url']);
132 // set the last-update so we don't keep polling
133 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
137 if (!Contact::updateFromProbe($contact["id"])) {
138 Contact::markForArchival($contact);
139 Logger::log('Contact is marked dead');
141 // set the last-update so we don't keep polling
142 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
145 Contact::unmarkForArchival($contact);
149 if (!in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
153 if ($importer_uid == 0) {
154 Logger::log('Ignore public contacts');
156 // set the last-update so we don't keep polling
157 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
161 $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",
162 intval($importer_uid)
165 if (!DBA::isResult($r)) {
166 Logger::log('No self contact for user '.$importer_uid);
168 // set the last-update so we don't keep polling
169 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
176 Logger::log("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
178 if ($contact['network'] === Protocol::DFRN) {
179 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
180 if (intval($contact['duplex']) && $contact['dfrn-id']) {
181 $idtosend = '0:' . $orig_id;
183 if (intval($contact['duplex']) && $contact['issued-id']) {
184 $idtosend = '1:' . $orig_id;
187 // they have permission to write to us. We already filtered this in the contact query.
190 // But this may be our first communication, so set the writable flag if it isn't set already.
192 if (!intval($contact['writable'])) {
193 $fields = ['writable' => true];
194 DBA::update('contact', $fields, ['id' => $contact['id']]);
197 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
198 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
199 . '&type=data&last_update=' . $last_update
202 $curlResult = Network::curl($url);
204 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
205 // set the last-update so we don't keep polling
206 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
207 Contact::markForArchival($contact);
211 $handshake_xml = $curlResult->getBody();
212 $html_code = $curlResult->getReturnCode();
214 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
216 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
217 Logger::log("$url appears to be dead - marking for death ");
219 // dead connection - might be a transient event, or this might
220 // mean the software was uninstalled or the domain expired.
221 // Will keep trying for one month.
223 Contact::markForArchival($contact);
225 // set the last-update so we don't keep polling
226 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
227 self::updateContact($contact, $fields);
231 if (!strstr($handshake_xml, '<')) {
232 Logger::log('response from ' . $url . ' did not contain XML.');
234 Contact::markForArchival($contact);
236 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
237 self::updateContact($contact, $fields);
242 $res = XML::parseString($handshake_xml);
244 if (intval($res->status) == 1) {
245 Logger::log("$url replied status 1 - marking for death ");
247 // we may not be friends anymore. Will keep trying for one month.
248 // set the last-update so we don't keep polling
249 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
250 self::updateContact($contact, $fields);
252 Contact::markForArchival($contact);
253 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
254 Logger::log("$url back from the dead - removing mark for death");
255 Contact::unmarkForArchival($contact);
258 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
259 // set the last-update so we don't keep polling
260 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
264 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
265 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
266 DBA::update('contact', $fields, ['id' => $contact['id']]);
271 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
272 $challenge = hex2bin((string) $res->challenge);
276 if ($contact['duplex'] && strlen($contact['prvkey'])) {
277 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
278 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
280 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
281 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
284 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
286 if (strpos($final_dfrn_id, ':') == 1) {
287 $final_dfrn_id = substr($final_dfrn_id, 2);
290 if ($final_dfrn_id != $orig_id) {
291 // did not decode properly - cannot trust this site
292 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
294 // set the last-update so we don't keep polling
295 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
296 Contact::markForArchival($contact);
300 $postvars['dfrn_id'] = $idtosend;
301 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
302 $postvars['perm'] = 'rw';
304 $xml = Network::post($contact['poll'], $postvars)->getBody();
306 } elseif (($contact['network'] === Protocol::OSTATUS)
307 || ($contact['network'] === Protocol::DIASPORA)
308 || ($contact['network'] === Protocol::FEED)) {
310 // Upgrading DB fields from an older Friendica version
311 // Will only do this once per notify-enabled OStatus contact
312 // or if relationship changes
314 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
316 // Contacts from OStatus are always writable
317 if ($contact['network'] === Protocol::OSTATUS) {
321 if ($stat_writeable != $contact['writable']) {
322 $fields = ['writable' => $stat_writeable];
323 DBA::update('contact', $fields, ['id' => $contact['id']]);
326 // Are we allowed to import from this person?
328 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
329 // set the last-update so we don't keep polling
330 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
334 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
335 $curlResult = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
338 if ($curlResult->isTimeout()) {
339 // set the last-update so we don't keep polling
340 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
341 Contact::markForArchival($contact);
345 $xml = $curlResult->getBody();
347 } elseif ($contact['network'] === Protocol::MAIL) {
348 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
350 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
351 if ($mail_disabled) {
352 // set the last-update so we don't keep polling
353 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
354 Contact::markForArchival($contact);
358 Logger::log("Mail: Enabled", Logger::DEBUG);
361 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
363 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
364 $mailconf = DBA::selectFirst('mailacct', [], $condition);
365 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
366 $mailbox = Email::constructMailboxName($mailconf);
368 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
369 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
371 Logger::log("Mail: Connect to " . $mailconf['user']);
373 $fields = ['last_check' => DateTimeFormat::utcNow()];
374 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
375 Logger::log("Mail: Connected to " . $mailconf['user']);
377 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
382 $msgs = Email::poll($mbox, $contact['addr']);
385 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
387 $metas = Email::messageMeta($mbox, implode(',', $msgs));
389 if (count($metas) != count($msgs)) {
390 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
392 $msgs = array_combine($msgs, $metas);
394 foreach ($msgs as $msg_uid => $meta) {
395 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
398 $datarray['verb'] = ACTIVITY_POST;
399 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
400 $datarray['network'] = Protocol::MAIL;
401 // $meta = Email::messageMeta($mbox, $msg_uid);
403 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
405 // Have we seen it before?
406 $fields = ['deleted', 'id'];
407 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
408 $item = Item::selectFirst($fields, $condition);
409 if (DBA::isResult($item)) {
410 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
412 // Only delete when mails aren't automatically moved or deleted
413 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
414 if ($meta->deleted && ! $item['deleted']) {
415 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
416 Item::update($fields, ['id' => $item['id']]);
419 switch ($mailconf['action']) {
421 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
424 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
425 imap_delete($mbox, $msg_uid, FT_UID);
428 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
429 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
432 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
433 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
434 if ($mailconf['movetofolder'] != "") {
435 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
443 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
444 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
445 if (!trim($raw_refs)) {
446 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
448 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
451 $refs_arr = explode(' ', $raw_refs);
452 if (count($refs_arr)) {
453 for ($x = 0; $x < count($refs_arr); $x ++) {
454 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
457 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
458 $parent = Item::selectFirst(['parent-uri'], $condition);
459 if (DBA::isResult($parent)) {
460 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
464 // Decoding the header
465 $subject = imap_mime_header_decode($meta->subject);
466 $datarray['title'] = "";
467 foreach ($subject as $subpart) {
468 if ($subpart->charset != "default") {
469 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
471 $datarray['title'] .= $subpart->text;
474 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
476 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
477 $datarray['created'] = DateTimeFormat::utc($meta->date);
480 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
481 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
484 // Remove Reply-signs in the subject
485 $datarray['title'] = self::RemoveReply($datarray['title']);
487 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
488 if (empty($datarray['parent-uri']) && $reply) {
489 $condition = ['title' => $datarray['title'], 'uid' => importer_uid, 'network' => Protocol::MAIL];
490 $params = ['order' => ['created' => true]];
491 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
492 if (DBA::isResult($parent)) {
493 $datarray['parent-uri'] = $parent['parent-uri'];
497 if (empty($datarray['parent-uri'])) {
498 $datarray['parent-uri'] = $datarray['uri'];
501 $r = Email::getMessage($mbox, $msg_uid, $reply);
503 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
506 $datarray['body'] = Strings::escapeHtml($r['body']);
507 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
509 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
511 /// @TODO Adding a gravatar for the original author would be cool
513 $from = imap_mime_header_decode($meta->from);
515 foreach ($from as $frompart) {
516 if ($frompart->charset != "default") {
517 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
519 $fromdecoded .= $frompart->text;
523 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->getHostName());
525 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
527 if (isset($fromarr[0]->personal)) {
528 $fromname = $fromarr[0]->personal;
530 $fromname = $frommail;
533 $datarray['author-name'] = $fromname;
534 $datarray['author-link'] = "mailto:".$frommail;
535 $datarray['author-avatar'] = $contact['photo'];
537 $datarray['owner-name'] = $contact['name'];
538 $datarray['owner-link'] = "mailto:".$contact['addr'];
539 $datarray['owner-avatar'] = $contact['photo'];
541 $datarray['uid'] = $importer_uid;
542 $datarray['contact-id'] = $contact['id'];
543 if ($datarray['parent-uri'] === $datarray['uri']) {
544 $datarray['private'] = 1;
546 if (($contact['network'] === Protocol::MAIL) && !PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
547 $datarray['private'] = 1;
548 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
551 $stored_item = Item::insert($datarray);
553 switch ($mailconf['action']) {
555 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
558 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
559 imap_delete($mbox, $msg_uid, FT_UID);
562 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
563 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
566 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
567 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
568 if ($mailconf['movetofolder'] != "") {
569 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
576 Logger::log("Mail: no mails for ".$mailconf['user']);
579 Logger::log("Mail: closing connection for ".$mailconf['user']);
585 Logger::log('received xml : ' . $xml, Logger::DATA);
586 if (!strstr($xml, '<')) {
587 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
589 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
590 self::updateContact($contact, $fields);
591 Contact::markForArchival($contact);
596 Logger::log("Consume feed of contact ".$contact['id']);
598 consume_feed($xml, $importer, $contact, $hub);
600 // do it a second time for DFRN so that any children find their parents.
601 if ($contact['network'] === Protocol::DFRN) {
602 consume_feed($xml, $importer, $contact, $hub);
605 $hubmode = 'subscribe';
606 if ($contact['network'] === Protocol::DFRN || $contact['blocked']) {
607 $hubmode = 'unsubscribe';
610 if (($contact['network'] === Protocol::OSTATUS || $contact['network'] == Protocol::FEED) && (! $contact['hub-verify'])) {
618 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
620 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $contact['network'] == Protocol::FEED)) {
621 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
622 $hubs = explode(',', $hub);
625 foreach ($hubs as $h) {
632 subscribe_to_hub($h, $importer, $contact, $hubmode);
637 $updated = DateTimeFormat::utcNow();
639 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
640 DBA::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
641 Contact::unmarkForArchival($contact);
642 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
643 $updated = DateTimeFormat::utcNow();
645 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
646 DBA::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
647 Contact::markForArchival($contact);
649 $updated = DateTimeFormat::utcNow();
650 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
656 private static function RemoveReply($subject)
658 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
659 $subject = trim(substr($subject, 4));
666 * @brief Updates a personal contact entry and the public contact entry
668 * @param array $contact The personal contact entry
669 * @param array $fields The fields that are updated
671 private static function updateContact(array $contact, array $fields)
673 DBA::update('contact', $fields, ['id' => $contact['id']]);
674 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);