chore: eslint no-var, vars-on-top

v1.18.x
Peter Jaszkowiak 4 years ago committed by Julian Lam
parent b56d9e12b5
commit dab3b23575

@ -110,8 +110,6 @@
// WORKING ON // WORKING ON
"prefer-rest-params": "off", "prefer-rest-params": "off",
"prefer-spread": "off", "prefer-spread": "off",
"no-var": "off",
"vars-on-top": "off",
// TODO // TODO
"consistent-return": "off", "consistent-return": "off",

@ -10,7 +10,7 @@ const winston = require('winston');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const env = process.env; const env = process.env;
var worker; let worker;
env.NODE_ENV = env.NODE_ENV || 'development'; env.NODE_ENV = env.NODE_ENV || 'development';
@ -19,10 +19,10 @@ const prestart = require('./src/prestart');
prestart.loadConfig(configFile); prestart.loadConfig(configFile);
var db = require('./src/database'); const db = require('./src/database');
module.exports = function (grunt) { module.exports = function (grunt) {
var args = []; const args = [];
if (!grunt.option('verbose')) { if (!grunt.option('verbose')) {
args.push('--log-level=info'); args.push('--log-level=info');
@ -39,7 +39,7 @@ module.exports = function (grunt) {
grunt.registerTask('default', ['watch']); grunt.registerTask('default', ['watch']);
grunt.registerTask('init', async function () { grunt.registerTask('init', async function () {
var done = this.async(); const done = this.async();
let plugins = []; let plugins = [];
if (!process.argv.includes('--core')) { if (!process.argv.includes('--core')) {
await db.init(); await db.init();
@ -165,7 +165,7 @@ module.exports = function (grunt) {
grunt.event.removeAllListeners('watch'); grunt.event.removeAllListeners('watch');
grunt.event.on('watch', (action, filepath, target) => { grunt.event.on('watch', (action, filepath, target) => {
var compiling; let compiling;
if (target === 'styleUpdated_Client') { if (target === 'styleUpdated_Client') {
compiling = 'clientCSS'; compiling = 'clientCSS';
} else if (target === 'styleUpdated_Admin') { } else if (target === 'styleUpdated_Admin') {

@ -83,7 +83,7 @@ function saveDatabaseConfig(config, databaseConfig) {
} }
const allQuestions = questions.redis.concat(questions.mongo).concat(questions.postgres); const allQuestions = questions.redis.concat(questions.mongo).concat(questions.postgres);
for (var x = 0; x < allQuestions.length; x += 1) { for (let x = 0; x < allQuestions.length; x += 1) {
delete config[allQuestions[x].name]; delete config[allQuestions[x].name];
} }

@ -27,7 +27,7 @@ const formats = [
]; ];
const timestampFormat = winston.format((info) => { const timestampFormat = winston.format((info) => {
var dateString = `${new Date().toISOString()} [${global.process.pid}]`; const dateString = `${new Date().toISOString()} [${global.process.pid}]`;
info.level = `${dateString} - ${info.level}`; info.level = `${dateString} - ${info.level}`;
return info; return info;
}); });
@ -117,9 +117,9 @@ function ping(req, res) {
} }
function welcome(req, res) { function welcome(req, res) {
var dbs = ['redis', 'mongo', 'postgres']; const dbs = ['redis', 'mongo', 'postgres'];
var databases = dbs.map((databaseName) => { const databases = dbs.map((databaseName) => {
var questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall); const questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall);
return { return {
name: databaseName, name: databaseName,
@ -127,7 +127,7 @@ function welcome(req, res) {
}; };
}); });
var defaults = require('./data/defaults'); const defaults = require('./data/defaults');
res.render('install/index', { res.render('install/index', {
url: nconf.get('url') || (`${req.protocol}://${req.get('host')}`), url: nconf.get('url') || (`${req.protocol}://${req.get('host')}`),
@ -150,8 +150,8 @@ function install(req, res) {
} }
req.setTimeout(0); req.setTimeout(0);
installing = true; installing = true;
var setupEnvVars = nconf.get(); const setupEnvVars = nconf.get();
for (var i in req.body) { for (const i in req.body) {
if (req.body.hasOwnProperty(i) && !process.env.hasOwnProperty(i)) { if (req.body.hasOwnProperty(i) && !process.env.hasOwnProperty(i)) {
setupEnvVars[i.replace(':', '__')] = req.body[i]; setupEnvVars[i.replace(':', '__')] = req.body[i];
} }
@ -161,7 +161,7 @@ function install(req, res) {
const pushToRoot = function (parentKey, key) { const pushToRoot = function (parentKey, key) {
setupEnvVars[`${parentKey}__${key}`] = setupEnvVars[parentKey][key]; setupEnvVars[`${parentKey}__${key}`] = setupEnvVars[parentKey][key];
}; };
for (var j in setupEnvVars) { for (const j in setupEnvVars) {
if (setupEnvVars.hasOwnProperty(j) && typeof setupEnvVars[j] === 'object' && setupEnvVars[j] !== null && !Array.isArray(setupEnvVars[j])) { if (setupEnvVars.hasOwnProperty(j) && typeof setupEnvVars[j] === 'object' && setupEnvVars[j] !== null && !Array.isArray(setupEnvVars[j])) {
Object.keys(setupEnvVars[j]).forEach(pushToRoot.bind(null, j)); Object.keys(setupEnvVars[j]).forEach(pushToRoot.bind(null, j));
delete setupEnvVars[j]; delete setupEnvVars[j];
@ -174,7 +174,7 @@ function install(req, res) {
winston.info(setupEnvVars); winston.info(setupEnvVars);
launchUrl = setupEnvVars.url; launchUrl = setupEnvVars.url;
var child = require('child_process').fork('app', ['--setup'], { const child = require('child_process').fork('app', ['--setup'], {
env: setupEnvVars, env: setupEnvVars,
}); });
@ -192,7 +192,7 @@ async function launch(req, res) {
res.json({}); res.json({});
server.close(); server.close();
req.setTimeout(0); req.setTimeout(0);
var child; let child;
if (!nconf.get('launchCmd')) { if (!nconf.get('launchCmd')) {
child = childProcess.spawn('node', ['loader.js'], { child = childProcess.spawn('node', ['loader.js'], {

@ -1,45 +1,45 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const nconf = require('nconf');
var fs = require('fs'); const fs = require('fs');
var url = require('url'); const url = require('url');
var path = require('path'); const path = require('path');
var fork = require('child_process').fork; const fork = require('child_process').fork;
var async = require('async'); const async = require('async');
var logrotate = require('logrotate-stream'); const logrotate = require('logrotate-stream');
var mkdirp = require('mkdirp'); const mkdirp = require('mkdirp');
var file = require('./src/file'); const file = require('./src/file');
var pkg = require('./package.json'); const pkg = require('./package.json');
var pathToConfig = path.resolve(__dirname, process.env.CONFIG || 'config.json'); const pathToConfig = path.resolve(__dirname, process.env.CONFIG || 'config.json');
nconf.argv().env().file({ nconf.argv().env().file({
file: pathToConfig, file: pathToConfig,
}); });
var pidFilePath = path.join(__dirname, 'pidfile'); const pidFilePath = path.join(__dirname, 'pidfile');
var outputLogFilePath = path.join(__dirname, nconf.get('logFile') || 'logs/output.log'); const outputLogFilePath = path.join(__dirname, nconf.get('logFile') || 'logs/output.log');
var logDir = path.dirname(outputLogFilePath); const logDir = path.dirname(outputLogFilePath);
if (!fs.existsSync(logDir)) { if (!fs.existsSync(logDir)) {
mkdirp.sync(path.dirname(outputLogFilePath)); mkdirp.sync(path.dirname(outputLogFilePath));
} }
var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true }); const output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
var silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false; const silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false;
var numProcs; let numProcs;
var workers = []; const workers = [];
var Loader = { const Loader = {
timesStarted: 0, timesStarted: 0,
}; };
var appPath = path.join(__dirname, 'app.js'); const appPath = path.join(__dirname, 'app.js');
Loader.init = function (callback) { Loader.init = function (callback) {
if (silent) { if (silent) {
console.log = function () { console.log = function () {
var args = Array.prototype.slice.call(arguments); const args = Array.prototype.slice.call(arguments);
output.write(`${args.join(' ')}\n`); output.write(`${args.join(' ')}\n`);
}; };
} }
@ -112,7 +112,7 @@ Loader.start = function (callback) {
numProcs = getPorts().length; numProcs = getPorts().length;
console.log(`Clustering enabled: Spinning up ${numProcs} process(es).\n`); console.log(`Clustering enabled: Spinning up ${numProcs} process(es).\n`);
for (var x = 0; x < numProcs; x += 1) { for (let x = 0; x < numProcs; x += 1) {
forkWorker(x, x === 0); forkWorker(x, x === 0);
} }
@ -122,8 +122,8 @@ Loader.start = function (callback) {
}; };
function forkWorker(index, isPrimary) { function forkWorker(index, isPrimary) {
var ports = getPorts(); const ports = getPorts();
var args = []; const args = [];
if (!ports[index]) { if (!ports[index]) {
return console.log(`[cluster] invalid port for worker : ${index} ports: ${ports.length}`); return console.log(`[cluster] invalid port for worker : ${index} ports: ${ports.length}`);
@ -133,7 +133,7 @@ function forkWorker(index, isPrimary) {
process.env.isCluster = nconf.get('isCluster') || ports.length > 1; process.env.isCluster = nconf.get('isCluster') || ports.length > 1;
process.env.port = ports[index]; process.env.port = ports[index];
var worker = fork(appPath, args, { const worker = fork(appPath, args, {
silent: silent, silent: silent,
env: process.env, env: process.env,
}); });
@ -146,20 +146,20 @@ function forkWorker(index, isPrimary) {
Loader.addWorkerEvents(worker); Loader.addWorkerEvents(worker);
if (silent) { if (silent) {
var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true }); const output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
worker.stdout.pipe(output); worker.stdout.pipe(output);
worker.stderr.pipe(output); worker.stderr.pipe(output);
} }
} }
function getPorts() { function getPorts() {
var _url = nconf.get('url'); const _url = nconf.get('url');
if (!_url) { if (!_url) {
console.log('[cluster] url is undefined, please check your config.json'); console.log('[cluster] url is undefined, please check your config.json');
process.exit(); process.exit();
} }
var urlObject = url.parse(_url); const urlObject = url.parse(_url);
var port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567; let port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567;
if (!Array.isArray(port)) { if (!Array.isArray(port)) {
port = [port]; port = [port];
} }
@ -178,7 +178,7 @@ Loader.restart = function () {
throw err; throw err;
} }
var conf = JSON.parse(configFile); const conf = JSON.parse(configFile);
nconf.stores.env.readOnly = false; nconf.stores.env.readOnly = false;
nconf.set('url', conf.url); nconf.set('url', conf.url);
@ -217,7 +217,7 @@ fs.open(pathToConfig, 'r', (err) => {
if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) { if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) {
if (file.existsSync(pidFilePath)) { if (file.existsSync(pidFilePath)) {
try { try {
var pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' }); const pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' });
process.kill(pid, 0); process.kill(pid, 0);
process.exit(); process.exit();
} catch (e) { } catch (e) {

@ -61,8 +61,8 @@ const fallbackCache = {};
async function initFallback(namespace) { async function initFallback(namespace) {
const template = await fs.promises.readFile(path.resolve(nconf.get('views_dir'), `${namespace}.tpl`), 'utf8'); const template = await fs.promises.readFile(path.resolve(nconf.get('views_dir'), `${namespace}.tpl`), 'utf8');
var title = nsToTitle(namespace); const title = nsToTitle(namespace);
var translations = sanitize(template); let translations = sanitize(template);
translations = Translator.removePatterns(translations); translations = Translator.removePatterns(translations);
translations = simplify(translations); translations = simplify(translations);
translations += `\n${title}`; translations += `\n${title}`;

@ -65,7 +65,7 @@ exports.doTopicAction = async function (action, event, caller, { tids }) {
async function logTopicAction(action, req, tid, title) { async function logTopicAction(action, req, tid, title) {
// Only log certain actions to system event log // Only log certain actions to system event log
var actionsToLog = ['delete', 'restore', 'purge']; const actionsToLog = ['delete', 'restore', 'purge'];
if (!actionsToLog.includes(action)) { if (!actionsToLog.includes(action)) {
return; return;
} }

@ -58,7 +58,7 @@ topicsAPI.create = async function (caller, data) {
}; };
topicsAPI.reply = async function (caller, data) { topicsAPI.reply = async function (caller, data) {
var payload = { const payload = {
tid: data.tid, tid: data.tid,
uid: caller.uid, uid: caller.uid,
req: apiHelpers.buildReqObject(caller), // For IP recording req: apiHelpers.buildReqObject(caller), // For IP recording

@ -1,13 +1,13 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var db = require('../database'); const db = require('../database');
var batch = require('../batch'); const batch = require('../batch');
var plugins = require('../plugins'); const plugins = require('../plugins');
var topics = require('../topics'); const topics = require('../topics');
var groups = require('../groups'); const groups = require('../groups');
var privileges = require('../privileges'); const privileges = require('../privileges');
var cache = require('../cache'); const cache = require('../cache');
module.exports = function (Categories) { module.exports = function (Categories) {
Categories.purge = async function (cid, uid) { Categories.purge = async function (cid, uid) {

@ -140,7 +140,6 @@ module.exports = function (Categories) {
if (category.posts.length) { if (category.posts.length) {
return; return;
} }
const posts = []; const posts = [];
getPostsRecursive(category, posts); getPostsRecursive(category, posts);

@ -30,9 +30,9 @@ module.exports = function (Categories) {
const result = await plugins.hooks.fire('filter:category.update', { cid: cid, category: modifiedFields }); const result = await plugins.hooks.fire('filter:category.update', { cid: cid, category: modifiedFields });
const category = result.category; const category = result.category;
var fields = Object.keys(category); const fields = Object.keys(category);
// move parent to front, so its updated first // move parent to front, so its updated first
var parentCidIndex = fields.indexOf('parentCid'); const parentCidIndex = fields.indexOf('parentCid');
if (parentCidIndex !== -1 && fields.length > 1) { if (parentCidIndex !== -1 && fields.length > 1) {
fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]); fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]);
} }

@ -5,17 +5,17 @@
// to include color styling in the output // to include color styling in the output
// so the CLI looks nice // so the CLI looks nice
var Command = require('commander').Command; const Command = require('commander').Command;
var commandColor = 'yellow'; const commandColor = 'yellow';
var optionColor = 'cyan'; const optionColor = 'cyan';
var argColor = 'magenta'; const argColor = 'magenta';
var subCommandColor = 'green'; const subCommandColor = 'green';
var subOptionColor = 'blue'; const subOptionColor = 'blue';
var subArgColor = 'red'; const subArgColor = 'red';
Command.prototype.helpInformation = function () { Command.prototype.helpInformation = function () {
var desc = []; let desc = [];
if (this._description) { if (this._description) {
desc = [ desc = [
` ${this._description}`, ` ${this._description}`,
@ -23,23 +23,23 @@ Command.prototype.helpInformation = function () {
]; ];
} }
var cmdName = this._name; let cmdName = this._name;
if (this._alias) { if (this._alias) {
cmdName = `${cmdName} | ${this._alias}`; cmdName = `${cmdName} | ${this._alias}`;
} }
var usage = [ const usage = [
'', '',
` Usage: ${cmdName[commandColor]}${' '.reset}${this.usage()}`, ` Usage: ${cmdName[commandColor]}${' '.reset}${this.usage()}`,
'', '',
]; ];
var cmds = []; let cmds = [];
var commandHelp = this.commandHelp(); const commandHelp = this.commandHelp();
if (commandHelp) { if (commandHelp) {
cmds = [commandHelp]; cmds = [commandHelp];
} }
var options = [ const options = [
'', '',
' Options:', ' Options:',
'', '',
@ -55,15 +55,15 @@ Command.prototype.helpInformation = function () {
}; };
function humanReadableArgName(arg) { function humanReadableArgName(arg) {
var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
return arg.required ? `<${nameOutput}>` : `[${nameOutput}]`; return arg.required ? `<${nameOutput}>` : `[${nameOutput}]`;
} }
Command.prototype.usage = function () { Command.prototype.usage = function () {
var args = this._args.map(arg => humanReadableArgName(arg)); const args = this._args.map(arg => humanReadableArgName(arg));
var usage = '[options]'[optionColor] + const usage = '[options]'[optionColor] +
(this.commands.length ? ' [command]' : '')[subCommandColor] + (this.commands.length ? ' [command]' : '')[subCommandColor] +
(this._args.length ? ` ${args.join(' ')}` : '')[argColor]; (this._args.length ? ` ${args.join(' ')}` : '')[argColor];
@ -71,7 +71,7 @@ Command.prototype.usage = function () {
}; };
function pad(str, width) { function pad(str, width) {
var len = Math.max(0, width - str.length); const len = Math.max(0, width - str.length);
return str + Array(len + 1).join(' '); return str + Array(len + 1).join(' ');
} }
@ -80,8 +80,8 @@ Command.prototype.commandHelp = function () {
return ''; return '';
} }
var commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => { const commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => {
var args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');
return [ return [
`${cmd._name[subCommandColor] + `${cmd._name[subCommandColor] +
@ -92,14 +92,14 @@ Command.prototype.commandHelp = function () {
]; ];
}); });
var width = commands.reduce((max, command) => Math.max(max, command[0].length), 0); const width = commands.reduce((max, command) => Math.max(max, command[0].length), 0);
return [ return [
'', '',
' Commands:', ' Commands:',
'', '',
commands.map((cmd) => { commands.map((cmd) => {
var desc = cmd[1] ? ` ${cmd[1]}` : ''; const desc = cmd[1] ? ` ${cmd[1]}` : '';
return pad(cmd[0], width) + desc; return pad(cmd[0], width) + desc;
}).join('\n').replace(/^/gm, ' '), }).join('\n').replace(/^/gm, ' '),
'', '',
@ -107,7 +107,7 @@ Command.prototype.commandHelp = function () {
}; };
Command.prototype.optionHelp = function () { Command.prototype.optionHelp = function () {
var width = this.largestOptionLength(); const width = this.largestOptionLength();
// Append the help information // Append the help information
return this.options return this.options

@ -54,7 +54,7 @@ function start(options) {
} }
// Spawn a new NodeBB process // Spawn a new NodeBB process
var child = fork(paths.loader, process.argv.slice(3), { const child = fork(paths.loader, process.argv.slice(3), {
env: process.env, env: process.env,
cwd, cwd,
}); });

@ -27,7 +27,7 @@ function setup(initConfig) {
return await install.setup(); return await install.setup();
}, },
function (next) { function (next) {
var configFile = paths.config; let configFile = paths.config;
if (nconf.get('config')) { if (nconf.get('config')) {
configFile = path.resolve(paths.baseDir, nconf.get('config')); configFile = path.resolve(paths.baseDir, nconf.get('config'));
} }
@ -44,9 +44,9 @@ function setup(initConfig) {
// Disregard build step data // Disregard build step data
data = data[0]; data = data[0];
var separator = ' '; let separator = ' ';
if (process.stdout.columns > 10) { if (process.stdout.columns > 10) {
for (var x = 0, cols = process.stdout.columns - 10; x < cols; x += 1) { for (let x = 0, cols = process.stdout.columns - 10; x < cols; x += 1) {
separator += '='; separator += '=';
} }
} }

@ -1,15 +1,15 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var nconf = require('nconf'); const nconf = require('nconf');
var packageInstall = require('./package-install'); const packageInstall = require('./package-install');
var upgrade = require('../upgrade'); const upgrade = require('../upgrade');
var build = require('../meta/build'); const build = require('../meta/build');
var db = require('../database'); const db = require('../database');
var upgradePlugins = require('./upgrade-plugins').upgradePlugins; const upgradePlugins = require('./upgrade-plugins').upgradePlugins;
var steps = { const steps = {
package: { package: {
message: 'Updating package.json file with defaults...', message: 'Updating package.json file with defaults...',
handler: function (next) { handler: function (next) {
@ -67,10 +67,10 @@ function runSteps(tasks) {
throw err; throw err;
} }
var message = 'NodeBB Upgrade Complete!'; const message = 'NodeBB Upgrade Complete!';
// some consoles will return undefined/zero columns, so just use 2 spaces in upgrade script if we can't get our column count // some consoles will return undefined/zero columns, so just use 2 spaces in upgrade script if we can't get our column count
var columns = process.stdout.columns; const columns = process.stdout.columns;
var spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' '; const spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' ';
console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`); console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`);
@ -85,7 +85,7 @@ function runUpgrade(upgrades, options) {
nconf.set('mongo:options:socketTimeoutMS', 0); nconf.set('mongo:options:socketTimeoutMS', 0);
if (upgrades === true) { if (upgrades === true) {
var tasks = Object.keys(steps); let tasks = Object.keys(steps);
if (options.package || options.install || if (options.package || options.install ||
options.plugins || options.schema || options.build) { options.plugins || options.schema || options.build) {
tasks = tasks.filter(key => options[key]); tasks = tasks.filter(key => options[key]);

@ -1,6 +1,6 @@
'use strict'; 'use strict';
var accountsController = { const accountsController = {
profile: require('./accounts/profile'), profile: require('./accounts/profile'),
edit: require('./accounts/edit'), edit: require('./accounts/edit'),
info: require('./accounts/info'), info: require('./accounts/info'),

@ -241,7 +241,7 @@ function filterLinks(links, states) {
canViewInfo: true, canViewInfo: true,
...link.visibility }; ...link.visibility };
var permit = Object.keys(states).some(state => states[state] && link.visibility[state]); const permit = Object.keys(states).some(state => states[state] && link.visibility[state]);
links[index].public = permit; links[index].public = permit;
return permit; return permit;

@ -110,7 +110,7 @@ async function getPosts(callerUid, userData, setSuffix) {
} }
function addMetaTags(res, userData) { function addMetaTags(res, userData) {
var plainAboutMe = userData.aboutme ? utils.stripHTMLTags(utils.decodeHTMLEntities(userData.aboutme)) : ''; const plainAboutMe = userData.aboutme ? utils.stripHTMLTags(utils.decodeHTMLEntities(userData.aboutme)) : '';
res.locals.metaTags = [ res.locals.metaTags = [
{ {
name: 'title', name: 'title',

@ -219,8 +219,8 @@ async function getHomePageRoutes(userData) {
let routes = await helpers.getHomePageRoutes(userData.uid); let routes = await helpers.getHomePageRoutes(userData.uid);
// Set selected for each route // Set selected for each route
var customIdx; let customIdx;
var hasSelected = false; let hasSelected = false;
routes = routes.map((route, idx) => { routes = routes.map((route, idx) => {
if (route.route === userData.settings.homePageRoute) { if (route.route === userData.settings.homePageRoute) {
route.selected = true; route.selected = true;

@ -3,7 +3,7 @@
const privileges = require('../privileges'); const privileges = require('../privileges');
const helpers = require('./helpers'); const helpers = require('./helpers');
var adminController = { const adminController = {
dashboard: require('./admin/dashboard'), dashboard: require('./admin/dashboard'),
categories: require('./admin/categories'), categories: require('./admin/categories'),
privileges: require('./admin/privileges'), privileges: require('./admin/privileges'),

@ -26,8 +26,8 @@ uploadsController.get = async function (req, res, next) {
let files = await fs.promises.readdir(currentFolder); let files = await fs.promises.readdir(currentFolder);
files = files.filter(filename => filename !== '.gitignore'); files = files.filter(filename => filename !== '.gitignore');
const itemCount = files.length; const itemCount = files.length;
var start = Math.max(0, (page - 1) * itemsPerPage); const start = Math.max(0, (page - 1) * itemsPerPage);
var stop = start + itemsPerPage; const stop = start + itemsPerPage;
files = files.slice(start, stop); files = files.slice(start, stop);
files = await filesToData(currentFolder, files); files = await filesToData(currentFolder, files);
@ -65,11 +65,11 @@ uploadsController.get = async function (req, res, next) {
}; };
function buildBreadcrumbs(currentFolder) { function buildBreadcrumbs(currentFolder) {
var crumbs = []; const crumbs = [];
var parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep); const parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep);
var currentPath = ''; let currentPath = '';
parts.forEach((part) => { parts.forEach((part) => {
var dir = path.join(currentPath, part); const dir = path.join(currentPath, part);
crumbs.push({ crumbs.push({
text: part || 'Uploads', text: part || 'Uploads',
url: part ? url: part ?

@ -191,7 +191,7 @@ usersController.registrationQueue = async function (req, res) {
customHeaders: plugins.hooks.fire('filter:admin.registrationQueue.customHeaders', { headers: [] }), customHeaders: plugins.hooks.fire('filter:admin.registrationQueue.customHeaders', { headers: [] }),
invites: getInvites(), invites: getInvites(),
}); });
var pageCount = Math.max(1, Math.ceil(data.registrationQueueCount / itemsPerPage)); const pageCount = Math.max(1, Math.ceil(data.registrationQueueCount / itemsPerPage));
data.pagination = pagination.create(page, pageCount); data.pagination = pagination.create(page, pageCount);
data.customHeaders = data.customHeaders.headers; data.customHeaders = data.customHeaders.headers;
res.render('admin/manage/registration', data); res.render('admin/manage/registration', data);

@ -142,7 +142,7 @@ authenticationController.registerComplete = function (req, res, next) {
return next(err); return next(err);
} }
var callbacks = data.interstitials.reduce((memo, cur) => { const callbacks = data.interstitials.reduce((memo, cur) => {
if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') { if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') {
req.body.files = req.files; req.body.files = req.files;
memo.push(cur.callback && cur.callback.constructor && cur.callback.constructor.name === 'AsyncFunction' ? cur.callback : util.promisify(cur.callback)); memo.push(cur.callback && cur.callback.constructor && cur.callback.constructor.name === 'AsyncFunction' ? cur.callback : util.promisify(cur.callback));
@ -151,7 +151,7 @@ authenticationController.registerComplete = function (req, res, next) {
return memo; return memo;
}, []); }, []);
var done = function (err, data) { const done = function (err, data) {
delete req.session.registration; delete req.session.registration;
if (err) { if (err) {
return res.redirect(`${nconf.get('relative_path')}/?register=${encodeURIComponent(err.message)}`); return res.redirect(`${nconf.get('relative_path')}/?register=${encodeURIComponent(err.message)}`);
@ -218,7 +218,7 @@ authenticationController.login = async (req, res, next) => {
return continueLogin(strategy, req, res, next); return continueLogin(strategy, req, res, next);
} }
var loginWith = meta.config.allowLoginWith || 'username-email'; const loginWith = meta.config.allowLoginWith || 'username-email';
req.body.username = req.body.username.trim(); req.body.username = req.body.username.trim();
plugins.hooks.fire('filter:login.check', { req: req, res: res, userData: req.body }, (err) => { plugins.hooks.fire('filter:login.check', { req: req, res: res, userData: req.body }, (err) => {
@ -262,7 +262,7 @@ function continueLogin(strategy, req, res, next) {
// Alter user cookie depending on passed-in option // Alter user cookie depending on passed-in option
if (req.body.remember === 'on') { if (req.body.remember === 'on') {
var duration = 1000 * 60 * 60 * 24 * meta.config.loginDays; const duration = 1000 * 60 * 60 * 24 * meta.config.loginDays;
req.session.cookie.maxAge = duration; req.session.cookie.maxAge = duration;
req.session.cookie.expires = new Date(Date.now() + duration); req.session.cookie.expires = new Date(Date.now() + duration);
} else { } else {
@ -283,7 +283,7 @@ function continueLogin(strategy, req, res, next) {
} else { } else {
delete req.query.lang; delete req.query.lang;
await authenticationController.doLogin(req, userData.uid); await authenticationController.doLogin(req, userData.uid);
var destination; let destination;
if (req.session.returnTo) { if (req.session.returnTo) {
destination = req.session.returnTo.startsWith('http') ? destination = req.session.returnTo.startsWith('http') ?
req.session.returnTo : req.session.returnTo :

@ -1,17 +1,17 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const nconf = require('nconf');
var winston = require('winston'); const winston = require('winston');
var validator = require('validator'); const validator = require('validator');
var plugins = require('../plugins'); const plugins = require('../plugins');
var middleware = require('../middleware'); const middleware = require('../middleware');
exports.handleURIErrors = async function handleURIErrors(err, req, res, next) { exports.handleURIErrors = async function handleURIErrors(err, req, res, next) {
// Handle cases where malformed URIs are passed in // Handle cases where malformed URIs are passed in
if (err instanceof URIError) { if (err instanceof URIError) {
const cleanPath = req.path.replace(new RegExp(`^${nconf.get('relative_path')}`), ''); const cleanPath = req.path.replace(new RegExp(`^${nconf.get('relative_path')}`), '');
var tidMatch = cleanPath.match(/^\/topic\/(\d+)\//); const tidMatch = cleanPath.match(/^\/topic\/(\d+)\//);
var cidMatch = cleanPath.match(/^\/category\/(\d+)\//); const cidMatch = cleanPath.match(/^\/category\/(\d+)\//);
if (tidMatch) { if (tidMatch) {
res.redirect(nconf.get('relative_path') + tidMatch[0]); res.redirect(nconf.get('relative_path') + tidMatch[0]);
@ -36,7 +36,7 @@ exports.handleURIErrors = async function handleURIErrors(err, req, res, next) {
// this needs to have four arguments or express treats it as `(req, res, next)` // this needs to have four arguments or express treats it as `(req, res, next)`
// don't remove `next`! // don't remove `next`!
exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-disable-line no-unused-vars exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-disable-line no-unused-vars
var cases = { const cases = {
EBADCSRFTOKEN: function () { EBADCSRFTOKEN: function () {
winston.error(`${req.path}\n${err.message}`); winston.error(`${req.path}\n${err.message}`);
res.sendStatus(403); res.sendStatus(403);
@ -45,9 +45,9 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di
res.status(403).type('text/plain').send(err.message); res.status(403).type('text/plain').send(err.message);
}, },
}; };
var defaultHandler = async function () { const defaultHandler = async function () {
// Display NodeBB error page // Display NodeBB error page
var status = parseInt(err.status, 10); const status = parseInt(err.status, 10);
if ((status === 302 || status === 308) && err.path) { if ((status === 302 || status === 308) && err.path) {
return res.locals.isAPI ? res.set('X-Redirect', err.path).status(200).json(err.path) : res.redirect(nconf.get('relative_path') + err.path); return res.locals.isAPI ? res.set('X-Redirect', err.path).status(200).json(err.path) : res.redirect(nconf.get('relative_path') + err.path);
} }
@ -56,7 +56,7 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di
res.status(status || 500); res.status(status || 500);
var path = String(req.path || ''); const path = String(req.path || '');
if (res.locals.isAPI) { if (res.locals.isAPI) {
res.json({ path: validator.escape(path), error: err.message }); res.json({ path: validator.escape(path), error: err.message });
} else { } else {

@ -487,7 +487,7 @@ async function generateBannedResponse(res) {
} }
helpers.generateError = (statusCode, message) => { helpers.generateError = (statusCode, message) => {
var payload = { const payload = {
status: { status: {
code: 'internal-server-error', code: 'internal-server-error',
message: 'An unexpected error was encountered while attempting to service your request.', message: 'An unexpected error was encountered while attempting to service your request.',

@ -52,7 +52,7 @@ async function rewrite(req, res, next) {
exports.rewrite = rewrite; exports.rewrite = rewrite;
function pluginHook(req, res, next) { function pluginHook(req, res, next) {
var hook = `action:homepage.get:${res.locals.homePageRoute}`; const hook = `action:homepage.get:${res.locals.homePageRoute}`;
plugins.hooks.fire(hook, { plugins.hooks.fire(hook, {
req: req, req: req,

@ -1,9 +1,9 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const nconf = require('nconf');
var databaseName = nconf.get('database'); const databaseName = nconf.get('database');
var winston = require('winston'); const winston = require('winston');
if (!databaseName) { if (!databaseName) {
winston.error(new Error('Database type not set! Run ./nodebb setup')); winston.error(new Error('Database type not set! Run ./nodebb setup'));

@ -9,8 +9,8 @@ const connection = module.exports;
connection.getConnectionString = function (mongo) { connection.getConnectionString = function (mongo) {
mongo = mongo || nconf.get('mongo'); mongo = mongo || nconf.get('mongo');
var usernamePassword = ''; let usernamePassword = '';
var uri = mongo.uri || ''; const uri = mongo.uri || '';
if (mongo.username && mongo.password) { if (mongo.username && mongo.password) {
usernamePassword = `${nconf.get('mongo:username')}:${encodeURIComponent(nconf.get('mongo:password'))}@`; usernamePassword = `${nconf.get('mongo:username')}:${encodeURIComponent(nconf.get('mongo:password'))}@`;
} else if (!uri.includes('@') || !uri.slice(uri.indexOf('://') + 3, uri.indexOf('@'))) { } else if (!uri.includes('@') || !uri.slice(uri.indexOf('://') + 3, uri.indexOf('@'))) {
@ -30,11 +30,11 @@ connection.getConnectionString = function (mongo) {
mongo.database = 'nodebb'; mongo.database = 'nodebb';
} }
var hosts = mongo.host.split(','); const hosts = mongo.host.split(',');
var ports = mongo.port.toString().split(','); const ports = mongo.port.toString().split(',');
var servers = []; const servers = [];
for (var i = 0; i < hosts.length; i += 1) { for (let i = 0; i < hosts.length; i += 1) {
servers.push(`${hosts[i]}:${ports[i]}`); servers.push(`${hosts[i]}:${ports[i]}`);
} }
@ -43,7 +43,7 @@ connection.getConnectionString = function (mongo) {
connection.getConnectionOptions = function (mongo) { connection.getConnectionOptions = function (mongo) {
mongo = mongo || nconf.get('mongo'); mongo = mongo || nconf.get('mongo');
var connOptions = { const connOptions = {
poolSize: 10, poolSize: 10,
connectTimeoutMS: 90000, connectTimeoutMS: 90000,
useNewUrlParser: true, useNewUrlParser: true,

@ -56,7 +56,7 @@ module.exports = function (module) {
if (!field) { if (!field) {
return; return;
} }
var data = {}; const data = {};
data[field] = value; data[field] = value;
await module.setObject(key, data); await module.setObject(key, data);
}; };
@ -177,7 +177,7 @@ module.exports = function (module) {
return; return;
} }
var data = {}; const data = {};
fields.forEach((field) => { fields.forEach((field) => {
field = helpers.fieldToString(field); field = helpers.fieldToString(field);
data[field] = ''; data[field] = '';
@ -205,12 +205,12 @@ module.exports = function (module) {
return null; return null;
} }
var increment = {}; const increment = {};
field = helpers.fieldToString(field); field = helpers.fieldToString(field);
increment[field] = value; increment[field] = value;
if (Array.isArray(key)) { if (Array.isArray(key)) {
var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
key.forEach((key) => { key.forEach((key) => {
bulk.find({ _key: key }).upsert().update({ $inc: increment }); bulk.find({ _key: key }).upsert().update({ $inc: increment });
}); });

@ -6,8 +6,8 @@ const utils = require('../../utils');
helpers.noop = function () {}; helpers.noop = function () {};
helpers.toMap = function (data) { helpers.toMap = function (data) {
var map = {}; const map = {};
for (var i = 0; i < data.length; i += 1) { for (let i = 0; i < data.length; i += 1) {
map[data[i]._key] = data[i]; map[data[i]._key] = data[i];
delete data[i]._key; delete data[i]._key;
} }

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.listPrepend = async function (key, value) { module.listPrepend = async function (key, value) {
if (!key) { if (!key) {

@ -66,7 +66,7 @@ module.exports = function (module) {
const objectData = await module.client.collection('objects').findOne({ _key: key }, { projection: { _id: 0 } }); const objectData = await module.client.collection('objects').findOne({ _key: key }, { projection: { _id: 0 } });
// fallback to old field name 'value' for backwards compatibility #6340 // fallback to old field name 'value' for backwards compatibility #6340
var value = null; let value = null;
if (objectData) { if (objectData) {
if (objectData.hasOwnProperty('data')) { if (objectData.hasOwnProperty('data')) {
value = objectData.data; value = objectData.data;
@ -105,7 +105,7 @@ module.exports = function (module) {
return null; return null;
} }
delete data.expireAt; delete data.expireAt;
var keys = Object.keys(data); const keys = Object.keys(data);
if (keys.length === 4 && data.hasOwnProperty('_key') && data.hasOwnProperty('score') && data.hasOwnProperty('value')) { if (keys.length === 4 && data.hasOwnProperty('_key') && data.hasOwnProperty('score') && data.hasOwnProperty('value')) {
return 'zset'; return 'zset';
} else if (keys.length === 3 && data.hasOwnProperty('_key') && data.hasOwnProperty('members')) { } else if (keys.length === 3 && data.hasOwnProperty('_key') && data.hasOwnProperty('members')) {

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.setAdd = async function (key, value) { module.setAdd = async function (key, value) {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {
@ -36,9 +36,9 @@ module.exports = function (module) {
value = value.map(v => helpers.valueToString(v)); value = value.map(v => helpers.valueToString(v));
var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (var i = 0; i < keys.length; i += 1) { for (let i = 0; i < keys.length; i += 1) {
bulk.find({ _key: keys[i] }).upsert().updateOne({ $addToSet: { bulk.find({ _key: keys[i] }).upsert().updateOne({ $addToSet: {
members: { members: {
$each: value, $each: value,
@ -103,7 +103,7 @@ module.exports = function (module) {
const result = await module.client.collection('objects').find({ _key: { $in: sets }, members: value }, { projection: { _id: 0, members: 0 } }).toArray(); const result = await module.client.collection('objects').find({ _key: { $in: sets }, members: value }, { projection: { _id: 0, members: 0 } }).toArray();
var map = {}; const map = {};
result.forEach((item) => { result.forEach((item) => {
map[item._key] = true; map[item._key] = true;
}); });
@ -126,7 +126,7 @@ module.exports = function (module) {
} }
const data = await module.client.collection('objects').find({ _key: { $in: keys } }, { projection: { _id: 0 } }).toArray(); const data = await module.client.collection('objects').find({ _key: { $in: keys } }, { projection: { _id: 0 } }).toArray();
var sets = {}; const sets = {};
data.forEach((set) => { data.forEach((set) => {
sets[set._key] = set.members || []; sets[set._key] = set.members || [];
}); });
@ -144,7 +144,7 @@ module.exports = function (module) {
module.setsCount = async function (keys) { module.setsCount = async function (keys) {
const setsMembers = await module.getSetsMembers(keys); const setsMembers = await module.getSetsMembers(keys);
var counts = setsMembers.map(members => (members && members.length) || 0); const counts = setsMembers.map(members => (members && members.length) || 0);
return counts; return counts;
}; };
@ -154,8 +154,8 @@ module.exports = function (module) {
return; return;
} }
var randomIndex = Math.floor(Math.random() * data.members.length); const randomIndex = Math.floor(Math.random() * data.members.length);
var value = data.members[randomIndex]; const value = data.members[randomIndex];
await module.setRemove(data._key, value); await module.setRemove(data._key, value);
return value; return value;
}; };

@ -143,7 +143,7 @@ module.exports = function (module) {
return; return;
} }
var query = { _key: key }; const query = { _key: key };
if (min !== '-inf') { if (min !== '-inf') {
query.score = { $gte: min }; query.score = { $gte: min };
} }
@ -226,8 +226,8 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) { if (!Array.isArray(keys) || !keys.length) {
return []; return [];
} }
var data = new Array(values.length); const data = new Array(values.length);
for (var i = 0; i < values.length; i += 1) { for (let i = 0; i < values.length; i += 1) {
data[i] = { key: keys[i], value: values[i] }; data[i] = { key: keys[i], value: values[i] };
} }
const promises = data.map(item => method(item.key, item.value)); const promises = data.map(item => method(item.key, item.value));
@ -271,7 +271,7 @@ module.exports = function (module) {
} }
value = helpers.valueToString(value); value = helpers.valueToString(value);
const result = await module.client.collection('objects').find({ _key: { $in: keys }, value: value }, { projection: { _id: 0, value: 0 } }).toArray(); const result = await module.client.collection('objects').find({ _key: { $in: keys }, value: value }, { projection: { _id: 0, value: 0 } }).toArray();
var map = {}; const map = {};
result.forEach((item) => { result.forEach((item) => {
if (item) { if (item) {
map[item._key] = item; map[item._key] = item;
@ -291,7 +291,7 @@ module.exports = function (module) {
values = values.map(helpers.valueToString); values = values.map(helpers.valueToString);
const result = await module.client.collection('objects').find({ _key: key, value: { $in: values } }, { projection: { _id: 0, _key: 0 } }).toArray(); const result = await module.client.collection('objects').find({ _key: key, value: { $in: values } }, { projection: { _id: 0, _key: 0 } }).toArray();
var valueToScore = {}; const valueToScore = {};
result.forEach((item) => { result.forEach((item) => {
if (item) { if (item) {
valueToScore[item.value] = item.score; valueToScore[item.value] = item.score;
@ -328,7 +328,7 @@ module.exports = function (module) {
projection: { _id: 0, value: 1 }, projection: { _id: 0, value: 1 },
}).toArray(); }).toArray();
var isMember = {}; const isMember = {};
results.forEach((item) => { results.forEach((item) => {
if (item) { if (item) {
isMember[item.value] = true; isMember[item.value] = true;
@ -349,7 +349,7 @@ module.exports = function (module) {
projection: { _id: 0, _key: 1, value: 1 }, projection: { _id: 0, _key: 1, value: 1 },
}).toArray(); }).toArray();
var isMember = {}; const isMember = {};
results.forEach((item) => { results.forEach((item) => {
if (item) { if (item) {
isMember[item._key] = true; isMember[item._key] = true;
@ -393,7 +393,7 @@ module.exports = function (module) {
if (!key) { if (!key) {
return; return;
} }
var data = {}; const data = {};
value = helpers.valueToString(value); value = helpers.valueToString(value);
data.score = parseFloat(increment); data.score = parseFloat(increment);
@ -426,7 +426,7 @@ module.exports = function (module) {
}; };
async function sortedSetLex(key, min, max, sort, start, count) { async function sortedSetLex(key, min, max, sort, start, count) {
var query = { _key: key }; const query = { _key: key };
start = start !== undefined ? start : 0; start = start !== undefined ? start : 0;
count = count !== undefined ? count : 0; count = count !== undefined ? count : 0;
buildLexQuery(query, min, max); buildLexQuery(query, min, max);
@ -441,7 +441,7 @@ module.exports = function (module) {
} }
module.sortedSetRemoveRangeByLex = async function (key, min, max) { module.sortedSetRemoveRangeByLex = async function (key, min, max) {
var query = { _key: key }; const query = { _key: key };
buildLexQuery(query, min, max); buildLexQuery(query, min, max);
await module.client.collection('objects').deleteMany(query); await module.client.collection('objects').deleteMany(query);
@ -499,14 +499,14 @@ module.exports = function (module) {
}; };
module.processSortedSet = async function (setKey, processFn, options) { module.processSortedSet = async function (setKey, processFn, options) {
var done = false; let done = false;
var ids = []; const ids = [];
var project = { _id: 0, _key: 0 }; const project = { _id: 0, _key: 0 };
if (!options.withScores) { if (!options.withScores) {
project.score = 0; project.score = 0;
} }
var cursor = await module.client.collection('objects').find({ _key: setKey }, { projection: project }) const cursor = await module.client.collection('objects').find({ _key: setKey }, { projection: project })
.sort({ score: 1 }) .sort({ score: 1 })
.batchSize(options.batch); .batchSize(options.batch);

@ -1,8 +1,8 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('../helpers'); const helpers = require('../helpers');
var utils = require('../../../utils'); const utils = require('../../../utils');
module.sortedSetAdd = async function (key, score, value) { module.sortedSetAdd = async function (key, score, value) {
if (!key) { if (!key) {
@ -40,8 +40,8 @@ module.exports = function (module) {
} }
values = values.map(helpers.valueToString); values = values.map(helpers.valueToString);
var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (var i = 0; i < scores.length; i += 1) { for (let i = 0; i < scores.length; i += 1) {
bulk.find({ _key: key, value: values[i] }).upsert().updateOne({ $set: { score: parseFloat(scores[i]) } }); bulk.find({ _key: key, value: values[i] }).upsert().updateOne({ $set: { score: parseFloat(scores[i]) } });
} }
await bulk.execute(); await bulk.execute();
@ -63,8 +63,8 @@ module.exports = function (module) {
value = helpers.valueToString(value); value = helpers.valueToString(value);
var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (var i = 0; i < keys.length; i += 1) { for (let i = 0; i < keys.length; i += 1) {
bulk.find({ _key: keys[i], value: value }).upsert().updateOne({ $set: { score: parseFloat(isArrayOfScores ? scores[i] : scores) } }); bulk.find({ _key: keys[i], value: value }).upsert().updateOne({ $set: { score: parseFloat(isArrayOfScores ? scores[i] : scores) } });
} }
await bulk.execute(); await bulk.execute();
@ -74,7 +74,7 @@ module.exports = function (module) {
if (!Array.isArray(data) || !data.length) { if (!Array.isArray(data) || !data.length) {
return; return;
} }
var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
data.forEach((item) => { data.forEach((item) => {
if (!utils.isNumber(item[1])) { if (!utils.isNumber(item[1])) {
throw new Error(`[[error:invalid-score, ${item[1]}]]`); throw new Error(`[[error:invalid-score, ${item[1]}]]`);

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('../helpers'); const helpers = require('../helpers');
module.sortedSetRemove = async function (key, value) { module.sortedSetRemove = async function (key, value) {
if (!key) { if (!key) {
@ -37,7 +37,7 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) { if (!Array.isArray(keys) || !keys.length) {
return; return;
} }
var query = { _key: { $in: keys } }; const query = { _key: { $in: keys } };
if (keys.length === 1) { if (keys.length === 1) {
query._key = keys[0]; query._key = keys[0];
} }
@ -56,7 +56,7 @@ module.exports = function (module) {
if (!Array.isArray(data) || !data.length) { if (!Array.isArray(data) || !data.length) {
return; return;
} }
var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
data.forEach(item => bulk.find({ _key: item[0], value: String(item[1]) }).remove()); data.forEach(item => bulk.find({ _key: item[0], value: String(item[1]) }).remove());
await bulk.execute(); await bulk.execute();
}; };

@ -28,19 +28,19 @@ module.exports = function (module) {
if (!Array.isArray(params.sets) || !params.sets.length) { if (!Array.isArray(params.sets) || !params.sets.length) {
return; return;
} }
var limit = params.stop - params.start + 1; let limit = params.stop - params.start + 1;
if (limit <= 0) { if (limit <= 0) {
limit = 0; limit = 0;
} }
var aggregate = {}; const aggregate = {};
if (params.aggregate) { if (params.aggregate) {
aggregate[`$${params.aggregate.toLowerCase()}`] = '$score'; aggregate[`$${params.aggregate.toLowerCase()}`] = '$score';
} else { } else {
aggregate.$sum = '$score'; aggregate.$sum = '$score';
} }
var pipeline = [ const pipeline = [
{ $match: { _key: { $in: params.sets } } }, { $match: { _key: { $in: params.sets } } },
{ $group: { _id: { value: '$value' }, totalScore: aggregate } }, { $group: { _id: { value: '$value' }, totalScore: aggregate } },
{ $sort: { totalScore: params.sort } }, { $sort: { totalScore: params.sort } },
@ -54,7 +54,7 @@ module.exports = function (module) {
pipeline.push({ $limit: limit }); pipeline.push({ $limit: limit });
} }
var project = { _id: 0, value: '$_id.value' }; const project = { _id: 0, value: '$_id.value' };
if (params.withScores) { if (params.withScores) {
project.score = '$totalScore'; project.score = '$totalScore';
} }

@ -64,7 +64,7 @@ postgresModule.init = async function () {
async function checkUpgrade(client) { async function checkUpgrade(client) {
var res = await client.query(` const res = await client.query(`
SELECT EXISTS(SELECT * SELECT EXISTS(SELECT *
FROM "information_schema"."columns" FROM "information_schema"."columns"
WHERE "table_schema" = 'public' WHERE "table_schema" = 'public'
@ -331,7 +331,7 @@ postgresModule.createIndices = function (callback) {
return callback(); return callback();
} }
var query = postgresModule.pool.query.bind(postgresModule.pool); const query = postgresModule.pool.query.bind(postgresModule.pool);
winston.info('[database] Checking database indices.'); winston.info('[database] Checking database indices.');
async.series([ async.series([
@ -348,7 +348,7 @@ postgresModule.createIndices = function (callback) {
}; };
postgresModule.checkCompatibility = function (callback) { postgresModule.checkCompatibility = function (callback) {
var postgresPkg = require('pg/package.json'); const postgresPkg = require('pg/package.json');
postgresModule.checkCompatibilityVersion(postgresPkg.version, callback); postgresModule.checkCompatibilityVersion(postgresPkg.version, callback);
}; };

@ -21,7 +21,7 @@ connection.getConnectionOptions = function (postgres) {
postgres.database = 'nodebb'; postgres.database = 'nodebb';
} }
var connOptions = { const connOptions = {
host: postgres.host, host: postgres.host,
port: postgres.port, port: postgres.port,
user: postgres.username, user: postgres.username,

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.setObject = async function (key, data) { module.setObject = async function (key, data) {
if (!key || !data) { if (!key || !data) {
@ -158,7 +158,7 @@ SELECT (SELECT jsonb_object_agg(f, d."value")
return res.rows[0].d; return res.rows[0].d;
} }
var obj = {}; const obj = {};
fields.forEach((f) => { fields.forEach((f) => {
obj[f] = null; obj[f] = null;
}); });

@ -1,17 +1,17 @@
'use strict'; 'use strict';
var helpers = module.exports; const helpers = module.exports;
helpers.valueToString = function (value) { helpers.valueToString = function (value) {
return String(value); return String(value);
}; };
helpers.removeDuplicateValues = function (values) { helpers.removeDuplicateValues = function (values) {
var others = Array.prototype.slice.call(arguments, 1); const others = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < values.length; i++) { for (let i = 0; i < values.length; i++) {
if (values.lastIndexOf(values[i]) !== i) { if (values.lastIndexOf(values[i]) !== i) {
values.splice(i, 1); values.splice(i, 1);
for (var j = 0; j < others.length; j++) { for (let j = 0; j < others.length; j++) {
others[j].splice(i, 1); others[j].splice(i, 1);
} }
i -= 1; i -= 1;
@ -81,14 +81,14 @@ SELECT "_key", "type"
values: [keys], values: [keys],
}); });
var invalid = res.rows.filter(r => r.type !== type); const invalid = res.rows.filter(r => r.type !== type);
if (invalid.length) { if (invalid.length) {
const parts = invalid.map(r => `${JSON.stringify(r._key)} is ${r.type}`); const parts = invalid.map(r => `${JSON.stringify(r._key)} is ${r.type}`);
throw new Error(`database: cannot insert multiple objects as ${type} because they already exist: ${parts.join(', ')}`); throw new Error(`database: cannot insert multiple objects as ${type} because they already exist: ${parts.join(', ')}`);
} }
var missing = keys.filter(k => !res.rows.some(r => r._key === k)); const missing = keys.filter(k => !res.rows.some(r => r._key === k));
if (missing.length) { if (missing.length) {
throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`); throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`);

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.listPrepend = async function (key, value) { module.listPrepend = async function (key, value) {
if (!key) { if (!key) {

@ -1,9 +1,9 @@
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.setAdd = async function (key, value) { module.setAdd = async function (key, value) {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {

@ -1,9 +1,9 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
const util = require('util'); const util = require('util');
var Cursor = require('pg-cursor'); const Cursor = require('pg-cursor');
Cursor.prototype.readAsync = util.promisify(Cursor.prototype.read); Cursor.prototype.readAsync = util.promisify(Cursor.prototype.read);
const sleep = util.promisify(setTimeout); const sleep = util.promisify(setTimeout);
@ -41,19 +41,19 @@ module.exports = function (module) {
return []; return [];
} }
var reverse = false; let reverse = false;
if (start === 0 && stop < -1) { if (start === 0 && stop < -1) {
reverse = true; reverse = true;
sort *= -1; sort *= -1;
start = Math.abs(stop + 1); start = Math.abs(stop + 1);
stop = -1; stop = -1;
} else if (start < 0 && stop > start) { } else if (start < 0 && stop > start) {
var tmp1 = Math.abs(stop + 1); const tmp1 = Math.abs(stop + 1);
stop = Math.abs(start + 1); stop = Math.abs(start + 1);
start = tmp1; start = tmp1;
} }
var limit = stop - start + 1; let limit = stop - start + 1;
if (limit <= 0) { if (limit <= 0) {
limit = null; limit = null;
} }
@ -346,7 +346,7 @@ SELECT o."_key" k,
}); });
return keys.map((k) => { return keys.map((k) => {
var s = res.rows.find(r => r.k === k); const s = res.rows.find(r => r.k === k);
return s ? parseFloat(s.s) : null; return s ? parseFloat(s.s) : null;
}); });
}; };
@ -375,7 +375,7 @@ SELECT z."value" v,
}); });
return values.map((v) => { return values.map((v) => {
var s = res.rows.find(r => r.v === v); const s = res.rows.find(r => r.v === v);
return s ? parseFloat(s.s) : null; return s ? parseFloat(s.s) : null;
}); });
}; };
@ -507,7 +507,7 @@ RETURNING "score" s`,
}; };
module.sortedSetLexCount = async function (key, min, max) { module.sortedSetLexCount = async function (key, min, max) {
var q = buildLexQuery(key, min, max); const q = buildLexQuery(key, min, max);
const res = await module.pool.query({ const res = await module.pool.query({
name: `sortedSetLexCount${q.suffix}`, name: `sortedSetLexCount${q.suffix}`,
@ -528,7 +528,7 @@ SELECT COUNT(*) c
start = start !== undefined ? start : 0; start = start !== undefined ? start : 0;
count = count !== undefined ? count : 0; count = count !== undefined ? count : 0;
var q = buildLexQuery(key, min, max); const q = buildLexQuery(key, min, max);
q.values.push(start); q.values.push(start);
q.values.push(count <= 0 ? null : count); q.values.push(count <= 0 ? null : count);
const res = await module.pool.query({ const res = await module.pool.query({
@ -550,7 +550,7 @@ OFFSET $${q.values.length - 1}::INTEGER`,
} }
module.sortedSetRemoveRangeByLex = async function (key, min, max) { module.sortedSetRemoveRangeByLex = async function (key, min, max) {
var q = buildLexQuery(key, min, max); const q = buildLexQuery(key, min, max);
await module.pool.query({ await module.pool.query({
name: `sortedSetRemoveRangeByLex${q.suffix}`, name: `sortedSetRemoveRangeByLex${q.suffix}`,
text: ` text: `
@ -564,7 +564,7 @@ DELETE FROM "legacy_zset" z
}; };
function buildLexQuery(key, min, max) { function buildLexQuery(key, min, max) {
var q = { const q = {
suffix: '', suffix: '',
where: `o."_key" = $1::TEXT`, where: `o."_key" = $1::TEXT`,
values: [key], values: [key],
@ -636,8 +636,8 @@ SELECT z."value",
module.processSortedSet = async function (setKey, process, options) { module.processSortedSet = async function (setKey, process, options) {
const client = await module.pool.connect(); const client = await module.pool.connect();
var batchSize = (options || {}).batch || 100; const batchSize = (options || {}).batch || 100;
var cursor = client.query(new Cursor(` const cursor = client.query(new Cursor(`
SELECT z."value", z."score" SELECT z."value", z."score"
FROM "legacy_object_live" o FROM "legacy_object_live" o
INNER JOIN "legacy_zset" z INNER JOIN "legacy_zset" z

@ -1,8 +1,8 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('../helpers'); const helpers = require('../helpers');
var utils = require('../../../utils'); const utils = require('../../../utils');
module.sortedSetAdd = async function (key, score, value) { module.sortedSetAdd = async function (key, score, value) {
if (!key) { if (!key) {

@ -37,11 +37,11 @@ SELECT COUNT(*) c
}; };
async function getSortedSetIntersect(params) { async function getSortedSetIntersect(params) {
var sets = params.sets; const sets = params.sets;
var start = params.hasOwnProperty('start') ? params.start : 0; const start = params.hasOwnProperty('start') ? params.start : 0;
var stop = params.hasOwnProperty('stop') ? params.stop : -1; const stop = params.hasOwnProperty('stop') ? params.stop : -1;
var weights = params.weights || []; let weights = params.weights || [];
var aggregate = params.aggregate || 'SUM'; const aggregate = params.aggregate || 'SUM';
if (sets.length < weights.length) { if (sets.length < weights.length) {
weights = weights.slice(0, sets.length); weights = weights.slice(0, sets.length);
@ -50,7 +50,7 @@ SELECT COUNT(*) c
weights.push(1); weights.push(1);
} }
var limit = stop - start + 1; let limit = stop - start + 1;
if (limit <= 0) { if (limit <= 0) {
limit = null; limit = null;
} }

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('../helpers'); const helpers = require('../helpers');
module.sortedSetRemove = async function (key, value) { module.sortedSetRemove = async function (key, value) {
if (!key) { if (!key) {

@ -31,11 +31,11 @@ SELECT COUNT(DISTINCT z."value") c
}; };
async function getSortedSetUnion(params) { async function getSortedSetUnion(params) {
var sets = params.sets; const sets = params.sets;
var start = params.hasOwnProperty('start') ? params.start : 0; const start = params.hasOwnProperty('start') ? params.start : 0;
var stop = params.hasOwnProperty('stop') ? params.stop : -1; const stop = params.hasOwnProperty('stop') ? params.stop : -1;
var weights = params.weights || []; let weights = params.weights || [];
var aggregate = params.aggregate || 'SUM'; const aggregate = params.aggregate || 'SUM';
if (sets.length < weights.length) { if (sets.length < weights.length) {
weights = weights.slice(0, sets.length); weights = weights.slice(0, sets.length);
@ -44,7 +44,7 @@ SELECT COUNT(DISTINCT z."value") c
weights.push(1); weights.push(1);
} }
var limit = stop - start + 1; let limit = stop - start + 1;
if (limit <= 0) { if (limit <= 0) {
limit = null; limit = null;
} }

@ -193,7 +193,7 @@ module.exports = function (module) {
} }
let result; let result;
if (Array.isArray(key)) { if (Array.isArray(key)) {
var batch = module.client.batch(); const batch = module.client.batch();
key.forEach(k => batch.hincrby(k, field, value)); key.forEach(k => batch.hincrby(k, field, value));
result = await helpers.execBatch(batch); result = await helpers.execBatch(batch);
} else { } else {

@ -2,7 +2,7 @@
const util = require('util'); const util = require('util');
var helpers = module.exports; const helpers = module.exports;
helpers.noop = function () {}; helpers.noop = function () {};
@ -12,7 +12,7 @@ helpers.execBatch = async function (batch) {
}; };
helpers.resultsToBool = function (results) { helpers.resultsToBool = function (results) {
for (var i = 0; i < results.length; i += 1) { for (let i = 0; i < results.length; i += 1) {
results[i] = results[i] === 1; results[i] = results[i] === 1;
} }
return results; return results;

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.flushdb = async function () { module.flushdb = async function () {
await module.client.async.send_command('flushdb', []); await module.client.async.send_command('flushdb', []);

@ -20,7 +20,7 @@ const PubSub = function () {
} }
try { try {
var msg = JSON.parse(message); const msg = JSON.parse(message);
self.emit(msg.event, msg.data); self.emit(msg.event, msg.data);
} catch (err) { } catch (err) {
winston.error(err.stack); winston.error(err.stack);

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('./helpers'); const helpers = require('./helpers');
module.setAdd = async function (key, value) { module.setAdd = async function (key, value) {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {
@ -30,13 +30,13 @@ module.exports = function (module) {
key = [key]; key = [key];
} }
var batch = module.client.batch(); const batch = module.client.batch();
key.forEach(k => batch.srem(String(k), value)); key.forEach(k => batch.srem(String(k), value));
await helpers.execBatch(batch); await helpers.execBatch(batch);
}; };
module.setsRemove = async function (keys, value) { module.setsRemove = async function (keys, value) {
var batch = module.client.batch(); const batch = module.client.batch();
keys.forEach(k => batch.srem(String(k), value)); keys.forEach(k => batch.srem(String(k), value));
await helpers.execBatch(batch); await helpers.execBatch(batch);
}; };

@ -111,7 +111,7 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) { if (!Array.isArray(keys) || !keys.length) {
return []; return [];
} }
var batch = module.client.batch(); const batch = module.client.batch();
keys.forEach(k => batch.zcard(String(k))); keys.forEach(k => batch.zcard(String(k)));
return await helpers.execBatch(batch); return await helpers.execBatch(batch);
}; };
@ -138,7 +138,7 @@ module.exports = function (module) {
module.sortedSetsRanks = async function (keys, values) { module.sortedSetsRanks = async function (keys, values) {
const batch = module.client.batch(); const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) { for (let i = 0; i < values.length; i += 1) {
batch.zrank(keys[i], String(values[i])); batch.zrank(keys[i], String(values[i]));
} }
return await helpers.execBatch(batch); return await helpers.execBatch(batch);
@ -146,7 +146,7 @@ module.exports = function (module) {
module.sortedSetsRevRanks = async function (keys, values) { module.sortedSetsRevRanks = async function (keys, values) {
const batch = module.client.batch(); const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) { for (let i = 0; i < values.length; i += 1) {
batch.zrevrank(keys[i], String(values[i])); batch.zrevrank(keys[i], String(values[i]));
} }
return await helpers.execBatch(batch); return await helpers.execBatch(batch);
@ -154,7 +154,7 @@ module.exports = function (module) {
module.sortedSetRanks = async function (key, values) { module.sortedSetRanks = async function (key, values) {
const batch = module.client.batch(); const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) { for (let i = 0; i < values.length; i += 1) {
batch.zrank(key, String(values[i])); batch.zrank(key, String(values[i]));
} }
return await helpers.execBatch(batch); return await helpers.execBatch(batch);
@ -162,7 +162,7 @@ module.exports = function (module) {
module.sortedSetRevRanks = async function (key, values) { module.sortedSetRevRanks = async function (key, values) {
const batch = module.client.batch(); const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) { for (let i = 0; i < values.length; i += 1) {
batch.zrevrank(key, String(values[i])); batch.zrevrank(key, String(values[i]));
} }
return await helpers.execBatch(batch); return await helpers.execBatch(batch);
@ -230,7 +230,7 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) { if (!Array.isArray(keys) || !keys.length) {
return []; return [];
} }
var batch = module.client.batch(); const batch = module.client.batch();
keys.forEach(k => batch.zrange(k, 0, -1)); keys.forEach(k => batch.zrange(k, 0, -1));
return await helpers.execBatch(batch); return await helpers.execBatch(batch);
}; };
@ -257,8 +257,8 @@ module.exports = function (module) {
}; };
async function sortedSetLex(method, reverse, key, min, max, start, count) { async function sortedSetLex(method, reverse, key, min, max, start, count) {
var minmin; let minmin;
var maxmax; let maxmax;
if (reverse) { if (reverse) {
minmin = '+'; minmin = '+';
maxmax = '-'; maxmax = '-';

@ -30,8 +30,8 @@ module.exports = function (module) {
throw new Error(`[[error:invalid-score, ${scores[i]}]]`); throw new Error(`[[error:invalid-score, ${scores[i]}]]`);
} }
} }
var args = [key]; const args = [key];
for (var i = 0; i < scores.length; i += 1) { for (let i = 0; i < scores.length; i += 1) {
args.push(scores[i], String(values[i])); args.push(scores[i], String(values[i]));
} }
await module.client.async.zadd(args); await module.client.async.zadd(args);
@ -51,8 +51,8 @@ module.exports = function (module) {
throw new Error('[[error:invalid-data]]'); throw new Error('[[error:invalid-data]]');
} }
var batch = module.client.batch(); const batch = module.client.batch();
for (var i = 0; i < keys.length; i += 1) { for (let i = 0; i < keys.length; i += 1) {
if (keys[i]) { if (keys[i]) {
batch.zadd(keys[i], isArrayOfScores ? scores[i] : scores, String(value)); batch.zadd(keys[i], isArrayOfScores ? scores[i] : scores, String(value));
} }
@ -64,7 +64,7 @@ module.exports = function (module) {
if (!Array.isArray(data) || !data.length) { if (!Array.isArray(data) || !data.length) {
return; return;
} }
var batch = module.client.batch(); const batch = module.client.batch();
data.forEach((item) => { data.forEach((item) => {
if (!utils.isNumber(item[1])) { if (!utils.isNumber(item[1])) {
throw new Error(`[[error:invalid-score, ${item[1]}]]`); throw new Error(`[[error:invalid-score, ${item[1]}]]`);

@ -7,11 +7,11 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) { if (!Array.isArray(keys) || !keys.length) {
return 0; return 0;
} }
var tempSetName = `temp_${Date.now()}`; const tempSetName = `temp_${Date.now()}`;
var interParams = [tempSetName, keys.length].concat(keys); const interParams = [tempSetName, keys.length].concat(keys);
var multi = module.client.multi(); const multi = module.client.multi();
multi.zinterstore(interParams); multi.zinterstore(interParams);
multi.zcard(tempSetName); multi.zcard(tempSetName);
multi.del(tempSetName); multi.del(tempSetName);
@ -30,14 +30,14 @@ module.exports = function (module) {
}; };
async function getSortedSetRevIntersect(params) { async function getSortedSetRevIntersect(params) {
var sets = params.sets; const sets = params.sets;
var start = params.hasOwnProperty('start') ? params.start : 0; const start = params.hasOwnProperty('start') ? params.start : 0;
var stop = params.hasOwnProperty('stop') ? params.stop : -1; const stop = params.hasOwnProperty('stop') ? params.stop : -1;
var weights = params.weights || []; const weights = params.weights || [];
var tempSetName = `temp_${Date.now()}`; const tempSetName = `temp_${Date.now()}`;
var interParams = [tempSetName, sets.length].concat(sets); let interParams = [tempSetName, sets.length].concat(sets);
if (weights.length) { if (weights.length) {
interParams = interParams.concat(['WEIGHTS'].concat(weights)); interParams = interParams.concat(['WEIGHTS'].concat(weights));
} }
@ -46,12 +46,12 @@ module.exports = function (module) {
interParams = interParams.concat(['AGGREGATE', params.aggregate]); interParams = interParams.concat(['AGGREGATE', params.aggregate]);
} }
var rangeParams = [tempSetName, start, stop]; const rangeParams = [tempSetName, start, stop];
if (params.withScores) { if (params.withScores) {
rangeParams.push('WITHSCORES'); rangeParams.push('WITHSCORES');
} }
var multi = module.client.multi(); const multi = module.client.multi();
multi.zinterstore(interParams); multi.zinterstore(interParams);
multi[params.method](rangeParams); multi[params.method](rangeParams);
multi.del(tempSetName); multi.del(tempSetName);

@ -2,7 +2,7 @@
'use strict'; 'use strict';
module.exports = function (module) { module.exports = function (module) {
var helpers = require('../helpers'); const helpers = require('../helpers');
module.sortedSetRemove = async function (key, value) { module.sortedSetRemove = async function (key, value) {
if (!key) { if (!key) {
@ -30,7 +30,7 @@ module.exports = function (module) {
}; };
module.sortedSetsRemoveRangeByScore = async function (keys, min, max) { module.sortedSetsRemoveRangeByScore = async function (keys, min, max) {
var batch = module.client.batch(); const batch = module.client.batch();
keys.forEach(k => batch.zremrangebyscore(k, min, max)); keys.forEach(k => batch.zremrangebyscore(k, min, max));
await helpers.execBatch(batch); await helpers.execBatch(batch);
}; };

@ -4,11 +4,11 @@
module.exports = function (module) { module.exports = function (module) {
const helpers = require('../helpers'); const helpers = require('../helpers');
module.sortedSetUnionCard = async function (keys) { module.sortedSetUnionCard = async function (keys) {
var tempSetName = `temp_${Date.now()}`; const tempSetName = `temp_${Date.now()}`;
if (!keys.length) { if (!keys.length) {
return 0; return 0;
} }
var multi = module.client.multi(); const multi = module.client.multi();
multi.zunionstore([tempSetName, keys.length].concat(keys)); multi.zunionstore([tempSetName, keys.length].concat(keys));
multi.zcard(tempSetName); multi.zcard(tempSetName);
multi.del(tempSetName); multi.del(tempSetName);
@ -31,14 +31,14 @@ module.exports = function (module) {
return []; return [];
} }
var tempSetName = `temp_${Date.now()}`; const tempSetName = `temp_${Date.now()}`;
var rangeParams = [tempSetName, params.start, params.stop]; const rangeParams = [tempSetName, params.start, params.stop];
if (params.withScores) { if (params.withScores) {
rangeParams.push('WITHSCORES'); rangeParams.push('WITHSCORES');
} }
var multi = module.client.multi(); const multi = module.client.multi();
multi.zunionstore([tempSetName, params.sets.length].concat(params.sets)); multi.zunionstore([tempSetName, params.sets.length].concat(params.sets));
multi[params.method](rangeParams); multi[params.method](rangeParams);
multi.del(tempSetName); multi.del(tempSetName);

@ -135,7 +135,7 @@ Flags.getFlagIdsWithFilters = async function ({ filters, uid }) {
filters.page = filters.hasOwnProperty('page') ? Math.abs(parseInt(filters.page, 10) || 1) : 1; filters.page = filters.hasOwnProperty('page') ? Math.abs(parseInt(filters.page, 10) || 1) : 1;
filters.perPage = filters.hasOwnProperty('perPage') ? Math.abs(parseInt(filters.perPage, 10) || 20) : 20; filters.perPage = filters.hasOwnProperty('perPage') ? Math.abs(parseInt(filters.perPage, 10) || 20) : 20;
for (var type in filters) { for (const type in filters) {
if (filters.hasOwnProperty(type)) { if (filters.hasOwnProperty(type)) {
if (Flags._filters.hasOwnProperty(type)) { if (Flags._filters.hasOwnProperty(type)) {
Flags._filters[type](sets, orSets, filters[type], uid); Flags._filters[type](sets, orSets, filters[type], uid);
@ -586,7 +586,7 @@ Flags.update = async function (flagId, uid, changeset) {
// Retrieve existing flag data to compare for history-saving/reference purposes // Retrieve existing flag data to compare for history-saving/reference purposes
const tasks = []; const tasks = [];
for (var prop in changeset) { for (const prop in changeset) {
if (changeset.hasOwnProperty(prop)) { if (changeset.hasOwnProperty(prop)) {
if (current[prop] === changeset[prop]) { if (current[prop] === changeset[prop]) {
delete changeset[prop]; delete changeset[prop];

@ -46,7 +46,7 @@ Groups.getEphemeralGroup = function (groupName) {
}; };
Groups.removeEphemeralGroups = function (groups) { Groups.removeEphemeralGroups = function (groups) {
for (var x = groups.length; x >= 0; x -= 1) { for (let x = groups.length; x >= 0; x -= 1) {
if (Groups.ephemeralGroups.includes(groups[x])) { if (Groups.ephemeralGroups.includes(groups[x])) {
groups.splice(x, 1); groups.splice(x, 1);
} }
@ -55,7 +55,7 @@ Groups.removeEphemeralGroups = function (groups) {
return groups; return groups;
}; };
var isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w\-:]+$/; const isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w\-:]+$/;
Groups.isPrivilegeGroup = function (groupName) { Groups.isPrivilegeGroup = function (groupName) {
return isPrivilegeGroupRegex.test(groupName); return isPrivilegeGroupRegex.test(groupName);
}; };

@ -87,7 +87,7 @@ function checkSetupFlag() {
} }
function checkCIFlag() { function checkCIFlag() {
var ciVals; let ciVals;
try { try {
ciVals = JSON.parse(nconf.get('ci')); ciVals = JSON.parse(nconf.get('ci'));
} catch (e) { } catch (e) {
@ -151,7 +151,7 @@ async function completeConfigSetup(config) {
// Add CI object // Add CI object
if (install.ciVals) { if (install.ciVals) {
config.test_database = {}; config.test_database = {};
for (var prop in install.ciVals) { for (const prop in install.ciVals) {
if (install.ciVals.hasOwnProperty(prop)) { if (install.ciVals.hasOwnProperty(prop)) {
config.test_database[prop] = install.ciVals[prop]; config.test_database[prop] = install.ciVals[prop];
} }
@ -173,7 +173,7 @@ async function completeConfigSetup(config) {
if (!/^http(?:s)?:\/\//.test(config.url)) { if (!/^http(?:s)?:\/\//.test(config.url)) {
config.url = `http://${config.url}`; config.url = `http://${config.url}`;
} }
var urlObj = url.parse(config.url); const urlObj = url.parse(config.url);
if (urlObj.port) { if (urlObj.port) {
config.port = urlObj.port; config.port = urlObj.port;
} }

@ -4,17 +4,17 @@
* Logger module: ability to dynamically turn on/off logging for http requests & socket.io events * Logger module: ability to dynamically turn on/off logging for http requests & socket.io events
*/ */
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var winston = require('winston'); const winston = require('winston');
var util = require('util'); const util = require('util');
var morgan = require('morgan'); const morgan = require('morgan');
var file = require('./file'); const file = require('./file');
var meta = require('./meta'); const meta = require('./meta');
var opts = { const opts = {
/* /*
* state used by Logger * state used by Logger
*/ */
@ -29,7 +29,7 @@ var opts = {
}; };
/* -- Logger -- */ /* -- Logger -- */
var Logger = module.exports; const Logger = module.exports;
Logger.init = function (app) { Logger.init = function (app) {
opts.express.app = app; opts.express.app = app;
@ -58,7 +58,7 @@ Logger.setup_one_log = function (value) {
* Otherwise, close the current stream * Otherwise, close the current stream
*/ */
if (meta.config.loggerStatus > 0 || meta.config.loggerIOStatus) { if (meta.config.loggerStatus > 0 || meta.config.loggerIOStatus) {
var stream = Logger.open(value); const stream = Logger.open(value);
if (stream) { if (stream) {
opts.streams.log.f = stream; opts.streams.log.f = stream;
} else { } else {
@ -71,10 +71,10 @@ Logger.setup_one_log = function (value) {
Logger.open = function (value) { Logger.open = function (value) {
/* Open the streams to log to: either a path or stdout */ /* Open the streams to log to: either a path or stdout */
var stream; let stream;
if (value) { if (value) {
if (file.existsSync(value)) { if (file.existsSync(value)) {
var stats = fs.statSync(value); const stats = fs.statSync(value);
if (stats) { if (stats) {
if (stats.isDirectory()) { if (stats.isDirectory()) {
stream = fs.createWriteStream(path.join(value, 'nodebb.log'), { flags: 'a' }); stream = fs.createWriteStream(path.join(value, 'nodebb.log'), { flags: 'a' });
@ -207,11 +207,11 @@ Logger.io_one = function (socket, uid) {
if (socket && meta.config.loggerIOStatus > 0) { if (socket && meta.config.loggerIOStatus > 0) {
// courtesy of: http://stackoverflow.com/a/9674248 // courtesy of: http://stackoverflow.com/a/9674248
socket.oEmit = socket.emit; socket.oEmit = socket.emit;
var emit = socket.emit; const emit = socket.emit;
socket.emit = override(emit, 'emit', 'Logger.io_one: emit.apply: Failed'); socket.emit = override(emit, 'emit', 'Logger.io_one: emit.apply: Failed');
socket.$onvent = socket.onevent; socket.$onvent = socket.onevent;
var $onevent = socket.onevent; const $onevent = socket.onevent;
socket.onevent = override($onevent, 'on', 'Logger.io_one: $emit.apply: Failed'); socket.onevent = override($onevent, 'on', 'Logger.io_one: $emit.apply: Failed');
} }
}; };

@ -64,7 +64,7 @@ module.exports = function (Messaging) {
message.fromUser.banned = !!message.fromUser.banned; message.fromUser.banned = !!message.fromUser.banned;
message.fromUser.deleted = message.fromuid !== message.fromUser.uid && message.fromUser.uid === 0; message.fromUser.deleted = message.fromuid !== message.fromUser.uid && message.fromUser.uid === 0;
var self = message.fromuid === parseInt(uid, 10); const self = message.fromuid === parseInt(uid, 10);
message.self = self ? 1 : 0; message.self = self ? 1 : 0;
message.newSet = false; message.newSet = false;
@ -104,7 +104,7 @@ module.exports = function (Messaging) {
}); });
} else if (messages.length === 1) { } else if (messages.length === 1) {
// For single messages, we don't know the context, so look up the previous message and compare // For single messages, we don't know the context, so look up the previous message and compare
var key = `uid:${uid}:chat:room:${roomId}:mids`; const key = `uid:${uid}:chat:room:${roomId}:mids`;
const index = await db.sortedSetRank(key, messages[0].messageId); const index = await db.sortedSetRank(key, messages[0].messageId);
if (index > 0) { if (index > 0) {
const mid = await db.getSortedSetRange(key, index - 1, index - 1); const mid = await db.getSortedSetRange(key, index - 1, index - 1);

@ -258,8 +258,8 @@ Messaging.hasPrivateChat = async (uid, withUid) => {
return 0; return 0;
} }
var index = 0; let index = 0;
var roomId = 0; let roomId = 0;
while (index < roomIds.length && !roomId) { while (index < roomIds.length && !roomId) {
/* eslint-disable no-await-in-loop */ /* eslint-disable no-await-in-loop */
const count = await Messaging.getUserCountInRoom(roomIds[index]); const count = await Messaging.getUserCountInRoom(roomIds[index]);

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var validator = require('validator'); const validator = require('validator');
var db = require('../database'); const db = require('../database');
var user = require('../user'); const user = require('../user');
var plugins = require('../plugins'); const plugins = require('../plugins');
var privileges = require('../privileges'); const privileges = require('../privileges');
var meta = require('../meta'); const meta = require('../meta');
module.exports = function (Messaging) { module.exports = function (Messaging) {
Messaging.getRoomData = async (roomId) => { Messaging.getRoomData = async (roomId) => {
@ -233,7 +233,7 @@ module.exports = function (Messaging) {
user.isAdminOrGlobalMod(uid), user.isAdminOrGlobalMod(uid),
]); ]);
var room = roomData; const room = roomData;
room.messages = messages; room.messages = messages;
room.isOwner = parseInt(room.owner, 10) === parseInt(uid, 10); room.isOwner = parseInt(room.owner, 10) === parseInt(uid, 10);
room.users = users.filter(user => user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10)); room.users = users.filter(user => user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10));

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var db = require('../database'); const db = require('../database');
var sockets = require('../socket.io'); const sockets = require('../socket.io');
module.exports = function (Messaging) { module.exports = function (Messaging) {
Messaging.getUnreadCount = async (uid) => { Messaging.getUnreadCount = async (uid) => {

@ -22,9 +22,9 @@ const aliases = {
exports.aliases = aliases; exports.aliases = aliases;
function buildTargets() { function buildTargets() {
var length = 0; let length = 0;
var output = Object.keys(aliases).map((name) => { const output = Object.keys(aliases).map((name) => {
var arr = aliases[name]; const arr = aliases[name];
if (name.length > length) { if (name.length > length) {
length = name.length; length = name.length;
} }

@ -53,7 +53,7 @@ Blacklist.test = async function (clientIp) {
} }
clientIp = clientIp.split(':').length === 2 ? clientIp.split(':')[0] : clientIp; clientIp = clientIp.split(':').length === 2 ? clientIp.split(':')[0] : clientIp;
var addr; let addr;
try { try {
addr = ipaddr.parse(clientIp); addr = ipaddr.parse(clientIp);
} catch (err) { } catch (err) {
@ -65,7 +65,7 @@ Blacklist.test = async function (clientIp) {
!Blacklist._rules.ipv4.includes(clientIp) && // not explicitly specified in ipv4 list !Blacklist._rules.ipv4.includes(clientIp) && // not explicitly specified in ipv4 list
!Blacklist._rules.ipv6.includes(clientIp) && // not explicitly specified in ipv6 list !Blacklist._rules.ipv6.includes(clientIp) && // not explicitly specified in ipv6 list
!Blacklist._rules.cidr.some((subnet) => { !Blacklist._rules.cidr.some((subnet) => {
var cidr = ipaddr.parseCIDR(subnet); const cidr = ipaddr.parseCIDR(subnet);
if (addr.kind() !== cidr[0].kind()) { if (addr.kind() !== cidr[0].kind()) {
return false; return false;
} }
@ -80,7 +80,7 @@ Blacklist.test = async function (clientIp) {
throw err; throw err;
} }
} else { } else {
var err = new Error('[[error:blacklisted-ip]]'); const err = new Error('[[error:blacklisted-ip]]');
err.code = 'blacklisted-ip'; err.code = 'blacklisted-ip';
analytics.increment('blacklist'); analytics.increment('blacklist');
@ -90,14 +90,14 @@ Blacklist.test = async function (clientIp) {
Blacklist.validate = function (rules) { Blacklist.validate = function (rules) {
rules = (rules || '').split('\n'); rules = (rules || '').split('\n');
var ipv4 = []; const ipv4 = [];
var ipv6 = []; const ipv6 = [];
var cidr = []; const cidr = [];
var invalid = []; const invalid = [];
var duplicateCount = 0; let duplicateCount = 0;
var inlineCommentMatch = /#.*$/; const inlineCommentMatch = /#.*$/;
var whitelist = ['127.0.0.1', '::1', '::ffff:0:127.0.0.1']; const whitelist = ['127.0.0.1', '::1', '::ffff:0:127.0.0.1'];
// Filter out blank lines and lines starting with the hash character (comments) // Filter out blank lines and lines starting with the hash character (comments)
// Also trim inputs and remove inline comments // Also trim inputs and remove inline comments
@ -113,8 +113,8 @@ Blacklist.validate = function (rules) {
// Filter out invalid rules // Filter out invalid rules
rules = rules.filter((rule) => { rules = rules.filter((rule) => {
var addr; let addr;
var isRange = false; let isRange = false;
try { try {
addr = ipaddr.parse(rule); addr = ipaddr.parse(rule);
} catch (e) { } catch (e) {
@ -161,9 +161,7 @@ Blacklist.validate = function (rules) {
}; };
Blacklist.addRule = async function (rule) { Blacklist.addRule = async function (rule) {
var valid; const { valid } = Blacklist.validate(rule);
const result = Blacklist.validate(rule);
valid = result.valid;
if (!valid.length) { if (!valid.length) {
throw new Error('[[error:invalid-rule]]'); throw new Error('[[error:invalid-rule]]');
} }

@ -50,7 +50,7 @@ const targetHandlers = {
}; };
const aliasMap = Object.keys(aliases).reduce((prev, key) => { const aliasMap = Object.keys(aliases).reduce((prev, key) => {
var arr = aliases[key]; const arr = aliases[key];
arr.forEach((alias) => { arr.forEach((alias) => {
prev[alias] = key; prev[alias] = key;
}); });

@ -201,7 +201,7 @@ Configs.cookie = {
cookie.secure = true; cookie.secure = true;
} }
var relativePath = nconf.get('relative_path'); const relativePath = nconf.get('relative_path');
if (relativePath !== '') { if (relativePath !== '') {
cookie.path = relativePath; cookie.path = relativePath;
} }

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var fork = require('child_process').fork; const fork = require('child_process').fork;
var debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg)); let debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg));
var debugging = !!debugArg; const debugging = !!debugArg;
debugArg = debugArg ? debugArg.replace('-brk', '').split('=') : ['--debug', 5859]; debugArg = debugArg ? debugArg.replace('-brk', '').split('=') : ['--debug', 5859];
var lastAddress = parseInt(debugArg[1], 10); let lastAddress = parseInt(debugArg[1], 10);
/** /**
* child-process.fork, but safe for use in debuggers * child-process.fork, but safe for use in debuggers
@ -15,7 +15,7 @@ var lastAddress = parseInt(debugArg[1], 10);
* @param {any} [options] * @param {any} [options]
*/ */
function debugFork(modulePath, args, options) { function debugFork(modulePath, args, options) {
var execArgv = []; let execArgv = [];
if (global.v8debug || debugging) { if (global.v8debug || debugging) {
lastAddress += 1; lastAddress += 1;

@ -61,9 +61,9 @@ function restart() {
} }
Meta.getSessionTTLSeconds = function () { Meta.getSessionTTLSeconds = function () {
var ttlDays = 60 * 60 * 24 * Meta.config.loginDays; const ttlDays = 60 * 60 * 24 * Meta.config.loginDays;
var ttlSeconds = Meta.config.loginSeconds; const ttlSeconds = Meta.config.loginSeconds;
var ttl = ttlSeconds || ttlDays || 1209600; // Default to 14 days const ttl = ttlSeconds || ttlDays || 1209600; // Default to 14 days
return ttl; return ttl;
}; };

@ -29,9 +29,9 @@ async function getTranslationMetadata() {
return; return;
} }
var rel = path.relative(coreLanguagesPath, p).split(/[/\\]/); const rel = path.relative(coreLanguagesPath, p).split(/[/\\]/);
var language = rel.shift().replace('_', '-').replace('@', '-x-'); const language = rel.shift().replace('_', '-').replace('@', '-x-');
var namespace = rel.join('/').replace(/\.json$/, ''); const namespace = rel.join('/').replace(/\.json$/, '');
if (!language || !namespace) { if (!language || !namespace) {
return; return;

@ -50,7 +50,7 @@ function getChild() {
return free.shift(); return free.shift();
} }
var proc = fork(__filename, [], { const proc = fork(__filename, [], {
cwd: __dirname, cwd: __dirname,
env: { env: {
minifier_child: true, minifier_child: true,
@ -67,14 +67,14 @@ function freeChild(proc) {
} }
function removeChild(proc) { function removeChild(proc) {
var i = pool.indexOf(proc); const i = pool.indexOf(proc);
if (i !== -1) { if (i !== -1) {
pool.splice(i, 1); pool.splice(i, 1);
} }
} }
function forkAction(action, callback) { function forkAction(action, callback) {
var proc = getChild(); const proc = getChild();
proc.on('message', (message) => { proc.on('message', (message) => {
freeChild(proc); freeChild(proc);
@ -99,12 +99,12 @@ function forkAction(action, callback) {
}); });
} }
var actions = {}; const actions = {};
if (process.env.minifier_child) { if (process.env.minifier_child) {
process.on('message', (message) => { process.on('message', (message) => {
if (message.type === 'action') { if (message.type === 'action') {
var action = message.action; const action = message.action;
if (typeof actions[action.act] !== 'function') { if (typeof actions[action.act] !== 'function') {
process.send({ process.send({
type: 'error', type: 'error',
@ -157,7 +157,7 @@ function concat(data, callback) {
return callback(err); return callback(err);
} }
var output = files.join('\n;'); const output = files.join('\n;');
fs.writeFile(data.destPath, output, callback); fs.writeFile(data.destPath, output, callback);
}); });
@ -175,7 +175,7 @@ function minifyJS_batch(data, callback) {
return next(err); return next(err);
} }
var filesToMinify = [ const filesToMinify = [
{ {
srcPath: fileObj.srcPath, srcPath: fileObj.srcPath,
filename: fileObj.filename, filename: fileObj.filename,
@ -220,7 +220,7 @@ function minifyJS(data, callback) {
actions.minifyJS = minifyJS; actions.minifyJS = minifyJS;
function minifyAndSave(data, callback) { function minifyAndSave(data, callback) {
var scripts = {}; const scripts = {};
data.files.forEach((ref) => { data.files.forEach((ref) => {
if (!ref) { if (!ref) {
return; return;
@ -229,7 +229,7 @@ function minifyAndSave(data, callback) {
scripts[ref.filename] = ref.source; scripts[ref.filename] = ref.source;
}); });
var minified = uglify.minify(scripts, { const minified = uglify.minify(scripts, {
sourceMap: { sourceMap: {
filename: data.filename, filename: data.filename,
url: `${String(data.filename).split(/[/\\]/).pop()}.map`, url: `${String(data.filename).split(/[/\\]/).pop()}.map`,

@ -56,7 +56,7 @@ Tags.parse = async (req, data, meta, link) => {
} }
// Link Tags // Link Tags
var defaultLinks = [{ const defaultLinks = [{
rel: 'icon', rel: 'icon',
type: 'image/x-icon', type: 'image/x-icon',
href: `${relative_path}/favicon.ico${Meta.config['cache-buster'] ? `?${Meta.config['cache-buster']}` : ''}`, href: `${relative_path}/favicon.ico${Meta.config['cache-buster'] ? `?${Meta.config['cache-buster']}` : ''}`,
@ -160,7 +160,7 @@ Tags.parse = async (req, data, meta, link) => {
addSiteOGImage(meta); addSiteOGImage(meta);
addIfNotExists(meta, 'property', 'og:title', Meta.config.title || 'NodeBB'); addIfNotExists(meta, 'property', 'og:title', Meta.config.title || 'NodeBB');
var ogUrl = url + (req.originalUrl !== '/' ? stripRelativePath(req.originalUrl) : ''); const ogUrl = url + (req.originalUrl !== '/' ? stripRelativePath(req.originalUrl) : '');
addIfNotExists(meta, 'property', 'og:url', ogUrl); addIfNotExists(meta, 'property', 'og:url', ogUrl);
addIfNotExists(meta, 'name', 'description', Meta.config.description); addIfNotExists(meta, 'name', 'description', Meta.config.description);
addIfNotExists(meta, 'property', 'og:description', Meta.config.description); addIfNotExists(meta, 'property', 'og:description', Meta.config.description);
@ -174,7 +174,7 @@ Tags.parse = async (req, data, meta, link) => {
}; };
function addIfNotExists(meta, keyName, tagName, value) { function addIfNotExists(meta, keyName, tagName, value) {
var exists = false; let exists = false;
meta.forEach((tag) => { meta.forEach((tag) => {
if (tag[keyName] === tagName) { if (tag[keyName] === tagName) {
exists = true; exists = true;
@ -182,7 +182,7 @@ function addIfNotExists(meta, keyName, tagName, value) {
}); });
if (!exists && value) { if (!exists && value) {
var data = { const data = {
content: utils.escapeHTML(String(value)), content: utils.escapeHTML(String(value)),
}; };
data[keyName] = tagName; data[keyName] = tagName;
@ -200,7 +200,7 @@ function stripRelativePath(url) {
function addSiteOGImage(meta) { function addSiteOGImage(meta) {
const key = Meta.config['og:image'] ? 'og:image' : 'brand:logo'; const key = Meta.config['og:image'] ? 'og:image' : 'brand:logo';
var ogImage = stripRelativePath(Meta.config[key] || ''); let ogImage = stripRelativePath(Meta.config[key] || '');
if (ogImage && !ogImage.startsWith('http')) { if (ogImage && !ogImage.startsWith('http')) {
ogImage = url + ogImage; ogImage = url + ogImage;
} }

@ -23,15 +23,15 @@ const viewsPath = nconf.get('views_dir');
const Templates = module.exports; const Templates = module.exports;
async function processImports(paths, templatePath, source) { async function processImports(paths, templatePath, source) {
var regex = /<!-- IMPORT (.+?) -->/; const regex = /<!-- IMPORT (.+?) -->/;
var matches = source.match(regex); const matches = source.match(regex);
if (!matches) { if (!matches) {
return source; return source;
} }
var partial = matches[1]; const partial = matches[1];
if (paths[partial] && templatePath !== partial) { if (paths[partial] && templatePath !== partial) {
const partialSource = await fs.promises.readFile(paths[partial], 'utf8'); const partialSource = await fs.promises.readFile(paths[partial], 'utf8');
source = source.replace(regex, partialSource); source = source.replace(regex, partialSource);
@ -72,9 +72,9 @@ async function getTemplateDirs(activePlugins) {
themeTemplates.push(nconf.get('base_templates_path')); themeTemplates.push(nconf.get('base_templates_path'));
themeTemplates = _.uniq(themeTemplates.reverse()); themeTemplates = _.uniq(themeTemplates.reverse());
var coreTemplatesPath = nconf.get('core_templates_path'); const coreTemplatesPath = nconf.get('core_templates_path');
var templateDirs = _.uniq([coreTemplatesPath].concat(themeTemplates, pluginTemplates)); let templateDirs = _.uniq([coreTemplatesPath].concat(themeTemplates, pluginTemplates));
templateDirs = await Promise.all(templateDirs.map(async path => (await file.exists(path) ? path : false))); templateDirs = await Promise.all(templateDirs.map(async path => (await file.exists(path) ? path : false)));
return templateDirs.filter(Boolean); return templateDirs.filter(Boolean);
@ -90,7 +90,7 @@ async function getTemplateFiles(dirs) {
return files; return files;
})); }));
var dict = {}; const dict = {};
buckets.forEach((files) => { buckets.forEach((files) => {
files.forEach((file) => { files.forEach((file) => {
dict[file.name] = file.path; dict[file.name] = file.path;
@ -103,7 +103,7 @@ async function getTemplateFiles(dirs) {
async function compileTemplate(filename, source) { async function compileTemplate(filename, source) {
let paths = await file.walk(viewsPath); let paths = await file.walk(viewsPath);
paths = _.fromPairs(paths.map((p) => { paths = _.fromPairs(paths.map((p) => {
var relative = path.relative(viewsPath, p).replace(/\\/g, '/'); const relative = path.relative(viewsPath, p).replace(/\\/g, '/');
return [relative, p]; return [relative, p];
})); }));

@ -139,13 +139,13 @@ Themes.setupPaths = async () => {
currentThemeId: Meta.configs.get('theme:id'), currentThemeId: Meta.configs.get('theme:id'),
}); });
var themeId = data.currentThemeId || 'nodebb-theme-persona'; const themeId = data.currentThemeId || 'nodebb-theme-persona';
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
winston.info(`[themes] Using theme ${themeId}`); winston.info(`[themes] Using theme ${themeId}`);
} }
var themeObj = data.themesData.find(themeObj => themeObj.id === themeId); const themeObj = data.themesData.find(themeObj => themeObj.id === themeId);
if (!themeObj) { if (!themeObj) {
throw new Error('[[error:theme-not-found]]'); throw new Error('[[error:theme-not-found]]');
@ -156,8 +156,8 @@ Themes.setupPaths = async () => {
Themes.setPath = function (themeObj) { Themes.setPath = function (themeObj) {
// Theme's templates path // Theme's templates path
var themePath = nconf.get('base_templates_path'); let themePath = nconf.get('base_templates_path');
var fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates'); const fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
if (themeObj.templates) { if (themeObj.templates) {
themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates); themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates);

@ -1,19 +1,19 @@
'use strict'; 'use strict';
var winston = require('winston'); const winston = require('winston');
var jsesc = require('jsesc'); const jsesc = require('jsesc');
var nconf = require('nconf'); const nconf = require('nconf');
var semver = require('semver'); const semver = require('semver');
var user = require('../user'); const user = require('../user');
var meta = require('../meta'); const meta = require('../meta');
var plugins = require('../plugins'); const plugins = require('../plugins');
var privileges = require('../privileges'); const privileges = require('../privileges');
var utils = require('../../public/src/utils'); const utils = require('../../public/src/utils');
var versions = require('../admin/versions'); const versions = require('../admin/versions');
var helpers = require('./helpers'); const helpers = require('./helpers');
var controllers = { const controllers = {
api: require('../controllers/api'), api: require('../controllers/api'),
helpers: require('../controllers/helpers'), helpers: require('../controllers/helpers'),
}; };
@ -27,7 +27,7 @@ middleware.buildHeader = helpers.try(async (req, res, next) => {
}); });
middleware.renderHeader = async (req, res, data) => { middleware.renderHeader = async (req, res, data) => {
var custom_header = { const custom_header = {
plugins: [], plugins: [],
authentication: [], authentication: [],
}; };
@ -42,21 +42,21 @@ middleware.renderHeader = async (req, res, data) => {
privileges: privileges.admin.get(req.uid), privileges: privileges.admin.get(req.uid),
}); });
var userData = results.userData; const userData = results.userData;
userData.uid = req.uid; userData.uid = req.uid;
userData['email:confirmed'] = userData['email:confirmed'] === 1; userData['email:confirmed'] = userData['email:confirmed'] === 1;
userData.privileges = results.privileges; userData.privileges = results.privileges;
var acpPath = req.path.slice(1).split('/'); let acpPath = req.path.slice(1).split('/');
acpPath.forEach((path, i) => { acpPath.forEach((path, i) => {
acpPath[i] = path.charAt(0).toUpperCase() + path.slice(1); acpPath[i] = path.charAt(0).toUpperCase() + path.slice(1);
}); });
acpPath = acpPath.join(' > '); acpPath = acpPath.join(' > ');
var version = nconf.get('version'); const version = nconf.get('version');
res.locals.config.userLang = res.locals.config.acpLang || res.locals.config.userLang; res.locals.config.userLang = res.locals.config.acpLang || res.locals.config.userLang;
var templateValues = { let templateValues = {
config: res.locals.config, config: res.locals.config,
configJSON: jsesc(JSON.stringify(res.locals.config), { isScriptContext: true }), configJSON: jsesc(JSON.stringify(res.locals.config), { isScriptContext: true }),
relative_path: res.locals.config.relative_path, relative_path: res.locals.config.relative_path,

@ -1,33 +1,33 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var path = require('path'); const path = require('path');
var csrf = require('csurf'); const csrf = require('csurf');
var validator = require('validator'); const validator = require('validator');
var nconf = require('nconf'); const nconf = require('nconf');
var ensureLoggedIn = require('connect-ensure-login'); const ensureLoggedIn = require('connect-ensure-login');
var toobusy = require('toobusy-js'); const toobusy = require('toobusy-js');
var LRU = require('lru-cache'); const LRU = require('lru-cache');
var util = require('util'); const util = require('util');
var plugins = require('../plugins'); const plugins = require('../plugins');
var meta = require('../meta'); const meta = require('../meta');
var user = require('../user'); const user = require('../user');
var groups = require('../groups'); const groups = require('../groups');
var analytics = require('../analytics'); const analytics = require('../analytics');
var privileges = require('../privileges'); const privileges = require('../privileges');
var helpers = require('./helpers'); const helpers = require('./helpers');
var controllers = { const controllers = {
api: require('../controllers/api'), api: require('../controllers/api'),
helpers: require('../controllers/helpers'), helpers: require('../controllers/helpers'),
}; };
var delayCache = new LRU({ const delayCache = new LRU({
maxAge: 1000 * 60, maxAge: 1000 * 60,
}); });
var middleware = module.exports; const middleware = module.exports;
const relative_path = nconf.get('relative_path'); const relative_path = nconf.get('relative_path');
@ -66,7 +66,7 @@ require('./expose')(middleware);
middleware.assert = require('./assert'); middleware.assert = require('./assert');
middleware.stripLeadingSlashes = function stripLeadingSlashes(req, res, next) { middleware.stripLeadingSlashes = function stripLeadingSlashes(req, res, next) {
var target = req.originalUrl.replace(relative_path, ''); const target = req.originalUrl.replace(relative_path, '');
if (target.startsWith('//')) { if (target.startsWith('//')) {
return res.redirect(relative_path + target.replace(/^\/+/, '/')); return res.redirect(relative_path + target.replace(/^\/+/, '/'));
} }
@ -118,7 +118,7 @@ middleware.routeTouchIcon = function routeTouchIcon(req, res) {
if (meta.config['brand:touchIcon'] && validator.isURL(meta.config['brand:touchIcon'])) { if (meta.config['brand:touchIcon'] && validator.isURL(meta.config['brand:touchIcon'])) {
return res.redirect(meta.config['brand:touchIcon']); return res.redirect(meta.config['brand:touchIcon']);
} }
var iconPath = ''; let iconPath = '';
if (meta.config['brand:touchIcon']) { if (meta.config['brand:touchIcon']) {
iconPath = path.join(nconf.get('upload_path'), meta.config['brand:touchIcon'].replace(/assets\/uploads/, '')); iconPath = path.join(nconf.get('upload_path'), meta.config['brand:touchIcon'].replace(/assets\/uploads/, ''));
} else { } else {
@ -160,8 +160,8 @@ middleware.privateUploads = function privateUploads(req, res, next) {
} }
if (req.path.startsWith(`${nconf.get('relative_path')}/assets/uploads/files`)) { if (req.path.startsWith(`${nconf.get('relative_path')}/assets/uploads/files`)) {
var extensions = (meta.config.privateUploadsExtensions || '').split(',').filter(Boolean); const extensions = (meta.config.privateUploadsExtensions || '').split(',').filter(Boolean);
var ext = path.extname(req.path); let ext = path.extname(req.path);
ext = ext ? ext.replace(/^\./, '') : ext; ext = ext ? ext.replace(/^\./, '') : ext;
if (!extensions.length || extensions.includes(ext)) { if (!extensions.length || extensions.includes(ext)) {
return res.status(403).json('not-allowed'); return res.status(403).json('not-allowed');
@ -192,7 +192,7 @@ middleware.delayLoading = function delayLoading(req, res, next) {
// Introduces an artificial delay during load so that brute force attacks are effectively mitigated // Introduces an artificial delay during load so that brute force attacks are effectively mitigated
// Add IP to cache so if too many requests are made, subsequent requests are blocked for a minute // Add IP to cache so if too many requests are made, subsequent requests are blocked for a minute
var timesSeen = delayCache.get(req.ip) || 0; let timesSeen = delayCache.get(req.ip) || 0;
if (timesSeen > 10) { if (timesSeen > 10) {
return res.sendStatus(429); return res.sendStatus(429);
} }

@ -384,12 +384,12 @@ Notifications.merge = async function (notifications) {
case 'notifications:user_started_following_you': case 'notifications:user_started_following_you':
case 'notifications:user_posted_to': case 'notifications:user_posted_to':
case 'notifications:user_flagged_post_in': case 'notifications:user_flagged_post_in':
case 'notifications:user_flagged_user': case 'notifications:user_flagged_user': {
var usernames = _.uniq(set.map(notifObj => notifObj && notifObj.user && notifObj.user.username)); const usernames = _.uniq(set.map(notifObj => notifObj && notifObj.user && notifObj.user.username));
var numUsers = usernames.length; const numUsers = usernames.length;
var title = utils.decodeHTMLEntities(notifications[modifyIndex].topicTitle || ''); const title = utils.decodeHTMLEntities(notifications[modifyIndex].topicTitle || '');
var titleEscaped = title.replace(/%/g, '&#37;').replace(/,/g, '&#44;'); let titleEscaped = title.replace(/%/g, '&#37;').replace(/,/g, '&#44;');
titleEscaped = titleEscaped ? (`, ${titleEscaped}`) : ''; titleEscaped = titleEscaped ? (`, ${titleEscaped}`) : '';
if (numUsers === 2) { if (numUsers === 2) {
@ -399,7 +399,7 @@ Notifications.merge = async function (notifications) {
} }
notifications[modifyIndex].path = set[set.length - 1].path; notifications[modifyIndex].path = set[set.length - 1].path;
break; } break;
case 'new_register': case 'new_register':
notifications[modifyIndex].bodyShort = `[[notifications:${mergeId}_multiple, ${set.length}]]`; notifications[modifyIndex].bodyShort = `[[notifications:${mergeId}_multiple, ${set.length}]]`;

@ -1,9 +1,9 @@
'use strict'; 'use strict';
var qs = require('querystring'); const qs = require('querystring');
var _ = require('lodash'); const _ = require('lodash');
var pagination = module.exports; const pagination = module.exports;
pagination.create = function (currentPage, pageCount, queryObj) { pagination.create = function (currentPage, pageCount, queryObj) {
if (pageCount <= 1) { if (pageCount <= 1) {
@ -19,17 +19,17 @@ pagination.create = function (currentPage, pageCount, queryObj) {
}; };
} }
pageCount = parseInt(pageCount, 10); pageCount = parseInt(pageCount, 10);
var pagesToShow = [1, 2, pageCount - 1, pageCount]; let pagesToShow = [1, 2, pageCount - 1, pageCount];
currentPage = parseInt(currentPage, 10) || 1; currentPage = parseInt(currentPage, 10) || 1;
var previous = Math.max(1, currentPage - 1); const previous = Math.max(1, currentPage - 1);
var next = Math.min(pageCount, currentPage + 1); const next = Math.min(pageCount, currentPage + 1);
var startPage = Math.max(1, currentPage - 2); let startPage = Math.max(1, currentPage - 2);
if (startPage > pageCount - 5) { if (startPage > pageCount - 5) {
startPage -= 2 - (pageCount - currentPage); startPage -= 2 - (pageCount - currentPage);
} }
var i; let i;
for (i = 0; i < 5; i += 1) { for (i = 0; i < 5; i += 1) {
pagesToShow.push(startPage + i); pagesToShow.push(startPage + i);
} }
@ -40,7 +40,7 @@ pagination.create = function (currentPage, pageCount, queryObj) {
delete queryObj._; delete queryObj._;
var pages = pagesToShow.map((page) => { const pages = pagesToShow.map((page) => {
queryObj.page = page; queryObj.page = page;
return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) }; return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) };
}); });
@ -53,7 +53,7 @@ pagination.create = function (currentPage, pageCount, queryObj) {
} }
} }
var data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount }; const data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount };
queryObj.page = previous; queryObj.page = previous;
data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) }; data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) };
queryObj.page = next; queryObj.page = next;

@ -43,7 +43,7 @@ Data.loadPluginInfo = async function (pluginPath) {
pluginData.nbbpm = packageData.nbbpm; pluginData.nbbpm = packageData.nbbpm;
pluginData.path = pluginPath; pluginData.path = pluginPath;
} catch (err) { } catch (err) {
var pluginDir = path.basename(pluginPath); const pluginDir = path.basename(pluginPath);
winston.error(`[plugins/${pluginDir}] Error in plugin.json or package.json!${err.stack}`); winston.error(`[plugins/${pluginDir}] Error in plugin.json or package.json!${err.stack}`);
throw new Error('[[error:parse-error]]'); throw new Error('[[error:parse-error]]');
@ -71,7 +71,7 @@ Data.getActive = async function () {
Data.getStaticDirectories = async function (pluginData) { Data.getStaticDirectories = async function (pluginData) {
var validMappedPath = /^[\w\-_]+$/; const validMappedPath = /^[\w\-_]+$/;
if (!pluginData.staticDirs) { if (!pluginData.staticDirs) {
return; return;
@ -187,10 +187,10 @@ Data.getModules = async function getModules(pluginData) {
let pluginModules = pluginData.modules; let pluginModules = pluginData.modules;
if (Array.isArray(pluginModules)) { if (Array.isArray(pluginModules)) {
var strip = parseInt(pluginData.modulesStrip, 10) || 0; const strip = parseInt(pluginData.modulesStrip, 10) || 0;
pluginModules = pluginModules.reduce((prev, modulePath) => { pluginModules = pluginModules.reduce((prev, modulePath) => {
var key; let key;
if (strip) { if (strip) {
key = modulePath.replace(new RegExp(`.?(/[^/]+){${strip}}/`), ''); key = modulePath.replace(new RegExp(`.?(/[^/]+){${strip}}/`), '');
} else { } else {

@ -80,7 +80,7 @@ Hooks.register = function (id, data) {
}; };
Hooks.unregister = function (id, hook, method) { Hooks.unregister = function (id, hook, method) {
var hooks = plugins.loadedHooks[hook] || []; const hooks = plugins.loadedHooks[hook] || [];
plugins.loadedHooks[hook] = hooks.filter(hookData => hookData && hookData.id !== id && hookData.method !== method); plugins.loadedHooks[hook] = hooks.filter(hookData => hookData && hookData.id !== id && hookData.method !== method);
}; };

@ -15,8 +15,8 @@ const meta = require('../meta');
const { pluginNamePattern, themeNamePattern, paths } = require('../constants'); const { pluginNamePattern, themeNamePattern, paths } = require('../constants');
var app; let app;
var middleware; let middleware;
const Plugins = module.exports; const Plugins = module.exports;
@ -136,7 +136,7 @@ Plugins.reload = async function () {
if (Plugins.versionWarning.length && nconf.get('isPrimary')) { if (Plugins.versionWarning.length && nconf.get('isPrimary')) {
console.log(''); console.log('');
winston.warn('[plugins/load] The following plugins may not be compatible with your version of NodeBB. This may cause unintended behaviour or crashing. In the event of an unresponsive NodeBB caused by this plugin, run `./nodebb reset -p PLUGINNAME` to disable it.'); winston.warn('[plugins/load] The following plugins may not be compatible with your version of NodeBB. This may cause unintended behaviour or crashing. In the event of an unresponsive NodeBB caused by this plugin, run `./nodebb reset -p PLUGINNAME` to disable it.');
for (var x = 0, numPlugins = Plugins.versionWarning.length; x < numPlugins; x += 1) { for (let x = 0, numPlugins = Plugins.versionWarning.length; x < numPlugins; x += 1) {
console.log(' * '.yellow + Plugins.versionWarning[x]); console.log(' * '.yellow + Plugins.versionWarning[x]);
} }
console.log(''); console.log('');
@ -156,7 +156,7 @@ Plugins.reload = async function () {
}; };
Plugins.reloadRoutes = async function (params) { Plugins.reloadRoutes = async function (params) {
var controllers = require('../controllers'); const controllers = require('../controllers');
await Plugins.hooks.fire('static:app.load', { app: app, router: params.router, middleware: middleware, controllers: controllers }); await Plugins.hooks.fire('static:app.load', { app: app, router: params.router, middleware: middleware, controllers: controllers });
winston.verbose('[plugins] All plugins reloaded and rerouted'); winston.verbose('[plugins] All plugins reloaded and rerouted');
}; };
@ -244,7 +244,7 @@ Plugins.normalise = async function (apiReturn) {
const pluginArray = []; const pluginArray = [];
for (var key in pluginMap) { for (const key in pluginMap) {
if (pluginMap.hasOwnProperty(key)) { if (pluginMap.hasOwnProperty(key)) {
pluginArray.push(pluginMap[key]); pluginArray.push(pluginMap[key]);
} }
@ -291,7 +291,7 @@ Plugins.showInstalled = async function () {
async function findNodeBBModules(dirs) { async function findNodeBBModules(dirs) {
const pluginPaths = []; const pluginPaths = [];
await async.each(dirs, (dirname, next) => { await async.each(dirs, (dirname, next) => {
var dirPath = path.join(Plugins.nodeModulesPath, dirname); const dirPath = path.join(Plugins.nodeModulesPath, dirname);
async.waterfall([ async.waterfall([
function (cb) { function (cb) {
@ -320,7 +320,7 @@ async function findNodeBBModules(dirs) {
return next(); return next();
} }
var subdirPath = path.join(dirPath, subdir); const subdirPath = path.join(dirPath, subdir);
fs.stat(subdirPath, (err, stats) => { fs.stat(subdirPath, (err, stats) => {
if (err && err.code !== 'ENOENT') { if (err && err.code !== 'ENOENT') {
return next(err); return next(err);

@ -42,7 +42,7 @@ module.exports = function (Plugins) {
}, },
}; };
var methods = {}; let methods = {};
if (Array.isArray(fields)) { if (Array.isArray(fields)) {
fields.forEach((field) => { fields.forEach((field) => {
methods[field] = handlers[field]; methods[field] = handlers[field];

@ -1,15 +1,15 @@
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
var meta = require('../meta'); const meta = require('../meta');
var db = require('../database'); const db = require('../database');
var plugins = require('../plugins'); const plugins = require('../plugins');
var user = require('../user'); const user = require('../user');
var topics = require('../topics'); const topics = require('../topics');
var categories = require('../categories'); const categories = require('../categories');
var groups = require('../groups'); const groups = require('../groups');
var utils = require('../utils'); const utils = require('../utils');
module.exports = function (Posts) { module.exports = function (Posts) {
Posts.create = async function (data) { Posts.create = async function (data) {

@ -1,15 +1,15 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const nconf = require('nconf');
var url = require('url'); const url = require('url');
var winston = require('winston'); const winston = require('winston');
const sanitize = require('sanitize-html'); const sanitize = require('sanitize-html');
const _ = require('lodash'); const _ = require('lodash');
var meta = require('../meta'); const meta = require('../meta');
var plugins = require('../plugins'); const plugins = require('../plugins');
var translator = require('../translator'); const translator = require('../translator');
var utils = require('../utils'); const utils = require('../utils');
let sanitizeConfig = { let sanitizeConfig = {
allowedTags: sanitize.defaults.allowedTags.concat([ allowedTags: sanitize.defaults.allowedTags.concat([
@ -78,9 +78,9 @@ module.exports = function (Posts) {
if (!content) { if (!content) {
return content; return content;
} }
var parsed; let parsed;
var current = regex.regex.exec(content); let current = regex.regex.exec(content);
var absolute; let absolute;
while (current !== null) { while (current !== null) {
if (current[1]) { if (current[1]) {
try { try {
@ -154,7 +154,7 @@ module.exports = function (Posts) {
function sanitizeSignature(signature) { function sanitizeSignature(signature) {
signature = translator.escape(signature); signature = translator.escape(signature);
var tagsToStrip = []; const tagsToStrip = [];
if (meta.config['signatures:disableLinks']) { if (meta.config['signatures:disableLinks']) {
tagsToStrip.push('a'); tagsToStrip.push('a');

@ -81,8 +81,8 @@ module.exports = function (Posts) {
} }
function toObject(key, data) { function toObject(key, data) {
var obj = {}; const obj = {};
for (var i = 0; i < data.length; i += 1) { for (let i = 0; i < data.length; i += 1) {
obj[data[i][key]] = data[i]; obj[data[i][key]] = data[i];
} }
return obj; return obj;

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var topics = require('../topics'); const topics = require('../topics');
var utils = require('../utils'); const utils = require('../utils');
module.exports = function (Posts) { module.exports = function (Posts) {
Posts.getPostsFromSet = async function (set, start, stop, uid, reverse) { Posts.getPostsFromSet = async function (set, start, stop, uid, reverse) {

@ -13,7 +13,7 @@ function setupWinston() {
return; return;
} }
var formats = []; const formats = [];
if (nconf.get('log-colorize') !== 'false') { if (nconf.get('log-colorize') !== 'false') {
formats.push(winston.format.colorize()); formats.push(winston.format.colorize());
} }
@ -23,7 +23,7 @@ function setupWinston() {
formats.push(winston.format.json()); formats.push(winston.format.json());
} else { } else {
const timestampFormat = winston.format((info) => { const timestampFormat = winston.format((info) => {
var dateString = `${new Date().toISOString()} [${nconf.get('port')}/${global.process.pid}]`; const dateString = `${new Date().toISOString()} [${nconf.get('port')}/${global.process.pid}]`;
info.level = `${dateString} - ${info.level}`; info.level = `${dateString} - ${info.level}`;
return info; return info;
}); });
@ -60,10 +60,10 @@ function loadConfig(configFile) {
}); });
// Explicitly cast as Bool, loader.js passes in isCluster as string 'true'/'false' // Explicitly cast as Bool, loader.js passes in isCluster as string 'true'/'false'
var castAsBool = ['isCluster', 'isPrimary', 'jobsDisabled']; const castAsBool = ['isCluster', 'isPrimary', 'jobsDisabled'];
nconf.stores.env.readOnly = false; nconf.stores.env.readOnly = false;
castAsBool.forEach((prop) => { castAsBool.forEach((prop) => {
var value = nconf.get(prop); const value = nconf.get(prop);
if (value !== undefined) { if (value !== undefined) {
nconf.set(prop, typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true'); nconf.set(prop, typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true');
} }
@ -104,10 +104,10 @@ function loadConfig(configFile) {
} }
function versionCheck() { function versionCheck() {
var version = process.version.slice(1); const version = process.version.slice(1);
var range = pkg.engines.node; const range = pkg.engines.node;
var semver = require('semver'); const semver = require('semver');
var compatible = semver.satisfies(version, range); const compatible = semver.satisfies(version, range);
if (!compatible) { if (!compatible) {
winston.warn('Your version of Node.js is too outdated for NodeBB. Please update your version of Node.js.'); winston.warn('Your version of Node.js is too outdated for NodeBB. Please update your version of Node.js.');

@ -112,7 +112,7 @@ helpers.getUserPrivileges = async function (cid, userPrivileges) {
memberData.forEach((member) => { memberData.forEach((member) => {
member.privileges = {}; member.privileges = {};
for (var x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) { for (let x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) {
member.privileges[userPrivileges[x]] = memberSets[x].includes(parseInt(member.uid, 10)); member.privileges[userPrivileges[x]] = memberSets[x].includes(parseInt(member.uid, 10));
} }
}); });
@ -145,7 +145,7 @@ helpers.getGroupPrivileges = async function (cid, groupPrivileges) {
const memberData = groupNames.map((member, index) => { const memberData = groupNames.map((member, index) => {
const memberPrivs = {}; const memberPrivs = {};
for (var x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) { for (let x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) {
memberPrivs[groupPrivileges[x]] = memberSets[x].includes(member); memberPrivs[groupPrivileges[x]] = memberSets[x].includes(member);
} }
return { return {

@ -1,6 +1,6 @@
'use strict'; 'use strict';
var privileges = module.exports; const privileges = module.exports;
privileges.privilegeLabels = [ privileges.privilegeLabels = [
{ name: '[[admin/manage/privileges:find-category]]' }, { name: '[[admin/manage/privileges:find-category]]' },

@ -162,12 +162,12 @@ module.exports = function (privileges) {
return { flag: false, message: '[[error:topic-locked]]' }; return { flag: false, message: '[[error:topic-locked]]' };
} }
var postDeleteDuration = meta.config.postDeleteDuration; const postDeleteDuration = meta.config.postDeleteDuration;
if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) { if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) {
return { flag: false, message: `[[error:post-delete-duration-expired, ${meta.config.postDeleteDuration}]]` }; return { flag: false, message: `[[error:post-delete-duration-expired, ${meta.config.postDeleteDuration}]]` };
} }
var deleterUid = postData.deleterUid; const deleterUid = postData.deleterUid;
var flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod); const flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod);
return { flag: flag, message: '[[error:no-privileges]]' }; return { flag: flag, message: '[[error:no-privileges]]' };
}; };

@ -1,18 +1,18 @@
'use strict'; 'use strict';
var EventEmitter = require('events'); const EventEmitter = require('events');
var nconf = require('nconf'); const nconf = require('nconf');
var real; let real;
var noCluster; let noCluster;
var singleHost; let singleHost;
function get() { function get() {
if (real) { if (real) {
return real; return real;
} }
var pubsub; let pubsub;
if (!nconf.get('isCluster')) { if (!nconf.get('isCluster')) {
if (noCluster) { if (noCluster) {

@ -3,13 +3,13 @@
const winston = require('winston'); const winston = require('winston');
const nconf = require('nconf'); const nconf = require('nconf');
var helpers = require('./helpers'); const helpers = require('./helpers');
var setupPageRoute = helpers.setupPageRoute; const setupPageRoute = helpers.setupPageRoute;
module.exports = function (app, middleware, controllers) { module.exports = function (app, middleware, controllers) {
var middlewares = [middleware.exposeUid, middleware.canViewUsers]; const middlewares = [middleware.exposeUid, middleware.canViewUsers];
var accountMiddlewares = [middleware.exposeUid, middleware.canViewUsers, middleware.checkAccountPermissions]; const accountMiddlewares = [middleware.exposeUid, middleware.canViewUsers, middleware.checkAccountPermissions];
setupPageRoute(app, '/me', middleware, [], middleware.redirectMeToUserslug); setupPageRoute(app, '/me', middleware, [], middleware.redirectMeToUserslug);
setupPageRoute(app, '/me/*', middleware, [], middleware.redirectMeToUserslug); setupPageRoute(app, '/me/*', middleware, [], middleware.redirectMeToUserslug);

@ -1,11 +1,11 @@
'use strict'; 'use strict';
var express = require('express'); const express = require('express');
var uploadsController = require('../controllers/uploads'); const uploadsController = require('../controllers/uploads');
module.exports = function (app, middleware, controllers) { module.exports = function (app, middleware, controllers) {
var router = express.Router(); const router = express.Router();
app.use('/api', router); app.use('/api', router);
router.get('/config', middleware.applyCSRF, middleware.authenticateOrGuest, controllers.api.getConfig); router.get('/config', middleware.applyCSRF, middleware.authenticateOrGuest, controllers.api.getConfig);
@ -25,9 +25,9 @@ module.exports = function (app, middleware, controllers) {
router.get('/topic/teaser/:topic_id', controllers.topics.teaser); router.get('/topic/teaser/:topic_id', controllers.topics.teaser);
router.get('/topic/pagination/:topic_id', controllers.topics.pagination); router.get('/topic/pagination/:topic_id', controllers.topics.pagination);
var multipart = require('connect-multiparty'); const multipart = require('connect-multiparty');
var multipartMiddleware = multipart(); const multipartMiddleware = multipart();
var middlewares = [middleware.maintenanceMode, multipartMiddleware, middleware.validateFiles, middleware.applyCSRF]; const middlewares = [middleware.maintenanceMode, multipartMiddleware, middleware.validateFiles, middleware.applyCSRF];
router.post('/post/upload', middlewares, uploadsController.uploadPost); router.post('/post/upload', middlewares, uploadsController.uploadPost);
router.post('/user/:userslug/uploadpicture', middlewares.concat([middleware.exposeUid, middleware.authenticate, middleware.canViewUsers, middleware.checkAccountPermissions]), controllers.accounts.edit.uploadPicture); router.post('/user/:userslug/uploadpicture', middlewares.concat([middleware.exposeUid, middleware.authenticate, middleware.canViewUsers, middleware.checkAccountPermissions]), controllers.accounts.edit.uploadPicture);

@ -1,19 +1,19 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var passport = require('passport'); const passport = require('passport');
var passportLocal = require('passport-local').Strategy; const passportLocal = require('passport-local').Strategy;
const BearerStrategy = require('passport-http-bearer').Strategy; const BearerStrategy = require('passport-http-bearer').Strategy;
var winston = require('winston'); const winston = require('winston');
const meta = require('../meta'); const meta = require('../meta');
var controllers = require('../controllers'); const controllers = require('../controllers');
var helpers = require('../controllers/helpers'); const helpers = require('../controllers/helpers');
var plugins = require('../plugins'); const plugins = require('../plugins');
var loginStrategies = []; let loginStrategies = [];
var Auth = module.exports; const Auth = module.exports;
Auth.initialize = function (app, middleware) { Auth.initialize = function (app, middleware) {
const passportInitMiddleware = passport.initialize(); const passportInitMiddleware = passport.initialize();
@ -161,9 +161,9 @@ Auth.reloadRoutes = async function (params) {
}); });
}); });
var multipart = require('connect-multiparty'); const multipart = require('connect-multiparty');
var multipartMiddleware = multipart(); const multipartMiddleware = multipart();
var middlewares = [multipartMiddleware, Auth.middleware.applyCSRF, Auth.middleware.applyBlacklist]; const middlewares = [multipartMiddleware, Auth.middleware.applyCSRF, Auth.middleware.applyBlacklist];
router.post('/register', middlewares, controllers.authentication.register); router.post('/register', middlewares, controllers.authentication.register);
router.post('/register/complete', middlewares, controllers.authentication.registerComplete); router.post('/register/complete', middlewares, controllers.authentication.registerComplete);

@ -1,13 +1,13 @@
'use strict'; 'use strict';
var express = require('express'); const express = require('express');
var nconf = require('nconf'); const nconf = require('nconf');
const fs = require('fs').promises; const fs = require('fs').promises;
const path = require('path'); const path = require('path');
module.exports = function (app) { module.exports = function (app) {
var router = express.Router(); const router = express.Router();
router.get('/test', (req, res) => { router.get('/test', (req, res) => {
res.redirect(404); res.redirect(404);

@ -355,7 +355,7 @@ function generateForPostsFeed(feedOptions, posts) {
feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url; feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url;
feedOptions.site_url = nconf.get('url') + feedOptions.site_url; feedOptions.site_url = nconf.get('url') + feedOptions.site_url;
var feed = new rss(feedOptions); const feed = new rss(feedOptions);
if (posts.length > 0) { if (posts.length > 0) {
feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString(); feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString();

@ -1,27 +1,27 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const nconf = require('nconf');
var winston = require('winston'); const winston = require('winston');
var path = require('path'); const path = require('path');
var express = require('express'); const express = require('express');
var meta = require('../meta'); const meta = require('../meta');
var controllers = require('../controllers'); const controllers = require('../controllers');
var plugins = require('../plugins'); const plugins = require('../plugins');
var accountRoutes = require('./accounts'); const accountRoutes = require('./accounts');
var metaRoutes = require('./meta'); const metaRoutes = require('./meta');
var apiRoutes = require('./api'); const apiRoutes = require('./api');
var adminRoutes = require('./admin'); const adminRoutes = require('./admin');
var feedRoutes = require('./feeds'); const feedRoutes = require('./feeds');
var authRoutes = require('./authentication'); const authRoutes = require('./authentication');
const writeRoutes = require('./write'); const writeRoutes = require('./write');
var helpers = require('./helpers'); const helpers = require('./helpers');
var setupPageRoute = helpers.setupPageRoute; const setupPageRoute = helpers.setupPageRoute;
function mainRoutes(app, middleware, controllers) { function mainRoutes(app, middleware, controllers) {
var loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn]; const loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn];
setupPageRoute(app, '/login', middleware, loginRegisterMiddleware, controllers.login); setupPageRoute(app, '/login', middleware, loginRegisterMiddleware, controllers.login);
setupPageRoute(app, '/register', middleware, loginRegisterMiddleware, controllers.register); setupPageRoute(app, '/register', middleware, loginRegisterMiddleware, controllers.register);
@ -78,13 +78,13 @@ function categoryRoutes(app, middleware, controllers) {
} }
function userRoutes(app, middleware, controllers) { function userRoutes(app, middleware, controllers) {
var middlewares = [middleware.canViewUsers]; const middlewares = [middleware.canViewUsers];
setupPageRoute(app, '/users', middleware, middlewares, controllers.users.index); setupPageRoute(app, '/users', middleware, middlewares, controllers.users.index);
} }
function groupRoutes(app, middleware, controllers) { function groupRoutes(app, middleware, controllers) {
var middlewares = [middleware.canViewGroups]; const middlewares = [middleware.canViewGroups];
setupPageRoute(app, '/groups', middleware, middlewares, controllers.groups.list); setupPageRoute(app, '/groups', middleware, middlewares, controllers.groups.list);
setupPageRoute(app, '/groups/:slug', middleware, middlewares, controllers.groups.details); setupPageRoute(app, '/groups/:slug', middleware, middlewares, controllers.groups.details);
@ -96,7 +96,7 @@ module.exports = async function (app, middleware) {
router.render = function () { router.render = function () {
app.render.apply(app, arguments); app.render.apply(app, arguments);
}; };
var ensureLoggedIn = require('connect-ensure-login'); const ensureLoggedIn = require('connect-ensure-login');
router.all('(/+api|/+api/*?)', middleware.prepareAPI); router.all('(/+api|/+api/*?)', middleware.prepareAPI);
router.all('(/+api/admin|/+api/admin/*?)', middleware.authenticate, middleware.admin.checkPrivileges); router.all('(/+api/admin|/+api/admin/*?)', middleware.authenticate, middleware.admin.checkPrivileges);
@ -135,7 +135,7 @@ function addCoreRoutes(app, router, middleware) {
userRoutes(router, middleware, controllers); userRoutes(router, middleware, controllers);
groupRoutes(router, middleware, controllers); groupRoutes(router, middleware, controllers);
var relativePath = nconf.get('relative_path'); const relativePath = nconf.get('relative_path');
app.use(relativePath || '/', router); app.use(relativePath || '/', router);
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
@ -144,12 +144,12 @@ function addCoreRoutes(app, router, middleware) {
app.use(middleware.privateUploads); app.use(middleware.privateUploads);
var statics = [ const statics = [
{ route: '/assets', path: path.join(__dirname, '../../build/public') }, { route: '/assets', path: path.join(__dirname, '../../build/public') },
{ route: '/assets', path: path.join(__dirname, '../../public') }, { route: '/assets', path: path.join(__dirname, '../../public') },
{ route: '/plugins', path: path.join(__dirname, '../../build/public/plugins') }, { route: '/plugins', path: path.join(__dirname, '../../build/public/plugins') },
]; ];
var staticOptions = { const staticOptions = {
maxAge: app.enabled('cache') ? 5184000000 : 0, maxAge: app.enabled('cache') ? 5184000000 : 0,
}; };

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save