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\Protocol\Email;
12 use Friendica\Protocol\PortableContact;
15 require_once 'include/dba.php';
19 public static function execute($contact_id = 0, $command = '') {
22 require_once 'include/datetime.php';
23 require_once 'include/items.php';
33 if ($command == "force") {
42 $d = datetime_convert();
44 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
45 if (!DBM::is_result($contact)) {
46 logger('Contact not found or cannot be used.');
50 $importer_uid = $contact['uid'];
52 // load current friends if possible.
53 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
54 $r = q("SELECT count(*) AS total FROM glink
55 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
56 intval($contact['id'])
58 if (DBM::is_result($r)) {
59 if (!$r[0]['total']) {
60 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
65 // Diaspora users, archived users and followers are only checked if they still exist.
66 if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
67 $last_updated = PortableContact::lastUpdated($contact["url"], true);
68 $updated = datetime_convert();
70 logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
72 // The last public item can be older than the last item we got
73 if ($last_updated < $contact['last-item']) {
74 $last_updated = $contact['last-item'];
77 $fields = ['last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated];
78 self::updateContact($contact, $fields);
79 Contact::unmarkForArchival($contact);
81 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
82 Contact::markForArchival($contact);
83 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
90 $t = $contact['last-update'];
92 if ($contact['subhub']) {
93 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
94 $contact['priority'] = intval($poll_interval);
97 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
104 $last_update = (($contact['last-update'] <= NULL_DATE)
105 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
106 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
109 // Update the contact entry
110 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
111 if (!PortableContact::reachable($contact['url'])) {
112 logger("Skipping probably dead contact ".$contact['url']);
114 // set the last-update so we don't keep polling
115 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
119 if (!Contact::updateFromProbe($contact["id"])) {
120 Contact::markForArchival($contact);
121 logger('Contact is marked dead');
123 // set the last-update so we don't keep polling
124 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
127 Contact::unmarkForArchival($contact);
131 if ($importer_uid == 0) {
132 logger('Ignore public contacts');
134 // set the last-update so we don't keep polling
135 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
139 $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",
140 intval($importer_uid)
143 if (!DBM::is_result($r)) {
144 logger('No self contact for user '.$importer_uid);
146 // set the last-update so we don't keep polling
147 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
153 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
155 if ($contact['network'] === NETWORK_DFRN) {
156 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
157 if (intval($contact['duplex']) && $contact['dfrn-id']) {
158 $idtosend = '0:' . $orig_id;
160 if (intval($contact['duplex']) && $contact['issued-id']) {
161 $idtosend = '1:' . $orig_id;
164 // they have permission to write to us. We already filtered this in the contact query.
167 // But this may be our first communication, so set the writable flag if it isn't set already.
169 if (!intval($contact['writable'])) {
170 $fields = ['writable' => true];
171 dba::update('contact', $fields, ['id' => $contact['id']]);
174 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
175 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
176 . '&type=data&last_update=' . $last_update
179 $ret = z_fetch_url($url);
181 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
182 // set the last-update so we don't keep polling
183 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
184 Contact::markForArchival($contact);
188 $handshake_xml = $ret['body'];
190 $html_code = $a->get_curl_code();
192 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
195 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
196 logger("$url appears to be dead - marking for death ");
198 // dead connection - might be a transient event, or this might
199 // mean the software was uninstalled or the domain expired.
200 // Will keep trying for one month.
202 Contact::markForArchival($contact);
204 // set the last-update so we don't keep polling
205 $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
206 self::updateContact($contact, $fields);
210 if (!strstr($handshake_xml, '<')) {
211 logger('response from ' . $url . ' did not contain XML.');
213 Contact::markForArchival($contact);
215 $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
216 self::updateContact($contact, $fields);
221 $res = parse_xml_string($handshake_xml);
223 if (intval($res->status) == 1) {
224 logger("$url replied status 1 - marking for death ");
226 // we may not be friends anymore. Will keep trying for one month.
227 // set the last-update so we don't keep polling
228 $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
229 self::updateContact($contact, $fields);
231 Contact::markForArchival($contact);
232 } elseif ($contact['term-date'] > NULL_DATE) {
233 logger("$url back from the dead - removing mark for death");
234 Contact::unmarkForArchival($contact);
237 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
238 // set the last-update so we don't keep polling
239 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
243 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
244 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
245 dba::update('contact', $fields, ['id' => $contact['id']]);
250 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
251 $challenge = hex2bin((string) $res->challenge);
255 if ($contact['duplex'] && strlen($contact['prvkey'])) {
256 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
257 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
259 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
260 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
263 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
265 if (strpos($final_dfrn_id, ':') == 1) {
266 $final_dfrn_id = substr($final_dfrn_id, 2);
269 if ($final_dfrn_id != $orig_id) {
270 // did not decode properly - cannot trust this site
271 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
273 // set the last-update so we don't keep polling
274 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
275 Contact::markForArchival($contact);
279 $postvars['dfrn_id'] = $idtosend;
280 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
281 $postvars['perm'] = 'rw';
283 $xml = post_url($contact['poll'], $postvars);
285 } elseif (($contact['network'] === NETWORK_OSTATUS)
286 || ($contact['network'] === NETWORK_DIASPORA)
287 || ($contact['network'] === NETWORK_FEED)) {
289 // Upgrading DB fields from an older Friendica version
290 // Will only do this once per notify-enabled OStatus contact
291 // or if relationship changes
293 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
295 // Contacts from OStatus are always writable
296 if ($contact['network'] === NETWORK_OSTATUS) {
300 if ($stat_writeable != $contact['writable']) {
301 $fields = ['writable' => $stat_writeable];
302 dba::update('contact', $fields, ['id' => $contact['id']]);
305 // Are we allowed to import from this person?
307 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
308 // set the last-update so we don't keep polling
309 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
313 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
314 $ret = z_fetch_url($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
317 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
318 // set the last-update so we don't keep polling
319 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
320 Contact::markForArchival($contact);
326 } elseif ($contact['network'] === NETWORK_MAIL) {
328 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
330 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
331 if ($mail_disabled) {
332 // set the last-update so we don't keep polling
333 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
334 Contact::markForArchival($contact);
338 logger("Mail: Enabled", LOGGER_DEBUG);
341 $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
343 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
344 $mailconf = dba::selectFirst('mailacct', [], $condition);
345 if (DBM::is_result($user) && DBM::is_result($mailconf)) {
346 $mailbox = Email::constructMailboxName($mailconf);
348 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
349 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
351 logger("Mail: Connect to " . $mailconf['user']);
353 $fields = ['last_check' => datetime_convert()];
354 dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
355 logger("Mail: Connected to " . $mailconf['user']);
357 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
362 $msgs = Email::poll($mbox, $contact['addr']);
365 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
367 $metas = Email::messageMeta($mbox, implode(',', $msgs));
368 if (count($metas) != count($msgs)) {
369 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
371 $msgs = array_combine($msgs, $metas);
373 foreach ($msgs as $msg_uid => $meta) {
374 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
377 $datarray['verb'] = ACTIVITY_POST;
378 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
379 // $meta = Email::messageMeta($mbox, $msg_uid);
381 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
383 // Have we seen it before?
384 $fields = ['deleted', 'id'];
385 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
386 $item = dba::selectFirst('item', $fields, $condition);
387 if (DBM::is_result($item)) {
388 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
390 // Only delete when mails aren't automatically moved or deleted
391 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
392 if ($meta->deleted && ! $item['deleted']) {
393 $fields = ['deleted' => true, 'changed' => datetime_convert()];
394 dba::update('item', $fields, ['id' => $item['id']]);
397 switch ($mailconf['action']) {
399 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
402 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
403 imap_delete($mbox, $msg_uid, FT_UID);
406 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
407 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
410 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
411 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
412 if ($mailconf['movetofolder'] != "") {
413 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
421 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
422 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
423 if (!trim($raw_refs)) {
424 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
426 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
429 $refs_arr = explode(' ', $raw_refs);
430 if (count($refs_arr)) {
431 for ($x = 0; $x < count($refs_arr); $x ++) {
432 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''],dbesc($refs_arr[$x]))) . "'";
435 $qstr = implode(',', $refs_arr);
436 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
437 intval($importer_uid)
439 if (DBM::is_result($r)) {
440 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
444 // Decoding the header
445 $subject = imap_mime_header_decode($meta->subject);
446 $datarray['title'] = "";
447 foreach ($subject as $subpart) {
448 if ($subpart->charset != "default") {
449 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
451 $datarray['title'] .= $subpart->text;
454 $datarray['title'] = notags(trim($datarray['title']));
456 //$datarray['title'] = notags(trim($meta->subject));
457 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
460 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
461 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
464 // Remove Reply-signs in the subject
465 $datarray['title'] = self::RemoveReply($datarray['title']);
467 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
468 if (empty($datarray['parent-uri']) && $reply) {
469 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
470 dbesc(protect_sprintf($datarray['title'])),
471 intval($importer_uid),
472 dbesc(NETWORK_MAIL));
473 if (DBM::is_result($r)) {
474 $datarray['parent-uri'] = $r[0]['parent-uri'];
478 if (empty($datarray['parent-uri'])) {
479 $datarray['parent-uri'] = $datarray['uri'];
482 $r = Email::getMessage($mbox, $msg_uid, $reply);
484 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
487 $datarray['body'] = escape_tags($r['body']);
488 $datarray['body'] = limit_body_size($datarray['body']);
490 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
492 /// @TODO Adding a gravatar for the original author would be cool
494 $from = imap_mime_header_decode($meta->from);
496 foreach ($from as $frompart) {
497 if ($frompart->charset != "default") {
498 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
500 $fromdecoded .= $frompart->text;
504 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
506 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
508 if (isset($fromarr[0]->personal)) {
509 $fromname = $fromarr[0]->personal;
511 $fromname = $frommail;
514 $datarray['author-name'] = $fromname;
515 $datarray['author-link'] = "mailto:".$frommail;
516 $datarray['author-avatar'] = $contact['photo'];
518 $datarray['owner-name'] = $contact['name'];
519 $datarray['owner-link'] = "mailto:".$contact['addr'];
520 $datarray['owner-avatar'] = $contact['photo'];
522 $datarray['uid'] = $importer_uid;
523 $datarray['contact-id'] = $contact['id'];
524 if ($datarray['parent-uri'] === $datarray['uri']) {
525 $datarray['private'] = 1;
527 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
528 $datarray['private'] = 1;
529 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
532 $stored_item = item_store($datarray);
534 $condition = ['parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid];
535 dba::update('item', ['last-child' => false], $condition);
537 dba::update('item', ['last-child' => true], ['id' => $stored_item]);
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' => datetime_convert(), 'failure_update' => datetime_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 = datetime_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 = datetime_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 = datetime_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']]);