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\Object\Contact;
11 use Friendica\Protocol\Email;
12 use Friendica\Protocol\PortableContact;
15 require_once 'include/follow.php';
19 public static function execute($contact_id = 0, $command = '') {
22 require_once 'include/datetime.php';
23 require_once 'include/items.php';
24 require_once 'include/queue_fn.php';
34 if ($command == "force") {
43 $d = datetime_convert();
45 $contact = dba::select('contact', [], ['id' => $contact_id], ['limit' => 1]);
46 if (!DBM::is_result($contact)) {
47 logger('Contact not found or cannot be used.');
51 $importer_uid = $contact['uid'];
53 // load current friends if possible.
54 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
55 $r = q("SELECT count(*) AS total FROM glink
56 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
57 intval($contact['id'])
59 if (DBM::is_result($r)) {
60 if (!$r[0]['total']) {
61 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
66 // Diaspora users and followers we only check if they still exist.
67 if (($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
68 if (PortableContact::updateNeeded($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
69 $last_updated = PortableContact::lastUpdated($contact["url"]);
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 dba::update('contact', $fields, array('id' => $contact['id']));
81 Contact::unmarkForArchival($contact);
83 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
84 Contact::markForArchival($contact);
85 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
93 $t = $contact['last-update'];
95 if ($contact['subhub']) {
96 $poll_interval = Config::get('system', 'pushpoll_frequency');
97 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
100 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
107 $last_update = (($contact['last-update'] <= NULL_DATE)
108 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
109 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
112 // Update the contact entry
113 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
114 if (!PortableContact::reachable($contact['url'])) {
115 logger("Skipping probably dead contact ".$contact['url']);
117 // set the last-update so we don't keep polling
118 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
122 if (!update_contact($contact["id"])) {
123 Contact::markForArchival($contact);
124 logger('Contact is marked dead');
126 // set the last-update so we don't keep polling
127 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
130 Contact::unmarkForArchival($contact);
134 if ($importer_uid == 0) {
135 logger('Ignore public contacts');
137 // set the last-update so we don't keep polling
138 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
142 $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",
143 intval($importer_uid)
146 if (!DBM::is_result($r)) {
147 logger('No self contact for user '.$importer_uid);
149 // set the last-update so we don't keep polling
150 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
156 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
158 if ($contact['network'] === NETWORK_DFRN) {
159 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
160 if (intval($contact['duplex']) && $contact['dfrn-id']) {
161 $idtosend = '0:' . $orig_id;
163 if (intval($contact['duplex']) && $contact['issued-id']) {
164 $idtosend = '1:' . $orig_id;
167 // they have permission to write to us. We already filtered this in the contact query.
170 // But this may be our first communication, so set the writable flag if it isn't set already.
172 if (!intval($contact['writable'])) {
173 $fields = array('writable' => true);
174 dba::update('contact', $fields, array('id' => $contact['id']));
177 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
178 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
179 . '&type=data&last_update=' . $last_update
182 $ret = z_fetch_url($url);
184 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
185 // set the last-update so we don't keep polling
186 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
187 Contact::markForArchival($contact);
191 $handshake_xml = $ret['body'];
193 $html_code = $a->get_curl_code();
195 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
198 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
199 logger("$url appears to be dead - marking for death ");
201 // dead connection - might be a transient event, or this might
202 // mean the software was uninstalled or the domain expired.
203 // Will keep trying for one month.
205 Contact::markForArchival($contact);
207 // set the last-update so we don't keep polling
208 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
209 dba::update('contact', $fields, array('id' => $contact['id']));
213 if (!strstr($handshake_xml, '<')) {
214 logger('response from ' . $url . ' did not contain XML.');
216 Contact::markForArchival($contact);
218 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
219 dba::update('contact', $fields, array('id' => $contact['id']));
224 $res = parse_xml_string($handshake_xml);
226 if (intval($res->status) == 1) {
227 logger("$url replied status 1 - marking for death ");
229 // we may not be friends anymore. Will keep trying for one month.
230 // set the last-update so we don't keep polling
231 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
232 dba::update('contact', $fields, array('id' => $contact['id']));
234 Contact::markForArchival($contact);
235 } elseif ($contact['term-date'] > NULL_DATE) {
236 logger("$url back from the dead - removing mark for death");
237 Contact::unmarkForArchival($contact);
240 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
241 // set the last-update so we don't keep polling
242 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
246 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
247 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
248 dba::update('contact', $fields, array('id' => $contact['id']));
253 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
254 $challenge = hex2bin((string) $res->challenge);
258 if ($contact['duplex'] && strlen($contact['prvkey'])) {
259 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
260 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
262 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
263 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
266 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
268 if (strpos($final_dfrn_id, ':') == 1) {
269 $final_dfrn_id = substr($final_dfrn_id, 2);
272 if ($final_dfrn_id != $orig_id) {
273 // did not decode properly - cannot trust this site
274 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
276 // set the last-update so we don't keep polling
277 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
278 Contact::markForArchival($contact);
282 $postvars['dfrn_id'] = $idtosend;
283 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
284 $postvars['perm'] = 'rw';
286 $xml = post_url($contact['poll'], $postvars);
288 } elseif (($contact['network'] === NETWORK_OSTATUS)
289 || ($contact['network'] === NETWORK_DIASPORA)
290 || ($contact['network'] === NETWORK_FEED)) {
292 // Upgrading DB fields from an older Friendica version
293 // Will only do this once per notify-enabled OStatus contact
294 // or if relationship changes
296 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
298 // Contacts from OStatus are always writable
299 if ($contact['network'] === NETWORK_OSTATUS) {
303 if ($stat_writeable != $contact['writable']) {
304 $fields = array('writable' => $stat_writeable);
305 dba::update('contact', $fields, array('id' => $contact['id']));
308 // Are we allowed to import from this person?
310 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
311 // set the last-update so we don't keep polling
312 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
316 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
317 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
320 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
321 // set the last-update so we don't keep polling
322 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
323 Contact::markForArchival($contact);
329 } elseif ($contact['network'] === NETWORK_MAIL) {
331 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
333 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
334 if ($mail_disabled) {
335 // set the last-update so we don't keep polling
336 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
337 Contact::markForArchival($contact);
341 logger("Mail: Enabled", LOGGER_DEBUG);
344 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
346 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
347 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
348 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
349 $mailbox = Email::constructMailboxName($mailconf);
351 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
352 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
354 logger("Mail: Connect to " . $mailconf['user']);
356 $fields = array('last_check' => datetime_convert());
357 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
358 logger("Mail: Connected to " . $mailconf['user']);
360 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
365 $msgs = Email::poll($mbox, $contact['addr']);
368 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
370 $metas = Email::messageMeta($mbox, implode(',', $msgs));
371 if (count($metas) != count($msgs)) {
372 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
374 $msgs = array_combine($msgs, $metas);
376 foreach ($msgs as $msg_uid => $meta) {
377 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
380 $datarray['verb'] = ACTIVITY_POST;
381 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
382 // $meta = Email::messageMeta($mbox, $msg_uid);
384 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
386 // Have we seen it before?
387 $fields = array('deleted', 'id');
388 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
389 $r = dba::select('item', $fields, $condition, array('limit' => 1));
391 if (DBM::is_result($r)) {
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 && ! $r['deleted']) {
397 $fields = array('deleted' => true, 'changed' => datetime_convert());
398 dba::update('item', $fields, array('id' => $r['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(array('<', '>', ' '),array('', '', ''),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'] = datetime_convert('UTC', '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'] = limit_body_size($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_store($datarray);
538 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
539 dba::update('item', array('last-child' => false), $condition);
541 dba::update('item', array('last-child' => true), array('id' => $stored_item));
543 switch ($mailconf['action']) {
545 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
548 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
549 imap_delete($mbox, $msg_uid, FT_UID);
552 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
553 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
556 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
557 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
558 if ($mailconf['movetofolder'] != "") {
559 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
566 logger("Mail: no mails for ".$mailconf['user']);
569 logger("Mail: closing connection for ".$mailconf['user']);
575 logger('received xml : ' . $xml, LOGGER_DATA);
576 if (!strstr($xml, '<')) {
577 logger('post_handshake: response from ' . $url . ' did not contain XML.');
579 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
580 dba::update('contact', $fields, array('id' => $contact['id']));
581 Contact::markForArchival($contact);
586 logger("Consume feed of contact ".$contact['id']);
588 consume_feed($xml, $importer, $contact, $hub, 1, 1);
590 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
592 consume_feed($xml, $importer, $contact, $hub, 1, 2);
594 $hubmode = 'subscribe';
595 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
596 $hubmode = 'unsubscribe';
599 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
607 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
609 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
610 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
611 $hubs = explode(',', $hub);
613 foreach ($hubs as $h) {
618 subscribe_to_hub($h, $importer, $contact, $hubmode);
623 $updated = datetime_convert();
625 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
626 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
627 Contact::unmarkForArchival($contact);
628 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
629 $updated = datetime_convert();
631 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
632 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
633 Contact::markForArchival($contact);
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));