3 require_once("boot.php");
4 require_once("include/follow.php");
6 function RemoveReply($subject) {
7 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
8 $subject = trim(substr($subject, 4));
13 function onepoll_run(&$argv, &$argc){
21 @include(".htconfig.php");
22 require_once("include/dba.php");
23 $db = new dba($db_host, $db_user, $db_pass, $db_data);
24 unset($db_host, $db_user, $db_pass, $db_data);
27 require_once('include/session.php');
28 require_once('include/datetime.php');
29 require_once('include/items.php');
30 require_once('include/Contact.php');
31 require_once('include/email.php');
32 require_once('include/socgraph.php');
33 require_once('include/queue_fn.php');
35 load_config('config');
36 load_config('system');
38 $a->set_baseurl(get_config('system','url'));
42 logger('onepoll: start');
50 if(($argc > 1) && (intval($argv[1])))
51 $contact_id = intval($argv[1]);
53 if(($argc > 2) && ($argv[2] == "force"))
57 logger('onepoll: no contact');
61 // Don't check this stuff if the function is called by the poller
62 if (App::callstack() != "poller_run")
63 if (App::is_already_running('onepoll'.$contact_id, '', 540))
66 $d = datetime_convert();
68 // Only poll from those with suitable relationships,
69 // and which have a polling address and ignore Diaspora since
70 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
72 $contacts = q("SELECT `contact`.* FROM `contact`
73 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
74 AND NOT `network` IN ( '%s', '%s' )
75 AND `contact`.`id` = %d
76 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
77 AND `contact`.`archive` = 0 LIMIT 1",
78 intval(CONTACT_IS_SHARING),
79 intval(CONTACT_IS_FRIEND),
80 dbesc(NETWORK_FACEBOOK),
81 dbesc(NETWORK_PUMPIO),
85 if(! count($contacts))
88 $contact = $contacts[0];
90 // load current friends if possible.
91 if (($contact['poco'] != "") AND ($contact['success_update'] > $contact['failure_update'])) {
92 $r = q("SELECT count(*) as total from glink
93 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
94 intval($contact['id'])
98 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
101 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
102 /// @TODO Check whether this is possible with Redmatrix
103 if ($contact["network"] == NETWORK_DIASPORA) {
104 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
105 $last_updated = poco_last_updated($contact["url"]);
106 $updated = datetime_convert();
108 q("UPDATE `contact` SET `last-item` = '%s', `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
109 dbesc($last_updated),
112 intval($contact['id'])
115 q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
118 intval($contact['id'])
127 $t = $contact['last-update'];
129 if($contact['subhub']) {
130 $poll_interval = get_config('system','pushpoll_frequency');
131 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
134 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
141 $importer_uid = $contact['uid'];
143 $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",
144 intval($importer_uid)
151 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
153 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
154 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
155 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
158 // Update the contact entry
159 if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
160 if (!poco_reachable($contact['url'])) {
161 logger("Skipping probably dead contact ".$contact['url']);
165 if (!update_contact($contact["id"])) {
166 mark_for_death($contact);
169 unmark_for_death($contact);
172 if($contact['network'] === NETWORK_DFRN) {
175 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
176 if(intval($contact['duplex']) && $contact['dfrn-id'])
177 $idtosend = '0:' . $orig_id;
178 if(intval($contact['duplex']) && $contact['issued-id'])
179 $idtosend = '1:' . $orig_id;
181 // they have permission to write to us. We already filtered this in the contact query.
184 // But this may be our first communication, so set the writable flag if it isn't set already.
186 if(! intval($contact['writable']))
187 q("update contact set writable = 1 where id = %d", intval($contact['id']));
190 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
191 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
192 . '&type=data&last_update=' . $last_update
195 $handshake_xml = fetch_url($url);
196 $html_code = $a->get_curl_code();
198 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
201 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
202 logger("poller: $url appears to be dead - marking for death ");
204 // dead connection - might be a transient event, or this might
205 // mean the software was uninstalled or the domain expired.
206 // Will keep trying for one month.
208 mark_for_death($contact);
210 // set the last-update so we don't keep polling
211 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
212 dbesc(datetime_convert()),
213 dbesc(datetime_convert()),
214 intval($contact['id'])
220 if(! strstr($handshake_xml,'<')) {
221 logger('poller: response from ' . $url . ' did not contain XML.');
223 mark_for_death($contact);
225 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
226 dbesc(datetime_convert()),
227 dbesc(datetime_convert()),
228 intval($contact['id'])
234 $res = parse_xml_string($handshake_xml);
236 if(intval($res->status) == 1) {
237 logger("poller: $url replied status 1 - marking for death ");
239 // we may not be friends anymore. Will keep trying for one month.
240 // set the last-update so we don't keep polling
243 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
244 dbesc(datetime_convert()),
245 dbesc(datetime_convert()),
246 intval($contact['id'])
248 mark_for_death($contact);
251 if($contact['term-date'] != '0000-00-00 00:00:00') {
252 logger("poller: $url back from the dead - removing mark for death");
253 unmark_for_death($contact);
257 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
260 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
261 q("update contact set poco = '%s' where id = %d",
262 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
263 intval($contact['id'])
269 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
270 $challenge = hex2bin((string) $res->challenge);
274 if(($contact['duplex']) && strlen($contact['prvkey'])) {
275 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
276 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
279 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
280 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
283 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
285 if(strpos($final_dfrn_id,':') == 1)
286 $final_dfrn_id = substr($final_dfrn_id,2);
288 if($final_dfrn_id != $orig_id) {
289 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
290 // did not decode properly - cannot trust this site
294 $postvars['dfrn_id'] = $idtosend;
295 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
296 $postvars['perm'] = 'rw';
298 $xml = post_url($contact['poll'],$postvars);
301 elseif(($contact['network'] === NETWORK_OSTATUS)
302 || ($contact['network'] === NETWORK_DIASPORA)
303 || ($contact['network'] === NETWORK_FEED) ) {
305 // Upgrading DB fields from an older Friendica version
306 // Will only do this once per notify-enabled OStatus contact
307 // or if relationship changes
309 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
311 // Contacts from OStatus are always writable
312 if($contact['network'] === NETWORK_OSTATUS)
315 if($stat_writeable != $contact['writable']) {
316 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
317 intval($stat_writeable),
318 intval($contact['id'])
322 // Are we allowed to import from this person?
324 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
327 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
328 $xml = fetch_url($contact['poll'], false, $redirects, 0, Null, $cookiejar);
331 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
333 logger("Mail: Fetching", LOGGER_DEBUG);
335 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
339 logger("Mail: Enabled", LOGGER_DEBUG);
342 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
343 intval($importer_uid)
345 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
346 intval($importer_uid)
348 if(count($x) && count($mailconf)) {
349 $mailbox = construct_mailbox_name($mailconf[0]);
351 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
352 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
354 logger("Mail: Connect to " . $mailconf[0]['user']);
356 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
357 dbesc(datetime_convert()),
358 intval($mailconf[0]['id']),
359 intval($importer_uid)
361 logger("Mail: Connected to " . $mailconf[0]['user']);
363 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors(), true));
367 $msgs = email_poll($mbox,$contact['addr']);
370 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
372 $metas = email_msg_meta($mbox,implode(',',$msgs));
373 if(count($metas) != count($msgs)) {
374 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
377 $msgs = array_combine($msgs, $metas);
379 foreach($msgs as $msg_uid => $meta) {
380 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
383 $datarray['verb'] = ACTIVITY_POST;
384 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
385 // $meta = email_msg_meta($mbox,$msg_uid);
386 // $headers = email_msg_headers($mbox,$msg_uid);
388 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
390 // Have we seen it before?
391 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
392 intval($importer_uid),
393 dbesc($datarray['uri'])
397 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
399 // Only delete when mails aren't automatically moved or deleted
400 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
401 if($meta->deleted && ! $r[0]['deleted']) {
402 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
403 dbesc(datetime_convert()),
408 switch ($mailconf[0]['action']) {
410 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
413 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
414 imap_delete($mbox, $msg_uid, FT_UID);
417 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
418 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
421 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
422 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
423 if ($mailconf[0]['movetofolder'] != "")
424 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
431 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
433 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
434 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
435 if(! trim($raw_refs))
436 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
437 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
440 $refs_arr = explode(' ', $raw_refs);
441 if(count($refs_arr)) {
442 for($x = 0; $x < count($refs_arr); $x ++)
443 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
445 $qstr = implode(',',$refs_arr);
446 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
447 intval($importer_uid)
450 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
451 // $datarray['parent-uri'] = $r[0]['uri'];
454 // Decoding the header
455 $subject = imap_mime_header_decode($meta->subject);
456 $datarray['title'] = "";
457 foreach($subject as $subpart)
458 if ($subpart->charset != "default")
459 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
461 $datarray['title'] .= $subpart->text;
463 $datarray['title'] = notags(trim($datarray['title']));
465 //$datarray['title'] = notags(trim($meta->subject));
466 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
469 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
470 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
473 // Remove Reply-signs in the subject
474 $datarray['title'] = RemoveReply($datarray['title']);
476 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
477 if(!x($datarray,'parent-uri') and $reply) {
478 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
479 dbesc(protect_sprintf($datarray['title'])),
480 intval($importer_uid));
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;
511 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
513 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
515 if (isset($fromarr[0]->personal))
516 $fromname = $fromarr[0]->personal;
518 $fromname = $frommail;
520 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
522 $datarray['author-name'] = $fromname;
523 $datarray['author-link'] = "mailto:".$frommail;
524 $datarray['author-avatar'] = $contact['photo'];
526 $datarray['owner-name'] = $contact['name'];
527 $datarray['owner-link'] = "mailto:".$contact['addr'];
528 $datarray['owner-avatar'] = $contact['photo'];
531 $datarray['author-name'] = $contact['name'];
532 $datarray['author-link'] = 'mailbox';
533 $datarray['author-avatar'] = $contact['photo'];
536 $datarray['uid'] = $importer_uid;
537 $datarray['contact-id'] = $contact['id'];
538 if($datarray['parent-uri'] === $datarray['uri'])
539 $datarray['private'] = 1;
540 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
541 $datarray['private'] = 1;
542 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
545 $stored_item = item_store($datarray);
546 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
547 dbesc($datarray['parent-uri']),
548 intval($importer_uid)
550 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
553 switch ($mailconf[0]['action']) {
555 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
558 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
559 imap_delete($mbox, $msg_uid, FT_UID);
562 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
563 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
566 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
567 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
568 if ($mailconf[0]['movetofolder'] != "")
569 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
575 logger("Mail: no mails for ".$mailconf[0]['user']);
577 logger("Mail: closing connection for ".$mailconf[0]['user']);
581 elseif($contact['network'] === NETWORK_FACEBOOK) {
582 // This is picked up by the Facebook plugin on a cron hook.
584 } elseif($contact['network'] === NETWORK_PUMPIO) {
585 // This is picked up by the pump.io plugin on a cron hook.
590 logger('poller: received xml : ' . $xml, LOGGER_DATA);
591 if(! strstr($xml,'<')) {
592 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
593 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
594 dbesc(datetime_convert()),
595 dbesc(datetime_convert()),
596 intval($contact['id'])
602 logger("Consume feed of contact ".$contact['id']);
604 consume_feed($xml,$importer,$contact,$hub,1,1);
606 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
608 consume_feed($xml,$importer,$contact,$hub,1,2);
610 $hubmode = 'subscribe';
611 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
612 $hubmode = 'unsubscribe';
614 if(($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
620 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
622 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
623 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
624 $hubs = explode(',', $hub);
626 foreach($hubs as $h) {
630 subscribe_to_hub($h,$importer,$contact,$hubmode);
635 $updated = datetime_convert();
637 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
640 intval($contact['id'])
643 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
645 dbesc($contact['nurl'])
648 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
649 $updated = datetime_convert();
651 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
654 intval($contact['id'])
657 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
659 dbesc($contact['nurl'])
662 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
664 intval($contact['id'])
671 if (array_search(__file__,get_included_files())===0){
672 onepoll_run($_SERVER["argv"],$_SERVER["argc"]);