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');
29 load_config('config');
30 load_config('system');
32 $a->set_baseurl(get_config('system','url'));
36 logger('onepoll: start');
38 $abandon_days = intval(get_config('system','account_abandon_days'));
49 if(($argc > 1) && (intval($argv[1])))
50 $contact_id = intval($argv[1]);
53 logger('onepoll: no contact');
57 $d = datetime_convert();
59 // Only poll from those with suitable relationships,
60 // and which have a polling address and ignore Diaspora since
61 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
63 $abandon_sql = (($abandon_days)
64 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
68 $contacts = q("SELECT `contact`.* FROM `contact`
69 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
70 AND NOT `network` IN ( '%s', '%s' )
71 AND `contact`.`id` = %d
72 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
73 AND `contact`.`archive` = 0 LIMIT 1",
74 intval(CONTACT_IS_SHARING),
75 intval(CONTACT_IS_FRIEND),
76 dbesc(NETWORK_DIASPORA),
77 dbesc(NETWORK_FACEBOOK),
81 if(! count($contacts)) {
85 $contact = $contacts[0];
90 $t = $contact['last-update'];
92 if($contact['subhub']) {
93 $interval = get_config('system','pushpoll_frequency');
94 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
97 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
104 $importer_uid = $contact['uid'];
106 $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",
107 intval($importer_uid)
114 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
116 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
117 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
118 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
121 if($contact['network'] === NETWORK_DFRN) {
123 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
124 if(intval($contact['duplex']) && $contact['dfrn-id'])
125 $idtosend = '0:' . $orig_id;
126 if(intval($contact['duplex']) && $contact['issued-id'])
127 $idtosend = '1:' . $orig_id;
129 // they have permission to write to us. We already filtered this in the contact query.
132 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
133 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
134 . '&type=data&last_update=' . $last_update
137 $handshake_xml = fetch_url($url);
139 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
142 if(! $handshake_xml) {
143 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.
147 mark_for_death($contact);
149 // set the last-update so we don't keep polling
150 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
151 dbesc(datetime_convert()),
152 intval($contact['id'])
158 if(! strstr($handshake_xml,'<?xml')) {
159 logger('poller: response from ' . $url . ' did not contain XML.');
160 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
161 dbesc(datetime_convert()),
162 intval($contact['id'])
168 $res = parse_xml_string($handshake_xml);
170 if(intval($res->status) == 1) {
171 logger("poller: $url replied status 1 - marking for death ");
173 // we may not be friends anymore. Will keep trying for one month.
174 // set the last-update so we don't keep polling
177 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
178 dbesc(datetime_convert()),
179 intval($contact['id'])
181 mark_for_death($contact);
184 if($contact['term-date'] != '0000-00-00 00:00:00') {
185 logger("poller: $url back from the dead - removing mark for death");
186 unmark_for_death($contact);
190 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
193 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
194 q("update contact set poco = '%s' where id = %d limit 1",
195 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
196 intval($contact['id'])
202 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
203 $challenge = hex2bin((string) $res->challenge);
207 if(($contact['duplex']) && strlen($contact['prvkey'])) {
208 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
209 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
212 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
213 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
216 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
218 if(strpos($final_dfrn_id,':') == 1)
219 $final_dfrn_id = substr($final_dfrn_id,2);
221 if($final_dfrn_id != $orig_id) {
222 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
223 // did not decode properly - cannot trust this site
227 $postvars['dfrn_id'] = $idtosend;
228 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
229 $postvars['perm'] = 'rw';
231 $xml = post_url($contact['poll'],$postvars);
234 elseif(($contact['network'] === NETWORK_OSTATUS)
235 || ($contact['network'] === NETWORK_DIASPORA)
236 || ($contact['network'] === NETWORK_FEED) ) {
238 // Upgrading DB fields from an older Friendica version
239 // Will only do this once per notify-enabled OStatus contact
240 // or if relationship changes
242 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
244 if($stat_writeable != $contact['writable']) {
245 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
246 intval($stat_writeable),
247 intval($contact['id'])
251 // Are we allowed to import from this person?
253 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
256 $xml = fetch_url($contact['poll']);
258 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
260 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
262 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
266 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
269 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
270 intval($importer_uid)
272 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
273 intval($importer_uid)
275 if(count($x) && count($mailconf)) {
276 $mailbox = construct_mailbox_name($mailconf[0]);
278 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
279 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
281 logger("Mail: Connect");
283 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
284 dbesc(datetime_convert()),
285 intval($mailconf[0]['id']),
286 intval($importer_uid)
292 $msgs = email_poll($mbox,$contact['addr']);
295 logger("Mail: Parsing ".count($msgs)." mails.", LOGGER_DEBUG);
297 foreach($msgs as $msg_uid) {
298 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
301 $meta = email_msg_meta($mbox,$msg_uid);
302 $headers = email_msg_headers($mbox,$msg_uid);
304 // look for a 'references' header and try and match with a parent item we have locally.
306 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
307 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
310 $refs_arr = explode(' ', $raw_refs);
311 if(count($refs_arr)) {
312 for($x = 0; $x < count($refs_arr); $x ++)
313 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
315 $qstr = implode(',',$refs_arr);
316 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
317 intval($importer_uid)
320 $datarray['parent-uri'] = $r[0]['uri'];
324 if(! x($datarray,'parent-uri'))
325 $datarray['parent-uri'] = $datarray['uri'];
327 // Have we seen it before?
328 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
329 intval($importer_uid),
330 dbesc($datarray['uri'])
334 // logger("Mail: Seen before ".$msg_uid);
335 if($meta->deleted && ! $r[0]['deleted']) {
336 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
337 dbesc(datetime_convert()),
341 switch ($mailconf[0]['action']) {
345 logger("Mail: Deleting ".$msg_uid);
346 imap_delete($mbox, $msg_uid, FT_UID);
349 logger("Mail: Mark as seen ".$msg_uid);
350 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
353 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
354 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
355 if ($mailconf[0]['movetofolder'] != "")
356 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
362 // Decoding the header
363 $subject = imap_mime_header_decode($meta->subject);
364 $datarray['title'] = "";
365 foreach($subject as $subpart)
366 if ($subpart->charset != "default")
367 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
369 $datarray['title'] .= $subpart->text;
371 $datarray['title'] = notags(trim($datarray['title']));
373 //$datarray['title'] = notags(trim($meta->subject));
374 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
377 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
378 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
381 $r = email_get_msg($mbox,$msg_uid, $reply);
383 logger("Mail: can't fetch msg ".$msg_uid);
386 $datarray['body'] = escape_tags($r['body']);
388 logger("Mail: Importing ".$msg_uid);
390 // some mailing lists have the original author as 'from' - add this sender info to msg body.
391 // todo: adding a gravatar for the original author would be cool
393 if(! stristr($meta->from,$contact['addr'])) {
394 $from = imap_mime_header_decode($meta->from);
396 foreach($from as $frompart)
397 if ($frompart->charset != "default")
398 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
400 $fromdecoded .= $frompart->text;
402 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
405 $datarray['uid'] = $importer_uid;
406 $datarray['contact-id'] = $contact['id'];
407 if($datarray['parent-uri'] === $datarray['uri'])
408 $datarray['private'] = 1;
409 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
410 $datarray['private'] = 1;
411 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
413 $datarray['author-name'] = $contact['name'];
414 $datarray['author-link'] = 'mailbox';
415 $datarray['author-avatar'] = $contact['photo'];
417 $stored_item = item_store($datarray);
418 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
419 dbesc($datarray['parent-uri']),
420 intval($importer_uid)
422 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
425 switch ($mailconf[0]['action']) {
429 logger("Mail: Deleting ".$msg_uid);
430 imap_delete($mbox, $msg_uid, FT_UID);
433 logger("Mail: Mark as seen ".$msg_uid);
434 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
437 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
438 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
439 if ($mailconf[0]['movetofolder'] != "")
440 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
448 elseif($contact['network'] === NETWORK_FACEBOOK) {
449 // This is picked up by the Facebook plugin on a cron hook.
454 logger('poller: received xml : ' . $xml, LOGGER_DATA);
455 if(! strstr($xml,'<?xml')) {
456 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
457 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
458 dbesc(datetime_convert()),
459 intval($contact['id'])
465 consume_feed($xml,$importer,$contact,$hub,1,1);
468 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
470 consume_feed($xml,$importer,$contact,$hub,1,2);
472 $hubmode = 'subscribe';
473 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
474 $hubmode = 'unsubscribe';
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);