3 use \Friendica\Core\Config;
5 require_once('include/follow.php');
7 function RemoveReply($subject) {
8 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
9 $subject = trim(substr($subject, 4));
14 function onepoll_run(&$argv, &$argc){
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/socgraph.php');
22 require_once('include/queue_fn.php');
24 logger('onepoll: start');
32 if (($argc > 1) && (intval($argv[1]))) {
33 $contact_id = intval($argv[1]);
36 if (($argc > 2) && ($argv[2] == "force")) {
41 logger('onepoll: no contact');
45 $d = datetime_convert();
47 // Only poll from those with suitable relationships,
48 // and which have a polling address and ignore Diaspora since
49 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
51 $contacts = q("SELECT `contact`.* FROM `contact`
52 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
53 AND NOT `network` IN ( '%s', '%s' )
54 AND `contact`.`id` = %d
55 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
56 AND `contact`.`archive` = 0 LIMIT 1",
57 intval(CONTACT_IS_SHARING),
58 intval(CONTACT_IS_FRIEND),
59 dbesc(NETWORK_FACEBOOK),
60 dbesc(NETWORK_PUMPIO),
64 if (! count($contacts)) {
68 $contact = $contacts[0];
70 // load current friends if possible.
71 if (($contact['poco'] != "") AND ($contact['success_update'] > $contact['failure_update'])) {
72 $r = q("SELECT count(*) as total from glink
73 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
74 intval($contact['id'])
76 if (dbm::is_result($r)) {
77 if (!$r[0]['total']) {
78 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
83 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
84 /// @TODO Check whether this is possible with Redmatrix
85 if ($contact["network"] == NETWORK_DIASPORA) {
86 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
87 $last_updated = poco_last_updated($contact["url"]);
88 $updated = datetime_convert();
90 q("UPDATE `contact` SET `last-item` = '%s', `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
94 intval($contact['id'])
97 q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
100 intval($contact['id'])
109 $t = $contact['last-update'];
111 if ($contact['subhub']) {
112 $poll_interval = get_config('system','pushpoll_frequency');
113 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
116 if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) {
123 $importer_uid = $contact['uid'];
125 $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",
126 intval($importer_uid)
128 if (!dbm::is_result($r)) {
134 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
136 $last_update = (($contact['last-update'] <= NULL_DATE)
137 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
138 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
141 // Update the contact entry
142 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
143 if (!poco_reachable($contact['url'])) {
144 logger("Skipping probably dead contact ".$contact['url']);
148 if (!update_contact($contact["id"])) {
149 mark_for_death($contact);
152 unmark_for_death($contact);
156 if ($contact['network'] === NETWORK_DFRN) {
159 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
160 if (intval($contact['duplex']) && $contact['dfrn-id']) {
161 $idtosend = '0:' . $orig_id;
163 if (intval($contact['duplex']) && $contact['issued-id']) {
164 $idtosend = '1:' . $orig_id;
167 // they have permission to write to us. We already filtered this in the contact query.
170 // But this may be our first communication, so set the writable flag if it isn't set already.
172 if (! intval($contact['writable'])) {
173 q("update contact set writable = 1 where id = %d", intval($contact['id']));
176 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
177 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
178 . '&type=data&last_update=' . $last_update
181 $ret = z_fetch_url($url);
183 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
187 $handshake_xml = $ret['body'];
189 $html_code = $a->get_curl_code();
191 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
194 if ((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
195 logger("poller: $url appears to be dead - marking for death ");
197 // dead connection - might be a transient event, or this might
198 // mean the software was uninstalled or the domain expired.
199 // Will keep trying for one month.
201 mark_for_death($contact);
203 // set the last-update so we don't keep polling
204 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
205 dbesc(datetime_convert()),
206 dbesc(datetime_convert()),
207 intval($contact['id'])
213 if (! strstr($handshake_xml,'<')) {
214 logger('poller: response from ' . $url . ' did not contain XML.');
216 mark_for_death($contact);
218 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
219 dbesc(datetime_convert()),
220 dbesc(datetime_convert()),
221 intval($contact['id'])
227 $res = parse_xml_string($handshake_xml);
229 if (intval($res->status) == 1) {
230 logger("poller: $url replied status 1 - marking for death ");
232 // we may not be friends anymore. Will keep trying for one month.
233 // set the last-update so we don't keep polling
236 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
237 dbesc(datetime_convert()),
238 dbesc(datetime_convert()),
239 intval($contact['id'])
241 mark_for_death($contact);
242 } elseif ($contact['term-date'] > NULL_DATE) {
243 logger("poller: $url back from the dead - removing mark for death");
244 unmark_for_death($contact);
247 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
251 if (((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
252 q("update contact set poco = '%s' where id = %d",
253 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
254 intval($contact['id'])
260 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
261 $challenge = hex2bin((string) $res->challenge);
265 if (($contact['duplex']) && strlen($contact['prvkey'])) {
266 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
267 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
269 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
270 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
273 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
275 if (strpos($final_dfrn_id,':') == 1) {
276 $final_dfrn_id = substr($final_dfrn_id,2);
279 if ($final_dfrn_id != $orig_id) {
280 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
281 // did not decode properly - cannot trust this site
285 $postvars['dfrn_id'] = $idtosend;
286 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
287 $postvars['perm'] = 'rw';
289 $xml = post_url($contact['poll'],$postvars);
291 } elseif (($contact['network'] === NETWORK_OSTATUS)
292 || ($contact['network'] === NETWORK_DIASPORA)
293 || ($contact['network'] === NETWORK_FEED)) {
295 // Upgrading DB fields from an older Friendica version
296 // Will only do this once per notify-enabled OStatus contact
297 // or if relationship changes
299 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
301 // Contacts from OStatus are always writable
302 if ($contact['network'] === NETWORK_OSTATUS) {
306 if ($stat_writeable != $contact['writable']) {
307 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
308 intval($stat_writeable),
309 intval($contact['id'])
313 // Are we allowed to import from this person?
315 if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
319 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
320 $ret = z_fetch_url($contact['poll'], false, $redirects, array('cookiejar' => $cookiejar));
322 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
329 } elseif ($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
331 logger("Mail: Fetching", LOGGER_DEBUG);
333 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
337 logger("Mail: Enabled", LOGGER_DEBUG);
340 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
341 intval($importer_uid)
343 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
344 intval($importer_uid)
346 if (count($x) && count($mailconf)) {
347 $mailbox = construct_mailbox_name($mailconf[0]);
349 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
350 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
352 logger("Mail: Connect to " . $mailconf[0]['user']);
354 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
355 dbesc(datetime_convert()),
356 intval($mailconf[0]['id']),
357 intval($importer_uid)
359 logger("Mail: Connected to " . $mailconf[0]['user']);
361 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors(), true));
366 $msgs = email_poll($mbox,$contact['addr']);
369 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
371 $metas = email_msg_meta($mbox,implode(',',$msgs));
372 if (count($metas) != count($msgs)) {
373 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
375 $msgs = array_combine($msgs, $metas);
377 foreach ($msgs as $msg_uid => $meta) {
378 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
381 $datarray['verb'] = ACTIVITY_POST;
382 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
383 // $meta = email_msg_meta($mbox,$msg_uid);
384 // $headers = email_msg_headers($mbox,$msg_uid);
386 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
388 // Have we seen it before?
389 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
390 intval($importer_uid),
391 dbesc($datarray['uri'])
394 if (dbm::is_result($r)) {
395 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
397 // Only delete when mails aren't automatically moved or deleted
398 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
399 if ($meta->deleted && ! $r[0]['deleted']) {
400 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
401 dbesc(datetime_convert()),
406 switch ($mailconf[0]['action']) {
408 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
411 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
412 imap_delete($mbox, $msg_uid, FT_UID);
415 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
416 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
419 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
420 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
421 if ($mailconf[0]['movetofolder'] != "")
422 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
429 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
431 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
432 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
433 if (! trim($raw_refs))
434 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
435 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
438 $refs_arr = explode(' ', $raw_refs);
439 if (count($refs_arr)) {
440 for($x = 0; $x < count($refs_arr); $x ++)
441 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
443 $qstr = implode(',',$refs_arr);
444 $r = q("SELECT `uri` , `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
445 intval($importer_uid)
447 if (dbm::is_result($r))
448 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
449 // $datarray['parent-uri'] = $r[0]['uri'];
452 // Decoding the header
453 $subject = imap_mime_header_decode($meta->subject);
454 $datarray['title'] = "";
455 foreach ($subject as $subpart) {
456 if ($subpart->charset != "default") {
457 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
459 $datarray['title'] .= $subpart->text;
462 $datarray['title'] = notags(trim($datarray['title']));
464 //$datarray['title'] = notags(trim($meta->subject));
465 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
468 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
469 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
472 // Remove Reply-signs in the subject
473 $datarray['title'] = RemoveReply($datarray['title']);
475 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
476 if (!x($datarray,'parent-uri') and $reply) {
477 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
478 dbesc(protect_sprintf($datarray['title'])),
479 intval($importer_uid),
480 dbesc(NETWORK_MAIL));
481 if (dbm::is_result($r))
482 $datarray['parent-uri'] = $r[0]['parent-uri'];
485 if (! x($datarray,'parent-uri'))
486 $datarray['parent-uri'] = $datarray['uri'];
489 $r = email_get_msg($mbox,$msg_uid, $reply);
491 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
494 $datarray['body'] = escape_tags($r['body']);
495 $datarray['body'] = limit_body_size($datarray['body']);
497 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
499 // some mailing lists have the original author as 'from' - add this sender info to msg body.
500 /// @TODO Adding a gravatar for the original author would be cool
502 if (! stristr($meta->from,$contact['addr'])) {
503 $from = imap_mime_header_decode($meta->from);
505 foreach ($from as $frompart) {
506 if ($frompart->charset != "default") {
507 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
509 $fromdecoded .= $frompart->text;
513 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
515 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
517 if (isset($fromarr[0]->personal)) {
518 $fromname = $fromarr[0]->personal;
520 $fromname = $frommail;
523 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
525 $datarray['author-name'] = $fromname;
526 $datarray['author-link'] = "mailto:".$frommail;
527 $datarray['author-avatar'] = $contact['photo'];
529 $datarray['owner-name'] = $contact['name'];
530 $datarray['owner-link'] = "mailto:".$contact['addr'];
531 $datarray['owner-avatar'] = $contact['photo'];
534 $datarray['author-name'] = $contact['name'];
535 $datarray['author-link'] = 'mailbox';
536 $datarray['author-avatar'] = $contact['photo'];
539 $datarray['uid'] = $importer_uid;
540 $datarray['contact-id'] = $contact['id'];
541 if ($datarray['parent-uri'] === $datarray['uri'])
542 $datarray['private'] = 1;
543 if (($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
544 $datarray['private'] = 1;
545 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
548 $stored_item = item_store($datarray);
549 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
550 dbesc($datarray['parent-uri']),
551 intval($importer_uid)
553 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
556 switch ($mailconf[0]['action']) {
558 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
561 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
562 imap_delete($mbox, $msg_uid, FT_UID);
565 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
566 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
569 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
570 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
571 if ($mailconf[0]['movetofolder'] != "")
572 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
578 logger("Mail: no mails for ".$mailconf[0]['user']);
581 logger("Mail: closing connection for ".$mailconf[0]['user']);
584 } elseif ($contact['network'] === NETWORK_FACEBOOK) {
585 // This is picked up by the Facebook plugin on a cron hook.
587 } elseif ($contact['network'] === NETWORK_PUMPIO) {
588 // This is picked up by the pump.io plugin on a cron hook.
593 logger('poller: received xml : ' . $xml, LOGGER_DATA);
594 if (! strstr($xml,'<')) {
595 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
596 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
597 dbesc(datetime_convert()),
598 dbesc(datetime_convert()),
599 intval($contact['id'])
605 logger("Consume feed of contact ".$contact['id']);
607 consume_feed($xml,$importer,$contact,$hub,1,1);
609 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
611 consume_feed($xml,$importer,$contact,$hub,1,2);
613 $hubmode = 'subscribe';
614 if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
615 $hubmode = 'unsubscribe';
617 if (($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
623 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
625 if ((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
626 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
627 $hubs = explode(',', $hub);
629 foreach ($hubs as $h) {
634 subscribe_to_hub($h,$importer,$contact,$hubmode);
639 $updated = datetime_convert();
641 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
644 intval($contact['id'])
647 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
649 dbesc($contact['nurl'])
652 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
653 $updated = datetime_convert();
655 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
658 intval($contact['id'])
661 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
663 dbesc($contact['nurl'])
666 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
668 intval($contact['id'])