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');
45 if(($argc > 1) && (intval($argv[1])))
46 $contact_id = intval($argv[1]);
49 logger('onepoll: no contact');
54 $d = datetime_convert();
56 // Only poll from those with suitable relationships,
57 // and which have a polling address and ignore Diaspora since
58 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
60 $contacts = q("SELECT `contact`.* FROM `contact`
61 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
62 AND NOT `network` IN ( '%s', '%s' )
63 AND `contact`.`id` = %d
64 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
65 AND `contact`.`archive` = 0 LIMIT 1",
66 intval(CONTACT_IS_SHARING),
67 intval(CONTACT_IS_FRIEND),
68 dbesc(NETWORK_DIASPORA),
69 dbesc(NETWORK_FACEBOOK),
73 if(! count($contacts)) {
77 $contact = $contacts[0];
81 $t = $contact['last-update'];
83 if($contact['subhub']) {
84 $poll_interval = get_config('system','pushpoll_frequency');
85 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
88 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
95 $importer_uid = $contact['uid'];
97 $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",
105 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
107 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
108 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
109 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
112 if($contact['network'] === NETWORK_DFRN) {
114 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
115 if(intval($contact['duplex']) && $contact['dfrn-id'])
116 $idtosend = '0:' . $orig_id;
117 if(intval($contact['duplex']) && $contact['issued-id'])
118 $idtosend = '1:' . $orig_id;
120 // they have permission to write to us. We already filtered this in the contact query.
123 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
124 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
125 . '&type=data&last_update=' . $last_update
128 $handshake_xml = fetch_url($url);
129 $html_code = $a->get_curl_code();
131 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
134 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
135 logger("poller: $url appears to be dead - marking for death ");
137 // dead connection - might be a transient event, or this might
138 // mean the software was uninstalled or the domain expired.
139 // Will keep trying for one month.
141 mark_for_death($contact);
143 // set the last-update so we don't keep polling
144 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
145 dbesc(datetime_convert()),
146 intval($contact['id'])
152 if(! strstr($handshake_xml,'<?xml')) {
153 logger('poller: response from ' . $url . ' did not contain XML.');
155 mark_for_death($contact);
157 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
158 dbesc(datetime_convert()),
159 intval($contact['id'])
165 $res = parse_xml_string($handshake_xml);
167 if(intval($res->status) == 1) {
168 logger("poller: $url replied status 1 - marking for death ");
170 // we may not be friends anymore. Will keep trying for one month.
171 // set the last-update so we don't keep polling
174 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
175 dbesc(datetime_convert()),
176 intval($contact['id'])
178 mark_for_death($contact);
181 if($contact['term-date'] != '0000-00-00 00:00:00') {
182 logger("poller: $url back from the dead - removing mark for death");
183 unmark_for_death($contact);
187 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
190 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
191 q("update contact set poco = '%s' where id = %d limit 1",
192 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
193 intval($contact['id'])
199 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
200 $challenge = hex2bin((string) $res->challenge);
204 if(($contact['duplex']) && strlen($contact['prvkey'])) {
205 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
206 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
209 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
210 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
213 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
215 if(strpos($final_dfrn_id,':') == 1)
216 $final_dfrn_id = substr($final_dfrn_id,2);
218 if($final_dfrn_id != $orig_id) {
219 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
220 // did not decode properly - cannot trust this site
224 $postvars['dfrn_id'] = $idtosend;
225 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
226 $postvars['perm'] = 'rw';
228 $xml = post_url($contact['poll'],$postvars);
231 elseif(($contact['network'] === NETWORK_OSTATUS)
232 || ($contact['network'] === NETWORK_DIASPORA)
233 || ($contact['network'] === NETWORK_FEED) ) {
235 // Upgrading DB fields from an older Friendica version
236 // Will only do this once per notify-enabled OStatus contact
237 // or if relationship changes
239 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
241 if($stat_writeable != $contact['writable']) {
242 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
243 intval($stat_writeable),
244 intval($contact['id'])
248 // Are we allowed to import from this person?
250 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
253 $xml = fetch_url($contact['poll']);
255 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
257 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
259 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
263 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
266 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
267 intval($importer_uid)
269 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
270 intval($importer_uid)
272 if(count($x) && count($mailconf)) {
273 $mailbox = construct_mailbox_name($mailconf[0]);
275 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
276 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
278 logger("Mail: Connect");
280 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
281 dbesc(datetime_convert()),
282 intval($mailconf[0]['id']),
283 intval($importer_uid)
289 $msgs = email_poll($mbox,$contact['addr']);
292 logger("Mail: Parsing ".count($msgs)." mails.", LOGGER_DEBUG);
294 foreach($msgs as $msg_uid) {
295 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
298 $meta = email_msg_meta($mbox,$msg_uid);
299 $headers = email_msg_headers($mbox,$msg_uid);
301 // look for a 'references' header and try and match with a parent item we have locally.
303 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
304 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
307 $refs_arr = explode(' ', $raw_refs);
308 if(count($refs_arr)) {
309 for($x = 0; $x < count($refs_arr); $x ++)
310 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
312 $qstr = implode(',',$refs_arr);
313 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
314 intval($importer_uid)
317 $datarray['parent-uri'] = $r[0]['uri'];
321 if(! x($datarray,'parent-uri'))
322 $datarray['parent-uri'] = $datarray['uri'];
324 // Have we seen it before?
325 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
326 intval($importer_uid),
327 dbesc($datarray['uri'])
331 // logger("Mail: Seen before ".$msg_uid);
332 if($meta->deleted && ! $r[0]['deleted']) {
333 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
334 dbesc(datetime_convert()),
338 switch ($mailconf[0]['action']) {
342 logger("Mail: Deleting ".$msg_uid);
343 imap_delete($mbox, $msg_uid, FT_UID);
346 logger("Mail: Mark as seen ".$msg_uid);
347 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
350 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
351 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
352 if ($mailconf[0]['movetofolder'] != "")
353 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
359 // Decoding the header
360 $subject = imap_mime_header_decode($meta->subject);
361 $datarray['title'] = "";
362 foreach($subject as $subpart)
363 if ($subpart->charset != "default")
364 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
366 $datarray['title'] .= $subpart->text;
368 $datarray['title'] = notags(trim($datarray['title']));
370 //$datarray['title'] = notags(trim($meta->subject));
371 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
374 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
375 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
378 $r = email_get_msg($mbox,$msg_uid, $reply);
380 logger("Mail: can't fetch msg ".$msg_uid);
383 $datarray['body'] = escape_tags($r['body']);
385 logger("Mail: Importing ".$msg_uid);
387 // some mailing lists have the original author as 'from' - add this sender info to msg body.
388 // todo: adding a gravatar for the original author would be cool
390 if(! stristr($meta->from,$contact['addr'])) {
391 $from = imap_mime_header_decode($meta->from);
393 foreach($from as $frompart)
394 if ($frompart->charset != "default")
395 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
397 $fromdecoded .= $frompart->text;
399 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
402 $datarray['uid'] = $importer_uid;
403 $datarray['contact-id'] = $contact['id'];
404 if($datarray['parent-uri'] === $datarray['uri'])
405 $datarray['private'] = 1;
406 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
407 $datarray['private'] = 1;
408 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
410 $datarray['author-name'] = $contact['name'];
411 $datarray['author-link'] = 'mailbox';
412 $datarray['author-avatar'] = $contact['photo'];
414 $stored_item = item_store($datarray);
415 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
416 dbesc($datarray['parent-uri']),
417 intval($importer_uid)
419 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
422 switch ($mailconf[0]['action']) {
426 logger("Mail: Deleting ".$msg_uid);
427 imap_delete($mbox, $msg_uid, FT_UID);
430 logger("Mail: Mark as seen ".$msg_uid);
431 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
434 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
435 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
436 if ($mailconf[0]['movetofolder'] != "")
437 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
445 elseif($contact['network'] === NETWORK_FACEBOOK) {
446 // This is picked up by the Facebook plugin on a cron hook.
451 logger('poller: received xml : ' . $xml, LOGGER_DATA);
452 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
453 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
454 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
455 dbesc(datetime_convert()),
456 intval($contact['id'])
462 consume_feed($xml,$importer,$contact,$hub,1,1);
465 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
467 consume_feed($xml,$importer,$contact,$hub,1,2);
469 $hubmode = 'subscribe';
470 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
471 $hubmode = 'unsubscribe';
473 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
476 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
477 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
478 $hubs = explode(',', $hub);
480 foreach($hubs as $h) {
484 subscribe_to_hub($h,$importer,$contact,$hubmode);
490 $updated = datetime_convert();
492 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
495 intval($contact['id'])
499 // load current friends if possible.
501 if($contact['poco']) {
502 $r = q("SELECT count(*) as total from glink
503 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
504 intval($contact['id'])
508 if(! $r[0]['total']) {
509 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
516 if (array_search(__file__,get_included_files())===0){
517 onepoll_run($argv,$argc);