3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
7 use Friendica\Content\Text\BBCode;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Item;
13 use Friendica\Protocol\Email;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Network;
17 use Friendica\Util\XML;
20 require_once 'include/dba.php';
24 public static function execute($contact_id = 0, $command = '') {
27 require_once 'include/items.php';
37 if ($command == "force") {
46 $d = DateTimeFormat::utcNow();
48 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
49 if (!DBM::is_result($contact)) {
50 logger('Contact not found or cannot be used.');
54 $importer_uid = $contact['uid'];
56 // load current friends if possible.
57 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
58 $r = q("SELECT count(*) AS total FROM glink
59 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
60 intval($contact['id'])
62 if (DBM::is_result($r)) {
63 if (!$r[0]['total']) {
64 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
69 // Diaspora users, archived users and followers are only checked if they still exist.
70 if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
71 $last_updated = PortableContact::lastUpdated($contact["url"], true);
72 $updated = DateTimeFormat::utcNow();
74 logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
76 // The last public item can be older than the last item we got
77 if ($last_updated < $contact['last-item']) {
78 $last_updated = $contact['last-item'];
81 $fields = ['last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated];
82 self::updateContact($contact, $fields);
83 Contact::unmarkForArchival($contact);
85 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
86 Contact::markForArchival($contact);
87 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
94 $t = $contact['last-update'];
96 if ($contact['subhub']) {
97 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
98 $contact['priority'] = intval($poll_interval);
101 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
108 $last_update = (($contact['last-update'] <= NULL_DATE)
109 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
110 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
113 // Update the contact entry
114 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
115 if (!PortableContact::reachable($contact['url'])) {
116 logger("Skipping probably dead contact ".$contact['url']);
118 // set the last-update so we don't keep polling
119 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
123 if (!Contact::updateFromProbe($contact["id"])) {
124 Contact::markForArchival($contact);
125 logger('Contact is marked dead');
127 // set the last-update so we don't keep polling
128 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
131 Contact::unmarkForArchival($contact);
135 if ($importer_uid == 0) {
136 logger('Ignore public contacts');
138 // set the last-update so we don't keep polling
139 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
143 $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",
144 intval($importer_uid)
147 if (!DBM::is_result($r)) {
148 logger('No self contact for user '.$importer_uid);
150 // set the last-update so we don't keep polling
151 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
157 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
159 if ($contact['network'] === NETWORK_DFRN) {
160 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
161 if (intval($contact['duplex']) && $contact['dfrn-id']) {
162 $idtosend = '0:' . $orig_id;
164 if (intval($contact['duplex']) && $contact['issued-id']) {
165 $idtosend = '1:' . $orig_id;
168 // they have permission to write to us. We already filtered this in the contact query.
171 // But this may be our first communication, so set the writable flag if it isn't set already.
173 if (!intval($contact['writable'])) {
174 $fields = ['writable' => true];
175 dba::update('contact', $fields, ['id' => $contact['id']]);
178 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
179 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
180 . '&type=data&last_update=' . $last_update
183 $ret = Network::curl($url);
185 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
186 // set the last-update so we don't keep polling
187 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
188 Contact::markForArchival($contact);
192 $handshake_xml = $ret['body'];
194 $html_code = $a->get_curl_code();
196 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
199 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
200 logger("$url appears to be dead - marking for death ");
202 // dead connection - might be a transient event, or this might
203 // mean the software was uninstalled or the domain expired.
204 // Will keep trying for one month.
206 Contact::markForArchival($contact);
208 // set the last-update so we don't keep polling
209 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
210 self::updateContact($contact, $fields);
214 if (!strstr($handshake_xml, '<')) {
215 logger('response from ' . $url . ' did not contain XML.');
217 Contact::markForArchival($contact);
219 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
220 self::updateContact($contact, $fields);
225 $res = XML::parseString($handshake_xml);
227 if (intval($res->status) == 1) {
228 logger("$url replied status 1 - marking for death ");
230 // we may not be friends anymore. Will keep trying for one month.
231 // set the last-update so we don't keep polling
232 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
233 self::updateContact($contact, $fields);
235 Contact::markForArchival($contact);
236 } elseif ($contact['term-date'] > NULL_DATE) {
237 logger("$url back from the dead - removing mark for death");
238 Contact::unmarkForArchival($contact);
241 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
242 // set the last-update so we don't keep polling
243 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
247 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
248 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
249 dba::update('contact', $fields, ['id' => $contact['id']]);
254 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
255 $challenge = hex2bin((string) $res->challenge);
259 if ($contact['duplex'] && strlen($contact['prvkey'])) {
260 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
261 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
263 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
264 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
267 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
269 if (strpos($final_dfrn_id, ':') == 1) {
270 $final_dfrn_id = substr($final_dfrn_id, 2);
273 if ($final_dfrn_id != $orig_id) {
274 // did not decode properly - cannot trust this site
275 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
277 // set the last-update so we don't keep polling
278 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
279 Contact::markForArchival($contact);
283 $postvars['dfrn_id'] = $idtosend;
284 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
285 $postvars['perm'] = 'rw';
287 $xml = Network::post($contact['poll'], $postvars);
289 } elseif (($contact['network'] === NETWORK_OSTATUS)
290 || ($contact['network'] === NETWORK_DIASPORA)
291 || ($contact['network'] === NETWORK_FEED)) {
293 // Upgrading DB fields from an older Friendica version
294 // Will only do this once per notify-enabled OStatus contact
295 // or if relationship changes
297 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
299 // Contacts from OStatus are always writable
300 if ($contact['network'] === NETWORK_OSTATUS) {
304 if ($stat_writeable != $contact['writable']) {
305 $fields = ['writable' => $stat_writeable];
306 dba::update('contact', $fields, ['id' => $contact['id']]);
309 // Are we allowed to import from this person?
311 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
312 // set the last-update so we don't keep polling
313 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
317 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
318 $ret = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
321 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
322 // set the last-update so we don't keep polling
323 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
324 Contact::markForArchival($contact);
330 } elseif ($contact['network'] === NETWORK_MAIL) {
332 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
334 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
335 if ($mail_disabled) {
336 // set the last-update so we don't keep polling
337 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
338 Contact::markForArchival($contact);
342 logger("Mail: Enabled", LOGGER_DEBUG);
345 $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
347 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
348 $mailconf = dba::selectFirst('mailacct', [], $condition);
349 if (DBM::is_result($user) && DBM::is_result($mailconf)) {
350 $mailbox = Email::constructMailboxName($mailconf);
352 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
353 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
355 logger("Mail: Connect to " . $mailconf['user']);
357 $fields = ['last_check' => DateTimeFormat::utcNow()];
358 dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
359 logger("Mail: Connected to " . $mailconf['user']);
361 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
366 $msgs = Email::poll($mbox, $contact['addr']);
369 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
371 $metas = Email::messageMeta($mbox, implode(',', $msgs));
372 if (count($metas) != count($msgs)) {
373 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
375 $msgs = array_combine($msgs, $metas);
377 foreach ($msgs as $msg_uid => $meta) {
378 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
381 $datarray['verb'] = ACTIVITY_POST;
382 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
383 // $meta = Email::messageMeta($mbox, $msg_uid);
385 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
387 // Have we seen it before?
388 $fields = ['deleted', 'id'];
389 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
390 $item = dba::selectFirst('item', $fields, $condition);
391 if (DBM::is_result($item)) {
392 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
394 // Only delete when mails aren't automatically moved or deleted
395 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
396 if ($meta->deleted && ! $item['deleted']) {
397 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
398 Item::update($fields, ['id' => $item['id']]);
401 switch ($mailconf['action']) {
403 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
406 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
407 imap_delete($mbox, $msg_uid, FT_UID);
410 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
411 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
414 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
415 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
416 if ($mailconf['movetofolder'] != "") {
417 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
425 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
426 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
427 if (!trim($raw_refs)) {
428 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
430 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
433 $refs_arr = explode(' ', $raw_refs);
434 if (count($refs_arr)) {
435 for ($x = 0; $x < count($refs_arr); $x ++) {
436 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''],dbesc($refs_arr[$x]))) . "'";
439 $qstr = implode(',', $refs_arr);
440 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
441 intval($importer_uid)
443 if (DBM::is_result($r)) {
444 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
448 // Decoding the header
449 $subject = imap_mime_header_decode($meta->subject);
450 $datarray['title'] = "";
451 foreach ($subject as $subpart) {
452 if ($subpart->charset != "default") {
453 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
455 $datarray['title'] .= $subpart->text;
458 $datarray['title'] = notags(trim($datarray['title']));
460 //$datarray['title'] = notags(trim($meta->subject));
461 $datarray['created'] = DateTimeFormat::utc($meta->date);
464 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
465 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
468 // Remove Reply-signs in the subject
469 $datarray['title'] = self::RemoveReply($datarray['title']);
471 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
472 if (empty($datarray['parent-uri']) && $reply) {
473 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
474 dbesc(protect_sprintf($datarray['title'])),
475 intval($importer_uid),
476 dbesc(NETWORK_MAIL));
477 if (DBM::is_result($r)) {
478 $datarray['parent-uri'] = $r[0]['parent-uri'];
482 if (empty($datarray['parent-uri'])) {
483 $datarray['parent-uri'] = $datarray['uri'];
486 $r = Email::getMessage($mbox, $msg_uid, $reply);
488 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
491 $datarray['body'] = escape_tags($r['body']);
492 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
494 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
496 /// @TODO Adding a gravatar for the original author would be cool
498 $from = imap_mime_header_decode($meta->from);
500 foreach ($from as $frompart) {
501 if ($frompart->charset != "default") {
502 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
504 $fromdecoded .= $frompart->text;
508 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
510 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
512 if (isset($fromarr[0]->personal)) {
513 $fromname = $fromarr[0]->personal;
515 $fromname = $frommail;
518 $datarray['author-name'] = $fromname;
519 $datarray['author-link'] = "mailto:".$frommail;
520 $datarray['author-avatar'] = $contact['photo'];
522 $datarray['owner-name'] = $contact['name'];
523 $datarray['owner-link'] = "mailto:".$contact['addr'];
524 $datarray['owner-avatar'] = $contact['photo'];
526 $datarray['uid'] = $importer_uid;
527 $datarray['contact-id'] = $contact['id'];
528 if ($datarray['parent-uri'] === $datarray['uri']) {
529 $datarray['private'] = 1;
531 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
532 $datarray['private'] = 1;
533 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
536 $stored_item = Item::insert($datarray);
538 switch ($mailconf['action']) {
540 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
543 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
544 imap_delete($mbox, $msg_uid, FT_UID);
547 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
548 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
551 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
552 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
553 if ($mailconf['movetofolder'] != "") {
554 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
561 logger("Mail: no mails for ".$mailconf['user']);
564 logger("Mail: closing connection for ".$mailconf['user']);
570 logger('received xml : ' . $xml, LOGGER_DATA);
571 if (!strstr($xml, '<')) {
572 logger('post_handshake: response from ' . $url . ' did not contain XML.');
574 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
575 self::updateContact($contact, $fields);
576 Contact::markForArchival($contact);
581 logger("Consume feed of contact ".$contact['id']);
583 consume_feed($xml, $importer, $contact, $hub, 1, 1);
585 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
587 consume_feed($xml, $importer, $contact, $hub, 1, 2);
589 $hubmode = 'subscribe';
590 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
591 $hubmode = 'unsubscribe';
594 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
602 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
604 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
605 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
606 $hubs = explode(',', $hub);
608 foreach ($hubs as $h) {
613 subscribe_to_hub($h, $importer, $contact, $hubmode);
618 $updated = DateTimeFormat::utcNow();
620 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
621 dba::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
622 Contact::unmarkForArchival($contact);
623 } elseif (in_array($contact["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED])) {
624 $updated = DateTimeFormat::utcNow();
626 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
627 dba::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
628 Contact::markForArchival($contact);
630 $updated = DateTimeFormat::utcNow();
631 dba::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
637 private static function RemoveReply($subject) {
638 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
639 $subject = trim(substr($subject, 4));
646 * @brief Updates a personal contact entry and the public contact entry
648 * @param array $contact The personal contact entry
649 * @param array $fields The fields that are updated
651 private static function updateContact($contact, $fields) {
652 dba::update('contact', $fields, ['id' => $contact['id']]);
653 dba::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);