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\PortableContact;
14 require_once 'include/follow.php';
18 public static function execute($contact_id = 0, $command = '') {
21 require_once 'include/datetime.php';
22 require_once 'include/items.php';
23 require_once 'include/Contact.php';
24 require_once 'include/email.php';
25 require_once 'include/queue_fn.php';
27 logger('onepoll: start');
35 if ($command == "force") {
40 logger('onepoll: no contact');
44 $d = datetime_convert();
46 // Only poll from those with suitable relationships,
47 // and which have a polling address and ignore Diaspora since
48 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
50 $contacts = q("SELECT `contact`.* FROM `contact`
51 WHERE (`rel` = %d OR `rel` = %d) AND `poll` != ''
52 AND NOT `network` IN ('%s', '%s')
53 AND `contact`.`id` = %d
54 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
55 AND `contact`.`archive` = 0 LIMIT 1",
56 intval(CONTACT_IS_SHARING),
57 intval(CONTACT_IS_FRIEND),
58 dbesc(NETWORK_FACEBOOK),
59 dbesc(NETWORK_PUMPIO),
63 if (!count($contacts)) {
64 logger('Contact not found or cannot be used.');
68 $contact = $contacts[0];
70 $importer_uid = $contact['uid'];
72 // load current friends if possible.
73 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
74 $r = q("SELECT count(*) AS total FROM glink
75 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
76 intval($contact['id'])
78 if (DBM::is_result($r)) {
79 if (!$r[0]['total']) {
80 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
85 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
86 /// @TODO Check whether this is possible with Redmatrix
87 if ($contact["network"] == NETWORK_DIASPORA) {
88 if (PortableContact::updateNeeded($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
89 $last_updated = PortableContact::lastUpdated($contact["url"]);
90 $updated = datetime_convert();
92 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
93 dba::update('contact', $fields, array('id' => $contact['id']));
95 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
103 $t = $contact['last-update'];
105 if ($contact['subhub']) {
106 $poll_interval = Config::get('system', 'pushpoll_frequency');
107 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
110 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
117 $last_update = (($contact['last-update'] <= NULL_DATE)
118 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
119 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
122 // Update the contact entry
123 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
124 if (!PortableContact::reachable($contact['url'])) {
125 logger("Skipping probably dead contact ".$contact['url']);
129 if (!update_contact($contact["id"])) {
130 mark_for_death($contact);
131 logger('Contact is marked dead');
134 unmark_for_death($contact);
138 if ($importer_uid == 0) {
139 logger('Ignore public contacts');
143 $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",
144 intval($importer_uid)
147 if (!DBM::is_result($r)) {
148 logger('No self contact for user '.$importer_uid);
154 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
156 if ($contact['network'] === NETWORK_DFRN) {
157 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
158 if (intval($contact['duplex']) && $contact['dfrn-id']) {
159 $idtosend = '0:' . $orig_id;
161 if (intval($contact['duplex']) && $contact['issued-id']) {
162 $idtosend = '1:' . $orig_id;
165 // they have permission to write to us. We already filtered this in the contact query.
168 // But this may be our first communication, so set the writable flag if it isn't set already.
170 if (!intval($contact['writable'])) {
171 $fields = array('writable' => true);
172 dba::update('contact', $fields, array('id' => $contact['id']));
175 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
176 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
177 . '&type=data&last_update=' . $last_update
180 $ret = z_fetch_url($url);
182 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
186 $handshake_xml = $ret['body'];
188 $html_code = $a->get_curl_code();
190 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
193 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
194 logger("poller: $url appears to be dead - marking for death ");
196 // dead connection - might be a transient event, or this might
197 // mean the software was uninstalled or the domain expired.
198 // Will keep trying for one month.
200 mark_for_death($contact);
202 // set the last-update so we don't keep polling
203 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
204 dba::update('contact', $fields, array('id' => $contact['id']));
209 if (!strstr($handshake_xml, '<')) {
210 logger('poller: response from ' . $url . ' did not contain XML.');
212 mark_for_death($contact);
214 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
215 dba::update('contact', $fields, array('id' => $contact['id']));
221 $res = parse_xml_string($handshake_xml);
223 if (intval($res->status) == 1) {
224 logger("poller: $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 = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
229 dba::update('contact', $fields, array('id' => $contact['id']));
231 mark_for_death($contact);
232 } elseif ($contact['term-date'] > NULL_DATE) {
233 logger("poller: $url back from the dead - removing mark for death");
234 unmark_for_death($contact);
237 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
241 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
242 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
243 dba::update('contact', $fields, array('id' => $contact['id']));
248 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
249 $challenge = hex2bin((string) $res->challenge);
253 if ($contact['duplex'] && strlen($contact['prvkey'])) {
254 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
255 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
257 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
258 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
261 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
263 if (strpos($final_dfrn_id, ':') == 1) {
264 $final_dfrn_id = substr($final_dfrn_id, 2);
267 if ($final_dfrn_id != $orig_id) {
268 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
269 // did not decode properly - cannot trust this site
273 $postvars['dfrn_id'] = $idtosend;
274 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
275 $postvars['perm'] = 'rw';
277 $xml = post_url($contact['poll'], $postvars);
279 } elseif (($contact['network'] === NETWORK_OSTATUS)
280 || ($contact['network'] === NETWORK_DIASPORA)
281 || ($contact['network'] === NETWORK_FEED)) {
283 // Upgrading DB fields from an older Friendica version
284 // Will only do this once per notify-enabled OStatus contact
285 // or if relationship changes
287 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
289 // Contacts from OStatus are always writable
290 if ($contact['network'] === NETWORK_OSTATUS) {
294 if ($stat_writeable != $contact['writable']) {
295 $fields = array('writable' => $stat_writeable);
296 dba::update('contact', $fields, array('id' => $contact['id']));
299 // Are we allowed to import from this person?
301 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
305 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
306 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
308 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
315 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
317 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
319 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
320 if ($mail_disabled) {
324 logger("Mail: Enabled", LOGGER_DEBUG);
327 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
329 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
330 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
331 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
332 $mailbox = construct_mailbox_name($mailconf);
334 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
335 $mbox = email_connect($mailbox, $mailconf['user'], $password);
337 logger("Mail: Connect to " . $mailconf['user']);
339 $fields = array('last_check' => datetime_convert());
340 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
341 logger("Mail: Connected to " . $mailconf['user']);
343 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
348 $msgs = email_poll($mbox, $contact['addr']);
351 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
353 $metas = email_msg_meta($mbox,implode(',', $msgs));
354 if (count($metas) != count($msgs)) {
355 logger("onepoll: for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
357 $msgs = array_combine($msgs, $metas);
359 foreach ($msgs as $msg_uid => $meta) {
360 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
363 $datarray['verb'] = ACTIVITY_POST;
364 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
365 // $meta = email_msg_meta($mbox, $msg_uid);
366 // $headers = email_msg_headers($mbox, $msg_uid);
368 $datarray['uri'] = msgid2iri(trim($meta->message_id, '<>'));
370 // Have we seen it before?
371 $fields = array('deleted', 'id');
372 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
373 $r = dba::select('item', $fields, $condition, array('limit' => 1));
375 if (DBM::is_result($r)) {
376 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
378 // Only delete when mails aren't automatically moved or deleted
379 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
380 if ($meta->deleted && ! $r['deleted']) {
381 $fields = array('deleted' => true, 'changed' => datetime_convert());
382 dba::update('item', $fields, array('id' => $r['id']));
385 switch ($mailconf['action']) {
387 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
390 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
391 imap_delete($mbox, $msg_uid, FT_UID);
394 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
395 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
398 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
399 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
400 if ($mailconf['movetofolder'] != "") {
401 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
409 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
410 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
411 if (!trim($raw_refs)) {
412 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
414 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
417 $refs_arr = explode(' ', $raw_refs);
418 if (count($refs_arr)) {
419 for ($x = 0; $x < count($refs_arr); $x ++) {
420 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
423 $qstr = implode(',', $refs_arr);
424 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
425 intval($importer_uid)
427 if (DBM::is_result($r)) {
428 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
432 // Decoding the header
433 $subject = imap_mime_header_decode($meta->subject);
434 $datarray['title'] = "";
435 foreach ($subject as $subpart) {
436 if ($subpart->charset != "default") {
437 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
439 $datarray['title'] .= $subpart->text;
442 $datarray['title'] = notags(trim($datarray['title']));
444 //$datarray['title'] = notags(trim($meta->subject));
445 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
448 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
449 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
452 // Remove Reply-signs in the subject
453 $datarray['title'] = self::RemoveReply($datarray['title']);
455 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
456 if (empty($datarray['parent-uri']) && $reply) {
457 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
458 dbesc(protect_sprintf($datarray['title'])),
459 intval($importer_uid),
460 dbesc(NETWORK_MAIL));
461 if (DBM::is_result($r)) {
462 $datarray['parent-uri'] = $r[0]['parent-uri'];
466 if (empty($datarray['parent-uri'])) {
467 $datarray['parent-uri'] = $datarray['uri'];
470 $r = email_get_msg($mbox, $msg_uid, $reply);
472 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
475 $datarray['body'] = escape_tags($r['body']);
476 $datarray['body'] = limit_body_size($datarray['body']);
478 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
480 /// @TODO Adding a gravatar for the original author would be cool
482 $from = imap_mime_header_decode($meta->from);
484 foreach ($from as $frompart) {
485 if ($frompart->charset != "default") {
486 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
488 $fromdecoded .= $frompart->text;
492 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
494 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
496 if (isset($fromarr[0]->personal)) {
497 $fromname = $fromarr[0]->personal;
499 $fromname = $frommail;
502 $datarray['author-name'] = $fromname;
503 $datarray['author-link'] = "mailto:".$frommail;
504 $datarray['author-avatar'] = $contact['photo'];
506 $datarray['owner-name'] = $contact['name'];
507 $datarray['owner-link'] = "mailto:".$contact['addr'];
508 $datarray['owner-avatar'] = $contact['photo'];
510 $datarray['uid'] = $importer_uid;
511 $datarray['contact-id'] = $contact['id'];
512 if ($datarray['parent-uri'] === $datarray['uri']) {
513 $datarray['private'] = 1;
515 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
516 $datarray['private'] = 1;
517 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
520 $stored_item = item_store($datarray);
522 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
523 dba::update('item', array('last-child' => false), $condition);
525 dba::update('item', array('last-child' => true), array('id' => $stored_item));
527 switch ($mailconf['action']) {
529 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
532 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
533 imap_delete($mbox, $msg_uid, FT_UID);
536 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
537 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
540 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
541 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
542 if ($mailconf['movetofolder'] != "") {
543 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
550 logger("Mail: no mails for ".$mailconf['user']);
553 logger("Mail: closing connection for ".$mailconf['user']);
559 logger('poller: received xml : ' . $xml, LOGGER_DATA);
560 if (!strstr($xml, '<')) {
561 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
563 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
564 dba::update('contact', $fields, array('id' => $contact['id']));
570 logger("Consume feed of contact ".$contact['id']);
572 consume_feed($xml, $importer, $contact, $hub, 1, 1);
574 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
576 consume_feed($xml, $importer, $contact, $hub, 1, 2);
578 $hubmode = 'subscribe';
579 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
580 $hubmode = 'unsubscribe';
583 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
591 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
593 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
594 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
595 $hubs = explode(',', $hub);
597 foreach ($hubs as $h) {
602 subscribe_to_hub($h, $importer, $contact, $hubmode);
607 $updated = datetime_convert();
609 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
610 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
611 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
612 $updated = datetime_convert();
614 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
615 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
617 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
623 private static function RemoveReply($subject) {
624 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
625 $subject = trim(substr($subject, 4));