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\XML;
23 require_once 'include/dba.php';
27 public static function execute($contact_id = 0, $command = '')
29 $a = BaseObject::getApp();
31 require_once 'include/items.php';
41 if ($command == "force") {
46 Logger::log('no contact');
50 $d = DateTimeFormat::utcNow();
52 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
53 if (!DBA::isResult($contact)) {
54 Logger::log('Contact not found or cannot be used.');
58 $importer_uid = $contact['uid'];
60 // Possibly switch the remote contact to AP
61 if ($contact['network'] === Protocol::OSTATUS) {
62 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
63 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
66 // We currently don't do anything with AP here
67 if ($contact['network'] === Protocol::ACTIVITYPUB) {
71 // load current friends if possible.
72 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
73 $r = q("SELECT count(*) AS total FROM glink
74 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
75 intval($contact['id'])
77 if (DBA::isResult($r)) {
78 if (!$r[0]['total']) {
79 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
84 // Diaspora users, archived users and followers are only checked if they still exist.
85 if ($contact['archive'] || ($contact["network"] == Protocol::DIASPORA) || ($contact["rel"] == Contact::FOLLOWER)) {
86 $last_updated = PortableContact::lastUpdated($contact["url"], true);
87 $updated = DateTimeFormat::utcNow();
90 Logger::log('Contact '.$contact['id'].' had last update on '.$last_updated, Logger::DEBUG);
92 // The last public item can be older than the last item we got
93 if ($last_updated < $contact['last-item']) {
94 $last_updated = $contact['last-item'];
97 $fields = ['last-item' => DateTimeFormat::utc($last_updated), 'last-update' => $updated, 'success_update' => $updated];
98 self::updateContact($contact, $fields);
99 Contact::unmarkForArchival($contact);
101 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
102 Contact::markForArchival($contact);
103 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
111 $t = $contact['last-update'];
113 if ($contact['subhub']) {
114 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
115 $contact['priority'] = intval($poll_interval);
118 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
125 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
126 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
127 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
130 // Update the contact entry
131 if (($contact['network'] === Protocol::OSTATUS) || ($contact['network'] === Protocol::DIASPORA) || ($contact['network'] === Protocol::DFRN)) {
132 if (!PortableContact::reachable($contact['url'])) {
133 Logger::log("Skipping probably dead contact ".$contact['url']);
135 // set the last-update so we don't keep polling
136 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
140 if (!Contact::updateFromProbe($contact["id"])) {
141 Contact::markForArchival($contact);
142 Logger::log('Contact is marked dead');
144 // set the last-update so we don't keep polling
145 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
148 Contact::unmarkForArchival($contact);
152 if (!in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
156 if ($importer_uid == 0) {
157 Logger::log('Ignore public contacts');
159 // set the last-update so we don't keep polling
160 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
164 $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",
165 intval($importer_uid)
168 if (!DBA::isResult($r)) {
169 Logger::log('No self contact for user '.$importer_uid);
171 // set the last-update so we don't keep polling
172 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
179 Logger::log("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
181 if ($contact['network'] === Protocol::DFRN) {
182 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
183 if (intval($contact['duplex']) && $contact['dfrn-id']) {
184 $idtosend = '0:' . $orig_id;
186 if (intval($contact['duplex']) && $contact['issued-id']) {
187 $idtosend = '1:' . $orig_id;
190 // they have permission to write to us. We already filtered this in the contact query.
193 // But this may be our first communication, so set the writable flag if it isn't set already.
195 if (!intval($contact['writable'])) {
196 $fields = ['writable' => true];
197 DBA::update('contact', $fields, ['id' => $contact['id']]);
200 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
201 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
202 . '&type=data&last_update=' . $last_update
205 $curlResult = Network::curl($url);
207 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
208 // set the last-update so we don't keep polling
209 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
210 Contact::markForArchival($contact);
214 $handshake_xml = $curlResult->getBody();
215 $html_code = $curlResult->getReturnCode();
217 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
219 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
220 Logger::log("$url appears to be dead - marking for death ");
222 // dead connection - might be a transient event, or this might
223 // mean the software was uninstalled or the domain expired.
224 // Will keep trying for one month.
226 Contact::markForArchival($contact);
228 // set the last-update so we don't keep polling
229 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
230 self::updateContact($contact, $fields);
234 if (!strstr($handshake_xml, '<')) {
235 Logger::log('response from ' . $url . ' did not contain XML.');
237 Contact::markForArchival($contact);
239 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
240 self::updateContact($contact, $fields);
245 $res = XML::parseString($handshake_xml);
247 if (intval($res->status) == 1) {
248 Logger::log("$url replied status 1 - marking for death ");
250 // we may not be friends anymore. Will keep trying for one month.
251 // set the last-update so we don't keep polling
252 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
253 self::updateContact($contact, $fields);
255 Contact::markForArchival($contact);
256 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
257 Logger::log("$url back from the dead - removing mark for death");
258 Contact::unmarkForArchival($contact);
261 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
262 // set the last-update so we don't keep polling
263 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
267 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
268 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
269 DBA::update('contact', $fields, ['id' => $contact['id']]);
274 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
275 $challenge = hex2bin((string) $res->challenge);
279 if ($contact['duplex'] && strlen($contact['prvkey'])) {
280 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
281 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
283 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
284 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
287 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
289 if (strpos($final_dfrn_id, ':') == 1) {
290 $final_dfrn_id = substr($final_dfrn_id, 2);
293 if ($final_dfrn_id != $orig_id) {
294 // did not decode properly - cannot trust this site
295 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
297 // set the last-update so we don't keep polling
298 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
299 Contact::markForArchival($contact);
303 $postvars['dfrn_id'] = $idtosend;
304 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
305 $postvars['perm'] = 'rw';
307 $xml = Network::post($contact['poll'], $postvars)->getBody();
309 } elseif (($contact['network'] === Protocol::OSTATUS)
310 || ($contact['network'] === Protocol::DIASPORA)
311 || ($contact['network'] === Protocol::FEED)) {
313 // Upgrading DB fields from an older Friendica version
314 // Will only do this once per notify-enabled OStatus contact
315 // or if relationship changes
317 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
319 // Contacts from OStatus are always writable
320 if ($contact['network'] === Protocol::OSTATUS) {
324 if ($stat_writeable != $contact['writable']) {
325 $fields = ['writable' => $stat_writeable];
326 DBA::update('contact', $fields, ['id' => $contact['id']]);
329 // Are we allowed to import from this person?
331 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
332 // set the last-update so we don't keep polling
333 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
337 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
338 $curlResult = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
341 if ($curlResult->isTimeout()) {
342 // set the last-update so we don't keep polling
343 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
344 Contact::markForArchival($contact);
348 $xml = $curlResult->getBody();
350 } elseif ($contact['network'] === Protocol::MAIL) {
351 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
353 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
354 if ($mail_disabled) {
355 // set the last-update so we don't keep polling
356 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
357 Contact::markForArchival($contact);
361 Logger::log("Mail: Enabled", Logger::DEBUG);
364 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
366 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
367 $mailconf = DBA::selectFirst('mailacct', [], $condition);
368 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
369 $mailbox = Email::constructMailboxName($mailconf);
371 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
372 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
374 Logger::log("Mail: Connect to " . $mailconf['user']);
376 $fields = ['last_check' => DateTimeFormat::utcNow()];
377 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
378 Logger::log("Mail: Connected to " . $mailconf['user']);
380 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
385 $msgs = Email::poll($mbox, $contact['addr']);
388 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
390 $metas = Email::messageMeta($mbox, implode(',', $msgs));
392 if (count($metas) != count($msgs)) {
393 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
395 $msgs = array_combine($msgs, $metas);
397 foreach ($msgs as $msg_uid => $meta) {
398 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
401 $datarray['verb'] = ACTIVITY_POST;
402 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
403 $datarray['network'] = Protocol::MAIL;
404 // $meta = Email::messageMeta($mbox, $msg_uid);
406 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
408 // Have we seen it before?
409 $fields = ['deleted', 'id'];
410 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
411 $item = Item::selectFirst($fields, $condition);
412 if (DBA::isResult($item)) {
413 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
415 // Only delete when mails aren't automatically moved or deleted
416 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
417 if ($meta->deleted && ! $item['deleted']) {
418 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
419 Item::update($fields, ['id' => $item['id']]);
422 switch ($mailconf['action']) {
424 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
427 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
428 imap_delete($mbox, $msg_uid, FT_UID);
431 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
432 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
435 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
436 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
437 if ($mailconf['movetofolder'] != "") {
438 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
446 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
447 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
448 if (!trim($raw_refs)) {
449 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
451 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
454 $refs_arr = explode(' ', $raw_refs);
455 if (count($refs_arr)) {
456 for ($x = 0; $x < count($refs_arr); $x ++) {
457 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
460 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
461 $parent = Item::selectFirst(['parent-uri'], $condition);
462 if (DBA::isResult($parent)) {
463 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
467 // Decoding the header
468 $subject = imap_mime_header_decode($meta->subject);
469 $datarray['title'] = "";
470 foreach ($subject as $subpart) {
471 if ($subpart->charset != "default") {
472 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
474 $datarray['title'] .= $subpart->text;
477 $datarray['title'] = notags(trim($datarray['title']));
479 //$datarray['title'] = notags(trim($meta->subject));
480 $datarray['created'] = DateTimeFormat::utc($meta->date);
483 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
484 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
487 // Remove Reply-signs in the subject
488 $datarray['title'] = self::RemoveReply($datarray['title']);
490 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
491 if (empty($datarray['parent-uri']) && $reply) {
492 $condition = ['title' => $datarray['title'], 'uid' => importer_uid, 'network' => Protocol::MAIL];
493 $params = ['order' => ['created' => true]];
494 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
495 if (DBA::isResult($parent)) {
496 $datarray['parent-uri'] = $parent['parent-uri'];
500 if (empty($datarray['parent-uri'])) {
501 $datarray['parent-uri'] = $datarray['uri'];
504 $r = Email::getMessage($mbox, $msg_uid, $reply);
506 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
509 $datarray['body'] = escape_tags($r['body']);
510 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
512 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
514 /// @TODO Adding a gravatar for the original author would be cool
516 $from = imap_mime_header_decode($meta->from);
518 foreach ($from as $frompart) {
519 if ($frompart->charset != "default") {
520 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
522 $fromdecoded .= $frompart->text;
526 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->getHostName());
528 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
530 if (isset($fromarr[0]->personal)) {
531 $fromname = $fromarr[0]->personal;
533 $fromname = $frommail;
536 $datarray['author-name'] = $fromname;
537 $datarray['author-link'] = "mailto:".$frommail;
538 $datarray['author-avatar'] = $contact['photo'];
540 $datarray['owner-name'] = $contact['name'];
541 $datarray['owner-link'] = "mailto:".$contact['addr'];
542 $datarray['owner-avatar'] = $contact['photo'];
544 $datarray['uid'] = $importer_uid;
545 $datarray['contact-id'] = $contact['id'];
546 if ($datarray['parent-uri'] === $datarray['uri']) {
547 $datarray['private'] = 1;
549 if (($contact['network'] === Protocol::MAIL) && !PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
550 $datarray['private'] = 1;
551 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
554 $stored_item = Item::insert($datarray);
556 switch ($mailconf['action']) {
558 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
561 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
562 imap_delete($mbox, $msg_uid, FT_UID);
565 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
566 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
569 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
570 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
571 if ($mailconf['movetofolder'] != "") {
572 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
579 Logger::log("Mail: no mails for ".$mailconf['user']);
582 Logger::log("Mail: closing connection for ".$mailconf['user']);
588 Logger::log('received xml : ' . $xml, Logger::DATA);
589 if (!strstr($xml, '<')) {
590 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
592 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
593 self::updateContact($contact, $fields);
594 Contact::markForArchival($contact);
599 Logger::log("Consume feed of contact ".$contact['id']);
601 consume_feed($xml, $importer, $contact, $hub);
603 // do it a second time for DFRN so that any children find their parents.
604 if ($contact['network'] === Protocol::DFRN) {
605 consume_feed($xml, $importer, $contact, $hub);
608 $hubmode = 'subscribe';
609 if ($contact['network'] === Protocol::DFRN || $contact['blocked']) {
610 $hubmode = 'unsubscribe';
613 if (($contact['network'] === Protocol::OSTATUS || $contact['network'] == Protocol::FEED) && (! $contact['hub-verify'])) {
621 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
623 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $contact['network'] == Protocol::FEED)) {
624 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
625 $hubs = explode(',', $hub);
628 foreach ($hubs as $h) {
635 subscribe_to_hub($h, $importer, $contact, $hubmode);
640 $updated = DateTimeFormat::utcNow();
642 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
643 DBA::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
644 Contact::unmarkForArchival($contact);
645 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
646 $updated = DateTimeFormat::utcNow();
648 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
649 DBA::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
650 Contact::markForArchival($contact);
652 $updated = DateTimeFormat::utcNow();
653 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
659 private static function RemoveReply($subject)
661 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
662 $subject = trim(substr($subject, 4));
669 * @brief Updates a personal contact entry and the public contact entry
671 * @param array $contact The personal contact entry
672 * @param array $fields The fields that are updated
674 private static function updateContact(array $contact, array $fields)
676 DBA::update('contact', $fields, ['id' => $contact['id']]);
677 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);