3 require_once("boot.php");
5 function onepoll_run($argv, $argc){
13 @include(".htconfig.php");
14 require_once("dba.php");
15 $db = new dba($db_host, $db_user, $db_pass, $db_data);
16 unset($db_host, $db_user, $db_pass, $db_data);
20 require_once('include/session.php');
21 require_once('include/datetime.php');
22 require_once('library/simplepie/simplepie.inc');
23 require_once('include/items.php');
24 require_once('include/Contact.php');
25 require_once('include/email.php');
26 require_once('include/socgraph.php');
27 require_once('include/pidfile.php');
28 require_once('include/queue_fn.php');
30 load_config('config');
31 load_config('system');
33 $a->set_baseurl(get_config('system','url'));
37 logger('onepoll: start');
39 $abandon_days = intval(get_config('system','account_abandon_days'));
50 if(($argc > 1) && (intval($argv[1])))
51 $contact_id = intval($argv[1]);
54 logger('onepoll: no contact');
59 $d = datetime_convert();
61 // Only poll from those with suitable relationships,
62 // and which have a polling address and ignore Diaspora since
63 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
65 $abandon_sql = (($abandon_days)
66 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
70 $contacts = q("SELECT `contact`.* FROM `contact`
71 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
72 AND NOT `network` IN ( '%s', '%s' )
73 AND `contact`.`id` = %d
74 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
75 AND `contact`.`archive` = 0 LIMIT 1",
76 intval(CONTACT_IS_SHARING),
77 intval(CONTACT_IS_FRIEND),
78 dbesc(NETWORK_DIASPORA),
79 dbesc(NETWORK_FACEBOOK),
83 if(! count($contacts)) {
87 $contact = $contacts[0];
88 logger('onepoll: ' . $contact['id'] . ' ' . $contact['name'], LOGGER_DEBUG);
92 $t = $contact['last-update'];
94 if($contact['subhub']) {
95 $poll_interval = get_config('system','pushpoll_frequency');
96 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
99 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
106 $importer_uid = $contact['uid'];
108 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` LEFT JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
109 intval($importer_uid)
116 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
118 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
119 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
120 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
123 if($contact['network'] === NETWORK_DFRN) {
125 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
126 if(intval($contact['duplex']) && $contact['dfrn-id'])
127 $idtosend = '0:' . $orig_id;
128 if(intval($contact['duplex']) && $contact['issued-id'])
129 $idtosend = '1:' . $orig_id;
131 // they have permission to write to us. We already filtered this in the contact query.
134 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
135 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
136 . '&type=data&last_update=' . $last_update
139 $handshake_xml = fetch_url($url);
140 $html_code = $a->get_curl_code();
142 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
145 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
146 logger("poller: $url appears to be dead - marking for death ");
148 // dead connection - might be a transient event, or this might
149 // mean the software was uninstalled or the domain expired.
150 // Will keep trying for one month.
152 mark_for_death($contact);
154 // set the last-update so we don't keep polling
155 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
156 dbesc(datetime_convert()),
157 intval($contact['id'])
163 if(! strstr($handshake_xml,'<?xml')) {
164 logger('poller: response from ' . $url . ' did not contain XML.');
165 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
166 dbesc(datetime_convert()),
167 intval($contact['id'])
173 $res = parse_xml_string($handshake_xml);
175 if(intval($res->status) == 1) {
176 logger("poller: $url replied status 1 - marking for death ");
178 // we may not be friends anymore. Will keep trying for one month.
179 // set the last-update so we don't keep polling
182 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
183 dbesc(datetime_convert()),
184 intval($contact['id'])
186 mark_for_death($contact);
189 if($contact['term-date'] != '0000-00-00 00:00:00') {
190 logger("poller: $url back from the dead - removing mark for death");
191 unmark_for_death($contact);
195 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
198 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
199 q("update contact set poco = '%s' where id = %d limit 1",
200 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
201 intval($contact['id'])
207 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
208 $challenge = hex2bin((string) $res->challenge);
212 if(($contact['duplex']) && strlen($contact['prvkey'])) {
213 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
214 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
217 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
218 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
221 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
223 if(strpos($final_dfrn_id,':') == 1)
224 $final_dfrn_id = substr($final_dfrn_id,2);
226 if($final_dfrn_id != $orig_id) {
227 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
228 // did not decode properly - cannot trust this site
232 $postvars['dfrn_id'] = $idtosend;
233 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
234 $postvars['perm'] = 'rw';
236 $xml = post_url($contact['poll'],$postvars);
239 elseif(($contact['network'] === NETWORK_OSTATUS)
240 || ($contact['network'] === NETWORK_DIASPORA)
241 || ($contact['network'] === NETWORK_FEED) ) {
243 // Upgrading DB fields from an older Friendica version
244 // Will only do this once per notify-enabled OStatus contact
245 // or if relationship changes
247 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
249 if($stat_writeable != $contact['writable']) {
250 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
251 intval($stat_writeable),
252 intval($contact['id'])
256 // Are we allowed to import from this person?
258 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
261 $xml = fetch_url($contact['poll']);
263 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
265 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
267 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
271 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
274 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
275 intval($importer_uid)
277 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
278 intval($importer_uid)
280 if(count($x) && count($mailconf)) {
281 $mailbox = construct_mailbox_name($mailconf[0]);
283 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
284 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
286 logger("Mail: Connect");
288 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
289 dbesc(datetime_convert()),
290 intval($mailconf[0]['id']),
291 intval($importer_uid)
297 $msgs = email_poll($mbox,$contact['addr']);
300 logger("Mail: Parsing ".count($msgs)." mails.", LOGGER_DEBUG);
302 foreach($msgs as $msg_uid) {
303 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
306 $meta = email_msg_meta($mbox,$msg_uid);
307 $headers = email_msg_headers($mbox,$msg_uid);
309 // look for a 'references' header and try and match with a parent item we have locally.
311 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
312 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
315 $refs_arr = explode(' ', $raw_refs);
316 if(count($refs_arr)) {
317 for($x = 0; $x < count($refs_arr); $x ++)
318 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
320 $qstr = implode(',',$refs_arr);
321 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
322 intval($importer_uid)
325 $datarray['parent-uri'] = $r[0]['uri'];
329 if(! x($datarray,'parent-uri'))
330 $datarray['parent-uri'] = $datarray['uri'];
332 // Have we seen it before?
333 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
334 intval($importer_uid),
335 dbesc($datarray['uri'])
339 // logger("Mail: Seen before ".$msg_uid);
340 if($meta->deleted && ! $r[0]['deleted']) {
341 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
342 dbesc(datetime_convert()),
346 switch ($mailconf[0]['action']) {
350 logger("Mail: Deleting ".$msg_uid);
351 imap_delete($mbox, $msg_uid, FT_UID);
354 logger("Mail: Mark as seen ".$msg_uid);
355 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
358 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
359 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
360 if ($mailconf[0]['movetofolder'] != "")
361 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
367 // Decoding the header
368 $subject = imap_mime_header_decode($meta->subject);
369 $datarray['title'] = "";
370 foreach($subject as $subpart)
371 if ($subpart->charset != "default")
372 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
374 $datarray['title'] .= $subpart->text;
376 $datarray['title'] = notags(trim($datarray['title']));
378 //$datarray['title'] = notags(trim($meta->subject));
379 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
382 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
383 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
386 $r = email_get_msg($mbox,$msg_uid, $reply);
388 logger("Mail: can't fetch msg ".$msg_uid);
391 $datarray['body'] = escape_tags($r['body']);
393 logger("Mail: Importing ".$msg_uid);
395 // some mailing lists have the original author as 'from' - add this sender info to msg body.
396 // todo: adding a gravatar for the original author would be cool
398 if(! stristr($meta->from,$contact['addr'])) {
399 $from = imap_mime_header_decode($meta->from);
401 foreach($from as $frompart)
402 if ($frompart->charset != "default")
403 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
405 $fromdecoded .= $frompart->text;
407 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
410 $datarray['uid'] = $importer_uid;
411 $datarray['contact-id'] = $contact['id'];
412 if($datarray['parent-uri'] === $datarray['uri'])
413 $datarray['private'] = 1;
414 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
415 $datarray['private'] = 1;
416 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
418 $datarray['author-name'] = $contact['name'];
419 $datarray['author-link'] = 'mailbox';
420 $datarray['author-avatar'] = $contact['photo'];
422 $stored_item = item_store($datarray);
423 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
424 dbesc($datarray['parent-uri']),
425 intval($importer_uid)
427 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
430 switch ($mailconf[0]['action']) {
434 logger("Mail: Deleting ".$msg_uid);
435 imap_delete($mbox, $msg_uid, FT_UID);
438 logger("Mail: Mark as seen ".$msg_uid);
439 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
442 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
443 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
444 if ($mailconf[0]['movetofolder'] != "")
445 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
453 elseif($contact['network'] === NETWORK_FACEBOOK) {
454 // This is picked up by the Facebook plugin on a cron hook.
459 logger('poller: received xml : ' . $xml, LOGGER_DATA);
460 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
461 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
462 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
463 dbesc(datetime_convert()),
464 intval($contact['id'])
470 consume_feed($xml,$importer,$contact,$hub,1,1);
473 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
475 consume_feed($xml,$importer,$contact,$hub,1,2);
477 $hubmode = 'subscribe';
478 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
479 $hubmode = 'unsubscribe';
481 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
484 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
485 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
486 $hubs = explode(',', $hub);
488 foreach($hubs as $h) {
492 subscribe_to_hub($h,$importer,$contact,$hubmode);
498 $updated = datetime_convert();
500 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
503 intval($contact['id'])
507 // load current friends if possible.
509 if($contact['poco']) {
510 $r = q("SELECT count(*) as total from glink
511 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
512 intval($contact['id'])
516 if(! $r[0]['total']) {
517 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
524 if (array_search(__file__,get_included_files())===0){
525 onepoll_run($argv,$argc);