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) {
115 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
116 if(intval($contact['duplex']) && $contact['dfrn-id'])
117 $idtosend = '0:' . $orig_id;
118 if(intval($contact['duplex']) && $contact['issued-id'])
119 $idtosend = '1:' . $orig_id;
121 // they have permission to write to us. We already filtered this in the contact query.
124 // But this may be our first communication, so set the writable flag if it isn't set already.
126 if(! intval($contact['writable']))
127 q("update contact set writable = 1 where id = %d limit 1", intval($contact['id']));
130 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
131 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
132 . '&type=data&last_update=' . $last_update
135 $handshake_xml = fetch_url($url);
136 $html_code = $a->get_curl_code();
138 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
141 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
142 logger("poller: $url appears to be dead - marking for death ");
144 // dead connection - might be a transient event, or this might
145 // mean the software was uninstalled or the domain expired.
146 // Will keep trying for one month.
148 mark_for_death($contact);
150 // set the last-update so we don't keep polling
151 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
152 dbesc(datetime_convert()),
153 intval($contact['id'])
159 if(! strstr($handshake_xml,'<?xml')) {
160 logger('poller: response from ' . $url . ' did not contain XML.');
162 mark_for_death($contact);
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 to " . $mailconf[0]['user']);
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 for ".$mailconf[0]['user'], LOGGER_DEBUG);
301 $metas = email_msg_meta($mbox,implode(',',$msgs));
302 if(count($metas) != count($msgs)) {
303 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
306 $msgs = array_combine($msgs, $metas);
308 foreach($msgs as $msg_uid => $meta) {
309 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
312 // $meta = email_msg_meta($mbox,$msg_uid);
313 // $headers = email_msg_headers($mbox,$msg_uid);
315 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
317 // Have we seen it before?
318 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
319 intval($importer_uid),
320 dbesc($datarray['uri'])
324 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'],LOGGER_DEBUG);
325 if($meta->deleted && ! $r[0]['deleted']) {
326 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
327 dbesc(datetime_convert()),
331 /*switch ($mailconf[0]['action']) {
333 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
336 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
337 imap_delete($mbox, $msg_uid, FT_UID);
340 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
341 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
344 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
345 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
346 if ($mailconf[0]['movetofolder'] != "")
347 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
354 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
356 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
357 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
358 if(! trim($raw_refs))
359 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
360 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
363 $refs_arr = explode(' ', $raw_refs);
364 if(count($refs_arr)) {
365 for($x = 0; $x < count($refs_arr); $x ++)
366 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
368 $qstr = implode(',',$refs_arr);
369 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
370 intval($importer_uid)
373 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
374 // $datarray['parent-uri'] = $r[0]['uri'];
378 if(! x($datarray,'parent-uri'))
379 $datarray['parent-uri'] = $datarray['uri'];
381 // Decoding the header
382 $subject = imap_mime_header_decode($meta->subject);
383 $datarray['title'] = "";
384 foreach($subject as $subpart)
385 if ($subpart->charset != "default")
386 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
388 $datarray['title'] .= $subpart->text;
390 $datarray['title'] = notags(trim($datarray['title']));
392 //$datarray['title'] = notags(trim($meta->subject));
393 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
396 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
397 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
400 $r = email_get_msg($mbox,$msg_uid, $reply);
402 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
405 $datarray['body'] = escape_tags($r['body']);
407 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
409 // some mailing lists have the original author as 'from' - add this sender info to msg body.
410 // todo: adding a gravatar for the original author would be cool
412 if(! stristr($meta->from,$contact['addr'])) {
413 $from = imap_mime_header_decode($meta->from);
415 foreach($from as $frompart)
416 if ($frompart->charset != "default")
417 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
419 $fromdecoded .= $frompart->text;
421 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
424 $datarray['uid'] = $importer_uid;
425 $datarray['contact-id'] = $contact['id'];
426 if($datarray['parent-uri'] === $datarray['uri'])
427 $datarray['private'] = 1;
428 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
429 $datarray['private'] = 1;
430 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
432 $datarray['author-name'] = $contact['name'];
433 $datarray['author-link'] = 'mailbox';
434 $datarray['author-avatar'] = $contact['photo'];
436 $stored_item = item_store($datarray);
437 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
438 dbesc($datarray['parent-uri']),
439 intval($importer_uid)
441 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
444 switch ($mailconf[0]['action']) {
446 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
449 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
450 imap_delete($mbox, $msg_uid, FT_UID);
453 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
454 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
457 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
458 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
459 if ($mailconf[0]['movetofolder'] != "")
460 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
469 elseif($contact['network'] === NETWORK_FACEBOOK) {
470 // This is picked up by the Facebook plugin on a cron hook.
475 logger('poller: received xml : ' . $xml, LOGGER_DATA);
476 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
477 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
478 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
479 dbesc(datetime_convert()),
480 intval($contact['id'])
486 consume_feed($xml,$importer,$contact,$hub,1,1);
489 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
491 consume_feed($xml,$importer,$contact,$hub,1,2);
493 $hubmode = 'subscribe';
494 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
495 $hubmode = 'unsubscribe';
497 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
500 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
501 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
502 $hubs = explode(',', $hub);
504 foreach($hubs as $h) {
508 subscribe_to_hub($h,$importer,$contact,$hubmode);
514 $updated = datetime_convert();
516 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
519 intval($contact['id'])
523 // load current friends if possible.
525 if($contact['poco']) {
526 $r = q("SELECT count(*) as total from glink
527 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
528 intval($contact['id'])
532 if(! $r[0]['total']) {
533 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
540 if (array_search(__file__,get_included_files())===0){
541 onepoll_run($argv,$argc);