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 // Only poll from those with suitable relationships,
46 // and which have a polling address and ignore Diaspora since
47 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
49 $contacts = q("SELECT `contact`.* FROM `contact`
50 WHERE (`rel` = %d OR `rel` = %d) AND `poll` != ''
51 AND NOT `network` IN ('%s', '%s')
52 AND `contact`.`id` = %d
53 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
54 AND `contact`.`archive` = 0 LIMIT 1",
55 intval(CONTACT_IS_SHARING),
56 intval(CONTACT_IS_FRIEND),
57 dbesc(NETWORK_FACEBOOK),
58 dbesc(NETWORK_PUMPIO),
62 if (!count($contacts)) {
63 logger('Contact not found or cannot be used.');
67 $contact = $contacts[0];
69 $importer_uid = $contact['uid'];
71 // load current friends if possible.
72 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
73 $r = q("SELECT count(*) AS total FROM glink
74 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
75 intval($contact['id'])
77 if (DBM::is_result($r)) {
78 if (!$r[0]['total']) {
79 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
84 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
85 /// @TODO Check whether this is possible with Redmatrix
86 if ($contact["network"] == NETWORK_DIASPORA) {
87 if (PortableContact::updateNeeded($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
88 $last_updated = PortableContact::lastUpdated($contact["url"]);
89 $updated = datetime_convert();
91 logger('Diaspora contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
93 // The last public item can be older than the last item we got
94 if ($last_updated < $contact['last-item']) {
95 $last_updated = $contact['last-item'];
98 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
99 dba::update('contact', $fields, array('id' => $contact['id']));
100 Contact::unmarkForArchival($contact);
102 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
103 Contact::markForArchival($contact);
104 logger('Diaspora contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
112 $t = $contact['last-update'];
114 if ($contact['subhub']) {
115 $poll_interval = Config::get('system', 'pushpoll_frequency');
116 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
119 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
126 $last_update = (($contact['last-update'] <= NULL_DATE)
127 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
128 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
131 // Update the contact entry
132 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
133 if (!PortableContact::reachable($contact['url'])) {
134 logger("Skipping probably dead contact ".$contact['url']);
136 // set the last-update so we don't keep polling
137 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
141 if (!update_contact($contact["id"])) {
142 Contact::markForArchival($contact);
143 logger('Contact is marked dead');
145 // set the last-update so we don't keep polling
146 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
149 Contact::unmarkForArchival($contact);
153 if ($importer_uid == 0) {
154 logger('Ignore public contacts');
156 // set the last-update so we don't keep polling
157 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
161 $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",
162 intval($importer_uid)
165 if (!DBM::is_result($r)) {
166 logger('No self contact for user '.$importer_uid);
168 // set the last-update so we don't keep polling
169 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
175 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
177 if ($contact['network'] === NETWORK_DFRN) {
178 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
179 if (intval($contact['duplex']) && $contact['dfrn-id']) {
180 $idtosend = '0:' . $orig_id;
182 if (intval($contact['duplex']) && $contact['issued-id']) {
183 $idtosend = '1:' . $orig_id;
186 // they have permission to write to us. We already filtered this in the contact query.
189 // But this may be our first communication, so set the writable flag if it isn't set already.
191 if (!intval($contact['writable'])) {
192 $fields = array('writable' => true);
193 dba::update('contact', $fields, array('id' => $contact['id']));
196 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
197 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
198 . '&type=data&last_update=' . $last_update
201 $ret = z_fetch_url($url);
203 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
204 // set the last-update so we don't keep polling
205 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
206 Contact::markForArchival($contact);
210 $handshake_xml = $ret['body'];
212 $html_code = $a->get_curl_code();
214 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
217 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
218 logger("$url appears to be dead - marking for death ");
220 // dead connection - might be a transient event, or this might
221 // mean the software was uninstalled or the domain expired.
222 // Will keep trying for one month.
224 Contact::markForArchival($contact);
226 // set the last-update so we don't keep polling
227 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
228 dba::update('contact', $fields, array('id' => $contact['id']));
232 if (!strstr($handshake_xml, '<')) {
233 logger('response from ' . $url . ' did not contain XML.');
235 Contact::markForArchival($contact);
237 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
238 dba::update('contact', $fields, array('id' => $contact['id']));
243 $res = parse_xml_string($handshake_xml);
245 if (intval($res->status) == 1) {
246 logger("$url replied status 1 - marking for death ");
248 // we may not be friends anymore. Will keep trying for one month.
249 // set the last-update so we don't keep polling
250 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
251 dba::update('contact', $fields, array('id' => $contact['id']));
253 Contact::markForArchival($contact);
254 } elseif ($contact['term-date'] > NULL_DATE) {
255 logger("$url back from the dead - removing mark for death");
256 Contact::unmarkForArchival($contact);
259 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
260 // set the last-update so we don't keep polling
261 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
265 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
266 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
267 dba::update('contact', $fields, array('id' => $contact['id']));
272 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
273 $challenge = hex2bin((string) $res->challenge);
277 if ($contact['duplex'] && strlen($contact['prvkey'])) {
278 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
279 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
281 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
282 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
285 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
287 if (strpos($final_dfrn_id, ':') == 1) {
288 $final_dfrn_id = substr($final_dfrn_id, 2);
291 if ($final_dfrn_id != $orig_id) {
292 // did not decode properly - cannot trust this site
293 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
295 // set the last-update so we don't keep polling
296 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
297 Contact::markForArchival($contact);
301 $postvars['dfrn_id'] = $idtosend;
302 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
303 $postvars['perm'] = 'rw';
305 $xml = post_url($contact['poll'], $postvars);
307 } elseif (($contact['network'] === NETWORK_OSTATUS)
308 || ($contact['network'] === NETWORK_DIASPORA)
309 || ($contact['network'] === NETWORK_FEED)) {
311 // Upgrading DB fields from an older Friendica version
312 // Will only do this once per notify-enabled OStatus contact
313 // or if relationship changes
315 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
317 // Contacts from OStatus are always writable
318 if ($contact['network'] === NETWORK_OSTATUS) {
322 if ($stat_writeable != $contact['writable']) {
323 $fields = array('writable' => $stat_writeable);
324 dba::update('contact', $fields, array('id' => $contact['id']));
327 // Are we allowed to import from this person?
329 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
330 // set the last-update so we don't keep polling
331 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
335 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
336 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
338 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
339 // set the last-update so we don't keep polling
340 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
341 Contact::markForArchival($contact);
348 } elseif ($contact['network'] === NETWORK_MAIL) {
350 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
352 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
353 if ($mail_disabled) {
354 // set the last-update so we don't keep polling
355 dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
356 Contact::markForArchival($contact);
360 logger("Mail: Enabled", LOGGER_DEBUG);
363 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
365 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
366 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
367 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
368 $mailbox = Email::constructMailboxName($mailconf);
370 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
371 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
373 logger("Mail: Connect to " . $mailconf['user']);
375 $fields = array('last_check' => datetime_convert());
376 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
377 logger("Mail: Connected to " . $mailconf['user']);
379 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
384 $msgs = Email::poll($mbox, $contact['addr']);
387 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
389 $metas = Email::messageMeta($mbox, implode(',', $msgs));
390 if (count($metas) != count($msgs)) {
391 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
393 $msgs = array_combine($msgs, $metas);
395 foreach ($msgs as $msg_uid => $meta) {
396 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
399 $datarray['verb'] = ACTIVITY_POST;
400 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
401 // $meta = Email::messageMeta($mbox, $msg_uid);
403 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
405 // Have we seen it before?
406 $fields = array('deleted', 'id');
407 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
408 $r = dba::select('item', $fields, $condition, array('limit' => 1));
410 if (DBM::is_result($r)) {
411 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
413 // Only delete when mails aren't automatically moved or deleted
414 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
415 if ($meta->deleted && ! $r['deleted']) {
416 $fields = array('deleted' => true, 'changed' => datetime_convert());
417 dba::update('item', $fields, array('id' => $r['id']));
420 switch ($mailconf['action']) {
422 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
425 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
426 imap_delete($mbox, $msg_uid, FT_UID);
429 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
430 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
433 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
434 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
435 if ($mailconf['movetofolder'] != "") {
436 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
444 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
445 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
446 if (!trim($raw_refs)) {
447 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
449 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
452 $refs_arr = explode(' ', $raw_refs);
453 if (count($refs_arr)) {
454 for ($x = 0; $x < count($refs_arr); $x ++) {
455 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
458 $qstr = implode(',', $refs_arr);
459 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
460 intval($importer_uid)
462 if (DBM::is_result($r)) {
463 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
467 // Decoding the header
468 $subject = imap_mime_header_decode($meta->subject);
469 $datarray['title'] = "";
470 foreach ($subject as $subpart) {
471 if ($subpart->charset != "default") {
472 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
474 $datarray['title'] .= $subpart->text;
477 $datarray['title'] = notags(trim($datarray['title']));
479 //$datarray['title'] = notags(trim($meta->subject));
480 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
483 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
484 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
487 // Remove Reply-signs in the subject
488 $datarray['title'] = self::RemoveReply($datarray['title']);
490 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
491 if (empty($datarray['parent-uri']) && $reply) {
492 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
493 dbesc(protect_sprintf($datarray['title'])),
494 intval($importer_uid),
495 dbesc(NETWORK_MAIL));
496 if (DBM::is_result($r)) {
497 $datarray['parent-uri'] = $r[0]['parent-uri'];
501 if (empty($datarray['parent-uri'])) {
502 $datarray['parent-uri'] = $datarray['uri'];
505 $r = Email::getMessage($mbox, $msg_uid, $reply);
507 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
510 $datarray['body'] = escape_tags($r['body']);
511 $datarray['body'] = limit_body_size($datarray['body']);
513 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
515 /// @TODO Adding a gravatar for the original author would be cool
517 $from = imap_mime_header_decode($meta->from);
519 foreach ($from as $frompart) {
520 if ($frompart->charset != "default") {
521 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
523 $fromdecoded .= $frompart->text;
527 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
529 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
531 if (isset($fromarr[0]->personal)) {
532 $fromname = $fromarr[0]->personal;
534 $fromname = $frommail;
537 $datarray['author-name'] = $fromname;
538 $datarray['author-link'] = "mailto:".$frommail;
539 $datarray['author-avatar'] = $contact['photo'];
541 $datarray['owner-name'] = $contact['name'];
542 $datarray['owner-link'] = "mailto:".$contact['addr'];
543 $datarray['owner-avatar'] = $contact['photo'];
545 $datarray['uid'] = $importer_uid;
546 $datarray['contact-id'] = $contact['id'];
547 if ($datarray['parent-uri'] === $datarray['uri']) {
548 $datarray['private'] = 1;
550 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
551 $datarray['private'] = 1;
552 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
555 $stored_item = item_store($datarray);
557 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
558 dba::update('item', array('last-child' => false), $condition);
560 dba::update('item', array('last-child' => true), array('id' => $stored_item));
562 switch ($mailconf['action']) {
564 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
567 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
568 imap_delete($mbox, $msg_uid, FT_UID);
571 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
572 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
575 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
576 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
577 if ($mailconf['movetofolder'] != "") {
578 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
585 logger("Mail: no mails for ".$mailconf['user']);
588 logger("Mail: closing connection for ".$mailconf['user']);
594 logger('received xml : ' . $xml, LOGGER_DATA);
595 if (!strstr($xml, '<')) {
596 logger('post_handshake: response from ' . $url . ' did not contain XML.');
598 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
599 dba::update('contact', $fields, array('id' => $contact['id']));
600 Contact::markForArchival($contact);
605 logger("Consume feed of contact ".$contact['id']);
607 consume_feed($xml, $importer, $contact, $hub, 1, 1);
609 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
611 consume_feed($xml, $importer, $contact, $hub, 1, 2);
613 $hubmode = 'subscribe';
614 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
615 $hubmode = 'unsubscribe';
618 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
626 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
628 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
629 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
630 $hubs = explode(',', $hub);
632 foreach ($hubs as $h) {
637 subscribe_to_hub($h, $importer, $contact, $hubmode);
642 $updated = datetime_convert();
644 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
645 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
646 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
647 $updated = datetime_convert();
649 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
650 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
652 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
658 private static function RemoveReply($subject) {
659 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
660 $subject = trim(substr($subject, 4));