3 use Friendica\Core\Config;
4 use Friendica\Core\PConfig;
5 use Friendica\Database\DBM;
7 require_once 'include/follow.php';
9 function RemoveReply($subject) {
10 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
11 $subject = trim(substr($subject, 4));
17 function onepoll_run(&$argv, &$argc) {
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/socgraph.php';
25 require_once 'include/queue_fn.php';
27 logger('onepoll: start');
35 if (($argc > 1) && (intval($argv[1]))) {
36 $contact_id = intval($argv[1]);
39 if (($argc > 2) && ($argv[2] == "force")) {
44 logger('onepoll: no contact');
48 $d = datetime_convert();
50 // Only poll from those with suitable relationships,
51 // and which have a polling address and ignore Diaspora since
52 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
54 $contacts = q("SELECT `contact`.* FROM `contact`
55 WHERE (`rel` = %d OR `rel` = %d) AND `poll` != ''
56 AND NOT `network` IN ('%s', '%s')
57 AND `contact`.`id` = %d
58 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
59 AND `contact`.`archive` = 0 LIMIT 1",
60 intval(CONTACT_IS_SHARING),
61 intval(CONTACT_IS_FRIEND),
62 dbesc(NETWORK_FACEBOOK),
63 dbesc(NETWORK_PUMPIO),
67 if (!count($contacts)) {
68 logger('Contact not found or cannot be used.');
72 $contact = $contacts[0];
74 $importer_uid = $contact['uid'];
76 // load current friends if possible.
77 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
78 $r = q("SELECT count(*) AS total FROM glink
79 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
80 intval($contact['id'])
82 if (DBM::is_result($r)) {
83 if (!$r[0]['total']) {
84 poco_load($contact['id'], $importer_uid, 0, $contact['poco']);
89 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
90 /// @TODO Check whether this is possible with Redmatrix
91 if ($contact["network"] == NETWORK_DIASPORA) {
92 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
93 $last_updated = poco_last_updated($contact["url"]);
94 $updated = datetime_convert();
96 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
97 dba::update('contact', $fields, array('id' => $contact['id']));
99 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
107 $t = $contact['last-update'];
109 if ($contact['subhub']) {
110 $poll_interval = Config::get('system', 'pushpoll_frequency');
111 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
114 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
121 $last_update = (($contact['last-update'] <= NULL_DATE)
122 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
123 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
126 // Update the contact entry
127 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
128 if (!poco_reachable($contact['url'])) {
129 logger("Skipping probably dead contact ".$contact['url']);
133 if (!update_contact($contact["id"])) {
134 mark_for_death($contact);
135 logger('Contact is marked dead');
138 unmark_for_death($contact);
142 if ($importer_uid == 0) {
143 logger('Ignore public contacts');
147 $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",
148 intval($importer_uid)
151 if (!DBM::is_result($r)) {
152 logger('No self contact for user '.$importer_uid);
158 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
160 if ($contact['network'] === NETWORK_DFRN) {
161 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
162 if (intval($contact['duplex']) && $contact['dfrn-id']) {
163 $idtosend = '0:' . $orig_id;
165 if (intval($contact['duplex']) && $contact['issued-id']) {
166 $idtosend = '1:' . $orig_id;
169 // they have permission to write to us. We already filtered this in the contact query.
172 // But this may be our first communication, so set the writable flag if it isn't set already.
174 if (!intval($contact['writable'])) {
175 $fields = array('writable' => true);
176 dba::update('contact', $fields, array('id' => $contact['id']));
179 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
180 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
181 . '&type=data&last_update=' . $last_update
184 $ret = z_fetch_url($url);
186 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
190 $handshake_xml = $ret['body'];
192 $html_code = $a->get_curl_code();
194 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
197 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
198 logger("poller: $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 mark_for_death($contact);
206 // set the last-update so we don't keep polling
207 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
208 dba::update('contact', $fields, array('id' => $contact['id']));
213 if (! strstr($handshake_xml, '<')) {
214 logger('poller: response from ' . $url . ' did not contain XML.');
216 mark_for_death($contact);
218 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
219 dba::update('contact', $fields, array('id' => $contact['id']));
225 $res = parse_xml_string($handshake_xml);
227 if (intval($res->status) == 1) {
228 logger("poller: $url replied status 1 - marking for death ");
230 // we may not be friends anymore. Will keep trying for one month.
231 // set the last-update so we don't keep polling
232 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
233 dba::update('contact', $fields, array('id' => $contact['id']));
235 mark_for_death($contact);
236 } elseif ($contact['term-date'] > NULL_DATE) {
237 logger("poller: $url back from the dead - removing mark for death");
238 unmark_for_death($contact);
241 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_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 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
273 // did not decode properly - cannot trust this site
277 $postvars['dfrn_id'] = $idtosend;
278 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
279 $postvars['perm'] = 'rw';
281 $xml = post_url($contact['poll'], $postvars);
283 } elseif (($contact['network'] === NETWORK_OSTATUS)
284 || ($contact['network'] === NETWORK_DIASPORA)
285 || ($contact['network'] === NETWORK_FEED)) {
287 // Upgrading DB fields from an older Friendica version
288 // Will only do this once per notify-enabled OStatus contact
289 // or if relationship changes
291 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
293 // Contacts from OStatus are always writable
294 if ($contact['network'] === NETWORK_OSTATUS) {
298 if ($stat_writeable != $contact['writable']) {
299 $fields = array('writable' => $stat_writeable);
300 dba::update('contact', $fields, array('id' => $contact['id']));
303 // Are we allowed to import from this person?
305 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
309 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
310 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
312 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
319 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
321 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
323 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
324 if ($mail_disabled) {
328 logger("Mail: Enabled", LOGGER_DEBUG);
331 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
333 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
334 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
335 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
336 $mailbox = construct_mailbox_name($mailconf);
338 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
339 $mbox = email_connect($mailbox, $mailconf['user'], $password);
341 logger("Mail: Connect to " . $mailconf['user']);
343 $fields = array('last_check' => datetime_convert());
344 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
345 logger("Mail: Connected to " . $mailconf['user']);
347 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
352 $msgs = email_poll($mbox, $contact['addr']);
355 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
357 $metas = email_msg_meta($mbox,implode(',', $msgs));
358 if (count($metas) != count($msgs)) {
359 logger("onepoll: for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
361 $msgs = array_combine($msgs, $metas);
363 foreach ($msgs as $msg_uid => $meta) {
364 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
367 $datarray['verb'] = ACTIVITY_POST;
368 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
369 // $meta = email_msg_meta($mbox, $msg_uid);
370 // $headers = email_msg_headers($mbox, $msg_uid);
372 $datarray['uri'] = msgid2iri(trim($meta->message_id, '<>'));
374 // Have we seen it before?
375 $fields = array('deleted', 'id');
376 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
377 $r = dba::select('item', $fields, $condition, array('limit' => 1));
379 if (DBM::is_result($r)) {
380 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
382 // Only delete when mails aren't automatically moved or deleted
383 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
384 if ($meta->deleted && ! $r['deleted']) {
385 $fields = array('deleted' => true, 'changed' => datetime_convert());
386 dba::update('item', $fields, array('id' => $r['id']));
389 switch ($mailconf['action']) {
391 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
394 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
395 imap_delete($mbox, $msg_uid, FT_UID);
398 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
399 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
402 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
403 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
404 if ($mailconf['movetofolder'] != "") {
405 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
413 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
414 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
415 if (! trim($raw_refs)) {
416 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
418 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
421 $refs_arr = explode(' ', $raw_refs);
422 if (count($refs_arr)) {
423 for ($x = 0; $x < count($refs_arr); $x ++) {
424 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
427 $qstr = implode(',', $refs_arr);
428 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
429 intval($importer_uid)
431 if (DBM::is_result($r)) {
432 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
436 // Decoding the header
437 $subject = imap_mime_header_decode($meta->subject);
438 $datarray['title'] = "";
439 foreach ($subject as $subpart) {
440 if ($subpart->charset != "default") {
441 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
443 $datarray['title'] .= $subpart->text;
446 $datarray['title'] = notags(trim($datarray['title']));
448 //$datarray['title'] = notags(trim($meta->subject));
449 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
452 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
453 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
456 // Remove Reply-signs in the subject
457 $datarray['title'] = RemoveReply($datarray['title']);
459 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
460 if (empty($datarray['parent-uri']) && $reply) {
461 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
462 dbesc(protect_sprintf($datarray['title'])),
463 intval($importer_uid),
464 dbesc(NETWORK_MAIL));
465 if (DBM::is_result($r)) {
466 $datarray['parent-uri'] = $r[0]['parent-uri'];
470 if (empty($datarray['parent-uri'])) {
471 $datarray['parent-uri'] = $datarray['uri'];
474 $r = email_get_msg($mbox, $msg_uid, $reply);
476 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
479 $datarray['body'] = escape_tags($r['body']);
480 $datarray['body'] = limit_body_size($datarray['body']);
482 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
484 /// @TODO Adding a gravatar for the original author would be cool
486 $from = imap_mime_header_decode($meta->from);
488 foreach ($from as $frompart) {
489 if ($frompart->charset != "default") {
490 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
492 $fromdecoded .= $frompart->text;
496 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
498 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
500 if (isset($fromarr[0]->personal)) {
501 $fromname = $fromarr[0]->personal;
503 $fromname = $frommail;
506 $datarray['author-name'] = $fromname;
507 $datarray['author-link'] = "mailto:".$frommail;
508 $datarray['author-avatar'] = $contact['photo'];
510 $datarray['owner-name'] = $contact['name'];
511 $datarray['owner-link'] = "mailto:".$contact['addr'];
512 $datarray['owner-avatar'] = $contact['photo'];
514 $datarray['uid'] = $importer_uid;
515 $datarray['contact-id'] = $contact['id'];
516 if ($datarray['parent-uri'] === $datarray['uri']) {
517 $datarray['private'] = 1;
519 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
520 $datarray['private'] = 1;
521 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
524 $stored_item = item_store($datarray);
526 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
527 dba::update('item', array('last-child' => false), $condition);
529 dba::update('item', array('last-child' => true), array('id' => $stored_item));
531 switch ($mailconf['action']) {
533 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
536 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
537 imap_delete($mbox, $msg_uid, FT_UID);
540 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
541 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
544 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
545 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
546 if ($mailconf['movetofolder'] != "") {
547 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
554 logger("Mail: no mails for ".$mailconf['user']);
557 logger("Mail: closing connection for ".$mailconf['user']);
563 logger('poller: received xml : ' . $xml, LOGGER_DATA);
564 if (!strstr($xml, '<')) {
565 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
567 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
568 dba::update('contact', $fields, array('id' => $contact['id']));
574 logger("Consume feed of contact ".$contact['id']);
576 consume_feed($xml, $importer, $contact, $hub, 1, 1);
578 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
580 consume_feed($xml, $importer, $contact, $hub, 1, 2);
582 $hubmode = 'subscribe';
583 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
584 $hubmode = 'unsubscribe';
587 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
595 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
597 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
598 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
599 $hubs = explode(',', $hub);
601 foreach ($hubs as $h) {
606 subscribe_to_hub($h, $importer, $contact, $hubmode);
611 $updated = datetime_convert();
613 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
614 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
615 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
616 $updated = datetime_convert();
618 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
619 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
621 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));