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\Protocol\PortableContact;
13 require_once 'include/follow.php';
17 public static function execute($contact_id = 0, $command = '') {
20 require_once 'include/datetime.php';
21 require_once 'include/items.php';
22 require_once 'include/Contact.php';
23 require_once 'include/email.php';
24 require_once 'include/queue_fn.php';
26 logger('onepoll: start');
34 if ($command == "force") {
39 logger('onepoll: no contact');
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 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
92 dba::update('contact', $fields, array('id' => $contact['id']));
94 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
102 $t = $contact['last-update'];
104 if ($contact['subhub']) {
105 $poll_interval = Config::get('system', 'pushpoll_frequency');
106 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
109 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
116 $last_update = (($contact['last-update'] <= NULL_DATE)
117 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
118 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
121 // Update the contact entry
122 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
123 if (!PortableContact::reachable($contact['url'])) {
124 logger("Skipping probably dead contact ".$contact['url']);
128 if (!update_contact($contact["id"])) {
129 mark_for_death($contact);
130 logger('Contact is marked dead');
133 unmark_for_death($contact);
137 if ($importer_uid == 0) {
138 logger('Ignore public contacts');
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);
153 logger("onepoll: poll: ({$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 = array('writable' => true);
171 dba::update('contact', $fields, array('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) {
185 $handshake_xml = $ret['body'];
187 $html_code = $a->get_curl_code();
189 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
192 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
193 logger("$url appears to be dead - marking for death ");
195 // dead connection - might be a transient event, or this might
196 // mean the software was uninstalled or the domain expired.
197 // Will keep trying for one month.
199 mark_for_death($contact);
201 // set the last-update so we don't keep polling
202 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
203 dba::update('contact', $fields, array('id' => $contact['id']));
208 if (!strstr($handshake_xml, '<')) {
209 logger('response from ' . $url . ' did not contain XML.');
211 mark_for_death($contact);
213 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
214 dba::update('contact', $fields, array('id' => $contact['id']));
220 $res = parse_xml_string($handshake_xml);
222 if (intval($res->status) == 1) {
223 logger("$url replied status 1 - marking for death ");
225 // we may not be friends anymore. Will keep trying for one month.
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']));
230 mark_for_death($contact);
231 } elseif ($contact['term-date'] > NULL_DATE) {
232 logger("$url back from the dead - removing mark for death");
233 unmark_for_death($contact);
236 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
240 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
241 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
242 dba::update('contact', $fields, array('id' => $contact['id']));
247 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
248 $challenge = hex2bin((string) $res->challenge);
252 if ($contact['duplex'] && strlen($contact['prvkey'])) {
253 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
254 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
256 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
257 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
260 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
262 if (strpos($final_dfrn_id, ':') == 1) {
263 $final_dfrn_id = substr($final_dfrn_id, 2);
266 if ($final_dfrn_id != $orig_id) {
267 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
268 // did not decode properly - cannot trust this site
272 $postvars['dfrn_id'] = $idtosend;
273 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
274 $postvars['perm'] = 'rw';
276 $xml = post_url($contact['poll'], $postvars);
278 } elseif (($contact['network'] === NETWORK_OSTATUS)
279 || ($contact['network'] === NETWORK_DIASPORA)
280 || ($contact['network'] === NETWORK_FEED)) {
282 // Upgrading DB fields from an older Friendica version
283 // Will only do this once per notify-enabled OStatus contact
284 // or if relationship changes
286 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
288 // Contacts from OStatus are always writable
289 if ($contact['network'] === NETWORK_OSTATUS) {
293 if ($stat_writeable != $contact['writable']) {
294 $fields = array('writable' => $stat_writeable);
295 dba::update('contact', $fields, array('id' => $contact['id']));
298 // Are we allowed to import from this person?
300 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
304 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
305 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
307 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
314 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
316 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
318 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
319 if ($mail_disabled) {
323 logger("Mail: Enabled", LOGGER_DEBUG);
326 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
328 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
329 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
330 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
331 $mailbox = construct_mailbox_name($mailconf);
333 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
334 $mbox = email_connect($mailbox, $mailconf['user'], $password);
336 logger("Mail: Connect to " . $mailconf['user']);
338 $fields = array('last_check' => datetime_convert());
339 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
340 logger("Mail: Connected to " . $mailconf['user']);
342 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
347 $msgs = email_poll($mbox, $contact['addr']);
350 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
352 $metas = email_msg_meta($mbox,implode(',', $msgs));
353 if (count($metas) != count($msgs)) {
354 logger("onepoll: for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
356 $msgs = array_combine($msgs, $metas);
358 foreach ($msgs as $msg_uid => $meta) {
359 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
362 $datarray['verb'] = ACTIVITY_POST;
363 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
364 // $meta = email_msg_meta($mbox, $msg_uid);
365 // $headers = email_msg_headers($mbox, $msg_uid);
367 $datarray['uri'] = msgid2iri(trim($meta->message_id, '<>'));
369 // Have we seen it before?
370 $fields = array('deleted', 'id');
371 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
372 $r = dba::select('item', $fields, $condition, array('limit' => 1));
374 if (DBM::is_result($r)) {
375 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
377 // Only delete when mails aren't automatically moved or deleted
378 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
379 if ($meta->deleted && ! $r['deleted']) {
380 $fields = array('deleted' => true, 'changed' => datetime_convert());
381 dba::update('item', $fields, array('id' => $r['id']));
384 switch ($mailconf['action']) {
386 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
389 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
390 imap_delete($mbox, $msg_uid, FT_UID);
393 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
394 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
397 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
398 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
399 if ($mailconf['movetofolder'] != "") {
400 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
408 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
409 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
410 if (!trim($raw_refs)) {
411 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
413 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
416 $refs_arr = explode(' ', $raw_refs);
417 if (count($refs_arr)) {
418 for ($x = 0; $x < count($refs_arr); $x ++) {
419 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
422 $qstr = implode(',', $refs_arr);
423 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
424 intval($importer_uid)
426 if (DBM::is_result($r)) {
427 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
431 // Decoding the header
432 $subject = imap_mime_header_decode($meta->subject);
433 $datarray['title'] = "";
434 foreach ($subject as $subpart) {
435 if ($subpart->charset != "default") {
436 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
438 $datarray['title'] .= $subpart->text;
441 $datarray['title'] = notags(trim($datarray['title']));
443 //$datarray['title'] = notags(trim($meta->subject));
444 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
447 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
448 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
451 // Remove Reply-signs in the subject
452 $datarray['title'] = self::RemoveReply($datarray['title']);
454 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
455 if (empty($datarray['parent-uri']) && $reply) {
456 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
457 dbesc(protect_sprintf($datarray['title'])),
458 intval($importer_uid),
459 dbesc(NETWORK_MAIL));
460 if (DBM::is_result($r)) {
461 $datarray['parent-uri'] = $r[0]['parent-uri'];
465 if (empty($datarray['parent-uri'])) {
466 $datarray['parent-uri'] = $datarray['uri'];
469 $r = email_get_msg($mbox, $msg_uid, $reply);
471 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
474 $datarray['body'] = escape_tags($r['body']);
475 $datarray['body'] = limit_body_size($datarray['body']);
477 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
479 /// @TODO Adding a gravatar for the original author would be cool
481 $from = imap_mime_header_decode($meta->from);
483 foreach ($from as $frompart) {
484 if ($frompart->charset != "default") {
485 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
487 $fromdecoded .= $frompart->text;
491 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
493 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
495 if (isset($fromarr[0]->personal)) {
496 $fromname = $fromarr[0]->personal;
498 $fromname = $frommail;
501 $datarray['author-name'] = $fromname;
502 $datarray['author-link'] = "mailto:".$frommail;
503 $datarray['author-avatar'] = $contact['photo'];
505 $datarray['owner-name'] = $contact['name'];
506 $datarray['owner-link'] = "mailto:".$contact['addr'];
507 $datarray['owner-avatar'] = $contact['photo'];
509 $datarray['uid'] = $importer_uid;
510 $datarray['contact-id'] = $contact['id'];
511 if ($datarray['parent-uri'] === $datarray['uri']) {
512 $datarray['private'] = 1;
514 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
515 $datarray['private'] = 1;
516 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
519 $stored_item = item_store($datarray);
521 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
522 dba::update('item', array('last-child' => false), $condition);
524 dba::update('item', array('last-child' => true), array('id' => $stored_item));
526 switch ($mailconf['action']) {
528 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
531 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
532 imap_delete($mbox, $msg_uid, FT_UID);
535 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
536 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
539 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
540 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
541 if ($mailconf['movetofolder'] != "") {
542 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
549 logger("Mail: no mails for ".$mailconf['user']);
552 logger("Mail: closing connection for ".$mailconf['user']);
558 logger('received xml : ' . $xml, LOGGER_DATA);
559 if (!strstr($xml, '<')) {
560 logger('post_handshake: response from ' . $url . ' did not contain XML.');
562 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
563 dba::update('contact', $fields, array('id' => $contact['id']));
569 logger("Consume feed of contact ".$contact['id']);
571 consume_feed($xml, $importer, $contact, $hub, 1, 1);
573 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
575 consume_feed($xml, $importer, $contact, $hub, 1, 2);
577 $hubmode = 'subscribe';
578 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
579 $hubmode = 'unsubscribe';
582 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
590 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
592 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
593 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
594 $hubs = explode(',', $hub);
596 foreach ($hubs as $h) {
601 subscribe_to_hub($h, $importer, $contact, $hubmode);
606 $updated = datetime_convert();
608 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
609 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
610 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
611 $updated = datetime_convert();
613 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
614 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
616 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
622 private static function RemoveReply($subject) {
623 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
624 $subject = trim(substr($subject, 4));