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("include/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($contact['network'] === NETWORK_OSTATUS && get_pconfig($importer_uid,'system','ostatus_autofriend'))
258 if($stat_writeable != $contact['writable']) {
259 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
260 intval($stat_writeable),
261 intval($contact['id'])
265 // Are we allowed to import from this person?
267 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
270 $xml = fetch_url($contact['poll']);
272 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
274 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
276 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
280 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
283 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
284 intval($importer_uid)
286 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
287 intval($importer_uid)
289 if(count($x) && count($mailconf)) {
290 $mailbox = construct_mailbox_name($mailconf[0]);
292 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
293 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
295 logger("Mail: Connect to " . $mailconf[0]['user']);
297 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
298 dbesc(datetime_convert()),
299 intval($mailconf[0]['id']),
300 intval($importer_uid)
306 $msgs = email_poll($mbox,$contact['addr']);
309 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
311 $metas = email_msg_meta($mbox,implode(',',$msgs));
312 if(count($metas) != count($msgs)) {
313 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
316 $msgs = array_combine($msgs, $metas);
318 foreach($msgs as $msg_uid => $meta) {
319 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
322 // $meta = email_msg_meta($mbox,$msg_uid);
323 // $headers = email_msg_headers($mbox,$msg_uid);
325 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
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." for ".$mailconf[0]['user'],LOGGER_DEBUG);
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']) {
343 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
346 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
347 imap_delete($mbox, $msg_uid, FT_UID);
350 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
351 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
354 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
355 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
356 if ($mailconf[0]['movetofolder'] != "")
357 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
364 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
366 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
367 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
368 if(! trim($raw_refs))
369 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
370 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
373 $refs_arr = explode(' ', $raw_refs);
374 if(count($refs_arr)) {
375 for($x = 0; $x < count($refs_arr); $x ++)
376 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
378 $qstr = implode(',',$refs_arr);
379 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
380 intval($importer_uid)
383 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
384 // $datarray['parent-uri'] = $r[0]['uri'];
387 // Decoding the header
388 $subject = imap_mime_header_decode($meta->subject);
389 $datarray['title'] = "";
390 foreach($subject as $subpart)
391 if ($subpart->charset != "default")
392 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
394 $datarray['title'] .= $subpart->text;
396 $datarray['title'] = notags(trim($datarray['title']));
398 //$datarray['title'] = notags(trim($meta->subject));
399 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
402 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
403 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
406 // Remove Reply-signs in the subject
407 $datarray['title'] = RemoveReply($datarray['title']);
409 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
410 if(!x($datarray,'parent-uri') and $reply) {
411 //$r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE MATCH (`title`) AGAINST ('".'"%s"'."' IN BOOLEAN MODE) AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
412 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
413 dbesc(protect_sprintf($datarray['title'])),
414 intval($importer_uid));
416 $datarray['parent-uri'] = $r[0]['parent-uri'];
419 if(! x($datarray,'parent-uri'))
420 $datarray['parent-uri'] = $datarray['uri'];
423 $r = email_get_msg($mbox,$msg_uid, $reply);
425 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
428 $datarray['body'] = escape_tags($r['body']);
429 $datarray['body'] = limit_body_size($datarray['body']);
431 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
433 // some mailing lists have the original author as 'from' - add this sender info to msg body.
434 // todo: adding a gravatar for the original author would be cool
436 if(! stristr($meta->from,$contact['addr'])) {
437 $from = imap_mime_header_decode($meta->from);
439 foreach($from as $frompart)
440 if ($frompart->charset != "default")
441 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
443 $fromdecoded .= $frompart->text;
445 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
447 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
449 if (isset($fromarr[0]->personal))
450 $fromname = $fromarr[0]->personal;
452 $fromname = $frommail;
454 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
456 $datarray['author-name'] = $fromname;
457 $datarray['author-link'] = "mailto:".$frommail;
458 $datarray['author-avatar'] = $contact['photo'];
460 $datarray['owner-name'] = $contact['name'];
461 $datarray['owner-link'] = "mailto:".$contact['addr'];
462 $datarray['owner-avatar'] = $contact['photo'];
465 $datarray['author-name'] = $contact['name'];
466 $datarray['author-link'] = 'mailbox';
467 $datarray['author-avatar'] = $contact['photo'];
470 $datarray['uid'] = $importer_uid;
471 $datarray['contact-id'] = $contact['id'];
472 if($datarray['parent-uri'] === $datarray['uri'])
473 $datarray['private'] = 1;
474 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
475 $datarray['private'] = 1;
476 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
479 $stored_item = item_store($datarray);
480 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
481 dbesc($datarray['parent-uri']),
482 intval($importer_uid)
484 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
487 switch ($mailconf[0]['action']) {
489 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
492 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
493 imap_delete($mbox, $msg_uid, FT_UID);
496 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
497 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
500 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
501 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
502 if ($mailconf[0]['movetofolder'] != "")
503 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
512 elseif($contact['network'] === NETWORK_FACEBOOK) {
513 // This is picked up by the Facebook plugin on a cron hook.
518 logger('poller: received xml : ' . $xml, LOGGER_DATA);
519 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
520 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
521 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
522 dbesc(datetime_convert()),
523 intval($contact['id'])
529 consume_feed($xml,$importer,$contact,$hub,1,1);
532 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
534 consume_feed($xml,$importer,$contact,$hub,1,2);
536 $hubmode = 'subscribe';
537 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
538 $hubmode = 'unsubscribe';
540 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
543 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
544 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
545 $hubs = explode(',', $hub);
547 foreach($hubs as $h) {
551 subscribe_to_hub($h,$importer,$contact,$hubmode);
557 $updated = datetime_convert();
559 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
562 intval($contact['id'])
566 // load current friends if possible.
568 if($contact['poco']) {
569 $r = q("SELECT count(*) as total from glink
570 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
571 intval($contact['id'])
575 if(! $r[0]['total']) {
576 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
583 if (array_search(__file__,get_included_files())===0){
584 onepoll_run($argv,$argc);