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];
91 $t = $contact['last-update'];
93 if($contact['subhub']) {
94 $poll_interval = get_config('system','pushpoll_frequency');
95 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
98 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
105 $importer_uid = $contact['uid'];
107 $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",
108 intval($importer_uid)
115 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
117 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
118 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
119 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
122 if($contact['network'] === NETWORK_DFRN) {
124 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
125 if(intval($contact['duplex']) && $contact['dfrn-id'])
126 $idtosend = '0:' . $orig_id;
127 if(intval($contact['duplex']) && $contact['issued-id'])
128 $idtosend = '1:' . $orig_id;
130 // they have permission to write to us. We already filtered this in the contact query.
133 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
134 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
135 . '&type=data&last_update=' . $last_update
138 $handshake_xml = fetch_url($url);
139 $html_code = $a->get_curl_code();
141 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
144 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
145 logger("poller: $url appears to be dead - marking for death ");
147 // dead connection - might be a transient event, or this might
148 // mean the software was uninstalled or the domain expired.
149 // 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.');
165 mark_for_death($contact);
167 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
168 dbesc(datetime_convert()),
169 intval($contact['id'])
175 $res = parse_xml_string($handshake_xml);
177 if(intval($res->status) == 1) {
178 logger("poller: $url replied status 1 - marking for death ");
180 // we may not be friends anymore. Will keep trying for one month.
181 // set the last-update so we don't keep polling
184 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
185 dbesc(datetime_convert()),
186 intval($contact['id'])
188 mark_for_death($contact);
191 if($contact['term-date'] != '0000-00-00 00:00:00') {
192 logger("poller: $url back from the dead - removing mark for death");
193 unmark_for_death($contact);
197 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
200 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
201 q("update contact set poco = '%s' where id = %d limit 1",
202 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
203 intval($contact['id'])
209 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
210 $challenge = hex2bin((string) $res->challenge);
214 if(($contact['duplex']) && strlen($contact['prvkey'])) {
215 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
216 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
219 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
220 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
223 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
225 if(strpos($final_dfrn_id,':') == 1)
226 $final_dfrn_id = substr($final_dfrn_id,2);
228 if($final_dfrn_id != $orig_id) {
229 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
230 // did not decode properly - cannot trust this site
234 $postvars['dfrn_id'] = $idtosend;
235 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
236 $postvars['perm'] = 'rw';
238 $xml = post_url($contact['poll'],$postvars);
241 elseif(($contact['network'] === NETWORK_OSTATUS)
242 || ($contact['network'] === NETWORK_DIASPORA)
243 || ($contact['network'] === NETWORK_FEED) ) {
245 // Upgrading DB fields from an older Friendica version
246 // Will only do this once per notify-enabled OStatus contact
247 // or if relationship changes
249 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
251 if($stat_writeable != $contact['writable']) {
252 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
253 intval($stat_writeable),
254 intval($contact['id'])
258 // Are we allowed to import from this person?
260 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
263 $xml = fetch_url($contact['poll']);
265 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
267 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
269 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
273 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
276 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
277 intval($importer_uid)
279 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
280 intval($importer_uid)
282 if(count($x) && count($mailconf)) {
283 $mailbox = construct_mailbox_name($mailconf[0]);
285 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
286 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
288 logger("Mail: Connect");
290 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
291 dbesc(datetime_convert()),
292 intval($mailconf[0]['id']),
293 intval($importer_uid)
299 $msgs = email_poll($mbox,$contact['addr']);
302 logger("Mail: Parsing ".count($msgs)." mails.", LOGGER_DEBUG);
304 foreach($msgs as $msg_uid) {
305 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
308 $meta = email_msg_meta($mbox,$msg_uid);
309 $headers = email_msg_headers($mbox,$msg_uid);
311 // look for a 'references' header and try and match with a parent item we have locally.
313 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
314 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
317 $refs_arr = explode(' ', $raw_refs);
318 if(count($refs_arr)) {
319 for($x = 0; $x < count($refs_arr); $x ++)
320 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
322 $qstr = implode(',',$refs_arr);
323 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
324 intval($importer_uid)
327 $datarray['parent-uri'] = $r[0]['uri'];
331 if(! x($datarray,'parent-uri'))
332 $datarray['parent-uri'] = $datarray['uri'];
334 // Have we seen it before?
335 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
336 intval($importer_uid),
337 dbesc($datarray['uri'])
341 // logger("Mail: Seen before ".$msg_uid);
342 if($meta->deleted && ! $r[0]['deleted']) {
343 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
344 dbesc(datetime_convert()),
348 switch ($mailconf[0]['action']) {
352 logger("Mail: Deleting ".$msg_uid);
353 imap_delete($mbox, $msg_uid, FT_UID);
356 logger("Mail: Mark as seen ".$msg_uid);
357 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
360 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
361 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
362 if ($mailconf[0]['movetofolder'] != "")
363 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
369 // Decoding the header
370 $subject = imap_mime_header_decode($meta->subject);
371 $datarray['title'] = "";
372 foreach($subject as $subpart)
373 if ($subpart->charset != "default")
374 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
376 $datarray['title'] .= $subpart->text;
378 $datarray['title'] = notags(trim($datarray['title']));
380 //$datarray['title'] = notags(trim($meta->subject));
381 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
384 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
385 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
388 $r = email_get_msg($mbox,$msg_uid, $reply);
390 logger("Mail: can't fetch msg ".$msg_uid);
393 $datarray['body'] = escape_tags($r['body']);
395 logger("Mail: Importing ".$msg_uid);
397 // some mailing lists have the original author as 'from' - add this sender info to msg body.
398 // todo: adding a gravatar for the original author would be cool
400 if(! stristr($meta->from,$contact['addr'])) {
401 $from = imap_mime_header_decode($meta->from);
403 foreach($from as $frompart)
404 if ($frompart->charset != "default")
405 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
407 $fromdecoded .= $frompart->text;
409 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
412 $datarray['uid'] = $importer_uid;
413 $datarray['contact-id'] = $contact['id'];
414 if($datarray['parent-uri'] === $datarray['uri'])
415 $datarray['private'] = 1;
416 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
417 $datarray['private'] = 1;
418 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
420 $datarray['author-name'] = $contact['name'];
421 $datarray['author-link'] = 'mailbox';
422 $datarray['author-avatar'] = $contact['photo'];
424 $stored_item = item_store($datarray);
425 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
426 dbesc($datarray['parent-uri']),
427 intval($importer_uid)
429 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
432 switch ($mailconf[0]['action']) {
436 logger("Mail: Deleting ".$msg_uid);
437 imap_delete($mbox, $msg_uid, FT_UID);
440 logger("Mail: Mark as seen ".$msg_uid);
441 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
444 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
445 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
446 if ($mailconf[0]['movetofolder'] != "")
447 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
455 elseif($contact['network'] === NETWORK_FACEBOOK) {
456 // This is picked up by the Facebook plugin on a cron hook.
461 logger('poller: received xml : ' . $xml, LOGGER_DATA);
462 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
463 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
464 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
465 dbesc(datetime_convert()),
466 intval($contact['id'])
472 consume_feed($xml,$importer,$contact,$hub,1,1);
475 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
477 consume_feed($xml,$importer,$contact,$hub,1,2);
479 $hubmode = 'subscribe';
480 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
481 $hubmode = 'unsubscribe';
483 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
486 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
487 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
488 $hubs = explode(',', $hub);
490 foreach($hubs as $h) {
494 subscribe_to_hub($h,$importer,$contact,$hubmode);
500 $updated = datetime_convert();
502 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
505 intval($contact['id'])
509 // load current friends if possible.
511 if($contact['poco']) {
512 $r = q("SELECT count(*) as total from glink
513 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
514 intval($contact['id'])
518 if(! $r[0]['total']) {
519 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
526 if (array_search(__file__,get_included_files())===0){
527 onepoll_run($argv,$argc);