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';
16 require_once 'include/follow.php';
20 public static function execute($contact_id = 0, $command = '') {
23 require_once 'include/datetime.php';
24 require_once 'include/items.php';
25 require_once 'include/queue_fn.php';
35 if ($command == "force") {
44 $d = datetime_convert();
46 $contact = dba::select('contact', [], ['id' => $contact_id], ['limit' => 1]);
47 if (!DBM::is_result($contact)) {
48 logger('Contact not found or cannot be used.');
52 $importer_uid = $contact['uid'];
54 // load current friends if possible.
55 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
56 $r = q("SELECT count(*) AS total FROM glink
57 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
58 intval($contact['id'])
60 if (DBM::is_result($r)) {
61 if (!$r[0]['total']) {
62 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
67 // Diaspora users, archived users and followers are only checked if they still exist.
68 if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
69 $last_updated = PortableContact::lastUpdated($contact["url"], true);
70 $updated = datetime_convert();
72 logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
74 // The last public item can be older than the last item we got
75 if ($last_updated < $contact['last-item']) {
76 $last_updated = $contact['last-item'];
79 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
80 self::updateContact($contact, $fields);
81 Contact::unmarkForArchival($contact);
83 self::updateContact($contact, array('last-update' => $updated, 'failure_update' => $updated));
84 Contact::markForArchival($contact);
85 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
92 $t = $contact['last-update'];
94 if ($contact['subhub']) {
95 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
96 $contact['priority'] = intval($poll_interval);
99 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
106 $last_update = (($contact['last-update'] <= NULL_DATE)
107 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
108 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
111 // Update the contact entry
112 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
113 if (!PortableContact::reachable($contact['url'])) {
114 logger("Skipping probably dead contact ".$contact['url']);
116 // set the last-update so we don't keep polling
117 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
121 if (!update_contact($contact["id"])) {
122 Contact::markForArchival($contact);
123 logger('Contact is marked dead');
125 // set the last-update so we don't keep polling
126 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
129 Contact::unmarkForArchival($contact);
133 if ($importer_uid == 0) {
134 logger('Ignore public contacts');
136 // set the last-update so we don't keep polling
137 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
141 $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",
142 intval($importer_uid)
145 if (!DBM::is_result($r)) {
146 logger('No self contact for user '.$importer_uid);
148 // set the last-update so we don't keep polling
149 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
155 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
157 if ($contact['network'] === NETWORK_DFRN) {
158 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
159 if (intval($contact['duplex']) && $contact['dfrn-id']) {
160 $idtosend = '0:' . $orig_id;
162 if (intval($contact['duplex']) && $contact['issued-id']) {
163 $idtosend = '1:' . $orig_id;
166 // they have permission to write to us. We already filtered this in the contact query.
169 // But this may be our first communication, so set the writable flag if it isn't set already.
171 if (!intval($contact['writable'])) {
172 $fields = array('writable' => true);
173 dba::update('contact', $fields, array('id' => $contact['id']));
176 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
177 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
178 . '&type=data&last_update=' . $last_update
181 $ret = z_fetch_url($url);
183 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
184 // set the last-update so we don't keep polling
185 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
186 Contact::markForArchival($contact);
190 $handshake_xml = $ret['body'];
192 $html_code = $a->get_curl_code();
194 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
197 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
198 logger("$url appears to be dead - marking for death ");
200 // dead connection - might be a transient event, or this might
201 // mean the software was uninstalled or the domain expired.
202 // Will keep trying for one month.
204 Contact::markForArchival($contact);
206 // set the last-update so we don't keep polling
207 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
208 self::updateContact($contact, $fields);
212 if (!strstr($handshake_xml, '<')) {
213 logger('response from ' . $url . ' did not contain XML.');
215 Contact::markForArchival($contact);
217 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
218 self::updateContact($contact, $fields);
223 $res = parse_xml_string($handshake_xml);
225 if (intval($res->status) == 1) {
226 logger("$url replied status 1 - marking for death ");
228 // we may not be friends anymore. Will keep trying for one month.
229 // set the last-update so we don't keep polling
230 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
231 self::updateContact($contact, $fields);
233 Contact::markForArchival($contact);
234 } elseif ($contact['term-date'] > NULL_DATE) {
235 logger("$url back from the dead - removing mark for death");
236 Contact::unmarkForArchival($contact);
239 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
240 // set the last-update so we don't keep polling
241 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
245 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
246 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
247 dba::update('contact', $fields, array('id' => $contact['id']));
252 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
253 $challenge = hex2bin((string) $res->challenge);
257 if ($contact['duplex'] && strlen($contact['prvkey'])) {
258 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
259 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
261 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
262 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
265 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
267 if (strpos($final_dfrn_id, ':') == 1) {
268 $final_dfrn_id = substr($final_dfrn_id, 2);
271 if ($final_dfrn_id != $orig_id) {
272 // did not decode properly - cannot trust this site
273 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
275 // set the last-update so we don't keep polling
276 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
277 Contact::markForArchival($contact);
281 $postvars['dfrn_id'] = $idtosend;
282 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
283 $postvars['perm'] = 'rw';
285 $xml = post_url($contact['poll'], $postvars);
287 } elseif (($contact['network'] === NETWORK_OSTATUS)
288 || ($contact['network'] === NETWORK_DIASPORA)
289 || ($contact['network'] === NETWORK_FEED)) {
291 // Upgrading DB fields from an older Friendica version
292 // Will only do this once per notify-enabled OStatus contact
293 // or if relationship changes
295 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
297 // Contacts from OStatus are always writable
298 if ($contact['network'] === NETWORK_OSTATUS) {
302 if ($stat_writeable != $contact['writable']) {
303 $fields = array('writable' => $stat_writeable);
304 dba::update('contact', $fields, array('id' => $contact['id']));
307 // Are we allowed to import from this person?
309 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
310 // set the last-update so we don't keep polling
311 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
315 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
316 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
319 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
320 // set the last-update so we don't keep polling
321 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
322 Contact::markForArchival($contact);
328 } elseif ($contact['network'] === NETWORK_MAIL) {
330 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
332 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
333 if ($mail_disabled) {
334 // set the last-update so we don't keep polling
335 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
336 Contact::markForArchival($contact);
340 logger("Mail: Enabled", LOGGER_DEBUG);
343 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
345 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
346 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
347 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
348 $mailbox = Email::constructMailboxName($mailconf);
350 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
351 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
353 logger("Mail: Connect to " . $mailconf['user']);
355 $fields = array('last_check' => datetime_convert());
356 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
357 logger("Mail: Connected to " . $mailconf['user']);
359 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
364 $msgs = Email::poll($mbox, $contact['addr']);
367 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
369 $metas = Email::messageMeta($mbox, implode(',', $msgs));
370 if (count($metas) != count($msgs)) {
371 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
373 $msgs = array_combine($msgs, $metas);
375 foreach ($msgs as $msg_uid => $meta) {
376 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
379 $datarray['verb'] = ACTIVITY_POST;
380 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
381 // $meta = Email::messageMeta($mbox, $msg_uid);
383 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
385 // Have we seen it before?
386 $fields = array('deleted', 'id');
387 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
388 $r = dba::select('item', $fields, $condition, array('limit' => 1));
390 if (DBM::is_result($r)) {
391 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
393 // Only delete when mails aren't automatically moved or deleted
394 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
395 if ($meta->deleted && ! $r['deleted']) {
396 $fields = array('deleted' => true, 'changed' => datetime_convert());
397 dba::update('item', $fields, array('id' => $r['id']));
400 switch ($mailconf['action']) {
402 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
405 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
406 imap_delete($mbox, $msg_uid, FT_UID);
409 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
410 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
413 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
414 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
415 if ($mailconf['movetofolder'] != "") {
416 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
424 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
425 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
426 if (!trim($raw_refs)) {
427 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
429 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
432 $refs_arr = explode(' ', $raw_refs);
433 if (count($refs_arr)) {
434 for ($x = 0; $x < count($refs_arr); $x ++) {
435 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
438 $qstr = implode(',', $refs_arr);
439 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
440 intval($importer_uid)
442 if (DBM::is_result($r)) {
443 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
447 // Decoding the header
448 $subject = imap_mime_header_decode($meta->subject);
449 $datarray['title'] = "";
450 foreach ($subject as $subpart) {
451 if ($subpart->charset != "default") {
452 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
454 $datarray['title'] .= $subpart->text;
457 $datarray['title'] = notags(trim($datarray['title']));
459 //$datarray['title'] = notags(trim($meta->subject));
460 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
463 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
464 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
467 // Remove Reply-signs in the subject
468 $datarray['title'] = self::RemoveReply($datarray['title']);
470 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
471 if (empty($datarray['parent-uri']) && $reply) {
472 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
473 dbesc(protect_sprintf($datarray['title'])),
474 intval($importer_uid),
475 dbesc(NETWORK_MAIL));
476 if (DBM::is_result($r)) {
477 $datarray['parent-uri'] = $r[0]['parent-uri'];
481 if (empty($datarray['parent-uri'])) {
482 $datarray['parent-uri'] = $datarray['uri'];
485 $r = Email::getMessage($mbox, $msg_uid, $reply);
487 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
490 $datarray['body'] = escape_tags($r['body']);
491 $datarray['body'] = limit_body_size($datarray['body']);
493 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
495 /// @TODO Adding a gravatar for the original author would be cool
497 $from = imap_mime_header_decode($meta->from);
499 foreach ($from as $frompart) {
500 if ($frompart->charset != "default") {
501 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
503 $fromdecoded .= $frompart->text;
507 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
509 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
511 if (isset($fromarr[0]->personal)) {
512 $fromname = $fromarr[0]->personal;
514 $fromname = $frommail;
517 $datarray['author-name'] = $fromname;
518 $datarray['author-link'] = "mailto:".$frommail;
519 $datarray['author-avatar'] = $contact['photo'];
521 $datarray['owner-name'] = $contact['name'];
522 $datarray['owner-link'] = "mailto:".$contact['addr'];
523 $datarray['owner-avatar'] = $contact['photo'];
525 $datarray['uid'] = $importer_uid;
526 $datarray['contact-id'] = $contact['id'];
527 if ($datarray['parent-uri'] === $datarray['uri']) {
528 $datarray['private'] = 1;
530 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
531 $datarray['private'] = 1;
532 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
535 $stored_item = item_store($datarray);
537 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
538 dba::update('item', array('last-child' => false), $condition);
540 dba::update('item', array('last-child' => true), array('id' => $stored_item));
542 switch ($mailconf['action']) {
544 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
547 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
548 imap_delete($mbox, $msg_uid, FT_UID);
551 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
552 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
555 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
556 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
557 if ($mailconf['movetofolder'] != "") {
558 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
565 logger("Mail: no mails for ".$mailconf['user']);
568 logger("Mail: closing connection for ".$mailconf['user']);
574 logger('received xml : ' . $xml, LOGGER_DATA);
575 if (!strstr($xml, '<')) {
576 logger('post_handshake: response from ' . $url . ' did not contain XML.');
578 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
579 self::updateContact($contact, $fields);
580 Contact::markForArchival($contact);
585 logger("Consume feed of contact ".$contact['id']);
587 consume_feed($xml, $importer, $contact, $hub, 1, 1);
589 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
591 consume_feed($xml, $importer, $contact, $hub, 1, 2);
593 $hubmode = 'subscribe';
594 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
595 $hubmode = 'unsubscribe';
598 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
606 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
608 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
609 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
610 $hubs = explode(',', $hub);
612 foreach ($hubs as $h) {
617 subscribe_to_hub($h, $importer, $contact, $hubmode);
622 $updated = datetime_convert();
624 self::updateContact($contact, array('last-update' => $updated, 'success_update' => $updated));
625 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
626 Contact::unmarkForArchival($contact);
627 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
628 $updated = datetime_convert();
630 self::updateContact($contact, array('last-update' => $updated, 'failure_update' => $updated));
631 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
632 Contact::markForArchival($contact);
634 $updated = datetime_convert();
635 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
641 private static function RemoveReply($subject) {
642 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
643 $subject = trim(substr($subject, 4));
650 * @brief Updates a personal contact entry and the public contact entry
652 * @param array $contact The personal contact entry
653 * @param array $fields The fields that are updated
655 private static function updateContact($contact, $fields) {
656 dba::update('contact', $fields, array('id' => $contact['id']));
657 dba::update('contact', $fields, array('uid' => 0, 'nurl' => $contact['nurl']));