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');
58 if(was_recently_delayed($contact_id))
61 $d = datetime_convert();
63 // Only poll from those with suitable relationships,
64 // and which have a polling address and ignore Diaspora since
65 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
67 $abandon_sql = (($abandon_days)
68 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
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_DIASPORA),
81 dbesc(NETWORK_FACEBOOK),
85 if(! count($contacts)) {
89 $contact = $contacts[0];
94 $t = $contact['last-update'];
96 if($contact['subhub']) {
97 $interval = get_config('system','pushpoll_frequency');
98 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
101 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
108 $importer_uid = $contact['uid'];
110 $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",
111 intval($importer_uid)
118 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
120 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
121 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
122 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
125 if($contact['network'] === NETWORK_DFRN) {
127 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
128 if(intval($contact['duplex']) && $contact['dfrn-id'])
129 $idtosend = '0:' . $orig_id;
130 if(intval($contact['duplex']) && $contact['issued-id'])
131 $idtosend = '1:' . $orig_id;
133 // they have permission to write to us. We already filtered this in the contact query.
136 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
137 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
138 . '&type=data&last_update=' . $last_update
141 $handshake_xml = fetch_url($url);
143 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
146 if(! $handshake_xml) {
147 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.
151 mark_for_death($contact);
153 // set the last-update so we don't keep polling
154 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
155 dbesc(datetime_convert()),
156 intval($contact['id'])
162 if(! strstr($handshake_xml,'<?xml')) {
163 logger('poller: response from ' . $url . ' did not contain XML.');
164 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
165 dbesc(datetime_convert()),
166 intval($contact['id'])
172 $res = parse_xml_string($handshake_xml);
174 if(intval($res->status) == 1) {
175 logger("poller: $url replied status 1 - marking for death ");
177 // we may not be friends anymore. Will keep trying for one month.
178 // set the last-update so we don't keep polling
181 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
182 dbesc(datetime_convert()),
183 intval($contact['id'])
185 mark_for_death($contact);
188 if($contact['term-date'] != '0000-00-00 00:00:00') {
189 logger("poller: $url back from the dead - removing mark for death");
190 unmark_for_death($contact);
194 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
197 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
198 q("update contact set poco = '%s' where id = %d limit 1",
199 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
200 intval($contact['id'])
206 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
207 $challenge = hex2bin((string) $res->challenge);
211 if(($contact['duplex']) && strlen($contact['prvkey'])) {
212 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
213 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
216 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
217 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
220 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
222 if(strpos($final_dfrn_id,':') == 1)
223 $final_dfrn_id = substr($final_dfrn_id,2);
225 if($final_dfrn_id != $orig_id) {
226 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
227 // did not decode properly - cannot trust this site
231 $postvars['dfrn_id'] = $idtosend;
232 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
233 $postvars['perm'] = 'rw';
235 $xml = post_url($contact['poll'],$postvars);
238 elseif(($contact['network'] === NETWORK_OSTATUS)
239 || ($contact['network'] === NETWORK_DIASPORA)
240 || ($contact['network'] === NETWORK_FEED) ) {
242 // Upgrading DB fields from an older Friendica version
243 // Will only do this once per notify-enabled OStatus contact
244 // or if relationship changes
246 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
248 if($stat_writeable != $contact['writable']) {
249 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
250 intval($stat_writeable),
251 intval($contact['id'])
255 // Are we allowed to import from this person?
257 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
260 $xml = fetch_url($contact['poll']);
262 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
264 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
266 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
270 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
273 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
274 intval($importer_uid)
276 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
277 intval($importer_uid)
279 if(count($x) && count($mailconf)) {
280 $mailbox = construct_mailbox_name($mailconf[0]);
282 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
283 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
285 logger("Mail: Connect");
287 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
288 dbesc(datetime_convert()),
289 intval($mailconf[0]['id']),
290 intval($importer_uid)
296 $msgs = email_poll($mbox,$contact['addr']);
299 logger("Mail: Parsing ".count($msgs)." mails.", LOGGER_DEBUG);
301 foreach($msgs as $msg_uid) {
302 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
305 $meta = email_msg_meta($mbox,$msg_uid);
306 $headers = email_msg_headers($mbox,$msg_uid);
308 // look for a 'references' header and try and match with a parent item we have locally.
310 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
311 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
314 $refs_arr = explode(' ', $raw_refs);
315 if(count($refs_arr)) {
316 for($x = 0; $x < count($refs_arr); $x ++)
317 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
319 $qstr = implode(',',$refs_arr);
320 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
321 intval($importer_uid)
324 $datarray['parent-uri'] = $r[0]['uri'];
328 if(! x($datarray,'parent-uri'))
329 $datarray['parent-uri'] = $datarray['uri'];
331 // Have we seen it before?
332 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
333 intval($importer_uid),
334 dbesc($datarray['uri'])
338 // logger("Mail: Seen before ".$msg_uid);
339 if($meta->deleted && ! $r[0]['deleted']) {
340 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
341 dbesc(datetime_convert()),
345 switch ($mailconf[0]['action']) {
349 logger("Mail: Deleting ".$msg_uid);
350 imap_delete($mbox, $msg_uid, FT_UID);
353 logger("Mail: Mark as seen ".$msg_uid);
354 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
357 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
358 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
359 if ($mailconf[0]['movetofolder'] != "")
360 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
366 // Decoding the header
367 $subject = imap_mime_header_decode($meta->subject);
368 $datarray['title'] = "";
369 foreach($subject as $subpart)
370 if ($subpart->charset != "default")
371 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
373 $datarray['title'] .= $subpart->text;
375 $datarray['title'] = notags(trim($datarray['title']));
377 //$datarray['title'] = notags(trim($meta->subject));
378 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
381 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
382 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
385 $r = email_get_msg($mbox,$msg_uid, $reply);
387 logger("Mail: can't fetch msg ".$msg_uid);
390 $datarray['body'] = escape_tags($r['body']);
392 logger("Mail: Importing ".$msg_uid);
394 // some mailing lists have the original author as 'from' - add this sender info to msg body.
395 // todo: adding a gravatar for the original author would be cool
397 if(! stristr($meta->from,$contact['addr'])) {
398 $from = imap_mime_header_decode($meta->from);
400 foreach($from as $frompart)
401 if ($frompart->charset != "default")
402 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
404 $fromdecoded .= $frompart->text;
406 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
409 $datarray['uid'] = $importer_uid;
410 $datarray['contact-id'] = $contact['id'];
411 if($datarray['parent-uri'] === $datarray['uri'])
412 $datarray['private'] = 1;
413 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
414 $datarray['private'] = 1;
415 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
417 $datarray['author-name'] = $contact['name'];
418 $datarray['author-link'] = 'mailbox';
419 $datarray['author-avatar'] = $contact['photo'];
421 $stored_item = item_store($datarray);
422 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
423 dbesc($datarray['parent-uri']),
424 intval($importer_uid)
426 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
429 switch ($mailconf[0]['action']) {
433 logger("Mail: Deleting ".$msg_uid);
434 imap_delete($mbox, $msg_uid, FT_UID);
437 logger("Mail: Mark as seen ".$msg_uid);
438 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
441 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
442 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
443 if ($mailconf[0]['movetofolder'] != "")
444 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
452 elseif($contact['network'] === NETWORK_FACEBOOK) {
453 // This is picked up by the Facebook plugin on a cron hook.
458 logger('poller: received xml : ' . $xml, LOGGER_DATA);
459 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
460 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
461 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
462 dbesc(datetime_convert()),
463 intval($contact['id'])
469 consume_feed($xml,$importer,$contact,$hub,1,1);
472 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
474 consume_feed($xml,$importer,$contact,$hub,1,2);
476 $hubmode = 'subscribe';
477 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
478 $hubmode = 'unsubscribe';
480 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
483 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
484 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
485 $hubs = explode(',', $hub);
487 foreach($hubs as $h) {
491 subscribe_to_hub($h,$importer,$contact,$hubmode);
497 $updated = datetime_convert();
499 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
502 intval($contact['id'])
506 // load current friends if possible.
508 if($contact['poco']) {
509 $r = q("SELECT count(*) as total from glink
510 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
511 intval($contact['id'])
515 if(! $r[0]['total']) {
516 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
523 if (array_search(__file__,get_included_files())===0){
524 onepoll_run($argv,$argc);