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');
60 $lockpath = get_lockpath();
61 if ($lockpath != '') {
62 $pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
63 if ($pidfile->is_already_running()) {
64 logger("onepoll: Already running for contact ".$contact_id);
65 if ($pidfile->running_time() > 9*60) {
67 logger("killed stale process");
73 $d = datetime_convert();
75 // Only poll from those with suitable relationships,
76 // and which have a polling address and ignore Diaspora since
77 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
79 $contacts = q("SELECT `contact`.* FROM `contact`
80 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
81 AND NOT `network` IN ( '%s', '%s', '%s' )
82 AND `contact`.`id` = %d
83 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
84 AND `contact`.`archive` = 0 LIMIT 1",
85 intval(CONTACT_IS_SHARING),
86 intval(CONTACT_IS_FRIEND),
87 dbesc(NETWORK_DIASPORA),
88 dbesc(NETWORK_FACEBOOK),
89 dbesc(NETWORK_PUMPIO),
93 if(! count($contacts)) {
97 $contact = $contacts[0];
101 $t = $contact['last-update'];
103 if($contact['subhub']) {
104 $poll_interval = get_config('system','pushpoll_frequency');
105 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
108 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
115 $importer_uid = $contact['uid'];
117 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
118 intval($importer_uid)
125 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
127 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
128 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
129 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
132 if($contact['network'] === NETWORK_DFRN) {
135 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
136 if(intval($contact['duplex']) && $contact['dfrn-id'])
137 $idtosend = '0:' . $orig_id;
138 if(intval($contact['duplex']) && $contact['issued-id'])
139 $idtosend = '1:' . $orig_id;
141 // they have permission to write to us. We already filtered this in the contact query.
144 // But this may be our first communication, so set the writable flag if it isn't set already.
146 if(! intval($contact['writable']))
147 q("update contact set writable = 1 where id = %d", intval($contact['id']));
150 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
151 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
152 . '&type=data&last_update=' . $last_update
155 $handshake_xml = fetch_url($url);
156 $html_code = $a->get_curl_code();
158 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
161 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
162 logger("poller: $url appears to be dead - marking for death ");
164 // dead connection - might be a transient event, or this might
165 // mean the software was uninstalled or the domain expired.
166 // Will keep trying for one month.
168 mark_for_death($contact);
170 // set the last-update so we don't keep polling
171 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
172 dbesc(datetime_convert()),
173 intval($contact['id'])
179 if(! strstr($handshake_xml,'<?xml')) {
180 logger('poller: response from ' . $url . ' did not contain XML.');
182 mark_for_death($contact);
184 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
185 dbesc(datetime_convert()),
186 intval($contact['id'])
192 $res = parse_xml_string($handshake_xml);
194 if(intval($res->status) == 1) {
195 logger("poller: $url replied status 1 - marking for death ");
197 // we may not be friends anymore. Will keep trying for one month.
198 // set the last-update so we don't keep polling
201 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
202 dbesc(datetime_convert()),
203 intval($contact['id'])
205 mark_for_death($contact);
208 if($contact['term-date'] != '0000-00-00 00:00:00') {
209 logger("poller: $url back from the dead - removing mark for death");
210 unmark_for_death($contact);
214 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
217 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
218 q("update contact set poco = '%s' where id = %d",
219 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
220 intval($contact['id'])
226 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
227 $challenge = hex2bin((string) $res->challenge);
231 if(($contact['duplex']) && strlen($contact['prvkey'])) {
232 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
233 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
236 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
237 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
240 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
242 if(strpos($final_dfrn_id,':') == 1)
243 $final_dfrn_id = substr($final_dfrn_id,2);
245 if($final_dfrn_id != $orig_id) {
246 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
247 // did not decode properly - cannot trust this site
251 $postvars['dfrn_id'] = $idtosend;
252 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
253 $postvars['perm'] = 'rw';
255 $xml = post_url($contact['poll'],$postvars);
258 elseif(($contact['network'] === NETWORK_OSTATUS)
259 || ($contact['network'] === NETWORK_DIASPORA)
260 || ($contact['network'] === NETWORK_FEED) ) {
262 // Upgrading DB fields from an older Friendica version
263 // Will only do this once per notify-enabled OStatus contact
264 // or if relationship changes
266 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
268 if($contact['network'] === NETWORK_OSTATUS && get_pconfig($importer_uid,'system','ostatus_autofriend'))
271 if($stat_writeable != $contact['writable']) {
272 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
273 intval($stat_writeable),
274 intval($contact['id'])
278 // Are we allowed to import from this person?
280 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
283 $xml = fetch_url($contact['poll']);
285 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
287 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
289 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
293 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
296 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
297 intval($importer_uid)
299 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
300 intval($importer_uid)
302 if(count($x) && count($mailconf)) {
303 $mailbox = construct_mailbox_name($mailconf[0]);
305 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
306 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
308 logger("Mail: Connect to " . $mailconf[0]['user']);
310 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
311 dbesc(datetime_convert()),
312 intval($mailconf[0]['id']),
313 intval($importer_uid)
319 $msgs = email_poll($mbox,$contact['addr']);
322 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
324 $metas = email_msg_meta($mbox,implode(',',$msgs));
325 if(count($metas) != count($msgs)) {
326 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
329 $msgs = array_combine($msgs, $metas);
331 foreach($msgs as $msg_uid => $meta) {
332 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
335 $datarray['verb'] = ACTIVITY_POST;
336 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
337 // $meta = email_msg_meta($mbox,$msg_uid);
338 // $headers = email_msg_headers($mbox,$msg_uid);
340 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
342 // Have we seen it before?
343 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
344 intval($importer_uid),
345 dbesc($datarray['uri'])
349 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
351 // Only delete when mails aren't automatically moved or deleted
352 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
353 if($meta->deleted && ! $r[0]['deleted']) {
354 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
355 dbesc(datetime_convert()),
360 switch ($mailconf[0]['action']) {
362 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
365 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
366 imap_delete($mbox, $msg_uid, FT_UID);
369 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
370 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
373 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
374 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
375 if ($mailconf[0]['movetofolder'] != "")
376 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
383 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
385 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
386 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
387 if(! trim($raw_refs))
388 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
389 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
392 $refs_arr = explode(' ', $raw_refs);
393 if(count($refs_arr)) {
394 for($x = 0; $x < count($refs_arr); $x ++)
395 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
397 $qstr = implode(',',$refs_arr);
398 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
399 intval($importer_uid)
402 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
403 // $datarray['parent-uri'] = $r[0]['uri'];
406 // Decoding the header
407 $subject = imap_mime_header_decode($meta->subject);
408 $datarray['title'] = "";
409 foreach($subject as $subpart)
410 if ($subpart->charset != "default")
411 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
413 $datarray['title'] .= $subpart->text;
415 $datarray['title'] = notags(trim($datarray['title']));
417 //$datarray['title'] = notags(trim($meta->subject));
418 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
421 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
422 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
425 // Remove Reply-signs in the subject
426 $datarray['title'] = RemoveReply($datarray['title']);
428 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
429 if(!x($datarray,'parent-uri') and $reply) {
430 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
431 dbesc(protect_sprintf($datarray['title'])),
432 intval($importer_uid));
434 $datarray['parent-uri'] = $r[0]['parent-uri'];
437 if(! x($datarray,'parent-uri'))
438 $datarray['parent-uri'] = $datarray['uri'];
441 $r = email_get_msg($mbox,$msg_uid, $reply);
443 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
446 $datarray['body'] = escape_tags($r['body']);
447 $datarray['body'] = limit_body_size($datarray['body']);
449 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
451 // some mailing lists have the original author as 'from' - add this sender info to msg body.
452 // todo: adding a gravatar for the original author would be cool
454 if(! stristr($meta->from,$contact['addr'])) {
455 $from = imap_mime_header_decode($meta->from);
457 foreach($from as $frompart)
458 if ($frompart->charset != "default")
459 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
461 $fromdecoded .= $frompart->text;
463 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
465 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
467 if (isset($fromarr[0]->personal))
468 $fromname = $fromarr[0]->personal;
470 $fromname = $frommail;
472 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
474 $datarray['author-name'] = $fromname;
475 $datarray['author-link'] = "mailto:".$frommail;
476 $datarray['author-avatar'] = $contact['photo'];
478 $datarray['owner-name'] = $contact['name'];
479 $datarray['owner-link'] = "mailto:".$contact['addr'];
480 $datarray['owner-avatar'] = $contact['photo'];
483 $datarray['author-name'] = $contact['name'];
484 $datarray['author-link'] = 'mailbox';
485 $datarray['author-avatar'] = $contact['photo'];
488 $datarray['uid'] = $importer_uid;
489 $datarray['contact-id'] = $contact['id'];
490 if($datarray['parent-uri'] === $datarray['uri'])
491 $datarray['private'] = 1;
492 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
493 $datarray['private'] = 1;
494 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
497 $stored_item = item_store($datarray);
498 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
499 dbesc($datarray['parent-uri']),
500 intval($importer_uid)
502 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
505 switch ($mailconf[0]['action']) {
507 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
510 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
511 imap_delete($mbox, $msg_uid, FT_UID);
514 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
515 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
518 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
519 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
520 if ($mailconf[0]['movetofolder'] != "")
521 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
530 elseif($contact['network'] === NETWORK_FACEBOOK) {
531 // This is picked up by the Facebook plugin on a cron hook.
533 } elseif($contact['network'] === NETWORK_PUMPIO) {
534 // This is picked up by the pump.io plugin on a cron hook.
539 logger('poller: received xml : ' . $xml, LOGGER_DATA);
540 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
541 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
542 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
543 dbesc(datetime_convert()),
544 intval($contact['id'])
550 consume_feed($xml,$importer,$contact,$hub,1,1);
553 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
555 consume_feed($xml,$importer,$contact,$hub,1,2);
557 $hubmode = 'subscribe';
558 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
559 $hubmode = 'unsubscribe';
561 if(($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
564 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
565 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
566 $hubs = explode(',', $hub);
568 foreach($hubs as $h) {
572 subscribe_to_hub($h,$importer,$contact,$hubmode);
578 $updated = datetime_convert();
580 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
583 intval($contact['id'])
587 // load current friends if possible.
589 if($contact['poco']) {
590 $r = q("SELECT count(*) as total from glink
591 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
592 intval($contact['id'])
596 if(! $r[0]['total']) {
597 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
604 if (array_search(__file__,get_included_files())===0){
605 onepoll_run($_SERVER["argv"],$_SERVER["argc"]);