3 require_once("boot.php");
5 function RemoveReply($subject) {
6 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
7 $subject = trim(substr($subject, 4));
12 function onepoll_run(&$argv, &$argc){
20 @include(".htconfig.php");
21 require_once("dba.php");
22 $db = new dba($db_host, $db_user, $db_pass, $db_data);
23 unset($db_host, $db_user, $db_pass, $db_data);
27 require_once('include/session.php');
28 require_once('include/datetime.php');
29 require_once('library/simplepie/simplepie.inc');
30 require_once('include/items.php');
31 require_once('include/Contact.php');
32 require_once('include/email.php');
33 require_once('include/socgraph.php');
34 require_once('include/pidfile.php');
35 require_once('include/queue_fn.php');
37 load_config('config');
38 load_config('system');
40 $a->set_baseurl(get_config('system','url'));
44 logger('onepoll: start');
52 if(($argc > 1) && (intval($argv[1])))
53 $contact_id = intval($argv[1]);
56 logger('onepoll: no contact');
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 $contacts = q("SELECT `contact`.* FROM `contact`
68 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
69 AND NOT `network` IN ( '%s', '%s' )
70 AND `contact`.`id` = %d
71 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
72 AND `contact`.`archive` = 0 LIMIT 1",
73 intval(CONTACT_IS_SHARING),
74 intval(CONTACT_IS_FRIEND),
75 dbesc(NETWORK_DIASPORA),
76 dbesc(NETWORK_FACEBOOK),
80 if(! count($contacts)) {
84 $contact = $contacts[0];
88 $t = $contact['last-update'];
90 if($contact['subhub']) {
91 $poll_interval = get_config('system','pushpoll_frequency');
92 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
95 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
102 $importer_uid = $contact['uid'];
104 $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 intval($importer_uid)
112 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
114 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
115 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
116 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
119 if($contact['network'] === NETWORK_DFRN) {
122 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
123 if(intval($contact['duplex']) && $contact['dfrn-id'])
124 $idtosend = '0:' . $orig_id;
125 if(intval($contact['duplex']) && $contact['issued-id'])
126 $idtosend = '1:' . $orig_id;
128 // they have permission to write to us. We already filtered this in the contact query.
131 // But this may be our first communication, so set the writable flag if it isn't set already.
133 if(! intval($contact['writable']))
134 q("update contact set writable = 1 where id = %d limit 1", intval($contact['id']));
137 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
138 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
139 . '&type=data&last_update=' . $last_update
142 $handshake_xml = fetch_url($url);
143 $html_code = $a->get_curl_code();
145 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
148 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
149 logger("poller: $url appears to be dead - marking for death ");
151 // dead connection - might be a transient event, or this might
152 // mean the software was uninstalled or the domain expired.
153 // Will keep trying for one month.
155 mark_for_death($contact);
157 // set the last-update so we don't keep polling
158 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
159 dbesc(datetime_convert()),
160 intval($contact['id'])
166 if(! strstr($handshake_xml,'<?xml')) {
167 logger('poller: response from ' . $url . ' did not contain XML.');
169 mark_for_death($contact);
171 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
172 dbesc(datetime_convert()),
173 intval($contact['id'])
179 $res = parse_xml_string($handshake_xml);
181 if(intval($res->status) == 1) {
182 logger("poller: $url replied status 1 - marking for death ");
184 // we may not be friends anymore. Will keep trying for one month.
185 // set the last-update so we don't keep polling
188 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
189 dbesc(datetime_convert()),
190 intval($contact['id'])
192 mark_for_death($contact);
195 if($contact['term-date'] != '0000-00-00 00:00:00') {
196 logger("poller: $url back from the dead - removing mark for death");
197 unmark_for_death($contact);
201 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
204 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
205 q("update contact set poco = '%s' where id = %d limit 1",
206 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
207 intval($contact['id'])
213 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
214 $challenge = hex2bin((string) $res->challenge);
218 if(($contact['duplex']) && strlen($contact['prvkey'])) {
219 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
220 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
223 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
224 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
227 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
229 if(strpos($final_dfrn_id,':') == 1)
230 $final_dfrn_id = substr($final_dfrn_id,2);
232 if($final_dfrn_id != $orig_id) {
233 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
234 // did not decode properly - cannot trust this site
238 $postvars['dfrn_id'] = $idtosend;
239 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
240 $postvars['perm'] = 'rw';
242 $xml = post_url($contact['poll'],$postvars);
245 elseif(($contact['network'] === NETWORK_OSTATUS)
246 || ($contact['network'] === NETWORK_DIASPORA)
247 || ($contact['network'] === NETWORK_FEED) ) {
249 // Upgrading DB fields from an older Friendica version
250 // Will only do this once per notify-enabled OStatus contact
251 // or if relationship changes
253 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
255 if($stat_writeable != $contact['writable']) {
256 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
257 intval($stat_writeable),
258 intval($contact['id'])
262 // Are we allowed to import from this person?
264 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
267 $xml = fetch_url($contact['poll']);
269 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
271 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
273 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
277 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
280 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
281 intval($importer_uid)
283 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
284 intval($importer_uid)
286 if(count($x) && count($mailconf)) {
287 $mailbox = construct_mailbox_name($mailconf[0]);
289 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
290 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
292 logger("Mail: Connect to " . $mailconf[0]['user']);
294 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
295 dbesc(datetime_convert()),
296 intval($mailconf[0]['id']),
297 intval($importer_uid)
303 $msgs = email_poll($mbox,$contact['addr']);
306 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
308 $metas = email_msg_meta($mbox,implode(',',$msgs));
309 if(count($metas) != count($msgs)) {
310 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
313 $msgs = array_combine($msgs, $metas);
315 foreach($msgs as $msg_uid => $meta) {
316 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
319 // $meta = email_msg_meta($mbox,$msg_uid);
320 // $headers = email_msg_headers($mbox,$msg_uid);
322 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
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." for ".$mailconf[0]['user'],LOGGER_DEBUG);
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']) {
340 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
343 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
344 imap_delete($mbox, $msg_uid, FT_UID);
347 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
348 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
351 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
352 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
353 if ($mailconf[0]['movetofolder'] != "")
354 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
361 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
363 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
364 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
365 if(! trim($raw_refs))
366 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
367 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
370 $refs_arr = explode(' ', $raw_refs);
371 if(count($refs_arr)) {
372 for($x = 0; $x < count($refs_arr); $x ++)
373 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
375 $qstr = implode(',',$refs_arr);
376 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
377 intval($importer_uid)
380 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
381 // $datarray['parent-uri'] = $r[0]['uri'];
384 // Decoding the header
385 $subject = imap_mime_header_decode($meta->subject);
386 $datarray['title'] = "";
387 foreach($subject as $subpart)
388 if ($subpart->charset != "default")
389 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
391 $datarray['title'] .= $subpart->text;
393 $datarray['title'] = notags(trim($datarray['title']));
395 //$datarray['title'] = notags(trim($meta->subject));
396 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
399 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
400 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
403 // Remove Reply-signs in the subject
404 $datarray['title'] = RemoveReply($datarray['title']);
406 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
407 if(!x($datarray,'parent-uri') and $reply) {
408 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE MATCH (`title`) AGAINST ('".'"%s"'."' IN BOOLEAN MODE) ORDER BY `created` DESC LIMIT 1",
409 dbesc(protect_sprintf($datarray['title'])));
411 $datarray['parent-uri'] = $r[0]['parent-uri'];
414 if(! x($datarray,'parent-uri'))
415 $datarray['parent-uri'] = $datarray['uri'];
418 $r = email_get_msg($mbox,$msg_uid, $reply);
420 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
423 $datarray['body'] = escape_tags($r['body']);
425 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
427 // some mailing lists have the original author as 'from' - add this sender info to msg body.
428 // todo: adding a gravatar for the original author would be cool
430 if(! stristr($meta->from,$contact['addr'])) {
431 $from = imap_mime_header_decode($meta->from);
433 foreach($from as $frompart)
434 if ($frompart->charset != "default")
435 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
437 $fromdecoded .= $frompart->text;
439 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
442 $datarray['uid'] = $importer_uid;
443 $datarray['contact-id'] = $contact['id'];
444 if($datarray['parent-uri'] === $datarray['uri'])
445 $datarray['private'] = 1;
446 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
447 $datarray['private'] = 1;
448 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
450 $datarray['author-name'] = $contact['name'];
451 $datarray['author-link'] = 'mailbox';
452 $datarray['author-avatar'] = $contact['photo'];
454 $stored_item = item_store($datarray);
455 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
456 dbesc($datarray['parent-uri']),
457 intval($importer_uid)
459 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
462 switch ($mailconf[0]['action']) {
464 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
467 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
468 imap_delete($mbox, $msg_uid, FT_UID);
471 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
472 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
475 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
476 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
477 if ($mailconf[0]['movetofolder'] != "")
478 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
487 elseif($contact['network'] === NETWORK_FACEBOOK) {
488 // This is picked up by the Facebook plugin on a cron hook.
493 logger('poller: received xml : ' . $xml, LOGGER_DATA);
494 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
495 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
496 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
497 dbesc(datetime_convert()),
498 intval($contact['id'])
504 consume_feed($xml,$importer,$contact,$hub,1,1);
507 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
509 consume_feed($xml,$importer,$contact,$hub,1,2);
511 $hubmode = 'subscribe';
512 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
513 $hubmode = 'unsubscribe';
515 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
518 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
519 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
520 $hubs = explode(',', $hub);
522 foreach($hubs as $h) {
526 subscribe_to_hub($h,$importer,$contact,$hubmode);
532 $updated = datetime_convert();
534 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
537 intval($contact['id'])
541 // load current friends if possible.
543 if($contact['poco']) {
544 $r = q("SELECT count(*) as total from glink
545 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
546 intval($contact['id'])
550 if(! $r[0]['total']) {
551 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
558 if (array_search(__file__,get_included_files())===0){
559 onepoll_run($argv,$argc);