3 use Friendica\Core\Config;
4 use Friendica\Core\PConfig;
6 require_once 'include/follow.php';
8 function RemoveReply($subject) {
9 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
10 $subject = trim(substr($subject, 4));
16 function onepoll_run(&$argv, &$argc) {
19 require_once 'include/datetime.php';
20 require_once 'include/items.php';
21 require_once 'include/Contact.php';
22 require_once 'include/email.php';
23 require_once 'include/socgraph.php';
24 require_once 'include/queue_fn.php';
26 logger('onepoll: start');
34 if (($argc > 1) && (intval($argv[1]))) {
35 $contact_id = intval($argv[1]);
38 if (($argc > 2) && ($argv[2] == "force")) {
43 logger('onepoll: no contact');
47 $d = datetime_convert();
49 // Only poll from those with suitable relationships,
50 // and which have a polling address and ignore Diaspora since
51 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
53 $contacts = q("SELECT `contact`.* FROM `contact`
54 WHERE (`rel` = %d OR `rel` = %d) AND `poll` != ''
55 AND NOT `network` IN ('%s', '%s')
56 AND `contact`.`id` = %d
57 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
58 AND `contact`.`archive` = 0 LIMIT 1",
59 intval(CONTACT_IS_SHARING),
60 intval(CONTACT_IS_FRIEND),
61 dbesc(NETWORK_FACEBOOK),
62 dbesc(NETWORK_PUMPIO),
66 if (!count($contacts)) {
67 logger('Contact not found or cannot be used.');
71 $contact = $contacts[0];
73 $importer_uid = $contact['uid'];
75 // load current friends if possible.
76 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
77 $r = q("SELECT count(*) AS total FROM glink
78 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
79 intval($contact['id'])
81 if (dbm::is_result($r)) {
82 if (!$r[0]['total']) {
83 poco_load($contact['id'], $importer_uid, 0, $contact['poco']);
88 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
89 /// @TODO Check whether this is possible with Redmatrix
90 if ($contact["network"] == NETWORK_DIASPORA) {
91 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
92 $last_updated = poco_last_updated($contact["url"]);
93 $updated = datetime_convert();
95 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
96 dba::update('contact', $fields, array('id' => $contact['id']));
98 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
106 $t = $contact['last-update'];
108 if ($contact['subhub']) {
109 $poll_interval = Config::get('system', 'pushpoll_frequency');
110 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
113 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
120 $last_update = (($contact['last-update'] <= NULL_DATE)
121 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
122 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
125 // Update the contact entry
126 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
127 if (!poco_reachable($contact['url'])) {
128 logger("Skipping probably dead contact ".$contact['url']);
132 if (!update_contact($contact["id"])) {
133 mark_for_death($contact);
134 logger('Contact is marked dead');
137 unmark_for_death($contact);
141 if ($importer_uid == 0) {
142 logger('Ignore public contacts');
146 $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",
147 intval($importer_uid)
150 if (!dbm::is_result($r)) {
151 logger('No self contact for user '.$importer_uid);
157 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
159 if ($contact['network'] === NETWORK_DFRN) {
160 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
161 if (intval($contact['duplex']) && $contact['dfrn-id']) {
162 $idtosend = '0:' . $orig_id;
164 if (intval($contact['duplex']) && $contact['issued-id']) {
165 $idtosend = '1:' . $orig_id;
168 // they have permission to write to us. We already filtered this in the contact query.
171 // But this may be our first communication, so set the writable flag if it isn't set already.
173 if (!intval($contact['writable'])) {
174 $fields = array('writable' => true);
175 dba::update('contact', $fields, array('id' => $contact['id']));
178 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
179 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
180 . '&type=data&last_update=' . $last_update
183 $ret = z_fetch_url($url);
185 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
189 $handshake_xml = $ret['body'];
191 $html_code = $a->get_curl_code();
193 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
196 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
197 logger("poller: $url appears to be dead - marking for death ");
199 // dead connection - might be a transient event, or this might
200 // mean the software was uninstalled or the domain expired.
201 // Will keep trying for one month.
203 mark_for_death($contact);
205 // set the last-update so we don't keep polling
206 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
207 dba::update('contact', $fields, array('id' => $contact['id']));
212 if (! strstr($handshake_xml, '<')) {
213 logger('poller: response from ' . $url . ' did not contain XML.');
215 mark_for_death($contact);
217 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
218 dba::update('contact', $fields, array('id' => $contact['id']));
224 $res = parse_xml_string($handshake_xml);
226 if (intval($res->status) == 1) {
227 logger("poller: $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 mark_for_death($contact);
235 } elseif ($contact['term-date'] > NULL_DATE) {
236 logger("poller: $url back from the dead - removing mark for death");
237 unmark_for_death($contact);
240 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
244 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
245 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
246 dba::update('contact', $fields, array('id' => $contact['id']));
251 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
252 $challenge = hex2bin((string) $res->challenge);
256 if ($contact['duplex'] && strlen($contact['prvkey'])) {
257 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
258 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
260 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
261 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
264 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
266 if (strpos($final_dfrn_id, ':') == 1) {
267 $final_dfrn_id = substr($final_dfrn_id, 2);
270 if ($final_dfrn_id != $orig_id) {
271 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
272 // did not decode properly - cannot trust this site
276 $postvars['dfrn_id'] = $idtosend;
277 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
278 $postvars['perm'] = 'rw';
280 $xml = post_url($contact['poll'], $postvars);
282 } elseif (($contact['network'] === NETWORK_OSTATUS)
283 || ($contact['network'] === NETWORK_DIASPORA)
284 || ($contact['network'] === NETWORK_FEED)) {
286 // Upgrading DB fields from an older Friendica version
287 // Will only do this once per notify-enabled OStatus contact
288 // or if relationship changes
290 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
292 // Contacts from OStatus are always writable
293 if ($contact['network'] === NETWORK_OSTATUS) {
297 if ($stat_writeable != $contact['writable']) {
298 $fields = array('writable' => $stat_writeable);
299 dba::update('contact', $fields, array('id' => $contact['id']));
302 // Are we allowed to import from this person?
304 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
308 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
309 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
311 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
318 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
320 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
322 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
323 if ($mail_disabled) {
327 logger("Mail: Enabled", LOGGER_DEBUG);
330 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
332 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
333 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
334 if (dbm::is_result($x) && dbm::is_result($mailconf)) {
335 $mailbox = construct_mailbox_name($mailconf);
337 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
338 $mbox = email_connect($mailbox, $mailconf['user'], $password);
340 logger("Mail: Connect to " . $mailconf['user']);
342 $fields = array('last_check' => datetime_convert());
343 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
344 logger("Mail: Connected to " . $mailconf['user']);
346 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
351 $msgs = email_poll($mbox, $contact['addr']);
354 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
356 $metas = email_msg_meta($mbox,implode(',', $msgs));
357 if (count($metas) != count($msgs)) {
358 logger("onepoll: for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
360 $msgs = array_combine($msgs, $metas);
362 foreach ($msgs as $msg_uid => $meta) {
363 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
366 $datarray['verb'] = ACTIVITY_POST;
367 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
368 // $meta = email_msg_meta($mbox, $msg_uid);
369 // $headers = email_msg_headers($mbox, $msg_uid);
371 $datarray['uri'] = msgid2iri(trim($meta->message_id, '<>'));
373 // Have we seen it before?
374 $fields = array('deleted', 'id');
375 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
376 $r = dba::select('item', $fields, $condition, array('limit' => 1));
378 if (dbm::is_result($r)) {
379 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
381 // Only delete when mails aren't automatically moved or deleted
382 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
383 if ($meta->deleted && ! $r['deleted']) {
384 $fields = array('deleted' => true, 'changed' => datetime_convert());
385 dba::update('item', $fields, array('id' => $r['id']));
388 switch ($mailconf['action']) {
390 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
393 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
394 imap_delete($mbox, $msg_uid, FT_UID);
397 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
398 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
401 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
402 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
403 if ($mailconf['movetofolder'] != "") {
404 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
412 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
413 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
414 if (! trim($raw_refs)) {
415 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
417 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
420 $refs_arr = explode(' ', $raw_refs);
421 if (count($refs_arr)) {
422 for ($x = 0; $x < count($refs_arr); $x ++) {
423 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
426 $qstr = implode(',', $refs_arr);
427 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
428 intval($importer_uid)
430 if (dbm::is_result($r)) {
431 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
435 // Decoding the header
436 $subject = imap_mime_header_decode($meta->subject);
437 $datarray['title'] = "";
438 foreach ($subject as $subpart) {
439 if ($subpart->charset != "default") {
440 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
442 $datarray['title'] .= $subpart->text;
445 $datarray['title'] = notags(trim($datarray['title']));
447 //$datarray['title'] = notags(trim($meta->subject));
448 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
451 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
452 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
455 // Remove Reply-signs in the subject
456 $datarray['title'] = RemoveReply($datarray['title']);
458 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
459 if (empty($datarray['parent-uri']) && $reply) {
460 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
461 dbesc(protect_sprintf($datarray['title'])),
462 intval($importer_uid),
463 dbesc(NETWORK_MAIL));
464 if (dbm::is_result($r)) {
465 $datarray['parent-uri'] = $r[0]['parent-uri'];
469 if (empty($datarray['parent-uri'])) {
470 $datarray['parent-uri'] = $datarray['uri'];
473 $r = email_get_msg($mbox, $msg_uid, $reply);
475 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
478 $datarray['body'] = escape_tags($r['body']);
479 $datarray['body'] = limit_body_size($datarray['body']);
481 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
483 /// @TODO Adding a gravatar for the original author would be cool
485 $from = imap_mime_header_decode($meta->from);
487 foreach ($from as $frompart) {
488 if ($frompart->charset != "default") {
489 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
491 $fromdecoded .= $frompart->text;
495 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
497 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
499 if (isset($fromarr[0]->personal)) {
500 $fromname = $fromarr[0]->personal;
502 $fromname = $frommail;
505 $datarray['author-name'] = $fromname;
506 $datarray['author-link'] = "mailto:".$frommail;
507 $datarray['author-avatar'] = $contact['photo'];
509 $datarray['owner-name'] = $contact['name'];
510 $datarray['owner-link'] = "mailto:".$contact['addr'];
511 $datarray['owner-avatar'] = $contact['photo'];
513 $datarray['uid'] = $importer_uid;
514 $datarray['contact-id'] = $contact['id'];
515 if ($datarray['parent-uri'] === $datarray['uri']) {
516 $datarray['private'] = 1;
518 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
519 $datarray['private'] = 1;
520 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
523 $stored_item = item_store($datarray);
525 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
526 dba::update('item', array('last-child' => false), $condition);
528 dba::update('item', array('last-child' => true), array('id' => $stored_item));
530 switch ($mailconf['action']) {
532 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
535 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
536 imap_delete($mbox, $msg_uid, FT_UID);
539 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
540 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
543 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
544 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
545 if ($mailconf['movetofolder'] != "") {
546 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
553 logger("Mail: no mails for ".$mailconf['user']);
556 logger("Mail: closing connection for ".$mailconf['user']);
562 logger('poller: received xml : ' . $xml, LOGGER_DATA);
563 if (!strstr($xml, '<')) {
564 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
566 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
567 dba::update('contact', $fields, array('id' => $contact['id']));
573 logger("Consume feed of contact ".$contact['id']);
575 consume_feed($xml, $importer, $contact, $hub, 1, 1);
577 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
579 consume_feed($xml, $importer, $contact, $hub, 1, 2);
581 $hubmode = 'subscribe';
582 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
583 $hubmode = 'unsubscribe';
586 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
594 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
596 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
597 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
598 $hubs = explode(',', $hub);
600 foreach ($hubs as $h) {
605 subscribe_to_hub($h, $importer, $contact, $hubmode);
610 $updated = datetime_convert();
612 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
613 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
614 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
615 $updated = datetime_convert();
617 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
618 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
620 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));