3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
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\Content\Text\BBCode;
13 use Friendica\Protocol\Email;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\Network;
16 use Friendica\Util\XML;
17 use Friendica\Util\Temporal;
20 require_once 'include/dba.php';
24 public static function execute($contact_id = 0, $command = '') {
27 require_once 'include/datetime.php';
28 require_once 'include/items.php';
38 if ($command == "force") {
47 $d = Temporal::convert();
49 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
50 if (!DBM::is_result($contact)) {
51 logger('Contact not found or cannot be used.');
55 $importer_uid = $contact['uid'];
57 // load current friends if possible.
58 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
59 $r = q("SELECT count(*) AS total FROM glink
60 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
61 intval($contact['id'])
63 if (DBM::is_result($r)) {
64 if (!$r[0]['total']) {
65 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
70 // Diaspora users, archived users and followers are only checked if they still exist.
71 if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
72 $last_updated = PortableContact::lastUpdated($contact["url"], true);
73 $updated = Temporal::convert();
75 logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
77 // The last public item can be older than the last item we got
78 if ($last_updated < $contact['last-item']) {
79 $last_updated = $contact['last-item'];
82 $fields = ['last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated];
83 self::updateContact($contact, $fields);
84 Contact::unmarkForArchival($contact);
86 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
87 Contact::markForArchival($contact);
88 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
95 $t = $contact['last-update'];
97 if ($contact['subhub']) {
98 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
99 $contact['priority'] = intval($poll_interval);
102 if (Temporal::convert('now') > Temporal::convert($t . " + 1 day")) {
109 $last_update = (($contact['last-update'] <= NULL_DATE)
110 ? Temporal::convert('now - 7 days', 'UTC', 'UTC', Temporal::ATOM)
111 : Temporal::convert($contact['last-update'], 'UTC', 'UTC', Temporal::ATOM)
114 // Update the contact entry
115 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
116 if (!PortableContact::reachable($contact['url'])) {
117 logger("Skipping probably dead contact ".$contact['url']);
119 // set the last-update so we don't keep polling
120 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
124 if (!Contact::updateFromProbe($contact["id"])) {
125 Contact::markForArchival($contact);
126 logger('Contact is marked dead');
128 // set the last-update so we don't keep polling
129 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
132 Contact::unmarkForArchival($contact);
136 if ($importer_uid == 0) {
137 logger('Ignore public contacts');
139 // set the last-update so we don't keep polling
140 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
144 $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",
145 intval($importer_uid)
148 if (!DBM::is_result($r)) {
149 logger('No self contact for user '.$importer_uid);
151 // set the last-update so we don't keep polling
152 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
158 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
160 if ($contact['network'] === NETWORK_DFRN) {
161 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
162 if (intval($contact['duplex']) && $contact['dfrn-id']) {
163 $idtosend = '0:' . $orig_id;
165 if (intval($contact['duplex']) && $contact['issued-id']) {
166 $idtosend = '1:' . $orig_id;
169 // they have permission to write to us. We already filtered this in the contact query.
172 // But this may be our first communication, so set the writable flag if it isn't set already.
174 if (!intval($contact['writable'])) {
175 $fields = ['writable' => true];
176 dba::update('contact', $fields, ['id' => $contact['id']]);
179 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
180 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
181 . '&type=data&last_update=' . $last_update
184 $ret = Network::curl($url);
186 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
187 // set the last-update so we don't keep polling
188 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
189 Contact::markForArchival($contact);
193 $handshake_xml = $ret['body'];
195 $html_code = $a->get_curl_code();
197 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
200 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
201 logger("$url appears to be dead - marking for death ");
203 // dead connection - might be a transient event, or this might
204 // mean the software was uninstalled or the domain expired.
205 // Will keep trying for one month.
207 Contact::markForArchival($contact);
209 // set the last-update so we don't keep polling
210 $fields = ['last-update' => Temporal::convert(), 'failure_update' => Temporal::convert()];
211 self::updateContact($contact, $fields);
215 if (!strstr($handshake_xml, '<')) {
216 logger('response from ' . $url . ' did not contain XML.');
218 Contact::markForArchival($contact);
220 $fields = ['last-update' => Temporal::convert(), 'failure_update' => Temporal::convert()];
221 self::updateContact($contact, $fields);
226 $res = XML::parseString($handshake_xml);
228 if (intval($res->status) == 1) {
229 logger("$url replied status 1 - marking for death ");
231 // we may not be friends anymore. Will keep trying for one month.
232 // set the last-update so we don't keep polling
233 $fields = ['last-update' => Temporal::convert(), 'failure_update' => Temporal::convert()];
234 self::updateContact($contact, $fields);
236 Contact::markForArchival($contact);
237 } elseif ($contact['term-date'] > NULL_DATE) {
238 logger("$url back from the dead - removing mark for death");
239 Contact::unmarkForArchival($contact);
242 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
243 // set the last-update so we don't keep polling
244 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
248 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
249 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
250 dba::update('contact', $fields, ['id' => $contact['id']]);
255 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
256 $challenge = hex2bin((string) $res->challenge);
260 if ($contact['duplex'] && strlen($contact['prvkey'])) {
261 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
262 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
264 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
265 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
268 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
270 if (strpos($final_dfrn_id, ':') == 1) {
271 $final_dfrn_id = substr($final_dfrn_id, 2);
274 if ($final_dfrn_id != $orig_id) {
275 // did not decode properly - cannot trust this site
276 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
278 // set the last-update so we don't keep polling
279 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
280 Contact::markForArchival($contact);
284 $postvars['dfrn_id'] = $idtosend;
285 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
286 $postvars['perm'] = 'rw';
288 $xml = Network::post($contact['poll'], $postvars);
290 } elseif (($contact['network'] === NETWORK_OSTATUS)
291 || ($contact['network'] === NETWORK_DIASPORA)
292 || ($contact['network'] === NETWORK_FEED)) {
294 // Upgrading DB fields from an older Friendica version
295 // Will only do this once per notify-enabled OStatus contact
296 // or if relationship changes
298 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
300 // Contacts from OStatus are always writable
301 if ($contact['network'] === NETWORK_OSTATUS) {
305 if ($stat_writeable != $contact['writable']) {
306 $fields = ['writable' => $stat_writeable];
307 dba::update('contact', $fields, ['id' => $contact['id']]);
310 // Are we allowed to import from this person?
312 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
313 // set the last-update so we don't keep polling
314 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
318 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
319 $ret = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
322 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
323 // set the last-update so we don't keep polling
324 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
325 Contact::markForArchival($contact);
331 } elseif ($contact['network'] === NETWORK_MAIL) {
333 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
335 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
336 if ($mail_disabled) {
337 // set the last-update so we don't keep polling
338 dba::update('contact', ['last-update' => Temporal::convert()], ['id' => $contact['id']]);
339 Contact::markForArchival($contact);
343 logger("Mail: Enabled", LOGGER_DEBUG);
346 $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
348 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
349 $mailconf = dba::selectFirst('mailacct', [], $condition);
350 if (DBM::is_result($user) && DBM::is_result($mailconf)) {
351 $mailbox = Email::constructMailboxName($mailconf);
353 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
354 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
356 logger("Mail: Connect to " . $mailconf['user']);
358 $fields = ['last_check' => Temporal::convert()];
359 dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
360 logger("Mail: Connected to " . $mailconf['user']);
362 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
367 $msgs = Email::poll($mbox, $contact['addr']);
370 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
372 $metas = Email::messageMeta($mbox, implode(',', $msgs));
373 if (count($metas) != count($msgs)) {
374 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
376 $msgs = array_combine($msgs, $metas);
378 foreach ($msgs as $msg_uid => $meta) {
379 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
382 $datarray['verb'] = ACTIVITY_POST;
383 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
384 // $meta = Email::messageMeta($mbox, $msg_uid);
386 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
388 // Have we seen it before?
389 $fields = ['deleted', 'id'];
390 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
391 $item = dba::selectFirst('item', $fields, $condition);
392 if (DBM::is_result($item)) {
393 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
395 // Only delete when mails aren't automatically moved or deleted
396 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
397 if ($meta->deleted && ! $item['deleted']) {
398 $fields = ['deleted' => true, 'changed' => Temporal::convert()];
399 dba::update('item', $fields, ['id' => $item['id']]);
402 switch ($mailconf['action']) {
404 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
407 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
408 imap_delete($mbox, $msg_uid, FT_UID);
411 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
412 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
415 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
416 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
417 if ($mailconf['movetofolder'] != "") {
418 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
426 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
427 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
428 if (!trim($raw_refs)) {
429 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
431 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
434 $refs_arr = explode(' ', $raw_refs);
435 if (count($refs_arr)) {
436 for ($x = 0; $x < count($refs_arr); $x ++) {
437 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''],dbesc($refs_arr[$x]))) . "'";
440 $qstr = implode(',', $refs_arr);
441 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
442 intval($importer_uid)
444 if (DBM::is_result($r)) {
445 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
449 // Decoding the header
450 $subject = imap_mime_header_decode($meta->subject);
451 $datarray['title'] = "";
452 foreach ($subject as $subpart) {
453 if ($subpart->charset != "default") {
454 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
456 $datarray['title'] .= $subpart->text;
459 $datarray['title'] = notags(trim($datarray['title']));
461 //$datarray['title'] = notags(trim($meta->subject));
462 $datarray['created'] = Temporal::convert($meta->date);
465 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
466 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
469 // Remove Reply-signs in the subject
470 $datarray['title'] = self::RemoveReply($datarray['title']);
472 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
473 if (empty($datarray['parent-uri']) && $reply) {
474 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
475 dbesc(protect_sprintf($datarray['title'])),
476 intval($importer_uid),
477 dbesc(NETWORK_MAIL));
478 if (DBM::is_result($r)) {
479 $datarray['parent-uri'] = $r[0]['parent-uri'];
483 if (empty($datarray['parent-uri'])) {
484 $datarray['parent-uri'] = $datarray['uri'];
487 $r = Email::getMessage($mbox, $msg_uid, $reply);
489 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
492 $datarray['body'] = escape_tags($r['body']);
493 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
495 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
497 /// @TODO Adding a gravatar for the original author would be cool
499 $from = imap_mime_header_decode($meta->from);
501 foreach ($from as $frompart) {
502 if ($frompart->charset != "default") {
503 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
505 $fromdecoded .= $frompart->text;
509 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
511 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
513 if (isset($fromarr[0]->personal)) {
514 $fromname = $fromarr[0]->personal;
516 $fromname = $frommail;
519 $datarray['author-name'] = $fromname;
520 $datarray['author-link'] = "mailto:".$frommail;
521 $datarray['author-avatar'] = $contact['photo'];
523 $datarray['owner-name'] = $contact['name'];
524 $datarray['owner-link'] = "mailto:".$contact['addr'];
525 $datarray['owner-avatar'] = $contact['photo'];
527 $datarray['uid'] = $importer_uid;
528 $datarray['contact-id'] = $contact['id'];
529 if ($datarray['parent-uri'] === $datarray['uri']) {
530 $datarray['private'] = 1;
532 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
533 $datarray['private'] = 1;
534 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
537 $stored_item = Item::insert($datarray);
539 switch ($mailconf['action']) {
541 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
544 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
545 imap_delete($mbox, $msg_uid, FT_UID);
548 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
549 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
552 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
553 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
554 if ($mailconf['movetofolder'] != "") {
555 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
562 logger("Mail: no mails for ".$mailconf['user']);
565 logger("Mail: closing connection for ".$mailconf['user']);
571 logger('received xml : ' . $xml, LOGGER_DATA);
572 if (!strstr($xml, '<')) {
573 logger('post_handshake: response from ' . $url . ' did not contain XML.');
575 $fields = ['last-update' => Temporal::convert(), 'failure_update' => Temporal::convert()];
576 self::updateContact($contact, $fields);
577 Contact::markForArchival($contact);
582 logger("Consume feed of contact ".$contact['id']);
584 consume_feed($xml, $importer, $contact, $hub, 1, 1);
586 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
588 consume_feed($xml, $importer, $contact, $hub, 1, 2);
590 $hubmode = 'subscribe';
591 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
592 $hubmode = 'unsubscribe';
595 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
603 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
605 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
606 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
607 $hubs = explode(',', $hub);
609 foreach ($hubs as $h) {
614 subscribe_to_hub($h, $importer, $contact, $hubmode);
619 $updated = Temporal::convert();
621 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
622 dba::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
623 Contact::unmarkForArchival($contact);
624 } elseif (in_array($contact["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED])) {
625 $updated = Temporal::convert();
627 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
628 dba::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
629 Contact::markForArchival($contact);
631 $updated = Temporal::convert();
632 dba::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
638 private static function RemoveReply($subject) {
639 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
640 $subject = trim(substr($subject, 4));
647 * @brief Updates a personal contact entry and the public contact entry
649 * @param array $contact The personal contact entry
650 * @param array $fields The fields that are updated
652 private static function updateContact($contact, $fields) {
653 dba::update('contact', $fields, ['id' => $contact['id']]);
654 dba::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);