var path = require('path');
var fs = require('fs');
module.exports = function(qwiki) {
qwiki.act('upload', function(req, res) {
res.writeHead(200, "OK", {
"Content-Type": "text/html",
});
qwiki.parsePage('upload', '', req, res);
});
qwiki.rule('upload', '@@CONTENT@@', function(req, res, instance, next) {
res.write('
Upload
');
var wiki_path = process.cwd() + '/wiki/';
if (typeof req.files.file !== 'undefined') {
var loc_path = (typeof req.fields.location !== 'undefined' ? req.fields.location+'/' : req.url+'/');
var total = 0;
if (req.files.file instanceof Array) {
for (var i = 0, len = req.files.file.length; i < len; i++) {
var file = req.files.file[i];
var full_path = path.normalize(wiki_path + loc_path + encodeURIComponent(file.name));
if (full_path.indexOf(wiki_path) == -1) {
// TODO: actually show the error to user
res.write('DENIED: Attempted location is out of wiki context.');
end(req, res);
next();
return;
}
moveFile(file.path, full_path, function(err) {
res.write('Uploaded: ' + path.basename(full_path) + '
');
total++;
if (total >= len) {
end(req, res);
next();
return;
}
});
}
} else {
var file = req.files.file;
var full_path = path.normalize(wiki_path + loc_path + encodeURIComponent(file.name));
if (full_path.indexOf(wiki_path) == -1) {
res.write('DENIED: Attempted location is out of wiki context.');
end();
next();
return;
}
moveFile(file.path, full_path, function(err) {
res.write('Uploaded: ' + path.basename(full_path) + '
');
end(req, res);
next();
});
}
return;
}
end(req, res);
next();
});
function end(req, res) {
res.write('');
};
function moveFile(from, to, cb) {
qwiki.r_mkdir(path.dirname(to), 0777, function() {
fs.rename(from, to, function(err) {
cb(err);
});
});
};
};