2 namespace Friendica\Worker;
4 use Friendica\Core\Config;
5 use Friendica\Core\PConfig;
6 use Friendica\Database\DBM;
7 use Friendica\Protocol\PortableContact;
10 require_once 'include/follow.php';
14 public static function execute($contact_id = 0, $command = '') {
17 require_once 'include/datetime.php';
18 require_once 'include/items.php';
19 require_once 'include/Contact.php';
20 require_once 'include/email.php';
21 require_once 'include/queue_fn.php';
23 logger('onepoll: start');
31 if ($command == "force") {
36 logger('onepoll: no contact');
40 $d = datetime_convert();
42 // Only poll from those with suitable relationships,
43 // and which have a polling address and ignore Diaspora since
44 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
46 $contacts = q("SELECT `contact`.* FROM `contact`
47 WHERE (`rel` = %d OR `rel` = %d) AND `poll` != ''
48 AND NOT `network` IN ('%s', '%s')
49 AND `contact`.`id` = %d
50 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
51 AND `contact`.`archive` = 0 LIMIT 1",
52 intval(CONTACT_IS_SHARING),
53 intval(CONTACT_IS_FRIEND),
54 dbesc(NETWORK_FACEBOOK),
55 dbesc(NETWORK_PUMPIO),
59 if (!count($contacts)) {
60 logger('Contact not found or cannot be used.');
64 $contact = $contacts[0];
66 $importer_uid = $contact['uid'];
68 // load current friends if possible.
69 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
70 $r = q("SELECT count(*) AS total FROM glink
71 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
72 intval($contact['id'])
74 if (DBM::is_result($r)) {
75 if (!$r[0]['total']) {
76 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
81 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
82 /// @TODO Check whether this is possible with Redmatrix
83 if ($contact["network"] == NETWORK_DIASPORA) {
84 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
85 $last_updated = poco_last_updated($contact["url"]);
86 $updated = datetime_convert();
88 $fields = array('last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated);
89 dba::update('contact', $fields, array('id' => $contact['id']));
91 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
99 $t = $contact['last-update'];
101 if ($contact['subhub']) {
102 $poll_interval = Config::get('system', 'pushpoll_frequency');
103 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
106 if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
113 $last_update = (($contact['last-update'] <= NULL_DATE)
114 ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
115 : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
118 // Update the contact entry
119 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
120 if (!poco_reachable($contact['url'])) {
121 logger("Skipping probably dead contact ".$contact['url']);
125 if (!update_contact($contact["id"])) {
126 mark_for_death($contact);
127 logger('Contact is marked dead');
130 unmark_for_death($contact);
134 if ($importer_uid == 0) {
135 logger('Ignore public contacts');
139 $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",
140 intval($importer_uid)
143 if (!DBM::is_result($r)) {
144 logger('No self contact for user '.$importer_uid);
150 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
152 if ($contact['network'] === NETWORK_DFRN) {
153 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
154 if (intval($contact['duplex']) && $contact['dfrn-id']) {
155 $idtosend = '0:' . $orig_id;
157 if (intval($contact['duplex']) && $contact['issued-id']) {
158 $idtosend = '1:' . $orig_id;
161 // they have permission to write to us. We already filtered this in the contact query.
164 // But this may be our first communication, so set the writable flag if it isn't set already.
166 if (!intval($contact['writable'])) {
167 $fields = array('writable' => true);
168 dba::update('contact', $fields, array('id' => $contact['id']));
171 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
172 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
173 . '&type=data&last_update=' . $last_update
176 $ret = z_fetch_url($url);
178 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
182 $handshake_xml = $ret['body'];
184 $html_code = $a->get_curl_code();
186 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
189 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
190 logger("poller: $url appears to be dead - marking for death ");
192 // dead connection - might be a transient event, or this might
193 // mean the software was uninstalled or the domain expired.
194 // Will keep trying for one month.
196 mark_for_death($contact);
198 // set the last-update so we don't keep polling
199 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
200 dba::update('contact', $fields, array('id' => $contact['id']));
205 if (!strstr($handshake_xml, '<')) {
206 logger('poller: response from ' . $url . ' did not contain XML.');
208 mark_for_death($contact);
210 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
211 dba::update('contact', $fields, array('id' => $contact['id']));
217 $res = parse_xml_string($handshake_xml);
219 if (intval($res->status) == 1) {
220 logger("poller: $url replied status 1 - marking for death ");
222 // we may not be friends anymore. Will keep trying for one month.
223 // set the last-update so we don't keep polling
224 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
225 dba::update('contact', $fields, array('id' => $contact['id']));
227 mark_for_death($contact);
228 } elseif ($contact['term-date'] > NULL_DATE) {
229 logger("poller: $url back from the dead - removing mark for death");
230 unmark_for_death($contact);
233 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
237 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
238 $fields = array('poco' => str_replace('/profile/', '/poco/', $contact['url']));
239 dba::update('contact', $fields, array('id' => $contact['id']));
244 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
245 $challenge = hex2bin((string) $res->challenge);
249 if ($contact['duplex'] && strlen($contact['prvkey'])) {
250 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
251 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
253 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
254 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
257 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
259 if (strpos($final_dfrn_id, ':') == 1) {
260 $final_dfrn_id = substr($final_dfrn_id, 2);
263 if ($final_dfrn_id != $orig_id) {
264 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
265 // did not decode properly - cannot trust this site
269 $postvars['dfrn_id'] = $idtosend;
270 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
271 $postvars['perm'] = 'rw';
273 $xml = post_url($contact['poll'], $postvars);
275 } elseif (($contact['network'] === NETWORK_OSTATUS)
276 || ($contact['network'] === NETWORK_DIASPORA)
277 || ($contact['network'] === NETWORK_FEED)) {
279 // Upgrading DB fields from an older Friendica version
280 // Will only do this once per notify-enabled OStatus contact
281 // or if relationship changes
283 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
285 // Contacts from OStatus are always writable
286 if ($contact['network'] === NETWORK_OSTATUS) {
290 if ($stat_writeable != $contact['writable']) {
291 $fields = array('writable' => $stat_writeable);
292 dba::update('contact', $fields, array('id' => $contact['id']));
295 // Are we allowed to import from this person?
297 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
301 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
302 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
304 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
311 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
313 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
315 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
316 if ($mail_disabled) {
320 logger("Mail: Enabled", LOGGER_DEBUG);
323 $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1));
325 $condition = array("`server` != '' AND `uid` = ?", $importer_uid);
326 $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1));
327 if (DBM::is_result($x) && DBM::is_result($mailconf)) {
328 $mailbox = construct_mailbox_name($mailconf);
330 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']);
331 $mbox = email_connect($mailbox, $mailconf['user'], $password);
333 logger("Mail: Connect to " . $mailconf['user']);
335 $fields = array('last_check' => datetime_convert());
336 dba::update('mailacct', $fields, array('id' => $mailconf['id']));
337 logger("Mail: Connected to " . $mailconf['user']);
339 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
344 $msgs = email_poll($mbox, $contact['addr']);
347 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
349 $metas = email_msg_meta($mbox,implode(',', $msgs));
350 if (count($metas) != count($msgs)) {
351 logger("onepoll: for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
353 $msgs = array_combine($msgs, $metas);
355 foreach ($msgs as $msg_uid => $meta) {
356 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
359 $datarray['verb'] = ACTIVITY_POST;
360 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
361 // $meta = email_msg_meta($mbox, $msg_uid);
362 // $headers = email_msg_headers($mbox, $msg_uid);
364 $datarray['uri'] = msgid2iri(trim($meta->message_id, '<>'));
366 // Have we seen it before?
367 $fields = array('deleted', 'id');
368 $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
369 $r = dba::select('item', $fields, $condition, array('limit' => 1));
371 if (DBM::is_result($r)) {
372 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
374 // Only delete when mails aren't automatically moved or deleted
375 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
376 if ($meta->deleted && ! $r['deleted']) {
377 $fields = array('deleted' => true, 'changed' => datetime_convert());
378 dba::update('item', $fields, array('id' => $r['id']));
381 switch ($mailconf['action']) {
383 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
386 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
387 imap_delete($mbox, $msg_uid, FT_UID);
390 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
391 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
394 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
395 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
396 if ($mailconf['movetofolder'] != "") {
397 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
405 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
406 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
407 if (!trim($raw_refs)) {
408 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
410 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
413 $refs_arr = explode(' ', $raw_refs);
414 if (count($refs_arr)) {
415 for ($x = 0; $x < count($refs_arr); $x ++) {
416 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
419 $qstr = implode(',', $refs_arr);
420 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
421 intval($importer_uid)
423 if (DBM::is_result($r)) {
424 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
428 // Decoding the header
429 $subject = imap_mime_header_decode($meta->subject);
430 $datarray['title'] = "";
431 foreach ($subject as $subpart) {
432 if ($subpart->charset != "default") {
433 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
435 $datarray['title'] .= $subpart->text;
438 $datarray['title'] = notags(trim($datarray['title']));
440 //$datarray['title'] = notags(trim($meta->subject));
441 $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
444 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
445 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
448 // Remove Reply-signs in the subject
449 $datarray['title'] = self::RemoveReply($datarray['title']);
451 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
452 if (empty($datarray['parent-uri']) && $reply) {
453 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
454 dbesc(protect_sprintf($datarray['title'])),
455 intval($importer_uid),
456 dbesc(NETWORK_MAIL));
457 if (DBM::is_result($r)) {
458 $datarray['parent-uri'] = $r[0]['parent-uri'];
462 if (empty($datarray['parent-uri'])) {
463 $datarray['parent-uri'] = $datarray['uri'];
466 $r = email_get_msg($mbox, $msg_uid, $reply);
468 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
471 $datarray['body'] = escape_tags($r['body']);
472 $datarray['body'] = limit_body_size($datarray['body']);
474 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
476 /// @TODO Adding a gravatar for the original author would be cool
478 $from = imap_mime_header_decode($meta->from);
480 foreach ($from as $frompart) {
481 if ($frompart->charset != "default") {
482 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
484 $fromdecoded .= $frompart->text;
488 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
490 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
492 if (isset($fromarr[0]->personal)) {
493 $fromname = $fromarr[0]->personal;
495 $fromname = $frommail;
498 $datarray['author-name'] = $fromname;
499 $datarray['author-link'] = "mailto:".$frommail;
500 $datarray['author-avatar'] = $contact['photo'];
502 $datarray['owner-name'] = $contact['name'];
503 $datarray['owner-link'] = "mailto:".$contact['addr'];
504 $datarray['owner-avatar'] = $contact['photo'];
506 $datarray['uid'] = $importer_uid;
507 $datarray['contact-id'] = $contact['id'];
508 if ($datarray['parent-uri'] === $datarray['uri']) {
509 $datarray['private'] = 1;
511 if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
512 $datarray['private'] = 1;
513 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
516 $stored_item = item_store($datarray);
518 $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
519 dba::update('item', array('last-child' => false), $condition);
521 dba::update('item', array('last-child' => true), array('id' => $stored_item));
523 switch ($mailconf['action']) {
525 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
528 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
529 imap_delete($mbox, $msg_uid, FT_UID);
532 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
533 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
536 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
537 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
538 if ($mailconf['movetofolder'] != "") {
539 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
546 logger("Mail: no mails for ".$mailconf['user']);
549 logger("Mail: closing connection for ".$mailconf['user']);
555 logger('poller: received xml : ' . $xml, LOGGER_DATA);
556 if (!strstr($xml, '<')) {
557 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
559 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
560 dba::update('contact', $fields, array('id' => $contact['id']));
566 logger("Consume feed of contact ".$contact['id']);
568 consume_feed($xml, $importer, $contact, $hub, 1, 1);
570 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
572 consume_feed($xml, $importer, $contact, $hub, 1, 2);
574 $hubmode = 'subscribe';
575 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
576 $hubmode = 'unsubscribe';
579 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
587 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
589 if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
590 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
591 $hubs = explode(',', $hub);
593 foreach ($hubs as $h) {
598 subscribe_to_hub($h, $importer, $contact, $hubmode);
603 $updated = datetime_convert();
605 dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
606 dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
607 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
608 $updated = datetime_convert();
610 dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
611 dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
613 dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
619 private static function RemoveReply($subject) {
620 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
621 $subject = trim(substr($subject, 4));