3 require_once("boot.php");
4 require_once("include/follow.php");
6 function RemoveReply($subject) {
7 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
8 $subject = trim(substr($subject, 4));
13 function onepoll_run(&$argv, &$argc){
21 @include(".htconfig.php");
22 require_once("include/dba.php");
23 $db = new dba($db_host, $db_user, $db_pass, $db_data);
24 unset($db_host, $db_user, $db_pass, $db_data);
28 require_once('include/session.php');
29 require_once('include/datetime.php');
30 require_once('library/simplepie/simplepie.inc');
31 require_once('include/items.php');
32 require_once('include/Contact.php');
33 require_once('include/email.php');
34 require_once('include/socgraph.php');
35 require_once('include/pidfile.php');
36 require_once('include/queue_fn.php');
38 load_config('config');
39 load_config('system');
41 $a->set_baseurl(get_config('system','url'));
45 logger('onepoll: start');
53 if(($argc > 1) && (intval($argv[1])))
54 $contact_id = intval($argv[1]);
57 logger('onepoll: no contact');
61 $lockpath = get_lockpath();
62 if ($lockpath != '') {
63 $pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
64 if ($pidfile->is_already_running()) {
65 logger("onepoll: Already running for contact ".$contact_id);
66 if ($pidfile->running_time() > 9*60) {
68 logger("killed stale process");
74 $d = datetime_convert();
76 // Only poll from those with suitable relationships,
77 // and which have a polling address and ignore Diaspora since
78 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
80 $contacts = q("SELECT `contact`.* FROM `contact`
81 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
82 AND NOT `network` IN ( '%s', '%s', '%s' )
83 AND `contact`.`id` = %d
84 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
85 AND `contact`.`archive` = 0 LIMIT 1",
86 intval(CONTACT_IS_SHARING),
87 intval(CONTACT_IS_FRIEND),
88 dbesc(NETWORK_DIASPORA),
89 dbesc(NETWORK_FACEBOOK),
90 dbesc(NETWORK_PUMPIO),
94 if(! count($contacts)) {
95 // Maybe it is a Redmatrix account. Then we can fetch their contacts via poco
96 $contacts = q("SELECT `id`, `poco` FROM `contact` WHERE `id` = %d AND `poco` != ''", intval($contact_id));
98 poco_load($contacts[0]['id'],$importer_uid,0,$contacts[0]['poco']);
102 $contact = $contacts[0];
106 $t = $contact['last-update'];
108 if($contact['subhub']) {
109 $poll_interval = get_config('system','pushpoll_frequency');
110 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
113 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
120 $importer_uid = $contact['uid'];
122 $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",
123 intval($importer_uid)
130 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
132 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
133 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
134 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
137 // Update the contact entry
138 if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN))
139 update_contact($contact["id"]);
141 if($contact['network'] === NETWORK_DFRN) {
144 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
145 if(intval($contact['duplex']) && $contact['dfrn-id'])
146 $idtosend = '0:' . $orig_id;
147 if(intval($contact['duplex']) && $contact['issued-id'])
148 $idtosend = '1:' . $orig_id;
150 // they have permission to write to us. We already filtered this in the contact query.
153 // But this may be our first communication, so set the writable flag if it isn't set already.
155 if(! intval($contact['writable']))
156 q("update contact set writable = 1 where id = %d", intval($contact['id']));
159 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
160 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
161 . '&type=data&last_update=' . $last_update
164 $handshake_xml = fetch_url($url);
165 $html_code = $a->get_curl_code();
167 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
170 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
171 logger("poller: $url appears to be dead - marking for death ");
173 // dead connection - might be a transient event, or this might
174 // mean the software was uninstalled or the domain expired.
175 // Will keep trying for one month.
177 mark_for_death($contact);
179 // set the last-update so we don't keep polling
180 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
181 dbesc(datetime_convert()),
182 intval($contact['id'])
188 if(! strstr($handshake_xml,'<')) {
189 logger('poller: response from ' . $url . ' did not contain XML.');
191 mark_for_death($contact);
193 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
194 dbesc(datetime_convert()),
195 intval($contact['id'])
201 $res = parse_xml_string($handshake_xml);
203 if(intval($res->status) == 1) {
204 logger("poller: $url replied status 1 - marking for death ");
206 // we may not be friends anymore. Will keep trying for one month.
207 // set the last-update so we don't keep polling
210 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
211 dbesc(datetime_convert()),
212 intval($contact['id'])
214 mark_for_death($contact);
217 if($contact['term-date'] != '0000-00-00 00:00:00') {
218 logger("poller: $url back from the dead - removing mark for death");
219 unmark_for_death($contact);
223 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
226 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
227 q("update contact set poco = '%s' where id = %d",
228 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
229 intval($contact['id'])
235 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
236 $challenge = hex2bin((string) $res->challenge);
240 if(($contact['duplex']) && strlen($contact['prvkey'])) {
241 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
242 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
245 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
246 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
249 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
251 if(strpos($final_dfrn_id,':') == 1)
252 $final_dfrn_id = substr($final_dfrn_id,2);
254 if($final_dfrn_id != $orig_id) {
255 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
256 // did not decode properly - cannot trust this site
260 $postvars['dfrn_id'] = $idtosend;
261 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
262 $postvars['perm'] = 'rw';
264 $xml = post_url($contact['poll'],$postvars);
267 elseif(($contact['network'] === NETWORK_OSTATUS)
268 || ($contact['network'] === NETWORK_DIASPORA)
269 || ($contact['network'] === NETWORK_FEED) ) {
271 // Upgrading DB fields from an older Friendica version
272 // Will only do this once per notify-enabled OStatus contact
273 // or if relationship changes
275 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
277 // Contacts from OStatus are always writable
278 if($contact['network'] === NETWORK_OSTATUS)
281 if($stat_writeable != $contact['writable']) {
282 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
283 intval($stat_writeable),
284 intval($contact['id'])
288 // Are we allowed to import from this person?
290 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
293 $xml = fetch_url($contact['poll']);
295 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
297 logger("Mail: Fetching", LOGGER_DEBUG);
299 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
303 logger("Mail: Enabled", LOGGER_DEBUG);
306 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
307 intval($importer_uid)
309 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
310 intval($importer_uid)
312 if(count($x) && count($mailconf)) {
313 $mailbox = construct_mailbox_name($mailconf[0]);
315 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
316 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
318 logger("Mail: Connect to " . $mailconf[0]['user']);
320 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
321 dbesc(datetime_convert()),
322 intval($mailconf[0]['id']),
323 intval($importer_uid)
325 logger("Mail: Connected to " . $mailconf[0]['user']);
327 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors()));
331 $msgs = email_poll($mbox,$contact['addr']);
334 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
336 $metas = email_msg_meta($mbox,implode(',',$msgs));
337 if(count($metas) != count($msgs)) {
338 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
341 $msgs = array_combine($msgs, $metas);
343 foreach($msgs as $msg_uid => $meta) {
344 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
347 $datarray['verb'] = ACTIVITY_POST;
348 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
349 // $meta = email_msg_meta($mbox,$msg_uid);
350 // $headers = email_msg_headers($mbox,$msg_uid);
352 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
354 // Have we seen it before?
355 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
356 intval($importer_uid),
357 dbesc($datarray['uri'])
361 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
363 // Only delete when mails aren't automatically moved or deleted
364 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
365 if($meta->deleted && ! $r[0]['deleted']) {
366 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
367 dbesc(datetime_convert()),
372 switch ($mailconf[0]['action']) {
374 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
377 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
378 imap_delete($mbox, $msg_uid, FT_UID);
381 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
382 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
385 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
386 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
387 if ($mailconf[0]['movetofolder'] != "")
388 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
395 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
397 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
398 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
399 if(! trim($raw_refs))
400 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
401 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
404 $refs_arr = explode(' ', $raw_refs);
405 if(count($refs_arr)) {
406 for($x = 0; $x < count($refs_arr); $x ++)
407 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
409 $qstr = implode(',',$refs_arr);
410 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
411 intval($importer_uid)
414 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
415 // $datarray['parent-uri'] = $r[0]['uri'];
418 // Decoding the header
419 $subject = imap_mime_header_decode($meta->subject);
420 $datarray['title'] = "";
421 foreach($subject as $subpart)
422 if ($subpart->charset != "default")
423 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
425 $datarray['title'] .= $subpart->text;
427 $datarray['title'] = notags(trim($datarray['title']));
429 //$datarray['title'] = notags(trim($meta->subject));
430 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
433 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
434 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
437 // Remove Reply-signs in the subject
438 $datarray['title'] = RemoveReply($datarray['title']);
440 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
441 if(!x($datarray,'parent-uri') and $reply) {
442 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
443 dbesc(protect_sprintf($datarray['title'])),
444 intval($importer_uid));
446 $datarray['parent-uri'] = $r[0]['parent-uri'];
449 if(! x($datarray,'parent-uri'))
450 $datarray['parent-uri'] = $datarray['uri'];
453 $r = email_get_msg($mbox,$msg_uid, $reply);
455 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
458 $datarray['body'] = escape_tags($r['body']);
459 $datarray['body'] = limit_body_size($datarray['body']);
461 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
463 // some mailing lists have the original author as 'from' - add this sender info to msg body.
464 // todo: adding a gravatar for the original author would be cool
466 if(! stristr($meta->from,$contact['addr'])) {
467 $from = imap_mime_header_decode($meta->from);
469 foreach($from as $frompart)
470 if ($frompart->charset != "default")
471 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
473 $fromdecoded .= $frompart->text;
475 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
477 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
479 if (isset($fromarr[0]->personal))
480 $fromname = $fromarr[0]->personal;
482 $fromname = $frommail;
484 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
486 $datarray['author-name'] = $fromname;
487 $datarray['author-link'] = "mailto:".$frommail;
488 $datarray['author-avatar'] = $contact['photo'];
490 $datarray['owner-name'] = $contact['name'];
491 $datarray['owner-link'] = "mailto:".$contact['addr'];
492 $datarray['owner-avatar'] = $contact['photo'];
495 $datarray['author-name'] = $contact['name'];
496 $datarray['author-link'] = 'mailbox';
497 $datarray['author-avatar'] = $contact['photo'];
500 $datarray['uid'] = $importer_uid;
501 $datarray['contact-id'] = $contact['id'];
502 if($datarray['parent-uri'] === $datarray['uri'])
503 $datarray['private'] = 1;
504 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
505 $datarray['private'] = 1;
506 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
509 $stored_item = item_store($datarray);
510 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
511 dbesc($datarray['parent-uri']),
512 intval($importer_uid)
514 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
517 switch ($mailconf[0]['action']) {
519 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
522 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
523 imap_delete($mbox, $msg_uid, FT_UID);
526 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
527 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
530 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
531 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
532 if ($mailconf[0]['movetofolder'] != "")
533 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
539 logger("Mail: no mails for ".$mailconf[0]['user']);
541 logger("Mail: closing connection for ".$mailconf[0]['user']);
545 elseif($contact['network'] === NETWORK_FACEBOOK) {
546 // This is picked up by the Facebook plugin on a cron hook.
548 } elseif($contact['network'] === NETWORK_PUMPIO) {
549 // This is picked up by the pump.io plugin on a cron hook.
554 logger('poller: received xml : ' . $xml, LOGGER_DATA);
555 if(! strstr($xml,'<')) {
556 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
557 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
558 dbesc(datetime_convert()),
559 intval($contact['id'])
565 consume_feed($xml,$importer,$contact,$hub,1,1);
568 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
570 consume_feed($xml,$importer,$contact,$hub,1,2);
572 $hubmode = 'subscribe';
573 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
574 $hubmode = 'unsubscribe';
576 if(($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
579 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
580 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
581 $hubs = explode(',', $hub);
583 foreach($hubs as $h) {
587 subscribe_to_hub($h,$importer,$contact,$hubmode);
593 $updated = datetime_convert();
595 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
598 intval($contact['id'])
602 // load current friends if possible.
604 if($contact['poco']) {
605 $r = q("SELECT count(*) as total from glink
606 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
607 intval($contact['id'])
611 if(! $r[0]['total']) {
612 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
619 if (array_search(__file__,get_included_files())===0){
620 onepoll_run($_SERVER["argv"],$_SERVER["argc"]);