2 namespace Friendica\Worker;
4 use Friendica\Core\Config;
5 use Friendica\Core\PConfig;
6 use Friendica\Database\DBM;
9 require_once 'include/follow.php';
12 public static function execute($contact_id = 0, $command = '') {
15 require_once 'include/datetime.php';
16 require_once 'include/items.php';
17 require_once 'include/Contact.php';
18 require_once 'include/email.php';
19 require_once 'include/socgraph.php';
20 require_once 'include/queue_fn.php';
22 logger('onepoll: start');
30 if ($command == "force") {
35 logger('onepoll: no contact');
39 $d = datetime_convert();
41 // Only poll from those with suitable relationships,
42 // and which have a polling address and ignore Diaspora since
43 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
45 $contacts = q("SELECT `contact`.* FROM `contact`
46 WHERE (`rel` = %d OR `rel` = %d) AND `poll` != ''
47 AND NOT `network` IN ('%s', '%s')
48 AND `contact`.`id` = %d
49 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
50 AND `contact`.`archive` = 0 LIMIT 1",
51 intval(CONTACT_IS_SHARING),
52 intval(CONTACT_IS_FRIEND),
53 dbesc(NETWORK_FACEBOOK),
54 dbesc(NETWORK_PUMPIO),
58 if (!count($contacts)) {
59 logger('Contact not found or cannot be used.');
63 $contact = $contacts[0];
65 $importer_uid = $contact['uid'];
67 // load current friends if possible.
68 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
69 $r = q("SELECT count(*) AS total FROM glink
70 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
71 intval($contact['id'])
73 if (DBM::is_result($r)) {
74 if (!$r[0]['total']) {
75 poco_load($contact['id'], $importer_uid, 0, $contact['poco']);
80 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
81 /// @TODO Check whether this is possible with Redmatrix
82 if ($contact["network"] == NETWORK_DIASPORA) {
83 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
84 $last_updated = poco_last_updated($contact["url"]);
85 $updated = datetime_convert();
87 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
88 dba::update('contact', $fields, array('id' => $contact['id']));
90 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
98 $t = $contact['last-update'];
100 if ($contact['subhub']) {
101 $poll_interval = Config::get('system', 'pushpoll_frequency');
102 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
105 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
112 $last_update = (($contact['last-update'] <= NULL_DATE)
113 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
114 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
117 // Update the contact entry
118 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
119 if (!poco_reachable($contact['url'])) {
120 logger("Skipping probably dead contact ".$contact['url']);
124 if (!update_contact($contact["id"])) {
125 mark_for_death($contact);
126 logger('Contact is marked dead');
129 unmark_for_death($contact);
133 if ($importer_uid == 0) {
134 logger('Ignore public contacts');
138 $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",
139 intval($importer_uid)
142 if (!DBM::is_result($r)) {
143 logger('No self contact for user '.$importer_uid);
149 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
151 if ($contact['network'] === NETWORK_DFRN) {
152 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
153 if (intval($contact['duplex']) && $contact['dfrn-id']) {
154 $idtosend = '0:' . $orig_id;
156 if (intval($contact['duplex']) && $contact['issued-id']) {
157 $idtosend = '1:' . $orig_id;
160 // they have permission to write to us. We already filtered this in the contact query.
163 // But this may be our first communication, so set the writable flag if it isn't set already.
165 if (!intval($contact['writable'])) {
166 $fields = array('writable' => true);
167 dba::update('contact', $fields, array('id' => $contact['id']));
170 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
171 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
172 . '&type=data&last_update=' . $last_update
175 $ret = z_fetch_url($url);
177 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
181 $handshake_xml = $ret['body'];
183 $html_code = $a->get_curl_code();
185 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
188 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
189 logger("poller: $url appears to be dead - marking for death ");
191 // dead connection - might be a transient event, or this might
192 // mean the software was uninstalled or the domain expired.
193 // Will keep trying for one month.
195 mark_for_death($contact);
197 // set the last-update so we don't keep polling
198 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
199 dba::update('contact', $fields, array('id' => $contact['id']));
204 if (!strstr($handshake_xml, '<')) {
205 logger('poller: response from ' . $url . ' did not contain XML.');
207 mark_for_death($contact);
209 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
210 dba::update('contact', $fields, array('id' => $contact['id']));
216 $res = parse_xml_string($handshake_xml);
218 if (intval($res->status) == 1) {
219 logger("poller: $url replied status 1 - marking for death ");
221 // we may not be friends anymore. Will keep trying for one month.
222 // set the last-update so we don't keep polling
223 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
224 dba::update('contact', $fields, array('id' => $contact['id']));
226 mark_for_death($contact);
227 } elseif ($contact['term-date'] > NULL_DATE) {
228 logger("poller: $url back from the dead - removing mark for death");
229 unmark_for_death($contact);
232 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
236 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
237 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
238 dba::update('contact', $fields, array('id' => $contact['id']));
243 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
244 $challenge = hex2bin((string) $res->challenge);
248 if ($contact['duplex'] && strlen($contact['prvkey'])) {
249 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
250 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
252 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
253 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
256 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
258 if (strpos($final_dfrn_id, ':') == 1) {
259 $final_dfrn_id = substr($final_dfrn_id, 2);
262 if ($final_dfrn_id != $orig_id) {
263 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
264 // did not decode properly - cannot trust this site
268 $postvars['dfrn_id'] = $idtosend;
269 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
270 $postvars['perm'] = 'rw';
272 $xml = post_url($contact['poll'], $postvars);
274 } elseif (($contact['network'] === NETWORK_OSTATUS)
275 || ($contact['network'] === NETWORK_DIASPORA)
276 || ($contact['network'] === NETWORK_FEED)) {
278 // Upgrading DB fields from an older Friendica version
279 // Will only do this once per notify-enabled OStatus contact
280 // or if relationship changes
282 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
284 // Contacts from OStatus are always writable
285 if ($contact['network'] === NETWORK_OSTATUS) {
289 if ($stat_writeable != $contact['writable']) {
290 $fields = array('writable' => $stat_writeable);
291 dba::update('contact', $fields, array('id' => $contact['id']));
294 // Are we allowed to import from this person?
296 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
300 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
301 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
303 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
310 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
312 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
314 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
315 if ($mail_disabled) {
319 logger("Mail: Enabled", LOGGER_DEBUG);
322 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
324 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
325 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
326 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
327 $mailbox = construct_mailbox_name($mailconf);
329 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
330 $mbox = email_connect($mailbox, $mailconf['user'], $password);
332 logger("Mail: Connect to " . $mailconf['user']);
334 $fields = array('last_check' => datetime_convert());
335 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
336 logger("Mail: Connected to " . $mailconf['user']);
338 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
343 $msgs = email_poll($mbox, $contact['addr']);
346 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
348 $metas = email_msg_meta($mbox,implode(',', $msgs));
349 if (count($metas) != count($msgs)) {
350 logger("onepoll: for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
352 $msgs = array_combine($msgs, $metas);
354 foreach ($msgs as $msg_uid => $meta) {
355 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
358 $datarray['verb'] = ACTIVITY_POST;
359 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
360 // $meta = email_msg_meta($mbox, $msg_uid);
361 // $headers = email_msg_headers($mbox, $msg_uid);
363 $datarray['uri'] = msgid2iri(trim($meta->message_id, '<>'));
365 // Have we seen it before?
366 $fields = array('deleted', 'id');
367 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
368 $r = dba::select('item', $fields, $condition, array('limit' => 1));
370 if (DBM::is_result($r)) {
371 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
373 // Only delete when mails aren't automatically moved or deleted
374 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
375 if ($meta->deleted && ! $r['deleted']) {
376 $fields = array('deleted' => true, 'changed' => datetime_convert());
377 dba::update('item', $fields, array('id' => $r['id']));
380 switch ($mailconf['action']) {
382 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
385 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
386 imap_delete($mbox, $msg_uid, FT_UID);
389 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
390 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
393 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
394 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
395 if ($mailconf['movetofolder'] != "") {
396 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
404 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
405 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
406 if (!trim($raw_refs)) {
407 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
409 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
412 $refs_arr = explode(' ', $raw_refs);
413 if (count($refs_arr)) {
414 for ($x = 0; $x < count($refs_arr); $x ++) {
415 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
418 $qstr = implode(',', $refs_arr);
419 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
420 intval($importer_uid)
422 if (DBM::is_result($r)) {
423 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
427 // Decoding the header
428 $subject = imap_mime_header_decode($meta->subject);
429 $datarray['title'] = "";
430 foreach ($subject as $subpart) {
431 if ($subpart->charset != "default") {
432 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
434 $datarray['title'] .= $subpart->text;
437 $datarray['title'] = notags(trim($datarray['title']));
439 //$datarray['title'] = notags(trim($meta->subject));
440 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
443 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
444 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
447 // Remove Reply-signs in the subject
448 $datarray['title'] = self::RemoveReply($datarray['title']);
450 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
451 if (empty($datarray['parent-uri']) && $reply) {
452 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
453 dbesc(protect_sprintf($datarray['title'])),
454 intval($importer_uid),
455 dbesc(NETWORK_MAIL));
456 if (DBM::is_result($r)) {
457 $datarray['parent-uri'] = $r[0]['parent-uri'];
461 if (empty($datarray['parent-uri'])) {
462 $datarray['parent-uri'] = $datarray['uri'];
465 $r = email_get_msg($mbox, $msg_uid, $reply);
467 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
470 $datarray['body'] = escape_tags($r['body']);
471 $datarray['body'] = limit_body_size($datarray['body']);
473 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
475 /// @TODO Adding a gravatar for the original author would be cool
477 $from = imap_mime_header_decode($meta->from);
479 foreach ($from as $frompart) {
480 if ($frompart->charset != "default") {
481 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
483 $fromdecoded .= $frompart->text;
487 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
489 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
491 if (isset($fromarr[0]->personal)) {
492 $fromname = $fromarr[0]->personal;
494 $fromname = $frommail;
497 $datarray['author-name'] = $fromname;
498 $datarray['author-link'] = "mailto:".$frommail;
499 $datarray['author-avatar'] = $contact['photo'];
501 $datarray['owner-name'] = $contact['name'];
502 $datarray['owner-link'] = "mailto:".$contact['addr'];
503 $datarray['owner-avatar'] = $contact['photo'];
505 $datarray['uid'] = $importer_uid;
506 $datarray['contact-id'] = $contact['id'];
507 if ($datarray['parent-uri'] === $datarray['uri']) {
508 $datarray['private'] = 1;
510 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
511 $datarray['private'] = 1;
512 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
515 $stored_item = item_store($datarray);
517 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
518 dba::update('item', array('last-child' => false), $condition);
520 dba::update('item', array('last-child' => true), array('id' => $stored_item));
522 switch ($mailconf['action']) {
524 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
527 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
528 imap_delete($mbox, $msg_uid, FT_UID);
531 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
532 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
535 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
536 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
537 if ($mailconf['movetofolder'] != "") {
538 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
545 logger("Mail: no mails for ".$mailconf['user']);
548 logger("Mail: closing connection for ".$mailconf['user']);
554 logger('poller: received xml : ' . $xml, LOGGER_DATA);
555 if (!strstr($xml, '<')) {
556 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
558 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
559 dba::update('contact', $fields, array('id' => $contact['id']));
565 logger("Consume feed of contact ".$contact['id']);
567 consume_feed($xml, $importer, $contact, $hub, 1, 1);
569 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
571 consume_feed($xml, $importer, $contact, $hub, 1, 2);
573 $hubmode = 'subscribe';
574 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
575 $hubmode = 'unsubscribe';
578 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
586 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
588 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
589 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
590 $hubs = explode(',', $hub);
592 foreach ($hubs as $h) {
597 subscribe_to_hub($h, $importer, $contact, $hubmode);
602 $updated = datetime_convert();
604 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
605 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
606 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
607 $updated = datetime_convert();
609 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
610 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
612 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
618 private static function RemoveReply($subject) {
619 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
620 $subject = trim(substr($subject, 4));