3 require_once("boot.php");
4 require_once("include/follow.php");
5 require_once("include/Scrape.php");
7 function RemoveReply($subject) {
8 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
9 $subject = trim(substr($subject, 4));
14 function onepoll_run(&$argv, &$argc){
22 @include(".htconfig.php");
23 require_once("include/dba.php");
24 $db = new dba($db_host, $db_user, $db_pass, $db_data);
25 unset($db_host, $db_user, $db_pass, $db_data);
29 require_once('include/session.php');
30 require_once('include/datetime.php');
31 require_once('library/simplepie/simplepie.inc');
32 require_once('include/items.php');
33 require_once('include/Contact.php');
34 require_once('include/email.php');
35 require_once('include/socgraph.php');
36 require_once('include/pidfile.php');
37 require_once('include/queue_fn.php');
39 load_config('config');
40 load_config('system');
42 $a->set_baseurl(get_config('system','url'));
46 logger('onepoll: start');
54 if(($argc > 1) && (intval($argv[1])))
55 $contact_id = intval($argv[1]);
58 logger('onepoll: no contact');
62 $lockpath = get_lockpath();
63 if ($lockpath != '') {
64 $pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
65 if ($pidfile->is_already_running()) {
66 logger("onepoll: Already running for contact ".$contact_id);
67 if ($pidfile->running_time() > 9*60) {
69 logger("killed stale process");
75 $d = datetime_convert();
77 // Only poll from those with suitable relationships,
78 // and which have a polling address and ignore Diaspora since
79 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
81 $contacts = q("SELECT `contact`.* FROM `contact`
82 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
83 AND NOT `network` IN ( '%s', '%s', '%s' )
84 AND `contact`.`id` = %d
85 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
86 AND `contact`.`archive` = 0 LIMIT 1",
87 intval(CONTACT_IS_SHARING),
88 intval(CONTACT_IS_FRIEND),
89 dbesc(NETWORK_DIASPORA),
90 dbesc(NETWORK_FACEBOOK),
91 dbesc(NETWORK_PUMPIO),
95 if(! count($contacts)) {
99 $contact = $contacts[0];
103 $t = $contact['last-update'];
105 if($contact['subhub']) {
106 $poll_interval = get_config('system','pushpoll_frequency');
107 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
110 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
117 $importer_uid = $contact['uid'];
119 $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",
120 intval($importer_uid)
127 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
129 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
130 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
131 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
134 // Update the contact entry
135 if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN))
136 update_contact($contact["id"]);
138 if($contact['network'] === NETWORK_DFRN) {
141 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
142 if(intval($contact['duplex']) && $contact['dfrn-id'])
143 $idtosend = '0:' . $orig_id;
144 if(intval($contact['duplex']) && $contact['issued-id'])
145 $idtosend = '1:' . $orig_id;
147 // they have permission to write to us. We already filtered this in the contact query.
150 // But this may be our first communication, so set the writable flag if it isn't set already.
152 if(! intval($contact['writable']))
153 q("update contact set writable = 1 where id = %d", intval($contact['id']));
156 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
157 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
158 . '&type=data&last_update=' . $last_update
161 $handshake_xml = fetch_url($url);
162 $html_code = $a->get_curl_code();
164 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
167 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
168 logger("poller: $url appears to be dead - marking for death ");
170 // dead connection - might be a transient event, or this might
171 // mean the software was uninstalled or the domain expired.
172 // Will keep trying for one month.
174 mark_for_death($contact);
176 // set the last-update so we don't keep polling
177 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
178 dbesc(datetime_convert()),
179 intval($contact['id'])
185 if(! strstr($handshake_xml,'<')) {
186 logger('poller: response from ' . $url . ' did not contain XML.');
188 mark_for_death($contact);
190 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
191 dbesc(datetime_convert()),
192 intval($contact['id'])
198 $res = parse_xml_string($handshake_xml);
200 if(intval($res->status) == 1) {
201 logger("poller: $url replied status 1 - marking for death ");
203 // we may not be friends anymore. Will keep trying for one month.
204 // set the last-update so we don't keep polling
207 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
208 dbesc(datetime_convert()),
209 intval($contact['id'])
211 mark_for_death($contact);
214 if($contact['term-date'] != '0000-00-00 00:00:00') {
215 logger("poller: $url back from the dead - removing mark for death");
216 unmark_for_death($contact);
220 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
223 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
224 q("update contact set poco = '%s' where id = %d",
225 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
226 intval($contact['id'])
232 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
233 $challenge = hex2bin((string) $res->challenge);
237 if(($contact['duplex']) && strlen($contact['prvkey'])) {
238 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
239 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
242 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
243 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
246 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
248 if(strpos($final_dfrn_id,':') == 1)
249 $final_dfrn_id = substr($final_dfrn_id,2);
251 if($final_dfrn_id != $orig_id) {
252 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
253 // did not decode properly - cannot trust this site
257 $postvars['dfrn_id'] = $idtosend;
258 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
259 $postvars['perm'] = 'rw';
261 $xml = post_url($contact['poll'],$postvars);
264 elseif(($contact['network'] === NETWORK_OSTATUS)
265 || ($contact['network'] === NETWORK_DIASPORA)
266 || ($contact['network'] === NETWORK_FEED) ) {
268 // Upgrading DB fields from an older Friendica version
269 // Will only do this once per notify-enabled OStatus contact
270 // or if relationship changes
272 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
274 // Contacts from OStatus are always writable
275 if($contact['network'] === NETWORK_OSTATUS)
278 if($stat_writeable != $contact['writable']) {
279 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
280 intval($stat_writeable),
281 intval($contact['id'])
285 // Are we allowed to import from this person?
287 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
290 $xml = fetch_url($contact['poll']);
292 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
294 logger("Mail: Fetching", LOGGER_DEBUG);
296 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
300 logger("Mail: Enabled", LOGGER_DEBUG);
303 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
304 intval($importer_uid)
306 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
307 intval($importer_uid)
309 if(count($x) && count($mailconf)) {
310 $mailbox = construct_mailbox_name($mailconf[0]);
312 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
313 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
315 logger("Mail: Connect to " . $mailconf[0]['user']);
317 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
318 dbesc(datetime_convert()),
319 intval($mailconf[0]['id']),
320 intval($importer_uid)
322 logger("Mail: Connected to " . $mailconf[0]['user']);
324 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors()));
328 $msgs = email_poll($mbox,$contact['addr']);
331 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
333 $metas = email_msg_meta($mbox,implode(',',$msgs));
334 if(count($metas) != count($msgs)) {
335 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
338 $msgs = array_combine($msgs, $metas);
340 foreach($msgs as $msg_uid => $meta) {
341 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
344 $datarray['verb'] = ACTIVITY_POST;
345 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
346 // $meta = email_msg_meta($mbox,$msg_uid);
347 // $headers = email_msg_headers($mbox,$msg_uid);
349 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
351 // Have we seen it before?
352 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
353 intval($importer_uid),
354 dbesc($datarray['uri'])
358 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
360 // Only delete when mails aren't automatically moved or deleted
361 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
362 if($meta->deleted && ! $r[0]['deleted']) {
363 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
364 dbesc(datetime_convert()),
369 switch ($mailconf[0]['action']) {
371 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
374 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
375 imap_delete($mbox, $msg_uid, FT_UID);
378 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
379 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
382 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
383 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
384 if ($mailconf[0]['movetofolder'] != "")
385 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
392 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
394 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
395 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
396 if(! trim($raw_refs))
397 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
398 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
401 $refs_arr = explode(' ', $raw_refs);
402 if(count($refs_arr)) {
403 for($x = 0; $x < count($refs_arr); $x ++)
404 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
406 $qstr = implode(',',$refs_arr);
407 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
408 intval($importer_uid)
411 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
412 // $datarray['parent-uri'] = $r[0]['uri'];
415 // Decoding the header
416 $subject = imap_mime_header_decode($meta->subject);
417 $datarray['title'] = "";
418 foreach($subject as $subpart)
419 if ($subpart->charset != "default")
420 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
422 $datarray['title'] .= $subpart->text;
424 $datarray['title'] = notags(trim($datarray['title']));
426 //$datarray['title'] = notags(trim($meta->subject));
427 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
430 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
431 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
434 // Remove Reply-signs in the subject
435 $datarray['title'] = RemoveReply($datarray['title']);
437 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
438 if(!x($datarray,'parent-uri') and $reply) {
439 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
440 dbesc(protect_sprintf($datarray['title'])),
441 intval($importer_uid));
443 $datarray['parent-uri'] = $r[0]['parent-uri'];
446 if(! x($datarray,'parent-uri'))
447 $datarray['parent-uri'] = $datarray['uri'];
450 $r = email_get_msg($mbox,$msg_uid, $reply);
452 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
455 $datarray['body'] = escape_tags($r['body']);
456 $datarray['body'] = limit_body_size($datarray['body']);
458 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
460 // some mailing lists have the original author as 'from' - add this sender info to msg body.
461 // todo: adding a gravatar for the original author would be cool
463 if(! stristr($meta->from,$contact['addr'])) {
464 $from = imap_mime_header_decode($meta->from);
466 foreach($from as $frompart)
467 if ($frompart->charset != "default")
468 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
470 $fromdecoded .= $frompart->text;
472 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
474 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
476 if (isset($fromarr[0]->personal))
477 $fromname = $fromarr[0]->personal;
479 $fromname = $frommail;
481 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
483 $datarray['author-name'] = $fromname;
484 $datarray['author-link'] = "mailto:".$frommail;
485 $datarray['author-avatar'] = $contact['photo'];
487 $datarray['owner-name'] = $contact['name'];
488 $datarray['owner-link'] = "mailto:".$contact['addr'];
489 $datarray['owner-avatar'] = $contact['photo'];
492 $datarray['author-name'] = $contact['name'];
493 $datarray['author-link'] = 'mailbox';
494 $datarray['author-avatar'] = $contact['photo'];
497 $datarray['uid'] = $importer_uid;
498 $datarray['contact-id'] = $contact['id'];
499 if($datarray['parent-uri'] === $datarray['uri'])
500 $datarray['private'] = 1;
501 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
502 $datarray['private'] = 1;
503 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
506 $stored_item = item_store($datarray);
507 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
508 dbesc($datarray['parent-uri']),
509 intval($importer_uid)
511 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
514 switch ($mailconf[0]['action']) {
516 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
519 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
520 imap_delete($mbox, $msg_uid, FT_UID);
523 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
524 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
527 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
528 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
529 if ($mailconf[0]['movetofolder'] != "")
530 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
536 logger("Mail: no mails for ".$mailconf[0]['user']);
538 logger("Mail: closing connection for ".$mailconf[0]['user']);
542 elseif($contact['network'] === NETWORK_FACEBOOK) {
543 // This is picked up by the Facebook plugin on a cron hook.
545 } elseif($contact['network'] === NETWORK_PUMPIO) {
546 // This is picked up by the pump.io plugin on a cron hook.
551 logger('poller: received xml : ' . $xml, LOGGER_DATA);
552 if(! strstr($xml,'<')) {
553 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
554 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
555 dbesc(datetime_convert()),
556 intval($contact['id'])
562 consume_feed($xml,$importer,$contact,$hub,1,1);
565 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
567 consume_feed($xml,$importer,$contact,$hub,1,2);
569 $hubmode = 'subscribe';
570 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
571 $hubmode = 'unsubscribe';
573 if(($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
576 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
577 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
578 $hubs = explode(',', $hub);
580 foreach($hubs as $h) {
584 subscribe_to_hub($h,$importer,$contact,$hubmode);
590 $updated = datetime_convert();
592 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
595 intval($contact['id'])
599 // load current friends if possible.
601 if($contact['poco']) {
602 $r = q("SELECT count(*) as total from glink
603 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
604 intval($contact['id'])
608 if(! $r[0]['total']) {
609 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
616 if (array_search(__file__,get_included_files())===0){
617 onepoll_run($_SERVER["argv"],$_SERVER["argc"]);