diff --git a/.eslintrc b/.eslintrc index 1ef276fdb5..03ef98455c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -110,8 +110,6 @@ // WORKING ON "prefer-rest-params": "off", "prefer-spread": "off", - "no-var": "off", - "vars-on-top": "off", // TODO "consistent-return": "off", diff --git a/Gruntfile.js b/Gruntfile.js index 5d97280f84..6ee95b186e 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -10,7 +10,7 @@ const winston = require('winston'); const fork = require('child_process').fork; const env = process.env; -var worker; +let worker; env.NODE_ENV = env.NODE_ENV || 'development'; @@ -19,10 +19,10 @@ const prestart = require('./src/prestart'); prestart.loadConfig(configFile); -var db = require('./src/database'); +const db = require('./src/database'); module.exports = function (grunt) { - var args = []; + const args = []; if (!grunt.option('verbose')) { args.push('--log-level=info'); @@ -39,7 +39,7 @@ module.exports = function (grunt) { grunt.registerTask('default', ['watch']); grunt.registerTask('init', async function () { - var done = this.async(); + const done = this.async(); let plugins = []; if (!process.argv.includes('--core')) { await db.init(); @@ -165,7 +165,7 @@ module.exports = function (grunt) { grunt.event.removeAllListeners('watch'); grunt.event.on('watch', (action, filepath, target) => { - var compiling; + let compiling; if (target === 'styleUpdated_Client') { compiling = 'clientCSS'; } else if (target === 'styleUpdated_Admin') { diff --git a/install/databases.js b/install/databases.js index 6a08c700ab..057de576c6 100644 --- a/install/databases.js +++ b/install/databases.js @@ -83,7 +83,7 @@ function saveDatabaseConfig(config, databaseConfig) { } 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]; } diff --git a/install/web.js b/install/web.js index 1329797498..baf4a16a65 100644 --- a/install/web.js +++ b/install/web.js @@ -27,7 +27,7 @@ const formats = [ ]; 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}`; return info; }); @@ -117,9 +117,9 @@ function ping(req, res) { } function welcome(req, res) { - var dbs = ['redis', 'mongo', 'postgres']; - var databases = dbs.map((databaseName) => { - var questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall); + const dbs = ['redis', 'mongo', 'postgres']; + const databases = dbs.map((databaseName) => { + const questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall); return { name: databaseName, @@ -127,7 +127,7 @@ function welcome(req, res) { }; }); - var defaults = require('./data/defaults'); + const defaults = require('./data/defaults'); res.render('install/index', { url: nconf.get('url') || (`${req.protocol}://${req.get('host')}`), @@ -150,8 +150,8 @@ function install(req, res) { } req.setTimeout(0); installing = true; - var setupEnvVars = nconf.get(); - for (var i in req.body) { + const setupEnvVars = nconf.get(); + for (const i in req.body) { if (req.body.hasOwnProperty(i) && !process.env.hasOwnProperty(i)) { setupEnvVars[i.replace(':', '__')] = req.body[i]; } @@ -161,7 +161,7 @@ function install(req, res) { const pushToRoot = function (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])) { Object.keys(setupEnvVars[j]).forEach(pushToRoot.bind(null, j)); delete setupEnvVars[j]; @@ -174,7 +174,7 @@ function install(req, res) { winston.info(setupEnvVars); launchUrl = setupEnvVars.url; - var child = require('child_process').fork('app', ['--setup'], { + const child = require('child_process').fork('app', ['--setup'], { env: setupEnvVars, }); @@ -192,7 +192,7 @@ async function launch(req, res) { res.json({}); server.close(); req.setTimeout(0); - var child; + let child; if (!nconf.get('launchCmd')) { child = childProcess.spawn('node', ['loader.js'], { diff --git a/loader.js b/loader.js index 67c8743a88..b7302b28ba 100644 --- a/loader.js +++ b/loader.js @@ -1,45 +1,45 @@ 'use strict'; -var nconf = require('nconf'); -var fs = require('fs'); -var url = require('url'); -var path = require('path'); -var fork = require('child_process').fork; -var async = require('async'); -var logrotate = require('logrotate-stream'); -var mkdirp = require('mkdirp'); +const nconf = require('nconf'); +const fs = require('fs'); +const url = require('url'); +const path = require('path'); +const fork = require('child_process').fork; +const async = require('async'); +const logrotate = require('logrotate-stream'); +const mkdirp = require('mkdirp'); -var file = require('./src/file'); -var pkg = require('./package.json'); +const file = require('./src/file'); +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({ 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)) { mkdirp.sync(path.dirname(outputLogFilePath)); } -var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true }); -var silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false; -var numProcs; -var workers = []; -var Loader = { +const output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true }); +const silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false; +let numProcs; +const workers = []; +const Loader = { timesStarted: 0, }; -var appPath = path.join(__dirname, 'app.js'); +const appPath = path.join(__dirname, 'app.js'); Loader.init = function (callback) { if (silent) { console.log = function () { - var args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); output.write(`${args.join(' ')}\n`); }; } @@ -112,7 +112,7 @@ Loader.start = function (callback) { numProcs = getPorts().length; 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); } @@ -122,8 +122,8 @@ Loader.start = function (callback) { }; function forkWorker(index, isPrimary) { - var ports = getPorts(); - var args = []; + const ports = getPorts(); + const args = []; if (!ports[index]) { 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.port = ports[index]; - var worker = fork(appPath, args, { + const worker = fork(appPath, args, { silent: silent, env: process.env, }); @@ -146,20 +146,20 @@ function forkWorker(index, isPrimary) { Loader.addWorkerEvents(worker); 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.stderr.pipe(output); } } function getPorts() { - var _url = nconf.get('url'); + const _url = nconf.get('url'); if (!_url) { console.log('[cluster] url is undefined, please check your config.json'); process.exit(); } - var urlObject = url.parse(_url); - var port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567; + const urlObject = url.parse(_url); + let port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567; if (!Array.isArray(port)) { port = [port]; } @@ -178,7 +178,7 @@ Loader.restart = function () { throw err; } - var conf = JSON.parse(configFile); + const conf = JSON.parse(configFile); nconf.stores.env.readOnly = false; nconf.set('url', conf.url); @@ -217,7 +217,7 @@ fs.open(pathToConfig, 'r', (err) => { if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) { if (file.existsSync(pidFilePath)) { try { - var pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' }); + const pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' }); process.kill(pid, 0); process.exit(); } catch (e) { diff --git a/src/admin/search.js b/src/admin/search.js index 8cc0d3ab12..143f535e67 100644 --- a/src/admin/search.js +++ b/src/admin/search.js @@ -61,8 +61,8 @@ const fallbackCache = {}; async function initFallback(namespace) { const template = await fs.promises.readFile(path.resolve(nconf.get('views_dir'), `${namespace}.tpl`), 'utf8'); - var title = nsToTitle(namespace); - var translations = sanitize(template); + const title = nsToTitle(namespace); + let translations = sanitize(template); translations = Translator.removePatterns(translations); translations = simplify(translations); translations += `\n${title}`; diff --git a/src/api/helpers.js b/src/api/helpers.js index c283449253..dc2ee14852 100644 --- a/src/api/helpers.js +++ b/src/api/helpers.js @@ -65,7 +65,7 @@ exports.doTopicAction = async function (action, event, caller, { tids }) { async function logTopicAction(action, req, tid, title) { // Only log certain actions to system event log - var actionsToLog = ['delete', 'restore', 'purge']; + const actionsToLog = ['delete', 'restore', 'purge']; if (!actionsToLog.includes(action)) { return; } diff --git a/src/api/topics.js b/src/api/topics.js index 67accba68b..521c3f77d7 100644 --- a/src/api/topics.js +++ b/src/api/topics.js @@ -58,7 +58,7 @@ topicsAPI.create = async function (caller, data) { }; topicsAPI.reply = async function (caller, data) { - var payload = { + const payload = { tid: data.tid, uid: caller.uid, req: apiHelpers.buildReqObject(caller), // For IP recording diff --git a/src/categories/delete.js b/src/categories/delete.js index 080f90a308..89f3228d44 100644 --- a/src/categories/delete.js +++ b/src/categories/delete.js @@ -1,13 +1,13 @@ 'use strict'; -var async = require('async'); -var db = require('../database'); -var batch = require('../batch'); -var plugins = require('../plugins'); -var topics = require('../topics'); -var groups = require('../groups'); -var privileges = require('../privileges'); -var cache = require('../cache'); +const async = require('async'); +const db = require('../database'); +const batch = require('../batch'); +const plugins = require('../plugins'); +const topics = require('../topics'); +const groups = require('../groups'); +const privileges = require('../privileges'); +const cache = require('../cache'); module.exports = function (Categories) { Categories.purge = async function (cid, uid) { diff --git a/src/categories/recentreplies.js b/src/categories/recentreplies.js index 93f2a283f1..e56d31dc66 100644 --- a/src/categories/recentreplies.js +++ b/src/categories/recentreplies.js @@ -140,7 +140,6 @@ module.exports = function (Categories) { if (category.posts.length) { return; } - const posts = []; getPostsRecursive(category, posts); diff --git a/src/categories/update.js b/src/categories/update.js index 6c2f5c5e0d..f54655b9fe 100644 --- a/src/categories/update.js +++ b/src/categories/update.js @@ -30,9 +30,9 @@ module.exports = function (Categories) { const result = await plugins.hooks.fire('filter:category.update', { cid: cid, category: modifiedFields }); const category = result.category; - var fields = Object.keys(category); + const fields = Object.keys(category); // move parent to front, so its updated first - var parentCidIndex = fields.indexOf('parentCid'); + const parentCidIndex = fields.indexOf('parentCid'); if (parentCidIndex !== -1 && fields.length > 1) { fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]); } diff --git a/src/cli/colors.js b/src/cli/colors.js index eeb00b8dab..1de89873d8 100644 --- a/src/cli/colors.js +++ b/src/cli/colors.js @@ -5,17 +5,17 @@ // to include color styling in the output // so the CLI looks nice -var Command = require('commander').Command; +const Command = require('commander').Command; -var commandColor = 'yellow'; -var optionColor = 'cyan'; -var argColor = 'magenta'; -var subCommandColor = 'green'; -var subOptionColor = 'blue'; -var subArgColor = 'red'; +const commandColor = 'yellow'; +const optionColor = 'cyan'; +const argColor = 'magenta'; +const subCommandColor = 'green'; +const subOptionColor = 'blue'; +const subArgColor = 'red'; Command.prototype.helpInformation = function () { - var desc = []; + let desc = []; if (this._description) { desc = [ ` ${this._description}`, @@ -23,23 +23,23 @@ Command.prototype.helpInformation = function () { ]; } - var cmdName = this._name; + let cmdName = this._name; if (this._alias) { cmdName = `${cmdName} | ${this._alias}`; } - var usage = [ + const usage = [ '', ` Usage: ${cmdName[commandColor]}${' '.reset}${this.usage()}`, '', ]; - var cmds = []; - var commandHelp = this.commandHelp(); + let cmds = []; + const commandHelp = this.commandHelp(); if (commandHelp) { cmds = [commandHelp]; } - var options = [ + const options = [ '', ' Options:', '', @@ -55,15 +55,15 @@ Command.prototype.helpInformation = function () { }; function humanReadableArgName(arg) { - var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); return arg.required ? `<${nameOutput}>` : `[${nameOutput}]`; } 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._args.length ? ` ${args.join(' ')}` : '')[argColor]; @@ -71,7 +71,7 @@ Command.prototype.usage = function () { }; 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(' '); } @@ -80,8 +80,8 @@ Command.prototype.commandHelp = function () { return ''; } - var commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => { - var args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); + const commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => { + const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); return [ `${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 [ '', ' Commands:', '', commands.map((cmd) => { - var desc = cmd[1] ? ` ${cmd[1]}` : ''; + const desc = cmd[1] ? ` ${cmd[1]}` : ''; return pad(cmd[0], width) + desc; }).join('\n').replace(/^/gm, ' '), '', @@ -107,7 +107,7 @@ Command.prototype.commandHelp = function () { }; Command.prototype.optionHelp = function () { - var width = this.largestOptionLength(); + const width = this.largestOptionLength(); // Append the help information return this.options diff --git a/src/cli/running.js b/src/cli/running.js index ac81f998fe..d52ab20812 100644 --- a/src/cli/running.js +++ b/src/cli/running.js @@ -54,7 +54,7 @@ function start(options) { } // 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, cwd, }); diff --git a/src/cli/setup.js b/src/cli/setup.js index e0822b44e0..d4f530f728 100644 --- a/src/cli/setup.js +++ b/src/cli/setup.js @@ -27,7 +27,7 @@ function setup(initConfig) { return await install.setup(); }, function (next) { - var configFile = paths.config; + let configFile = paths.config; if (nconf.get('config')) { configFile = path.resolve(paths.baseDir, nconf.get('config')); } @@ -44,9 +44,9 @@ function setup(initConfig) { // Disregard build step data data = data[0]; - var separator = ' '; + let separator = ' '; 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 += '='; } } diff --git a/src/cli/upgrade.js b/src/cli/upgrade.js index 28858ab537..fc2d993707 100644 --- a/src/cli/upgrade.js +++ b/src/cli/upgrade.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var nconf = require('nconf'); +const async = require('async'); +const nconf = require('nconf'); -var packageInstall = require('./package-install'); -var upgrade = require('../upgrade'); -var build = require('../meta/build'); -var db = require('../database'); -var upgradePlugins = require('./upgrade-plugins').upgradePlugins; +const packageInstall = require('./package-install'); +const upgrade = require('../upgrade'); +const build = require('../meta/build'); +const db = require('../database'); +const upgradePlugins = require('./upgrade-plugins').upgradePlugins; -var steps = { +const steps = { package: { message: 'Updating package.json file with defaults...', handler: function (next) { @@ -67,10 +67,10 @@ function runSteps(tasks) { 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 - var columns = process.stdout.columns; - var spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' '; + const columns = process.stdout.columns; + const spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' '; console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`); @@ -85,7 +85,7 @@ function runUpgrade(upgrades, options) { nconf.set('mongo:options:socketTimeoutMS', 0); if (upgrades === true) { - var tasks = Object.keys(steps); + let tasks = Object.keys(steps); if (options.package || options.install || options.plugins || options.schema || options.build) { tasks = tasks.filter(key => options[key]); diff --git a/src/controllers/accounts.js b/src/controllers/accounts.js index 8a7f1f1db6..eb2911dce3 100644 --- a/src/controllers/accounts.js +++ b/src/controllers/accounts.js @@ -1,6 +1,6 @@ 'use strict'; -var accountsController = { +const accountsController = { profile: require('./accounts/profile'), edit: require('./accounts/edit'), info: require('./accounts/info'), diff --git a/src/controllers/accounts/helpers.js b/src/controllers/accounts/helpers.js index 94723980ec..a38d1659c3 100644 --- a/src/controllers/accounts/helpers.js +++ b/src/controllers/accounts/helpers.js @@ -241,7 +241,7 @@ function filterLinks(links, states) { canViewInfo: true, ...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; return permit; diff --git a/src/controllers/accounts/profile.js b/src/controllers/accounts/profile.js index b721b04c46..434a6ef925 100644 --- a/src/controllers/accounts/profile.js +++ b/src/controllers/accounts/profile.js @@ -110,7 +110,7 @@ async function getPosts(callerUid, userData, setSuffix) { } 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 = [ { name: 'title', diff --git a/src/controllers/accounts/settings.js b/src/controllers/accounts/settings.js index e78ccc8158..37feace88b 100644 --- a/src/controllers/accounts/settings.js +++ b/src/controllers/accounts/settings.js @@ -219,8 +219,8 @@ async function getHomePageRoutes(userData) { let routes = await helpers.getHomePageRoutes(userData.uid); // Set selected for each route - var customIdx; - var hasSelected = false; + let customIdx; + let hasSelected = false; routes = routes.map((route, idx) => { if (route.route === userData.settings.homePageRoute) { route.selected = true; diff --git a/src/controllers/admin.js b/src/controllers/admin.js index d616a67a6a..c56c8f2ed8 100644 --- a/src/controllers/admin.js +++ b/src/controllers/admin.js @@ -3,7 +3,7 @@ const privileges = require('../privileges'); const helpers = require('./helpers'); -var adminController = { +const adminController = { dashboard: require('./admin/dashboard'), categories: require('./admin/categories'), privileges: require('./admin/privileges'), diff --git a/src/controllers/admin/uploads.js b/src/controllers/admin/uploads.js index eb3d7eed5e..2fb3d2741f 100644 --- a/src/controllers/admin/uploads.js +++ b/src/controllers/admin/uploads.js @@ -26,8 +26,8 @@ uploadsController.get = async function (req, res, next) { let files = await fs.promises.readdir(currentFolder); files = files.filter(filename => filename !== '.gitignore'); const itemCount = files.length; - var start = Math.max(0, (page - 1) * itemsPerPage); - var stop = start + itemsPerPage; + const start = Math.max(0, (page - 1) * itemsPerPage); + const stop = start + itemsPerPage; files = files.slice(start, stop); files = await filesToData(currentFolder, files); @@ -65,11 +65,11 @@ uploadsController.get = async function (req, res, next) { }; function buildBreadcrumbs(currentFolder) { - var crumbs = []; - var parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep); - var currentPath = ''; + const crumbs = []; + const parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep); + let currentPath = ''; parts.forEach((part) => { - var dir = path.join(currentPath, part); + const dir = path.join(currentPath, part); crumbs.push({ text: part || 'Uploads', url: part ? diff --git a/src/controllers/admin/users.js b/src/controllers/admin/users.js index 386a821b7a..3dfa5927a9 100644 --- a/src/controllers/admin/users.js +++ b/src/controllers/admin/users.js @@ -191,7 +191,7 @@ usersController.registrationQueue = async function (req, res) { customHeaders: plugins.hooks.fire('filter:admin.registrationQueue.customHeaders', { headers: [] }), 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.customHeaders = data.customHeaders.headers; res.render('admin/manage/registration', data); diff --git a/src/controllers/authentication.js b/src/controllers/authentication.js index 7f54289c95..fcd38f3314 100644 --- a/src/controllers/authentication.js +++ b/src/controllers/authentication.js @@ -142,7 +142,7 @@ authenticationController.registerComplete = function (req, res, next) { 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') { req.body.files = req.files; 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; }, []); - var done = function (err, data) { + const done = function (err, data) { delete req.session.registration; if (err) { 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); } - var loginWith = meta.config.allowLoginWith || 'username-email'; + const loginWith = meta.config.allowLoginWith || 'username-email'; req.body.username = req.body.username.trim(); 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 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.expires = new Date(Date.now() + duration); } else { @@ -283,7 +283,7 @@ function continueLogin(strategy, req, res, next) { } else { delete req.query.lang; await authenticationController.doLogin(req, userData.uid); - var destination; + let destination; if (req.session.returnTo) { destination = req.session.returnTo.startsWith('http') ? req.session.returnTo : diff --git a/src/controllers/errors.js b/src/controllers/errors.js index d2877d9b48..682868549c 100644 --- a/src/controllers/errors.js +++ b/src/controllers/errors.js @@ -1,17 +1,17 @@ 'use strict'; -var nconf = require('nconf'); -var winston = require('winston'); -var validator = require('validator'); -var plugins = require('../plugins'); -var middleware = require('../middleware'); +const nconf = require('nconf'); +const winston = require('winston'); +const validator = require('validator'); +const plugins = require('../plugins'); +const middleware = require('../middleware'); exports.handleURIErrors = async function handleURIErrors(err, req, res, next) { // Handle cases where malformed URIs are passed in if (err instanceof URIError) { const cleanPath = req.path.replace(new RegExp(`^${nconf.get('relative_path')}`), ''); - var tidMatch = cleanPath.match(/^\/topic\/(\d+)\//); - var cidMatch = cleanPath.match(/^\/category\/(\d+)\//); + const tidMatch = cleanPath.match(/^\/topic\/(\d+)\//); + const cidMatch = cleanPath.match(/^\/category\/(\d+)\//); if (tidMatch) { 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)` // don't remove `next`! exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-disable-line no-unused-vars - var cases = { + const cases = { EBADCSRFTOKEN: function () { winston.error(`${req.path}\n${err.message}`); 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); }, }; - var defaultHandler = async function () { + const defaultHandler = async function () { // Display NodeBB error page - var status = parseInt(err.status, 10); + const status = parseInt(err.status, 10); 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); } @@ -56,7 +56,7 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di res.status(status || 500); - var path = String(req.path || ''); + const path = String(req.path || ''); if (res.locals.isAPI) { res.json({ path: validator.escape(path), error: err.message }); } else { diff --git a/src/controllers/helpers.js b/src/controllers/helpers.js index e7c9826d19..236b06720c 100644 --- a/src/controllers/helpers.js +++ b/src/controllers/helpers.js @@ -487,7 +487,7 @@ async function generateBannedResponse(res) { } helpers.generateError = (statusCode, message) => { - var payload = { + const payload = { status: { code: 'internal-server-error', message: 'An unexpected error was encountered while attempting to service your request.', diff --git a/src/controllers/home.js b/src/controllers/home.js index 916a9ea49e..cd9886883c 100644 --- a/src/controllers/home.js +++ b/src/controllers/home.js @@ -52,7 +52,7 @@ async function rewrite(req, res, next) { exports.rewrite = rewrite; 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, { req: req, diff --git a/src/database/index.js b/src/database/index.js index 7119d55228..b66ab7a8a2 100644 --- a/src/database/index.js +++ b/src/database/index.js @@ -1,9 +1,9 @@ 'use strict'; -var nconf = require('nconf'); +const nconf = require('nconf'); -var databaseName = nconf.get('database'); -var winston = require('winston'); +const databaseName = nconf.get('database'); +const winston = require('winston'); if (!databaseName) { winston.error(new Error('Database type not set! Run ./nodebb setup')); diff --git a/src/database/mongo/connection.js b/src/database/mongo/connection.js index 21aac81b84..4986a5058c 100644 --- a/src/database/mongo/connection.js +++ b/src/database/mongo/connection.js @@ -9,8 +9,8 @@ const connection = module.exports; connection.getConnectionString = function (mongo) { mongo = mongo || nconf.get('mongo'); - var usernamePassword = ''; - var uri = mongo.uri || ''; + let usernamePassword = ''; + const uri = mongo.uri || ''; if (mongo.username && mongo.password) { usernamePassword = `${nconf.get('mongo:username')}:${encodeURIComponent(nconf.get('mongo:password'))}@`; } else if (!uri.includes('@') || !uri.slice(uri.indexOf('://') + 3, uri.indexOf('@'))) { @@ -30,11 +30,11 @@ connection.getConnectionString = function (mongo) { mongo.database = 'nodebb'; } - var hosts = mongo.host.split(','); - var ports = mongo.port.toString().split(','); - var servers = []; + const hosts = mongo.host.split(','); + const ports = mongo.port.toString().split(','); + 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]}`); } @@ -43,7 +43,7 @@ connection.getConnectionString = function (mongo) { connection.getConnectionOptions = function (mongo) { mongo = mongo || nconf.get('mongo'); - var connOptions = { + const connOptions = { poolSize: 10, connectTimeoutMS: 90000, useNewUrlParser: true, diff --git a/src/database/mongo/hash.js b/src/database/mongo/hash.js index 4056b64b7a..e6911a09b2 100644 --- a/src/database/mongo/hash.js +++ b/src/database/mongo/hash.js @@ -56,7 +56,7 @@ module.exports = function (module) { if (!field) { return; } - var data = {}; + const data = {}; data[field] = value; await module.setObject(key, data); }; @@ -177,7 +177,7 @@ module.exports = function (module) { return; } - var data = {}; + const data = {}; fields.forEach((field) => { field = helpers.fieldToString(field); data[field] = ''; @@ -205,12 +205,12 @@ module.exports = function (module) { return null; } - var increment = {}; + const increment = {}; field = helpers.fieldToString(field); increment[field] = value; if (Array.isArray(key)) { - var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); + const bulk = module.client.collection('objects').initializeUnorderedBulkOp(); key.forEach((key) => { bulk.find({ _key: key }).upsert().update({ $inc: increment }); }); diff --git a/src/database/mongo/helpers.js b/src/database/mongo/helpers.js index f7aed28c41..60f18381a5 100644 --- a/src/database/mongo/helpers.js +++ b/src/database/mongo/helpers.js @@ -6,8 +6,8 @@ const utils = require('../../utils'); helpers.noop = function () {}; helpers.toMap = function (data) { - var map = {}; - for (var i = 0; i < data.length; i += 1) { + const map = {}; + for (let i = 0; i < data.length; i += 1) { map[data[i]._key] = data[i]; delete data[i]._key; } diff --git a/src/database/mongo/list.js b/src/database/mongo/list.js index 398d8f2528..1c4fb63140 100644 --- a/src/database/mongo/list.js +++ b/src/database/mongo/list.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.listPrepend = async function (key, value) { if (!key) { diff --git a/src/database/mongo/main.js b/src/database/mongo/main.js index a3e513583c..1e4f7e51df 100644 --- a/src/database/mongo/main.js +++ b/src/database/mongo/main.js @@ -66,7 +66,7 @@ module.exports = function (module) { const objectData = await module.client.collection('objects').findOne({ _key: key }, { projection: { _id: 0 } }); // fallback to old field name 'value' for backwards compatibility #6340 - var value = null; + let value = null; if (objectData) { if (objectData.hasOwnProperty('data')) { value = objectData.data; @@ -105,7 +105,7 @@ module.exports = function (module) { return null; } 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')) { return 'zset'; } else if (keys.length === 3 && data.hasOwnProperty('_key') && data.hasOwnProperty('members')) { diff --git a/src/database/mongo/sets.js b/src/database/mongo/sets.js index 9e10ef312a..93c43c7529 100644 --- a/src/database/mongo/sets.js +++ b/src/database/mongo/sets.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.setAdd = async function (key, value) { if (!Array.isArray(value)) { @@ -36,9 +36,9 @@ module.exports = function (module) { 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: { members: { $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(); - var map = {}; + const map = {}; result.forEach((item) => { 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(); - var sets = {}; + const sets = {}; data.forEach((set) => { sets[set._key] = set.members || []; }); @@ -144,7 +144,7 @@ module.exports = function (module) { module.setsCount = async function (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; }; @@ -154,8 +154,8 @@ module.exports = function (module) { return; } - var randomIndex = Math.floor(Math.random() * data.members.length); - var value = data.members[randomIndex]; + const randomIndex = Math.floor(Math.random() * data.members.length); + const value = data.members[randomIndex]; await module.setRemove(data._key, value); return value; }; diff --git a/src/database/mongo/sorted.js b/src/database/mongo/sorted.js index d852c4535a..39f2258466 100644 --- a/src/database/mongo/sorted.js +++ b/src/database/mongo/sorted.js @@ -143,7 +143,7 @@ module.exports = function (module) { return; } - var query = { _key: key }; + const query = { _key: key }; if (min !== '-inf') { query.score = { $gte: min }; } @@ -226,8 +226,8 @@ module.exports = function (module) { if (!Array.isArray(keys) || !keys.length) { return []; } - var data = new Array(values.length); - for (var i = 0; i < values.length; i += 1) { + const data = new Array(values.length); + for (let i = 0; i < values.length; i += 1) { data[i] = { key: keys[i], value: values[i] }; } const promises = data.map(item => method(item.key, item.value)); @@ -271,7 +271,7 @@ module.exports = function (module) { } value = helpers.valueToString(value); 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) => { if (item) { map[item._key] = item; @@ -291,7 +291,7 @@ module.exports = function (module) { values = values.map(helpers.valueToString); 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) => { if (item) { valueToScore[item.value] = item.score; @@ -328,7 +328,7 @@ module.exports = function (module) { projection: { _id: 0, value: 1 }, }).toArray(); - var isMember = {}; + const isMember = {}; results.forEach((item) => { if (item) { isMember[item.value] = true; @@ -349,7 +349,7 @@ module.exports = function (module) { projection: { _id: 0, _key: 1, value: 1 }, }).toArray(); - var isMember = {}; + const isMember = {}; results.forEach((item) => { if (item) { isMember[item._key] = true; @@ -393,7 +393,7 @@ module.exports = function (module) { if (!key) { return; } - var data = {}; + const data = {}; value = helpers.valueToString(value); data.score = parseFloat(increment); @@ -426,7 +426,7 @@ module.exports = function (module) { }; async function sortedSetLex(key, min, max, sort, start, count) { - var query = { _key: key }; + const query = { _key: key }; start = start !== undefined ? start : 0; count = count !== undefined ? count : 0; buildLexQuery(query, min, max); @@ -441,7 +441,7 @@ module.exports = function (module) { } module.sortedSetRemoveRangeByLex = async function (key, min, max) { - var query = { _key: key }; + const query = { _key: key }; buildLexQuery(query, min, max); await module.client.collection('objects').deleteMany(query); @@ -499,14 +499,14 @@ module.exports = function (module) { }; module.processSortedSet = async function (setKey, processFn, options) { - var done = false; - var ids = []; - var project = { _id: 0, _key: 0 }; + let done = false; + const ids = []; + const project = { _id: 0, _key: 0 }; if (!options.withScores) { 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 }) .batchSize(options.batch); diff --git a/src/database/mongo/sorted/add.js b/src/database/mongo/sorted/add.js index f157774293..90940e1d1d 100644 --- a/src/database/mongo/sorted/add.js +++ b/src/database/mongo/sorted/add.js @@ -1,8 +1,8 @@ 'use strict'; module.exports = function (module) { - var helpers = require('../helpers'); - var utils = require('../../../utils'); + const helpers = require('../helpers'); + const utils = require('../../../utils'); module.sortedSetAdd = async function (key, score, value) { if (!key) { @@ -40,8 +40,8 @@ module.exports = function (module) { } values = values.map(helpers.valueToString); - var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); - for (var i = 0; i < scores.length; i += 1) { + const bulk = module.client.collection('objects').initializeUnorderedBulkOp(); + for (let i = 0; i < scores.length; i += 1) { bulk.find({ _key: key, value: values[i] }).upsert().updateOne({ $set: { score: parseFloat(scores[i]) } }); } await bulk.execute(); @@ -63,8 +63,8 @@ module.exports = function (module) { value = helpers.valueToString(value); - var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); - for (var i = 0; i < keys.length; i += 1) { + const bulk = module.client.collection('objects').initializeUnorderedBulkOp(); + 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) } }); } await bulk.execute(); @@ -74,7 +74,7 @@ module.exports = function (module) { if (!Array.isArray(data) || !data.length) { return; } - var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); + const bulk = module.client.collection('objects').initializeUnorderedBulkOp(); data.forEach((item) => { if (!utils.isNumber(item[1])) { throw new Error(`[[error:invalid-score, ${item[1]}]]`); diff --git a/src/database/mongo/sorted/remove.js b/src/database/mongo/sorted/remove.js index b34ce385f5..aecb137c12 100644 --- a/src/database/mongo/sorted/remove.js +++ b/src/database/mongo/sorted/remove.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('../helpers'); + const helpers = require('../helpers'); module.sortedSetRemove = async function (key, value) { if (!key) { @@ -37,7 +37,7 @@ module.exports = function (module) { if (!Array.isArray(keys) || !keys.length) { return; } - var query = { _key: { $in: keys } }; + const query = { _key: { $in: keys } }; if (keys.length === 1) { query._key = keys[0]; } @@ -56,7 +56,7 @@ module.exports = function (module) { if (!Array.isArray(data) || !data.length) { 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()); await bulk.execute(); }; diff --git a/src/database/mongo/sorted/union.js b/src/database/mongo/sorted/union.js index e528bc2fe0..86f86683f3 100644 --- a/src/database/mongo/sorted/union.js +++ b/src/database/mongo/sorted/union.js @@ -28,19 +28,19 @@ module.exports = function (module) { if (!Array.isArray(params.sets) || !params.sets.length) { return; } - var limit = params.stop - params.start + 1; + let limit = params.stop - params.start + 1; if (limit <= 0) { limit = 0; } - var aggregate = {}; + const aggregate = {}; if (params.aggregate) { aggregate[`$${params.aggregate.toLowerCase()}`] = '$score'; } else { aggregate.$sum = '$score'; } - var pipeline = [ + const pipeline = [ { $match: { _key: { $in: params.sets } } }, { $group: { _id: { value: '$value' }, totalScore: aggregate } }, { $sort: { totalScore: params.sort } }, @@ -54,7 +54,7 @@ module.exports = function (module) { pipeline.push({ $limit: limit }); } - var project = { _id: 0, value: '$_id.value' }; + const project = { _id: 0, value: '$_id.value' }; if (params.withScores) { project.score = '$totalScore'; } diff --git a/src/database/postgres.js b/src/database/postgres.js index 25809ca1e6..276e74ff53 100644 --- a/src/database/postgres.js +++ b/src/database/postgres.js @@ -64,7 +64,7 @@ postgresModule.init = async function () { async function checkUpgrade(client) { - var res = await client.query(` + const res = await client.query(` SELECT EXISTS(SELECT * FROM "information_schema"."columns" WHERE "table_schema" = 'public' @@ -331,7 +331,7 @@ postgresModule.createIndices = function (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.'); async.series([ @@ -348,7 +348,7 @@ postgresModule.createIndices = function (callback) { }; postgresModule.checkCompatibility = function (callback) { - var postgresPkg = require('pg/package.json'); + const postgresPkg = require('pg/package.json'); postgresModule.checkCompatibilityVersion(postgresPkg.version, callback); }; diff --git a/src/database/postgres/connection.js b/src/database/postgres/connection.js index 0d5b78d5db..8877882904 100644 --- a/src/database/postgres/connection.js +++ b/src/database/postgres/connection.js @@ -21,7 +21,7 @@ connection.getConnectionOptions = function (postgres) { postgres.database = 'nodebb'; } - var connOptions = { + const connOptions = { host: postgres.host, port: postgres.port, user: postgres.username, diff --git a/src/database/postgres/hash.js b/src/database/postgres/hash.js index 7321e31d47..c6f46e1e74 100644 --- a/src/database/postgres/hash.js +++ b/src/database/postgres/hash.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.setObject = async function (key, data) { if (!key || !data) { @@ -158,7 +158,7 @@ SELECT (SELECT jsonb_object_agg(f, d."value") return res.rows[0].d; } - var obj = {}; + const obj = {}; fields.forEach((f) => { obj[f] = null; }); diff --git a/src/database/postgres/helpers.js b/src/database/postgres/helpers.js index 9749d67444..7471df997b 100644 --- a/src/database/postgres/helpers.js +++ b/src/database/postgres/helpers.js @@ -1,17 +1,17 @@ 'use strict'; -var helpers = module.exports; +const helpers = module.exports; helpers.valueToString = function (value) { return String(value); }; helpers.removeDuplicateValues = function (values) { - var others = Array.prototype.slice.call(arguments, 1); - for (var i = 0; i < values.length; i++) { + const others = Array.prototype.slice.call(arguments, 1); + for (let i = 0; i < values.length; i++) { if (values.lastIndexOf(values[i]) !== i) { 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); } i -= 1; @@ -81,14 +81,14 @@ SELECT "_key", "type" values: [keys], }); - var invalid = res.rows.filter(r => r.type !== type); + const invalid = res.rows.filter(r => r.type !== type); if (invalid.length) { 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(', ')}`); } - 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) { throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`); diff --git a/src/database/postgres/list.js b/src/database/postgres/list.js index a67705660c..c2b91a85ac 100644 --- a/src/database/postgres/list.js +++ b/src/database/postgres/list.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.listPrepend = async function (key, value) { if (!key) { diff --git a/src/database/postgres/sets.js b/src/database/postgres/sets.js index de84bbbc67..82c3f16aff 100644 --- a/src/database/postgres/sets.js +++ b/src/database/postgres/sets.js @@ -1,9 +1,9 @@ 'use strict'; -var _ = require('lodash'); +const _ = require('lodash'); module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.setAdd = async function (key, value) { if (!Array.isArray(value)) { diff --git a/src/database/postgres/sorted.js b/src/database/postgres/sorted.js index dfae4df874..211b0608cb 100644 --- a/src/database/postgres/sorted.js +++ b/src/database/postgres/sorted.js @@ -1,9 +1,9 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); const util = require('util'); - var Cursor = require('pg-cursor'); + const Cursor = require('pg-cursor'); Cursor.prototype.readAsync = util.promisify(Cursor.prototype.read); const sleep = util.promisify(setTimeout); @@ -41,19 +41,19 @@ module.exports = function (module) { return []; } - var reverse = false; + let reverse = false; if (start === 0 && stop < -1) { reverse = true; sort *= -1; start = Math.abs(stop + 1); stop = -1; } else if (start < 0 && stop > start) { - var tmp1 = Math.abs(stop + 1); + const tmp1 = Math.abs(stop + 1); stop = Math.abs(start + 1); start = tmp1; } - var limit = stop - start + 1; + let limit = stop - start + 1; if (limit <= 0) { limit = null; } @@ -346,7 +346,7 @@ SELECT o."_key" 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; }); }; @@ -375,7 +375,7 @@ SELECT z."value" 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; }); }; @@ -507,7 +507,7 @@ RETURNING "score" s`, }; 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({ name: `sortedSetLexCount${q.suffix}`, @@ -528,7 +528,7 @@ SELECT COUNT(*) c start = start !== undefined ? start : 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(count <= 0 ? null : count); const res = await module.pool.query({ @@ -550,7 +550,7 @@ OFFSET $${q.values.length - 1}::INTEGER`, } module.sortedSetRemoveRangeByLex = async function (key, min, max) { - var q = buildLexQuery(key, min, max); + const q = buildLexQuery(key, min, max); await module.pool.query({ name: `sortedSetRemoveRangeByLex${q.suffix}`, text: ` @@ -564,7 +564,7 @@ DELETE FROM "legacy_zset" z }; function buildLexQuery(key, min, max) { - var q = { + const q = { suffix: '', where: `o."_key" = $1::TEXT`, values: [key], @@ -636,8 +636,8 @@ SELECT z."value", module.processSortedSet = async function (setKey, process, options) { const client = await module.pool.connect(); - var batchSize = (options || {}).batch || 100; - var cursor = client.query(new Cursor(` + const batchSize = (options || {}).batch || 100; + const cursor = client.query(new Cursor(` SELECT z."value", z."score" FROM "legacy_object_live" o INNER JOIN "legacy_zset" z diff --git a/src/database/postgres/sorted/add.js b/src/database/postgres/sorted/add.js index 058946d1a2..6f87416089 100644 --- a/src/database/postgres/sorted/add.js +++ b/src/database/postgres/sorted/add.js @@ -1,8 +1,8 @@ 'use strict'; module.exports = function (module) { - var helpers = require('../helpers'); - var utils = require('../../../utils'); + const helpers = require('../helpers'); + const utils = require('../../../utils'); module.sortedSetAdd = async function (key, score, value) { if (!key) { diff --git a/src/database/postgres/sorted/intersect.js b/src/database/postgres/sorted/intersect.js index 6e20ed49c1..e201d2e077 100644 --- a/src/database/postgres/sorted/intersect.js +++ b/src/database/postgres/sorted/intersect.js @@ -37,11 +37,11 @@ SELECT COUNT(*) c }; async function getSortedSetIntersect(params) { - var sets = params.sets; - var start = params.hasOwnProperty('start') ? params.start : 0; - var stop = params.hasOwnProperty('stop') ? params.stop : -1; - var weights = params.weights || []; - var aggregate = params.aggregate || 'SUM'; + const sets = params.sets; + const start = params.hasOwnProperty('start') ? params.start : 0; + const stop = params.hasOwnProperty('stop') ? params.stop : -1; + let weights = params.weights || []; + const aggregate = params.aggregate || 'SUM'; if (sets.length < weights.length) { weights = weights.slice(0, sets.length); @@ -50,7 +50,7 @@ SELECT COUNT(*) c weights.push(1); } - var limit = stop - start + 1; + let limit = stop - start + 1; if (limit <= 0) { limit = null; } diff --git a/src/database/postgres/sorted/remove.js b/src/database/postgres/sorted/remove.js index 2e2eb8e2ca..54bed38505 100644 --- a/src/database/postgres/sorted/remove.js +++ b/src/database/postgres/sorted/remove.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('../helpers'); + const helpers = require('../helpers'); module.sortedSetRemove = async function (key, value) { if (!key) { diff --git a/src/database/postgres/sorted/union.js b/src/database/postgres/sorted/union.js index e9b9154156..5daf8d112c 100644 --- a/src/database/postgres/sorted/union.js +++ b/src/database/postgres/sorted/union.js @@ -31,11 +31,11 @@ SELECT COUNT(DISTINCT z."value") c }; async function getSortedSetUnion(params) { - var sets = params.sets; - var start = params.hasOwnProperty('start') ? params.start : 0; - var stop = params.hasOwnProperty('stop') ? params.stop : -1; - var weights = params.weights || []; - var aggregate = params.aggregate || 'SUM'; + const sets = params.sets; + const start = params.hasOwnProperty('start') ? params.start : 0; + const stop = params.hasOwnProperty('stop') ? params.stop : -1; + let weights = params.weights || []; + const aggregate = params.aggregate || 'SUM'; if (sets.length < weights.length) { weights = weights.slice(0, sets.length); @@ -44,7 +44,7 @@ SELECT COUNT(DISTINCT z."value") c weights.push(1); } - var limit = stop - start + 1; + let limit = stop - start + 1; if (limit <= 0) { limit = null; } diff --git a/src/database/redis/hash.js b/src/database/redis/hash.js index 4965790468..276ada4a05 100644 --- a/src/database/redis/hash.js +++ b/src/database/redis/hash.js @@ -193,7 +193,7 @@ module.exports = function (module) { } let result; if (Array.isArray(key)) { - var batch = module.client.batch(); + const batch = module.client.batch(); key.forEach(k => batch.hincrby(k, field, value)); result = await helpers.execBatch(batch); } else { diff --git a/src/database/redis/helpers.js b/src/database/redis/helpers.js index 4f6fe46067..30b440d4e2 100644 --- a/src/database/redis/helpers.js +++ b/src/database/redis/helpers.js @@ -2,7 +2,7 @@ const util = require('util'); -var helpers = module.exports; +const helpers = module.exports; helpers.noop = function () {}; @@ -12,7 +12,7 @@ helpers.execBatch = async function (batch) { }; 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; } return results; diff --git a/src/database/redis/main.js b/src/database/redis/main.js index 0d98058d36..46aa9e8360 100644 --- a/src/database/redis/main.js +++ b/src/database/redis/main.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.flushdb = async function () { await module.client.async.send_command('flushdb', []); diff --git a/src/database/redis/pubsub.js b/src/database/redis/pubsub.js index 2287798674..9938e0a974 100644 --- a/src/database/redis/pubsub.js +++ b/src/database/redis/pubsub.js @@ -20,7 +20,7 @@ const PubSub = function () { } try { - var msg = JSON.parse(message); + const msg = JSON.parse(message); self.emit(msg.event, msg.data); } catch (err) { winston.error(err.stack); diff --git a/src/database/redis/sets.js b/src/database/redis/sets.js index 73811b66c4..2146e1ae5e 100644 --- a/src/database/redis/sets.js +++ b/src/database/redis/sets.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('./helpers'); + const helpers = require('./helpers'); module.setAdd = async function (key, value) { if (!Array.isArray(value)) { @@ -30,13 +30,13 @@ module.exports = function (module) { key = [key]; } - var batch = module.client.batch(); + const batch = module.client.batch(); key.forEach(k => batch.srem(String(k), value)); await helpers.execBatch(batch); }; module.setsRemove = async function (keys, value) { - var batch = module.client.batch(); + const batch = module.client.batch(); keys.forEach(k => batch.srem(String(k), value)); await helpers.execBatch(batch); }; diff --git a/src/database/redis/sorted.js b/src/database/redis/sorted.js index 3e293eafff..ccb87df99c 100644 --- a/src/database/redis/sorted.js +++ b/src/database/redis/sorted.js @@ -111,7 +111,7 @@ module.exports = function (module) { if (!Array.isArray(keys) || !keys.length) { return []; } - var batch = module.client.batch(); + const batch = module.client.batch(); keys.forEach(k => batch.zcard(String(k))); return await helpers.execBatch(batch); }; @@ -138,7 +138,7 @@ module.exports = function (module) { module.sortedSetsRanks = async function (keys, values) { 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])); } return await helpers.execBatch(batch); @@ -146,7 +146,7 @@ module.exports = function (module) { module.sortedSetsRevRanks = async function (keys, values) { 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])); } return await helpers.execBatch(batch); @@ -154,7 +154,7 @@ module.exports = function (module) { module.sortedSetRanks = async function (key, values) { 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])); } return await helpers.execBatch(batch); @@ -162,7 +162,7 @@ module.exports = function (module) { module.sortedSetRevRanks = async function (key, values) { 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])); } return await helpers.execBatch(batch); @@ -230,7 +230,7 @@ module.exports = function (module) { if (!Array.isArray(keys) || !keys.length) { return []; } - var batch = module.client.batch(); + const batch = module.client.batch(); keys.forEach(k => batch.zrange(k, 0, -1)); return await helpers.execBatch(batch); }; @@ -257,8 +257,8 @@ module.exports = function (module) { }; async function sortedSetLex(method, reverse, key, min, max, start, count) { - var minmin; - var maxmax; + let minmin; + let maxmax; if (reverse) { minmin = '+'; maxmax = '-'; diff --git a/src/database/redis/sorted/add.js b/src/database/redis/sorted/add.js index 56920e0454..6662b50efd 100644 --- a/src/database/redis/sorted/add.js +++ b/src/database/redis/sorted/add.js @@ -30,8 +30,8 @@ module.exports = function (module) { throw new Error(`[[error:invalid-score, ${scores[i]}]]`); } } - var args = [key]; - for (var i = 0; i < scores.length; i += 1) { + const args = [key]; + for (let i = 0; i < scores.length; i += 1) { args.push(scores[i], String(values[i])); } await module.client.async.zadd(args); @@ -51,8 +51,8 @@ module.exports = function (module) { throw new Error('[[error:invalid-data]]'); } - var batch = module.client.batch(); - for (var i = 0; i < keys.length; i += 1) { + const batch = module.client.batch(); + for (let i = 0; i < keys.length; i += 1) { if (keys[i]) { batch.zadd(keys[i], isArrayOfScores ? scores[i] : scores, String(value)); } @@ -64,7 +64,7 @@ module.exports = function (module) { if (!Array.isArray(data) || !data.length) { return; } - var batch = module.client.batch(); + const batch = module.client.batch(); data.forEach((item) => { if (!utils.isNumber(item[1])) { throw new Error(`[[error:invalid-score, ${item[1]}]]`); diff --git a/src/database/redis/sorted/intersect.js b/src/database/redis/sorted/intersect.js index 17a2041e69..b23f09869f 100644 --- a/src/database/redis/sorted/intersect.js +++ b/src/database/redis/sorted/intersect.js @@ -7,11 +7,11 @@ module.exports = function (module) { if (!Array.isArray(keys) || !keys.length) { 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.zcard(tempSetName); multi.del(tempSetName); @@ -30,14 +30,14 @@ module.exports = function (module) { }; async function getSortedSetRevIntersect(params) { - var sets = params.sets; - var start = params.hasOwnProperty('start') ? params.start : 0; - var stop = params.hasOwnProperty('stop') ? params.stop : -1; - var weights = params.weights || []; + const sets = params.sets; + const start = params.hasOwnProperty('start') ? params.start : 0; + const stop = params.hasOwnProperty('stop') ? params.stop : -1; + 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) { interParams = interParams.concat(['WEIGHTS'].concat(weights)); } @@ -46,12 +46,12 @@ module.exports = function (module) { interParams = interParams.concat(['AGGREGATE', params.aggregate]); } - var rangeParams = [tempSetName, start, stop]; + const rangeParams = [tempSetName, start, stop]; if (params.withScores) { rangeParams.push('WITHSCORES'); } - var multi = module.client.multi(); + const multi = module.client.multi(); multi.zinterstore(interParams); multi[params.method](rangeParams); multi.del(tempSetName); diff --git a/src/database/redis/sorted/remove.js b/src/database/redis/sorted/remove.js index 3e57e9f50f..363569f0e6 100644 --- a/src/database/redis/sorted/remove.js +++ b/src/database/redis/sorted/remove.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = function (module) { - var helpers = require('../helpers'); + const helpers = require('../helpers'); module.sortedSetRemove = async function (key, value) { if (!key) { @@ -30,7 +30,7 @@ module.exports = function (module) { }; 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)); await helpers.execBatch(batch); }; diff --git a/src/database/redis/sorted/union.js b/src/database/redis/sorted/union.js index bb08312901..acd57c2db0 100644 --- a/src/database/redis/sorted/union.js +++ b/src/database/redis/sorted/union.js @@ -4,11 +4,11 @@ module.exports = function (module) { const helpers = require('../helpers'); module.sortedSetUnionCard = async function (keys) { - var tempSetName = `temp_${Date.now()}`; + const tempSetName = `temp_${Date.now()}`; if (!keys.length) { return 0; } - var multi = module.client.multi(); + const multi = module.client.multi(); multi.zunionstore([tempSetName, keys.length].concat(keys)); multi.zcard(tempSetName); multi.del(tempSetName); @@ -31,14 +31,14 @@ module.exports = function (module) { 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) { rangeParams.push('WITHSCORES'); } - var multi = module.client.multi(); + const multi = module.client.multi(); multi.zunionstore([tempSetName, params.sets.length].concat(params.sets)); multi[params.method](rangeParams); multi.del(tempSetName); diff --git a/src/flags.js b/src/flags.js index 09ae62067d..913e21543d 100644 --- a/src/flags.js +++ b/src/flags.js @@ -135,7 +135,7 @@ Flags.getFlagIdsWithFilters = async function ({ filters, uid }) { 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; - for (var type in filters) { + for (const type in filters) { if (filters.hasOwnProperty(type)) { if (Flags._filters.hasOwnProperty(type)) { 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 const tasks = []; - for (var prop in changeset) { + for (const prop in changeset) { if (changeset.hasOwnProperty(prop)) { if (current[prop] === changeset[prop]) { delete changeset[prop]; diff --git a/src/groups/index.js b/src/groups/index.js index 4c5bda43ae..0e3408ad1f 100644 --- a/src/groups/index.js +++ b/src/groups/index.js @@ -46,7 +46,7 @@ Groups.getEphemeralGroup = function (groupName) { }; 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])) { groups.splice(x, 1); } @@ -55,7 +55,7 @@ Groups.removeEphemeralGroups = function (groups) { return groups; }; -var isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w\-:]+$/; +const isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w\-:]+$/; Groups.isPrivilegeGroup = function (groupName) { return isPrivilegeGroupRegex.test(groupName); }; diff --git a/src/install.js b/src/install.js index b802df977c..ee12efc3d8 100644 --- a/src/install.js +++ b/src/install.js @@ -87,7 +87,7 @@ function checkSetupFlag() { } function checkCIFlag() { - var ciVals; + let ciVals; try { ciVals = JSON.parse(nconf.get('ci')); } catch (e) { @@ -151,7 +151,7 @@ async function completeConfigSetup(config) { // Add CI object if (install.ciVals) { config.test_database = {}; - for (var prop in install.ciVals) { + for (const prop in install.ciVals) { if (install.ciVals.hasOwnProperty(prop)) { config.test_database[prop] = install.ciVals[prop]; } @@ -173,7 +173,7 @@ async function completeConfigSetup(config) { if (!/^http(?:s)?:\/\//.test(config.url)) { config.url = `http://${config.url}`; } - var urlObj = url.parse(config.url); + const urlObj = url.parse(config.url); if (urlObj.port) { config.port = urlObj.port; } diff --git a/src/logger.js b/src/logger.js index 88e8abf577..734651cd9a 100644 --- a/src/logger.js +++ b/src/logger.js @@ -4,17 +4,17 @@ * Logger module: ability to dynamically turn on/off logging for http requests & socket.io events */ -var fs = require('fs'); -var path = require('path'); -var winston = require('winston'); -var util = require('util'); -var morgan = require('morgan'); +const fs = require('fs'); +const path = require('path'); +const winston = require('winston'); +const util = require('util'); +const morgan = require('morgan'); -var file = require('./file'); -var meta = require('./meta'); +const file = require('./file'); +const meta = require('./meta'); -var opts = { +const opts = { /* * state used by Logger */ @@ -29,7 +29,7 @@ var opts = { }; /* -- Logger -- */ -var Logger = module.exports; +const Logger = module.exports; Logger.init = function (app) { opts.express.app = app; @@ -58,7 +58,7 @@ Logger.setup_one_log = function (value) { * Otherwise, close the current stream */ if (meta.config.loggerStatus > 0 || meta.config.loggerIOStatus) { - var stream = Logger.open(value); + const stream = Logger.open(value); if (stream) { opts.streams.log.f = stream; } else { @@ -71,10 +71,10 @@ Logger.setup_one_log = function (value) { Logger.open = function (value) { /* Open the streams to log to: either a path or stdout */ - var stream; + let stream; if (value) { if (file.existsSync(value)) { - var stats = fs.statSync(value); + const stats = fs.statSync(value); if (stats) { if (stats.isDirectory()) { 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) { // courtesy of: http://stackoverflow.com/a/9674248 socket.oEmit = socket.emit; - var emit = socket.emit; + const emit = socket.emit; socket.emit = override(emit, 'emit', 'Logger.io_one: emit.apply: Failed'); socket.$onvent = socket.onevent; - var $onevent = socket.onevent; + const $onevent = socket.onevent; socket.onevent = override($onevent, 'on', 'Logger.io_one: $emit.apply: Failed'); } }; diff --git a/src/messaging/data.js b/src/messaging/data.js index 4486a4c82b..9391c5c4a7 100644 --- a/src/messaging/data.js +++ b/src/messaging/data.js @@ -64,7 +64,7 @@ module.exports = function (Messaging) { message.fromUser.banned = !!message.fromUser.banned; 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.newSet = false; @@ -104,7 +104,7 @@ module.exports = function (Messaging) { }); } else if (messages.length === 1) { // 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); if (index > 0) { const mid = await db.getSortedSetRange(key, index - 1, index - 1); diff --git a/src/messaging/index.js b/src/messaging/index.js index 793752c40f..eaedcc3a11 100644 --- a/src/messaging/index.js +++ b/src/messaging/index.js @@ -258,8 +258,8 @@ Messaging.hasPrivateChat = async (uid, withUid) => { return 0; } - var index = 0; - var roomId = 0; + let index = 0; + let roomId = 0; while (index < roomIds.length && !roomId) { /* eslint-disable no-await-in-loop */ const count = await Messaging.getUserCountInRoom(roomIds[index]); diff --git a/src/messaging/rooms.js b/src/messaging/rooms.js index 8eca129412..09aa643fbe 100644 --- a/src/messaging/rooms.js +++ b/src/messaging/rooms.js @@ -1,12 +1,12 @@ 'use strict'; -var validator = require('validator'); +const validator = require('validator'); -var db = require('../database'); -var user = require('../user'); -var plugins = require('../plugins'); -var privileges = require('../privileges'); -var meta = require('../meta'); +const db = require('../database'); +const user = require('../user'); +const plugins = require('../plugins'); +const privileges = require('../privileges'); +const meta = require('../meta'); module.exports = function (Messaging) { Messaging.getRoomData = async (roomId) => { @@ -233,7 +233,7 @@ module.exports = function (Messaging) { user.isAdminOrGlobalMod(uid), ]); - var room = roomData; + const room = roomData; room.messages = messages; 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)); diff --git a/src/messaging/unread.js b/src/messaging/unread.js index f1a3a5c1ff..4a1ab60cfb 100644 --- a/src/messaging/unread.js +++ b/src/messaging/unread.js @@ -1,7 +1,7 @@ 'use strict'; -var db = require('../database'); -var sockets = require('../socket.io'); +const db = require('../database'); +const sockets = require('../socket.io'); module.exports = function (Messaging) { Messaging.getUnreadCount = async (uid) => { diff --git a/src/meta/aliases.js b/src/meta/aliases.js index 4224dc0c3d..ba3a50fcd1 100644 --- a/src/meta/aliases.js +++ b/src/meta/aliases.js @@ -22,9 +22,9 @@ const aliases = { exports.aliases = aliases; function buildTargets() { - var length = 0; - var output = Object.keys(aliases).map((name) => { - var arr = aliases[name]; + let length = 0; + const output = Object.keys(aliases).map((name) => { + const arr = aliases[name]; if (name.length > length) { length = name.length; } diff --git a/src/meta/blacklist.js b/src/meta/blacklist.js index 638795ae8c..8fd15bd5be 100644 --- a/src/meta/blacklist.js +++ b/src/meta/blacklist.js @@ -53,7 +53,7 @@ Blacklist.test = async function (clientIp) { } clientIp = clientIp.split(':').length === 2 ? clientIp.split(':')[0] : clientIp; - var addr; + let addr; try { addr = ipaddr.parse(clientIp); } catch (err) { @@ -65,7 +65,7 @@ Blacklist.test = async function (clientIp) { !Blacklist._rules.ipv4.includes(clientIp) && // not explicitly specified in ipv4 list !Blacklist._rules.ipv6.includes(clientIp) && // not explicitly specified in ipv6 list !Blacklist._rules.cidr.some((subnet) => { - var cidr = ipaddr.parseCIDR(subnet); + const cidr = ipaddr.parseCIDR(subnet); if (addr.kind() !== cidr[0].kind()) { return false; } @@ -80,7 +80,7 @@ Blacklist.test = async function (clientIp) { throw err; } } else { - var err = new Error('[[error:blacklisted-ip]]'); + const err = new Error('[[error:blacklisted-ip]]'); err.code = 'blacklisted-ip'; analytics.increment('blacklist'); @@ -90,14 +90,14 @@ Blacklist.test = async function (clientIp) { Blacklist.validate = function (rules) { rules = (rules || '').split('\n'); - var ipv4 = []; - var ipv6 = []; - var cidr = []; - var invalid = []; - var duplicateCount = 0; + const ipv4 = []; + const ipv6 = []; + const cidr = []; + const invalid = []; + let duplicateCount = 0; - var inlineCommentMatch = /#.*$/; - var whitelist = ['127.0.0.1', '::1', '::ffff:0:127.0.0.1']; + const inlineCommentMatch = /#.*$/; + 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) // Also trim inputs and remove inline comments @@ -113,8 +113,8 @@ Blacklist.validate = function (rules) { // Filter out invalid rules rules = rules.filter((rule) => { - var addr; - var isRange = false; + let addr; + let isRange = false; try { addr = ipaddr.parse(rule); } catch (e) { @@ -161,9 +161,7 @@ Blacklist.validate = function (rules) { }; Blacklist.addRule = async function (rule) { - var valid; - const result = Blacklist.validate(rule); - valid = result.valid; + const { valid } = Blacklist.validate(rule); if (!valid.length) { throw new Error('[[error:invalid-rule]]'); } diff --git a/src/meta/build.js b/src/meta/build.js index 9b3b7ea6fb..e7828fe1ad 100644 --- a/src/meta/build.js +++ b/src/meta/build.js @@ -50,7 +50,7 @@ const targetHandlers = { }; const aliasMap = Object.keys(aliases).reduce((prev, key) => { - var arr = aliases[key]; + const arr = aliases[key]; arr.forEach((alias) => { prev[alias] = key; }); diff --git a/src/meta/configs.js b/src/meta/configs.js index d72caa2f46..237597f5fa 100644 --- a/src/meta/configs.js +++ b/src/meta/configs.js @@ -201,7 +201,7 @@ Configs.cookie = { cookie.secure = true; } - var relativePath = nconf.get('relative_path'); + const relativePath = nconf.get('relative_path'); if (relativePath !== '') { cookie.path = relativePath; } diff --git a/src/meta/debugFork.js b/src/meta/debugFork.js index 6756ade770..44b2ab3e99 100644 --- a/src/meta/debugFork.js +++ b/src/meta/debugFork.js @@ -1,12 +1,12 @@ 'use strict'; -var fork = require('child_process').fork; +const fork = require('child_process').fork; -var debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg)); -var debugging = !!debugArg; +let debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg)); +const debugging = !!debugArg; 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 @@ -15,7 +15,7 @@ var lastAddress = parseInt(debugArg[1], 10); * @param {any} [options] */ function debugFork(modulePath, args, options) { - var execArgv = []; + let execArgv = []; if (global.v8debug || debugging) { lastAddress += 1; diff --git a/src/meta/index.js b/src/meta/index.js index a45a07475b..8fd3abb471 100644 --- a/src/meta/index.js +++ b/src/meta/index.js @@ -61,9 +61,9 @@ function restart() { } Meta.getSessionTTLSeconds = function () { - var ttlDays = 60 * 60 * 24 * Meta.config.loginDays; - var ttlSeconds = Meta.config.loginSeconds; - var ttl = ttlSeconds || ttlDays || 1209600; // Default to 14 days + const ttlDays = 60 * 60 * 24 * Meta.config.loginDays; + const ttlSeconds = Meta.config.loginSeconds; + const ttl = ttlSeconds || ttlDays || 1209600; // Default to 14 days return ttl; }; diff --git a/src/meta/languages.js b/src/meta/languages.js index f6133a5e88..72bcf866a5 100644 --- a/src/meta/languages.js +++ b/src/meta/languages.js @@ -29,9 +29,9 @@ async function getTranslationMetadata() { return; } - var rel = path.relative(coreLanguagesPath, p).split(/[/\\]/); - var language = rel.shift().replace('_', '-').replace('@', '-x-'); - var namespace = rel.join('/').replace(/\.json$/, ''); + const rel = path.relative(coreLanguagesPath, p).split(/[/\\]/); + const language = rel.shift().replace('_', '-').replace('@', '-x-'); + const namespace = rel.join('/').replace(/\.json$/, ''); if (!language || !namespace) { return; diff --git a/src/meta/minifier.js b/src/meta/minifier.js index 0d27a602dd..00363aad76 100644 --- a/src/meta/minifier.js +++ b/src/meta/minifier.js @@ -50,7 +50,7 @@ function getChild() { return free.shift(); } - var proc = fork(__filename, [], { + const proc = fork(__filename, [], { cwd: __dirname, env: { minifier_child: true, @@ -67,14 +67,14 @@ function freeChild(proc) { } function removeChild(proc) { - var i = pool.indexOf(proc); + const i = pool.indexOf(proc); if (i !== -1) { pool.splice(i, 1); } } function forkAction(action, callback) { - var proc = getChild(); + const proc = getChild(); proc.on('message', (message) => { freeChild(proc); @@ -99,12 +99,12 @@ function forkAction(action, callback) { }); } -var actions = {}; +const actions = {}; if (process.env.minifier_child) { process.on('message', (message) => { if (message.type === 'action') { - var action = message.action; + const action = message.action; if (typeof actions[action.act] !== 'function') { process.send({ type: 'error', @@ -157,7 +157,7 @@ function concat(data, callback) { return callback(err); } - var output = files.join('\n;'); + const output = files.join('\n;'); fs.writeFile(data.destPath, output, callback); }); @@ -175,7 +175,7 @@ function minifyJS_batch(data, callback) { return next(err); } - var filesToMinify = [ + const filesToMinify = [ { srcPath: fileObj.srcPath, filename: fileObj.filename, @@ -220,7 +220,7 @@ function minifyJS(data, callback) { actions.minifyJS = minifyJS; function minifyAndSave(data, callback) { - var scripts = {}; + const scripts = {}; data.files.forEach((ref) => { if (!ref) { return; @@ -229,7 +229,7 @@ function minifyAndSave(data, callback) { scripts[ref.filename] = ref.source; }); - var minified = uglify.minify(scripts, { + const minified = uglify.minify(scripts, { sourceMap: { filename: data.filename, url: `${String(data.filename).split(/[/\\]/).pop()}.map`, diff --git a/src/meta/tags.js b/src/meta/tags.js index 7d0a50c024..b719ad49f4 100644 --- a/src/meta/tags.js +++ b/src/meta/tags.js @@ -56,7 +56,7 @@ Tags.parse = async (req, data, meta, link) => { } // Link Tags - var defaultLinks = [{ + const defaultLinks = [{ rel: 'icon', type: 'image/x-icon', 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); 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, 'name', '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) { - var exists = false; + let exists = false; meta.forEach((tag) => { if (tag[keyName] === tagName) { exists = true; @@ -182,7 +182,7 @@ function addIfNotExists(meta, keyName, tagName, value) { }); if (!exists && value) { - var data = { + const data = { content: utils.escapeHTML(String(value)), }; data[keyName] = tagName; @@ -200,7 +200,7 @@ function stripRelativePath(url) { function addSiteOGImage(meta) { 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')) { ogImage = url + ogImage; } diff --git a/src/meta/templates.js b/src/meta/templates.js index 8948115982..e801b79e44 100644 --- a/src/meta/templates.js +++ b/src/meta/templates.js @@ -23,15 +23,15 @@ const viewsPath = nconf.get('views_dir'); const Templates = module.exports; async function processImports(paths, templatePath, source) { - var regex = //; + const regex = //; - var matches = source.match(regex); + const matches = source.match(regex); if (!matches) { return source; } - var partial = matches[1]; + const partial = matches[1]; if (paths[partial] && templatePath !== partial) { const partialSource = await fs.promises.readFile(paths[partial], 'utf8'); source = source.replace(regex, partialSource); @@ -72,9 +72,9 @@ async function getTemplateDirs(activePlugins) { themeTemplates.push(nconf.get('base_templates_path')); 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))); return templateDirs.filter(Boolean); @@ -90,7 +90,7 @@ async function getTemplateFiles(dirs) { return files; })); - var dict = {}; + const dict = {}; buckets.forEach((files) => { files.forEach((file) => { dict[file.name] = file.path; @@ -103,7 +103,7 @@ async function getTemplateFiles(dirs) { async function compileTemplate(filename, source) { let paths = await file.walk(viewsPath); paths = _.fromPairs(paths.map((p) => { - var relative = path.relative(viewsPath, p).replace(/\\/g, '/'); + const relative = path.relative(viewsPath, p).replace(/\\/g, '/'); return [relative, p]; })); diff --git a/src/meta/themes.js b/src/meta/themes.js index 3a4865a1cd..bed7249283 100644 --- a/src/meta/themes.js +++ b/src/meta/themes.js @@ -139,13 +139,13 @@ Themes.setupPaths = async () => { 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') { 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) { throw new Error('[[error:theme-not-found]]'); @@ -156,8 +156,8 @@ Themes.setupPaths = async () => { Themes.setPath = function (themeObj) { // Theme's templates path - var themePath = nconf.get('base_templates_path'); - var fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates'); + let themePath = nconf.get('base_templates_path'); + const fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates'); if (themeObj.templates) { themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates); diff --git a/src/middleware/admin.js b/src/middleware/admin.js index 024f8aac25..e8c9a77cf3 100644 --- a/src/middleware/admin.js +++ b/src/middleware/admin.js @@ -1,19 +1,19 @@ 'use strict'; -var winston = require('winston'); -var jsesc = require('jsesc'); -var nconf = require('nconf'); -var semver = require('semver'); - -var user = require('../user'); -var meta = require('../meta'); -var plugins = require('../plugins'); -var privileges = require('../privileges'); -var utils = require('../../public/src/utils'); -var versions = require('../admin/versions'); -var helpers = require('./helpers'); - -var controllers = { +const winston = require('winston'); +const jsesc = require('jsesc'); +const nconf = require('nconf'); +const semver = require('semver'); + +const user = require('../user'); +const meta = require('../meta'); +const plugins = require('../plugins'); +const privileges = require('../privileges'); +const utils = require('../../public/src/utils'); +const versions = require('../admin/versions'); +const helpers = require('./helpers'); + +const controllers = { api: require('../controllers/api'), helpers: require('../controllers/helpers'), }; @@ -27,7 +27,7 @@ middleware.buildHeader = helpers.try(async (req, res, next) => { }); middleware.renderHeader = async (req, res, data) => { - var custom_header = { + const custom_header = { plugins: [], authentication: [], }; @@ -42,21 +42,21 @@ middleware.renderHeader = async (req, res, data) => { privileges: privileges.admin.get(req.uid), }); - var userData = results.userData; + const userData = results.userData; userData.uid = req.uid; userData['email:confirmed'] = userData['email:confirmed'] === 1; userData.privileges = results.privileges; - var acpPath = req.path.slice(1).split('/'); + let acpPath = req.path.slice(1).split('/'); acpPath.forEach((path, i) => { acpPath[i] = path.charAt(0).toUpperCase() + path.slice(1); }); 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; - var templateValues = { + let templateValues = { config: res.locals.config, configJSON: jsesc(JSON.stringify(res.locals.config), { isScriptContext: true }), relative_path: res.locals.config.relative_path, diff --git a/src/middleware/index.js b/src/middleware/index.js index 203f84454f..6590477306 100644 --- a/src/middleware/index.js +++ b/src/middleware/index.js @@ -1,33 +1,33 @@ 'use strict'; -var async = require('async'); -var path = require('path'); -var csrf = require('csurf'); -var validator = require('validator'); -var nconf = require('nconf'); -var ensureLoggedIn = require('connect-ensure-login'); -var toobusy = require('toobusy-js'); -var LRU = require('lru-cache'); -var util = require('util'); - -var plugins = require('../plugins'); -var meta = require('../meta'); -var user = require('../user'); -var groups = require('../groups'); -var analytics = require('../analytics'); -var privileges = require('../privileges'); -var helpers = require('./helpers'); - -var controllers = { +const async = require('async'); +const path = require('path'); +const csrf = require('csurf'); +const validator = require('validator'); +const nconf = require('nconf'); +const ensureLoggedIn = require('connect-ensure-login'); +const toobusy = require('toobusy-js'); +const LRU = require('lru-cache'); +const util = require('util'); + +const plugins = require('../plugins'); +const meta = require('../meta'); +const user = require('../user'); +const groups = require('../groups'); +const analytics = require('../analytics'); +const privileges = require('../privileges'); +const helpers = require('./helpers'); + +const controllers = { api: require('../controllers/api'), helpers: require('../controllers/helpers'), }; -var delayCache = new LRU({ +const delayCache = new LRU({ maxAge: 1000 * 60, }); -var middleware = module.exports; +const middleware = module.exports; const relative_path = nconf.get('relative_path'); @@ -66,7 +66,7 @@ require('./expose')(middleware); middleware.assert = require('./assert'); middleware.stripLeadingSlashes = function stripLeadingSlashes(req, res, next) { - var target = req.originalUrl.replace(relative_path, ''); + const target = req.originalUrl.replace(relative_path, ''); if (target.startsWith('//')) { 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'])) { return res.redirect(meta.config['brand:touchIcon']); } - var iconPath = ''; + let iconPath = ''; if (meta.config['brand:touchIcon']) { iconPath = path.join(nconf.get('upload_path'), meta.config['brand:touchIcon'].replace(/assets\/uploads/, '')); } else { @@ -160,8 +160,8 @@ middleware.privateUploads = function privateUploads(req, res, next) { } if (req.path.startsWith(`${nconf.get('relative_path')}/assets/uploads/files`)) { - var extensions = (meta.config.privateUploadsExtensions || '').split(',').filter(Boolean); - var ext = path.extname(req.path); + const extensions = (meta.config.privateUploadsExtensions || '').split(',').filter(Boolean); + let ext = path.extname(req.path); ext = ext ? ext.replace(/^\./, '') : ext; if (!extensions.length || extensions.includes(ext)) { 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 // 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) { return res.sendStatus(429); } diff --git a/src/notifications.js b/src/notifications.js index ec29117017..7b1be349e5 100644 --- a/src/notifications.js +++ b/src/notifications.js @@ -384,12 +384,12 @@ Notifications.merge = async function (notifications) { case 'notifications:user_started_following_you': case 'notifications:user_posted_to': case 'notifications:user_flagged_post_in': - case 'notifications:user_flagged_user': - var usernames = _.uniq(set.map(notifObj => notifObj && notifObj.user && notifObj.user.username)); - var numUsers = usernames.length; + case 'notifications:user_flagged_user': { + const usernames = _.uniq(set.map(notifObj => notifObj && notifObj.user && notifObj.user.username)); + const numUsers = usernames.length; - var title = utils.decodeHTMLEntities(notifications[modifyIndex].topicTitle || ''); - var titleEscaped = title.replace(/%/g, '%').replace(/,/g, ','); + const title = utils.decodeHTMLEntities(notifications[modifyIndex].topicTitle || ''); + let titleEscaped = title.replace(/%/g, '%').replace(/,/g, ','); titleEscaped = titleEscaped ? (`, ${titleEscaped}`) : ''; if (numUsers === 2) { @@ -399,7 +399,7 @@ Notifications.merge = async function (notifications) { } notifications[modifyIndex].path = set[set.length - 1].path; - break; + } break; case 'new_register': notifications[modifyIndex].bodyShort = `[[notifications:${mergeId}_multiple, ${set.length}]]`; diff --git a/src/pagination.js b/src/pagination.js index 89251d82de..bed225560a 100644 --- a/src/pagination.js +++ b/src/pagination.js @@ -1,9 +1,9 @@ 'use strict'; -var qs = require('querystring'); -var _ = require('lodash'); +const qs = require('querystring'); +const _ = require('lodash'); -var pagination = module.exports; +const pagination = module.exports; pagination.create = function (currentPage, pageCount, queryObj) { if (pageCount <= 1) { @@ -19,17 +19,17 @@ pagination.create = function (currentPage, pageCount, queryObj) { }; } pageCount = parseInt(pageCount, 10); - var pagesToShow = [1, 2, pageCount - 1, pageCount]; + let pagesToShow = [1, 2, pageCount - 1, pageCount]; currentPage = parseInt(currentPage, 10) || 1; - var previous = Math.max(1, currentPage - 1); - var next = Math.min(pageCount, currentPage + 1); + const previous = Math.max(1, 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) { startPage -= 2 - (pageCount - currentPage); } - var i; + let i; for (i = 0; i < 5; i += 1) { pagesToShow.push(startPage + i); } @@ -40,7 +40,7 @@ pagination.create = function (currentPage, pageCount, queryObj) { delete queryObj._; - var pages = pagesToShow.map((page) => { + const pages = pagesToShow.map((page) => { queryObj.page = page; 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; data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) }; queryObj.page = next; diff --git a/src/plugins/data.js b/src/plugins/data.js index 59f54e5671..e9ff0e9c6f 100644 --- a/src/plugins/data.js +++ b/src/plugins/data.js @@ -43,7 +43,7 @@ Data.loadPluginInfo = async function (pluginPath) { pluginData.nbbpm = packageData.nbbpm; pluginData.path = pluginPath; } 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}`); throw new Error('[[error:parse-error]]'); @@ -71,7 +71,7 @@ Data.getActive = async function () { Data.getStaticDirectories = async function (pluginData) { - var validMappedPath = /^[\w\-_]+$/; + const validMappedPath = /^[\w\-_]+$/; if (!pluginData.staticDirs) { return; @@ -187,10 +187,10 @@ Data.getModules = async function getModules(pluginData) { let pluginModules = pluginData.modules; if (Array.isArray(pluginModules)) { - var strip = parseInt(pluginData.modulesStrip, 10) || 0; + const strip = parseInt(pluginData.modulesStrip, 10) || 0; pluginModules = pluginModules.reduce((prev, modulePath) => { - var key; + let key; if (strip) { key = modulePath.replace(new RegExp(`.?(/[^/]+){${strip}}/`), ''); } else { diff --git a/src/plugins/hooks.js b/src/plugins/hooks.js index 12d9f5b3dc..69381694ee 100644 --- a/src/plugins/hooks.js +++ b/src/plugins/hooks.js @@ -80,7 +80,7 @@ Hooks.register = function (id, data) { }; 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); }; diff --git a/src/plugins/index.js b/src/plugins/index.js index 1022566239..3775de3620 100644 --- a/src/plugins/index.js +++ b/src/plugins/index.js @@ -15,8 +15,8 @@ const meta = require('../meta'); const { pluginNamePattern, themeNamePattern, paths } = require('../constants'); -var app; -var middleware; +let app; +let middleware; const Plugins = module.exports; @@ -136,7 +136,7 @@ Plugins.reload = async function () { if (Plugins.versionWarning.length && nconf.get('isPrimary')) { 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.'); - 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(''); @@ -156,7 +156,7 @@ Plugins.reload = async function () { }; 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 }); winston.verbose('[plugins] All plugins reloaded and rerouted'); }; @@ -244,7 +244,7 @@ Plugins.normalise = async function (apiReturn) { const pluginArray = []; - for (var key in pluginMap) { + for (const key in pluginMap) { if (pluginMap.hasOwnProperty(key)) { pluginArray.push(pluginMap[key]); } @@ -291,7 +291,7 @@ Plugins.showInstalled = async function () { async function findNodeBBModules(dirs) { const pluginPaths = []; await async.each(dirs, (dirname, next) => { - var dirPath = path.join(Plugins.nodeModulesPath, dirname); + const dirPath = path.join(Plugins.nodeModulesPath, dirname); async.waterfall([ function (cb) { @@ -320,7 +320,7 @@ async function findNodeBBModules(dirs) { return next(); } - var subdirPath = path.join(dirPath, subdir); + const subdirPath = path.join(dirPath, subdir); fs.stat(subdirPath, (err, stats) => { if (err && err.code !== 'ENOENT') { return next(err); diff --git a/src/plugins/load.js b/src/plugins/load.js index f9a0f04880..0f7937a02c 100644 --- a/src/plugins/load.js +++ b/src/plugins/load.js @@ -42,7 +42,7 @@ module.exports = function (Plugins) { }, }; - var methods = {}; + let methods = {}; if (Array.isArray(fields)) { fields.forEach((field) => { methods[field] = handlers[field]; diff --git a/src/posts/create.js b/src/posts/create.js index c86a2c2fb9..34079e9168 100644 --- a/src/posts/create.js +++ b/src/posts/create.js @@ -1,15 +1,15 @@ 'use strict'; -var _ = require('lodash'); +const _ = require('lodash'); -var meta = require('../meta'); -var db = require('../database'); -var plugins = require('../plugins'); -var user = require('../user'); -var topics = require('../topics'); -var categories = require('../categories'); -var groups = require('../groups'); -var utils = require('../utils'); +const meta = require('../meta'); +const db = require('../database'); +const plugins = require('../plugins'); +const user = require('../user'); +const topics = require('../topics'); +const categories = require('../categories'); +const groups = require('../groups'); +const utils = require('../utils'); module.exports = function (Posts) { Posts.create = async function (data) { diff --git a/src/posts/parse.js b/src/posts/parse.js index ef2d9b8f5c..2f47ff140a 100644 --- a/src/posts/parse.js +++ b/src/posts/parse.js @@ -1,15 +1,15 @@ 'use strict'; -var nconf = require('nconf'); -var url = require('url'); -var winston = require('winston'); +const nconf = require('nconf'); +const url = require('url'); +const winston = require('winston'); const sanitize = require('sanitize-html'); const _ = require('lodash'); -var meta = require('../meta'); -var plugins = require('../plugins'); -var translator = require('../translator'); -var utils = require('../utils'); +const meta = require('../meta'); +const plugins = require('../plugins'); +const translator = require('../translator'); +const utils = require('../utils'); let sanitizeConfig = { allowedTags: sanitize.defaults.allowedTags.concat([ @@ -78,9 +78,9 @@ module.exports = function (Posts) { if (!content) { return content; } - var parsed; - var current = regex.regex.exec(content); - var absolute; + let parsed; + let current = regex.regex.exec(content); + let absolute; while (current !== null) { if (current[1]) { try { @@ -154,7 +154,7 @@ module.exports = function (Posts) { function sanitizeSignature(signature) { signature = translator.escape(signature); - var tagsToStrip = []; + const tagsToStrip = []; if (meta.config['signatures:disableLinks']) { tagsToStrip.push('a'); diff --git a/src/posts/summary.js b/src/posts/summary.js index 5f1b708f9d..a88c61c109 100644 --- a/src/posts/summary.js +++ b/src/posts/summary.js @@ -81,8 +81,8 @@ module.exports = function (Posts) { } function toObject(key, data) { - var obj = {}; - for (var i = 0; i < data.length; i += 1) { + const obj = {}; + for (let i = 0; i < data.length; i += 1) { obj[data[i][key]] = data[i]; } return obj; diff --git a/src/posts/topics.js b/src/posts/topics.js index 1bd13deb36..4a467e77ca 100644 --- a/src/posts/topics.js +++ b/src/posts/topics.js @@ -1,8 +1,8 @@ 'use strict'; -var topics = require('../topics'); -var utils = require('../utils'); +const topics = require('../topics'); +const utils = require('../utils'); module.exports = function (Posts) { Posts.getPostsFromSet = async function (set, start, stop, uid, reverse) { diff --git a/src/prestart.js b/src/prestart.js index 6b56b773ff..8f89336b9a 100644 --- a/src/prestart.js +++ b/src/prestart.js @@ -13,7 +13,7 @@ function setupWinston() { return; } - var formats = []; + const formats = []; if (nconf.get('log-colorize') !== 'false') { formats.push(winston.format.colorize()); } @@ -23,7 +23,7 @@ function setupWinston() { formats.push(winston.format.json()); } else { 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}`; return info; }); @@ -60,10 +60,10 @@ function loadConfig(configFile) { }); // 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; castAsBool.forEach((prop) => { - var value = nconf.get(prop); + const value = nconf.get(prop); if (value !== undefined) { nconf.set(prop, typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true'); } @@ -104,10 +104,10 @@ function loadConfig(configFile) { } function versionCheck() { - var version = process.version.slice(1); - var range = pkg.engines.node; - var semver = require('semver'); - var compatible = semver.satisfies(version, range); + const version = process.version.slice(1); + const range = pkg.engines.node; + const semver = require('semver'); + const compatible = semver.satisfies(version, range); if (!compatible) { winston.warn('Your version of Node.js is too outdated for NodeBB. Please update your version of Node.js.'); diff --git a/src/privileges/helpers.js b/src/privileges/helpers.js index 25333e5336..61198b0015 100644 --- a/src/privileges/helpers.js +++ b/src/privileges/helpers.js @@ -112,7 +112,7 @@ helpers.getUserPrivileges = async function (cid, userPrivileges) { memberData.forEach((member) => { 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)); } }); @@ -145,7 +145,7 @@ helpers.getGroupPrivileges = async function (cid, groupPrivileges) { const memberData = groupNames.map((member, index) => { 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); } return { diff --git a/src/privileges/index.js b/src/privileges/index.js index afaeced3d3..4f9a482815 100644 --- a/src/privileges/index.js +++ b/src/privileges/index.js @@ -1,6 +1,6 @@ 'use strict'; -var privileges = module.exports; +const privileges = module.exports; privileges.privilegeLabels = [ { name: '[[admin/manage/privileges:find-category]]' }, diff --git a/src/privileges/posts.js b/src/privileges/posts.js index 807de31277..e6610a8278 100644 --- a/src/privileges/posts.js +++ b/src/privileges/posts.js @@ -162,12 +162,12 @@ module.exports = function (privileges) { 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)) { return { flag: false, message: `[[error:post-delete-duration-expired, ${meta.config.postDeleteDuration}]]` }; } - var deleterUid = postData.deleterUid; - var flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod); + const deleterUid = postData.deleterUid; + const flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod); return { flag: flag, message: '[[error:no-privileges]]' }; }; diff --git a/src/pubsub.js b/src/pubsub.js index 95e07d0f81..f5c057c9e0 100644 --- a/src/pubsub.js +++ b/src/pubsub.js @@ -1,18 +1,18 @@ 'use strict'; -var EventEmitter = require('events'); -var nconf = require('nconf'); +const EventEmitter = require('events'); +const nconf = require('nconf'); -var real; -var noCluster; -var singleHost; +let real; +let noCluster; +let singleHost; function get() { if (real) { return real; } - var pubsub; + let pubsub; if (!nconf.get('isCluster')) { if (noCluster) { diff --git a/src/routes/accounts.js b/src/routes/accounts.js index 81bbbd88e2..b1d4b61049 100644 --- a/src/routes/accounts.js +++ b/src/routes/accounts.js @@ -3,13 +3,13 @@ const winston = require('winston'); 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) { - var middlewares = [middleware.exposeUid, middleware.canViewUsers]; - var accountMiddlewares = [middleware.exposeUid, middleware.canViewUsers, middleware.checkAccountPermissions]; + const middlewares = [middleware.exposeUid, middleware.canViewUsers]; + const accountMiddlewares = [middleware.exposeUid, middleware.canViewUsers, middleware.checkAccountPermissions]; setupPageRoute(app, '/me', middleware, [], middleware.redirectMeToUserslug); setupPageRoute(app, '/me/*', middleware, [], middleware.redirectMeToUserslug); diff --git a/src/routes/api.js b/src/routes/api.js index b316d38d2e..e0b2694cf9 100644 --- a/src/routes/api.js +++ b/src/routes/api.js @@ -1,11 +1,11 @@ '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) { - var router = express.Router(); + const router = express.Router(); app.use('/api', router); 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/pagination/:topic_id', controllers.topics.pagination); - var multipart = require('connect-multiparty'); - var multipartMiddleware = multipart(); - var middlewares = [middleware.maintenanceMode, multipartMiddleware, middleware.validateFiles, middleware.applyCSRF]; + const multipart = require('connect-multiparty'); + const multipartMiddleware = multipart(); + const middlewares = [middleware.maintenanceMode, multipartMiddleware, middleware.validateFiles, middleware.applyCSRF]; 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); diff --git a/src/routes/authentication.js b/src/routes/authentication.js index bef61ba9d5..8c0238330c 100644 --- a/src/routes/authentication.js +++ b/src/routes/authentication.js @@ -1,19 +1,19 @@ 'use strict'; -var async = require('async'); -var passport = require('passport'); -var passportLocal = require('passport-local').Strategy; +const async = require('async'); +const passport = require('passport'); +const passportLocal = require('passport-local').Strategy; const BearerStrategy = require('passport-http-bearer').Strategy; -var winston = require('winston'); +const winston = require('winston'); const meta = require('../meta'); -var controllers = require('../controllers'); -var helpers = require('../controllers/helpers'); -var plugins = require('../plugins'); +const controllers = require('../controllers'); +const helpers = require('../controllers/helpers'); +const plugins = require('../plugins'); -var loginStrategies = []; +let loginStrategies = []; -var Auth = module.exports; +const Auth = module.exports; Auth.initialize = function (app, middleware) { const passportInitMiddleware = passport.initialize(); @@ -161,9 +161,9 @@ Auth.reloadRoutes = async function (params) { }); }); - var multipart = require('connect-multiparty'); - var multipartMiddleware = multipart(); - var middlewares = [multipartMiddleware, Auth.middleware.applyCSRF, Auth.middleware.applyBlacklist]; + const multipart = require('connect-multiparty'); + const multipartMiddleware = multipart(); + const middlewares = [multipartMiddleware, Auth.middleware.applyCSRF, Auth.middleware.applyBlacklist]; router.post('/register', middlewares, controllers.authentication.register); router.post('/register/complete', middlewares, controllers.authentication.registerComplete); diff --git a/src/routes/debug.js b/src/routes/debug.js index 23900aee6c..6358a95609 100644 --- a/src/routes/debug.js +++ b/src/routes/debug.js @@ -1,13 +1,13 @@ 'use strict'; -var express = require('express'); -var nconf = require('nconf'); +const express = require('express'); +const nconf = require('nconf'); const fs = require('fs').promises; const path = require('path'); module.exports = function (app) { - var router = express.Router(); + const router = express.Router(); router.get('/test', (req, res) => { res.redirect(404); diff --git a/src/routes/feeds.js b/src/routes/feeds.js index 4bdbd31bd1..af0099c15f 100644 --- a/src/routes/feeds.js +++ b/src/routes/feeds.js @@ -355,7 +355,7 @@ function generateForPostsFeed(feedOptions, posts) { feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url; feedOptions.site_url = nconf.get('url') + feedOptions.site_url; - var feed = new rss(feedOptions); + const feed = new rss(feedOptions); if (posts.length > 0) { feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString(); diff --git a/src/routes/index.js b/src/routes/index.js index 1840e1b930..a8ef01646c 100644 --- a/src/routes/index.js +++ b/src/routes/index.js @@ -1,27 +1,27 @@ 'use strict'; -var nconf = require('nconf'); -var winston = require('winston'); -var path = require('path'); -var express = require('express'); - -var meta = require('../meta'); -var controllers = require('../controllers'); -var plugins = require('../plugins'); - -var accountRoutes = require('./accounts'); -var metaRoutes = require('./meta'); -var apiRoutes = require('./api'); -var adminRoutes = require('./admin'); -var feedRoutes = require('./feeds'); -var authRoutes = require('./authentication'); +const nconf = require('nconf'); +const winston = require('winston'); +const path = require('path'); +const express = require('express'); + +const meta = require('../meta'); +const controllers = require('../controllers'); +const plugins = require('../plugins'); + +const accountRoutes = require('./accounts'); +const metaRoutes = require('./meta'); +const apiRoutes = require('./api'); +const adminRoutes = require('./admin'); +const feedRoutes = require('./feeds'); +const authRoutes = require('./authentication'); 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) { - var loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn]; + const loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn]; setupPageRoute(app, '/login', middleware, loginRegisterMiddleware, controllers.login); setupPageRoute(app, '/register', middleware, loginRegisterMiddleware, controllers.register); @@ -78,13 +78,13 @@ function categoryRoutes(app, middleware, controllers) { } function userRoutes(app, middleware, controllers) { - var middlewares = [middleware.canViewUsers]; + const middlewares = [middleware.canViewUsers]; setupPageRoute(app, '/users', middleware, middlewares, controllers.users.index); } function groupRoutes(app, middleware, controllers) { - var middlewares = [middleware.canViewGroups]; + const middlewares = [middleware.canViewGroups]; setupPageRoute(app, '/groups', middleware, middlewares, controllers.groups.list); setupPageRoute(app, '/groups/:slug', middleware, middlewares, controllers.groups.details); @@ -96,7 +96,7 @@ module.exports = async function (app, middleware) { router.render = function () { 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/admin|/+api/admin/*?)', middleware.authenticate, middleware.admin.checkPrivileges); @@ -135,7 +135,7 @@ function addCoreRoutes(app, router, middleware) { userRoutes(router, middleware, controllers); groupRoutes(router, middleware, controllers); - var relativePath = nconf.get('relative_path'); + const relativePath = nconf.get('relative_path'); app.use(relativePath || '/', router); if (process.env.NODE_ENV === 'development') { @@ -144,12 +144,12 @@ function addCoreRoutes(app, router, middleware) { app.use(middleware.privateUploads); - var statics = [ + const statics = [ { route: '/assets', path: path.join(__dirname, '../../build/public') }, { route: '/assets', path: path.join(__dirname, '../../public') }, { route: '/plugins', path: path.join(__dirname, '../../build/public/plugins') }, ]; - var staticOptions = { + const staticOptions = { maxAge: app.enabled('cache') ? 5184000000 : 0, }; diff --git a/src/routes/write/topics.js b/src/routes/write/topics.js index 7276fd9a3d..9f415c9e7b 100644 --- a/src/routes/write/topics.js +++ b/src/routes/write/topics.js @@ -10,8 +10,8 @@ const setupApiRoute = routeHelpers.setupApiRoute; module.exports = function () { const middlewares = [middleware.authenticate]; - var multipart = require('connect-multiparty'); - var multipartMiddleware = multipart(); + const multipart = require('connect-multiparty'); + const multipartMiddleware = multipart(); setupApiRoute(router, 'post', '/', [middleware.authenticateOrGuest, middleware.checkRequired.bind(null, ['cid', 'title', 'content'])], controllers.write.topics.create); setupApiRoute(router, 'get', '/:tid', [middleware.authenticateOrGuest], controllers.write.topics.get); diff --git a/src/search.js b/src/search.js index 86e1f056e9..b8c2717941 100644 --- a/src/search.js +++ b/src/search.js @@ -221,7 +221,7 @@ function filterByTimerange(posts, timeRange, timeFilter) { function filterByTags(posts, hasTags) { if (Array.isArray(hasTags) && hasTags.length) { posts = posts.filter((post) => { - var hasAllTags = false; + let hasAllTags = false; if (post && post.topic && Array.isArray(post.topic.tags) && post.topic.tags.length) { hasAllTags = hasTags.every(tag => post.topic.tags.includes(tag)); } diff --git a/src/settings.js b/src/settings.js index 11c33cf788..0471193310 100644 --- a/src/settings.js +++ b/src/settings.js @@ -1,14 +1,14 @@ 'use strict'; -var meta = require('./meta'); -var pubsub = require('./pubsub'); +const meta = require('./meta'); +const pubsub = require('./pubsub'); function expandObjBy(obj1, obj2) { - var key; - var val1; - var val2; - var xorValIsArray; - var changed = false; + let key; + let val1; + let val2; + let xorValIsArray; + let changed = false; for (key in obj2) { if (obj2.hasOwnProperty(key)) { val2 = obj2[key]; @@ -28,8 +28,8 @@ function expandObjBy(obj1, obj2) { } function trim(obj1, obj2) { - var key; - var val1; + let key; + let val1; for (key in obj1) { if (obj1.hasOwnProperty(key)) { val1 = obj1[key]; @@ -69,7 +69,7 @@ function Settings(hash, version, defCfg, callback, forceUpdate, reset) { this.hash = hash; this.version = version || this.version; this.defCfg = defCfg; - var self = this; + const self = this; if (reset) { this.reset(callback); @@ -95,7 +95,7 @@ Settings.prototype.version = '0.0.0'; @param callback Gets called when done. */ Settings.prototype.sync = function (callback) { - var _this = this; + const _this = this; meta.settings.get(this.hash, (err, settings) => { try { if (settings._) { @@ -119,8 +119,8 @@ Settings.prototype.sync = function (callback) { @param callback Gets called when done. */ Settings.prototype.persist = function (callback) { - var conf = this.cfg._; - var _this = this; + let conf = this.cfg._; + const _this = this; if (typeof conf === 'object') { conf = JSON.stringify(conf); } @@ -139,10 +139,10 @@ Settings.prototype.persist = function (callback) { @returns Object The setting to be used. */ Settings.prototype.get = function (key, def) { - var obj = this.cfg._; - var parts = (key || '').split('.'); - var part; - for (var i = 0; i < parts.length; i += 1) { + let obj = this.cfg._; + const parts = (key || '').split('.'); + let part; + for (let i = 0; i < parts.length; i += 1) { part = parts[i]; if (part && obj != null) { obj = obj[part]; @@ -151,7 +151,7 @@ Settings.prototype.get = function (key, def) { if (obj === undefined) { if (def === undefined) { def = this.defCfg; - for (var j = 0; j < parts.length; j += 1) { + for (let j = 0; j < parts.length; j += 1) { part = parts[j]; if (part && def != null) { def = def[part]; @@ -196,16 +196,16 @@ Settings.prototype.createDefaultWrapper = function () { @param val The value to set. */ Settings.prototype.set = function (key, val) { - var part; - var obj; - var parts; + let part; + let obj; + let parts; this.cfg.v = this.version; if (val == null || !key) { this.cfg._ = val || key; } else { obj = this.cfg._; parts = key.split('.'); - for (var i = 0, _len = parts.length - 1; i < _len; i += 1) { + for (let i = 0, _len = parts.length - 1; i < _len; i += 1) { part = parts[i]; if (part) { if (!obj.hasOwnProperty(part)) { diff --git a/src/sitemap.js b/src/sitemap.js index 3c3b1a1352..df0988fd7b 100644 --- a/src/sitemap.js +++ b/src/sitemap.js @@ -24,7 +24,7 @@ sitemap.render = async function () { }; const topicCount = await db.getObjectField('global', 'topicCount'); const numPages = Math.ceil(Math.max(0, topicCount / topicsPerPage)); - for (var x = 1; x <= numPages; x += 1) { + for (let x = 1; x <= numPages; x += 1) { returnData.topics.push(x); } diff --git a/src/socket.io/admin/rooms.js b/src/socket.io/admin/rooms.js index 57782b8fa3..7b688a35b9 100644 --- a/src/socket.io/admin/rooms.js +++ b/src/socket.io/admin/rooms.js @@ -34,8 +34,8 @@ pubsub.on('sync:stats:guests', (eventId) => { }); SocketRooms.getTotalGuestCount = function (callback) { - var count = 0; - var eventId = `sync:stats:guests:end:${utils.generateUUID()}`; + let count = 0; + const eventId = `sync:stats:guests:end:${utils.generateUUID()}`; pubsub.on(eventId, (guestCount) => { count += guestCount; }); @@ -64,7 +64,7 @@ SocketRooms.getAll = async function () { category: 0, }; - for (var instance in stats) { + for (const instance in stats) { if (stats.hasOwnProperty(instance)) { totals.onlineGuestCount += stats[instance].onlineGuestCount; totals.onlineRegisteredCount += stats[instance].onlineRegisteredCount; @@ -82,14 +82,14 @@ SocketRooms.getAll = async function () { } } - var topTenTopics = []; + let topTenTopics = []; Object.keys(totals.topics).forEach((tid) => { topTenTopics.push({ tid: tid, count: totals.topics[tid].count || 0 }); }); topTenTopics = topTenTopics.sort((a, b) => b.count - a.count).slice(0, 10); - var topTenTids = topTenTopics.map(topic => topic.tid); + const topTenTids = topTenTopics.map(topic => topic.tid); const titles = await topics.getTopicsFields(topTenTids, ['title']); totals.topTenTopics = topTenTopics.map((topic, index) => { @@ -100,7 +100,7 @@ SocketRooms.getAll = async function () { }; SocketRooms.getOnlineUserCount = function (io) { - var count = 0; + let count = 0; if (io) { for (const [key] of io.sockets.adapter.rooms) { @@ -114,10 +114,10 @@ SocketRooms.getOnlineUserCount = function (io) { }; SocketRooms.getLocalStats = function () { - var Sockets = require('../index'); - var io = Sockets.server; + const Sockets = require('../index'); + const io = Sockets.server; - var socketData = { + const socketData = { onlineGuestCount: 0, onlineRegisteredCount: 0, socketCount: 0, @@ -139,8 +139,8 @@ SocketRooms.getLocalStats = function () { socketData.users.recent = Sockets.getCountInRoom('recent_topics'); socketData.users.unread = Sockets.getCountInRoom('unread_topics'); - var topTenTopics = []; - var tid; + let topTenTopics = []; + let tid; for (const [room, clients] of io.sockets.adapter.rooms) { tid = room.match(/^topic_(\d+)/); diff --git a/src/socket.io/groups.js b/src/socket.io/groups.js index 73f6af7d81..2e69e873a6 100644 --- a/src/socket.io/groups.js +++ b/src/socket.io/groups.js @@ -62,7 +62,7 @@ async function isOwner(socket, data) { group: await groups.getGroupData(data.groupName), }); - var isOwner = results.isOwner || results.isAdmin || (results.isGlobalModerator && !results.group.system); + const isOwner = results.isOwner || results.isAdmin || (results.isGlobalModerator && !results.group.system); if (!isOwner) { throw new Error('[[error:no-privileges]]'); } diff --git a/src/socket.io/index.js b/src/socket.io/index.js index 14dca06ca6..5e49562360 100644 --- a/src/socket.io/index.js +++ b/src/socket.io/index.js @@ -162,7 +162,7 @@ async function onMessage(socket, payload) { } function requireModules() { - var modules = ['admin', 'categories', 'groups', 'meta', 'modules', + const modules = ['admin', 'categories', 'groups', 'meta', 'modules', 'notifications', 'plugins', 'posts', 'topics', 'user', 'blacklist', 'flags', 'uploads', ]; @@ -188,7 +188,7 @@ async function checkMaintenance(socket) { const getSessionAsync = util.promisify((sid, callback) => db.sessionStore.get(sid, (err, sessionObj) => callback(err, sessionObj || null))); async function validateSession(socket) { - var req = socket.request; + const req = socket.request; if (!req.signedCookies || !req.signedCookies[nconf.get('sessionKey')]) { return; } diff --git a/src/socket.io/meta.js b/src/socket.io/meta.js index d9911b8c68..68230bd6f0 100644 --- a/src/socket.io/meta.js +++ b/src/socket.io/meta.js @@ -1,10 +1,10 @@ 'use strict'; -var user = require('../user'); -var topics = require('../topics'); +const user = require('../user'); +const topics = require('../topics'); -var SocketMeta = { +const SocketMeta = { rooms: {}, }; diff --git a/src/socket.io/plugins.js b/src/socket.io/plugins.js index 923c31e437..7bb2f456bf 100644 --- a/src/socket.io/plugins.js +++ b/src/socket.io/plugins.js @@ -1,6 +1,6 @@ 'use strict'; -var SocketPlugins = {}; +const SocketPlugins = {}; /* This file is provided exclusively so that plugins can require it and add their own socket listeners. diff --git a/src/socket.io/posts.js b/src/socket.io/posts.js index c3a1e6c254..b9361dd650 100644 --- a/src/socket.io/posts.js +++ b/src/socket.io/posts.js @@ -154,7 +154,7 @@ SocketPosts.getReplies = async function (socket, pid) { const pids = await posts.getPidsFromSet(`pid:${pid}:replies`, 0, -1, false); - var [postData, postPrivileges] = await Promise.all([ + let [postData, postPrivileges] = await Promise.all([ posts.getPostsByPids(pids, socket.uid), privileges.posts.get(pids, socket.uid), ]); diff --git a/src/socket.io/posts/tools.js b/src/socket.io/posts/tools.js index 2b6255a449..5efd5b53a6 100644 --- a/src/socket.io/posts/tools.js +++ b/src/socket.io/posts/tools.js @@ -103,8 +103,8 @@ module.exports = function (SocketPosts) { throw new Error('[[error:no-privileges]]'); } - var postData = await posts.changeOwner(data.pids, data.toUid); - var logs = postData.map(({ pid, uid, cid }) => (events.log({ + const postData = await posts.changeOwner(data.pids, data.toUid); + const logs = postData.map(({ pid, uid, cid }) => (events.log({ type: 'post-change-owner', uid: socket.uid, ip: socket.ip, diff --git a/src/socket.io/single-host-cluster.js b/src/socket.io/single-host-cluster.js index c091a9a689..ca420997c5 100644 --- a/src/socket.io/single-host-cluster.js +++ b/src/socket.io/single-host-cluster.js @@ -1,6 +1,6 @@ 'use strict'; -var Client = { +const Client = { sendMessage: function (channel, message) { process.send({ action: 'socket.io', @@ -49,7 +49,7 @@ process.on('message', (message) => { } }); -var adapter = require('socket.io-adapter-cluster')({ +const adapter = require('socket.io-adapter-cluster')({ client: Client, }); // Otherwise, every node thinks it is the master node and ignores messages diff --git a/src/topics/bookmarks.js b/src/topics/bookmarks.js index c604d20f5a..2f3d814cb6 100644 --- a/src/topics/bookmarks.js +++ b/src/topics/bookmarks.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var db = require('../database'); -var user = require('../user'); +const db = require('../database'); +const user = require('../user'); module.exports = function (Topics) { Topics.getUserBookmark = async function (tid, uid) { @@ -37,11 +37,11 @@ module.exports = function (Topics) { const bookmarks = await Topics.getTopicBookmarks(tid); - var uidData = bookmarks.map(b => ({ uid: b.value, bookmark: parseInt(b.score, 10) })) + const uidData = bookmarks.map(b => ({ uid: b.value, bookmark: parseInt(b.score, 10) })) .filter(data => data.bookmark >= minIndex); await async.eachLimit(uidData, 50, async (data) => { - var bookmark = Math.min(data.bookmark, maxIndex); + let bookmark = Math.min(data.bookmark, maxIndex); postIndices.forEach((i) => { if (i < data.bookmark) { diff --git a/src/topics/create.js b/src/topics/create.js index 2ad633ee86..44cebbe872 100644 --- a/src/topics/create.js +++ b/src/topics/create.js @@ -62,7 +62,7 @@ module.exports = function (Topics) { }; Topics.post = async function (data) { - var uid = data.uid; + const uid = data.uid; data.title = String(data.title).trim(); data.tags = data.tags || []; if (data.content) { @@ -199,8 +199,8 @@ module.exports = function (Topics) { }; async function onNewPost(postData, data) { - var tid = postData.tid; - var uid = postData.uid; + const tid = postData.tid; + const uid = postData.uid; await Topics.markAsUnreadForAll(tid); await Topics.markAsRead([tid], uid); const [ diff --git a/src/topics/data.js b/src/topics/data.js index 1696eb145d..db87b9e122 100644 --- a/src/topics/data.js +++ b/src/topics/data.js @@ -1,11 +1,11 @@ 'use strict'; -var validator = require('validator'); +const validator = require('validator'); -var db = require('../database'); -var categories = require('../categories'); -var utils = require('../utils'); -var translator = require('../translator'); +const db = require('../database'); +const categories = require('../categories'); +const utils = require('../utils'); +const translator = require('../translator'); const plugins = require('../plugins'); const intFields = [ diff --git a/src/topics/delete.js b/src/topics/delete.js index bbafb20bcf..c55b1ba662 100644 --- a/src/topics/delete.js +++ b/src/topics/delete.js @@ -1,13 +1,13 @@ 'use strict'; -var async = require('async'); -var db = require('../database'); +const async = require('async'); +const db = require('../database'); -var user = require('../user'); -var posts = require('../posts'); +const user = require('../user'); +const posts = require('../posts'); const categories = require('../categories'); -var plugins = require('../plugins'); -var batch = require('../batch'); +const plugins = require('../plugins'); +const batch = require('../batch'); module.exports = function (Topics) { @@ -38,8 +38,8 @@ module.exports = function (Topics) { ]); let postData = await posts.getPostsFields(pids, ['pid', 'timestamp', 'deleted']); postData = postData.filter(post => post && !post.deleted); - var pidsToAdd = []; - var scores = []; + const pidsToAdd = []; + const scores = []; postData.forEach((post) => { pidsToAdd.push(post.pid); scores.push(post.timestamp); @@ -134,10 +134,10 @@ module.exports = function (Topics) { } async function reduceCounters(tid) { - var incr = -1; + const incr = -1; await db.incrObjectFieldBy('global', 'topicCount', incr); const topicData = await Topics.getTopicFields(tid, ['cid', 'postcount']); - var postCountChange = incr * topicData.postcount; + const postCountChange = incr * topicData.postcount; await Promise.all([ db.incrObjectFieldBy('global', 'postCount', postCountChange), db.incrObjectFieldBy(`category:${topicData.cid}`, 'post_count', postCountChange), diff --git a/src/topics/index.js b/src/topics/index.js index c5f990a662..95ddf5a81d 100644 --- a/src/topics/index.js +++ b/src/topics/index.js @@ -1,19 +1,19 @@ 'use strict'; -var _ = require('lodash'); +const _ = require('lodash'); const validator = require('validator'); -var db = require('../database'); -var posts = require('../posts'); -var utils = require('../utils'); -var plugins = require('../plugins'); -var meta = require('../meta'); -var user = require('../user'); -var categories = require('../categories'); -var privileges = require('../privileges'); -var social = require('../social'); +const db = require('../database'); +const posts = require('../posts'); +const utils = require('../utils'); +const plugins = require('../plugins'); +const meta = require('../meta'); +const user = require('../user'); +const categories = require('../categories'); +const privileges = require('../privileges'); +const social = require('../social'); -var Topics = module.exports; +const Topics = module.exports; require('./data')(Topics); require('./create')(Topics); @@ -221,7 +221,7 @@ async function getMainPostAndReplies(topic, set, uid, start, stop, reverse) { if (!postData.length) { return []; } - var replies = postData; + let replies = postData; if (topic.mainPid && start === 0) { postData[0].index = 0; replies = postData.slice(1); diff --git a/src/topics/posts.js b/src/topics/posts.js index 5d1649d2de..ed6f6089ad 100644 --- a/src/topics/posts.js +++ b/src/topics/posts.js @@ -1,15 +1,15 @@ 'use strict'; -var _ = require('lodash'); -var validator = require('validator'); +const _ = require('lodash'); +const validator = require('validator'); -var db = require('../database'); -var user = require('../user'); -var posts = require('../posts'); -var meta = require('../meta'); -var plugins = require('../plugins'); -var utils = require('../../public/src/utils'); +const db = require('../database'); +const user = require('../user'); +const posts = require('../posts'); +const meta = require('../meta'); +const plugins = require('../plugins'); +const utils = require('../../public/src/utils'); module.exports = function (Topics) { Topics.onNewPostMade = async function (postData) { @@ -97,7 +97,7 @@ module.exports = function (Topics) { }; Topics.addParentPosts = async function (postData) { - var parentPids = postData.map(postObj => (postObj && postObj.hasOwnProperty('toPid') ? parseInt(postObj.toPid, 10) : null)).filter(Boolean); + let parentPids = postData.map(postObj => (postObj && postObj.hasOwnProperty('toPid') ? parseInt(postObj.toPid, 10) : null)).filter(Boolean); if (!parentPids.length) { return; @@ -107,11 +107,11 @@ module.exports = function (Topics) { const parentUids = _.uniq(parentPosts.map(postObj => postObj && postObj.uid)); const userData = await user.getUsersFields(parentUids, ['username']); - var usersMap = {}; + const usersMap = {}; userData.forEach((user) => { usersMap[user.uid] = user.username; }); - var parents = {}; + const parents = {}; parentPosts.forEach((post, i) => { parents[parentPids[i]] = { username: usersMap[post.uid] }; }); @@ -140,8 +140,8 @@ module.exports = function (Topics) { }; Topics.getLatestUndeletedReply = async function (tid) { - var isDeleted = false; - var index = 0; + let isDeleted = false; + let index = 0; do { /* eslint-disable no-await-in-loop */ const pids = await db.getSortedSetRevRange(`tid:${tid}:posts`, index, index); @@ -189,7 +189,7 @@ module.exports = function (Topics) { }; Topics.getPids = async function (tid) { - var [mainPid, pids] = await Promise.all([ + let [mainPid, pids] = await Promise.all([ Topics.getTopicField(tid, 'mainPid'), db.getSortedSetRange(`tid:${tid}:posts`, 0, -1), ]); diff --git a/src/topics/suggested.js b/src/topics/suggested.js index c2edf5a355..1273e79a6e 100644 --- a/src/topics/suggested.js +++ b/src/topics/suggested.js @@ -1,12 +1,12 @@ 'use strict'; -var _ = require('lodash'); +const _ = require('lodash'); const db = require('../database'); const user = require('../user'); -var privileges = require('../privileges'); -var search = require('../search'); +const privileges = require('../privileges'); +const search = require('../search'); module.exports = function (Topics) { Topics.getSuggestedTopics = async function (tid, uid, start, stop) { diff --git a/src/topics/teaser.js b/src/topics/teaser.js index 7b97976f7d..d72f1ec921 100644 --- a/src/topics/teaser.js +++ b/src/topics/teaser.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var _ = require('lodash'); +const async = require('async'); +const _ = require('lodash'); -var db = require('../database'); -var meta = require('../meta'); -var user = require('../user'); -var posts = require('../posts'); -var plugins = require('../plugins'); -var utils = require('../utils'); +const db = require('../database'); +const meta = require('../meta'); +const user = require('../user'); +const posts = require('../posts'); +const plugins = require('../plugins'); +const utils = require('../utils'); module.exports = function (Topics) { Topics.getTeasers = async function (topics, options) { @@ -23,9 +23,9 @@ module.exports = function (Topics) { teaserPost = options.teaserPost || meta.config.teaserPost; } - var counts = []; - var teaserPids = []; - var tidToPost = {}; + const counts = []; + const teaserPids = []; + const tidToPost = {}; topics.forEach((topic) => { counts.push(topic && topic.postcount); @@ -51,7 +51,7 @@ module.exports = function (Topics) { const usersData = await user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture']); - var users = {}; + const users = {}; usersData.forEach((user) => { users[user.uid] = user; }); @@ -69,7 +69,7 @@ module.exports = function (Topics) { const { tags } = await plugins.hooks.fire('filter:teasers.configureStripTags', { tags: utils.stripTags.concat(['img']) }); - var teasers = topics.map((topic, index) => { + const teasers = topics.map((topic, index) => { if (!topic) { return null; } diff --git a/src/topics/user.js b/src/topics/user.js index 4156eae38d..d3fbdc91ef 100644 --- a/src/topics/user.js +++ b/src/topics/user.js @@ -1,6 +1,6 @@ 'use strict'; -var db = require('../database'); +const db = require('../database'); module.exports = function (Topics) { Topics.isOwner = async function (tid, uid) { diff --git a/src/upgrade.js b/src/upgrade.js index 330330252b..36c5ed214e 100644 --- a/src/upgrade.js +++ b/src/upgrade.js @@ -183,9 +183,9 @@ Upgrade.incrementProgress = function (value) { if (this.counter > step || this.current >= this.total) { this.counter -= step; - var percentage = 0; - var filled = 0; - var unfilled = 15; + let percentage = 0; + let filled = 0; + let unfilled = 15; if (this.total) { percentage = `${Math.floor((this.current / this.total) * 100)}%`; filled = Math.floor((this.current / this.total) * 15); diff --git a/src/upgrades/1.0.0/chat_room_hashes.js b/src/upgrades/1.0.0/chat_room_hashes.js index e77bf00058..78de201a85 100644 --- a/src/upgrades/1.0.0/chat_room_hashes.js +++ b/src/upgrades/1.0.0/chat_room_hashes.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { @@ -12,7 +12,7 @@ module.exports = { if (err) { return callback(err); } - var currentChatRoomId = 1; + let currentChatRoomId = 1; async.whilst((next) => { next(null, currentChatRoomId <= nextChatRoomId); }, (next) => { diff --git a/src/upgrades/1.0.0/chat_upgrade.js b/src/upgrades/1.0.0/chat_upgrade.js index 83ef810fa4..d4567bffff 100644 --- a/src/upgrades/1.0.0/chat_upgrade.js +++ b/src/upgrades/1.0.0/chat_upgrade.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Upgrading chats', @@ -14,15 +14,22 @@ module.exports = { return callback(err); } - var rooms = {}; - var roomId = globalData.nextChatRoomId || 1; - var currentMid = 1; + const rooms = {}; + let roomId = globalData.nextChatRoomId || 1; + let currentMid = 1; async.whilst((next) => { next(null, currentMid <= globalData.nextMid); }, (next) => { db.getObject(`message:${currentMid}`, (err, message) => { - var msgTime; + if (err || !message) { + winston.verbose('skipping chat message ', currentMid); + currentMid += 1; + return next(err); + } + + const pairID = [parseInt(message.fromuid, 10), parseInt(message.touid, 10)].sort().join(':'); + const msgTime = parseInt(message.timestamp, 10); function addMessageToUids(roomId, callback) { async.parallel([ @@ -35,15 +42,6 @@ module.exports = { ], callback); } - if (err || !message) { - winston.verbose('skipping chat message ', currentMid); - currentMid += 1; - return next(err); - } - - var pairID = [parseInt(message.fromuid, 10), parseInt(message.touid, 10)].sort().join(':'); - msgTime = parseInt(message.timestamp, 10); - if (rooms[pairID]) { winston.verbose(`adding message ${currentMid} to existing roomID ${roomId}`); addMessageToUids(rooms[pairID], (err) => { diff --git a/src/upgrades/1.0.0/global_moderators.js b/src/upgrades/1.0.0/global_moderators.js index 7639da9453..2c7895996a 100644 --- a/src/upgrades/1.0.0/global_moderators.js +++ b/src/upgrades/1.0.0/global_moderators.js @@ -1,12 +1,12 @@ 'use strict'; -var async = require('async'); +const async = require('async'); module.exports = { name: 'Creating Global moderators group', timestamp: Date.UTC(2016, 0, 23), method: function (callback) { - var groups = require('../../groups'); + const groups = require('../../groups'); async.waterfall([ function (next) { groups.exists('Global Moderators', next); diff --git a/src/upgrades/1.0.0/social_post_sharing.js b/src/upgrades/1.0.0/social_post_sharing.js index 99dbdbdb4d..98d3de7ed8 100644 --- a/src/upgrades/1.0.0/social_post_sharing.js +++ b/src/upgrades/1.0.0/social_post_sharing.js @@ -1,14 +1,14 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Social: Post Sharing', timestamp: Date.UTC(2016, 1, 25), method: function (callback) { - var social = require('../../social'); + const social = require('../../social'); async.parallel([ function (next) { social.setActivePostSharingNetworks(['facebook', 'google', 'twitter'], next); diff --git a/src/upgrades/1.0.0/theme_to_active_plugins.js b/src/upgrades/1.0.0/theme_to_active_plugins.js index 08fee6ad2b..a541fde331 100644 --- a/src/upgrades/1.0.0/theme_to_active_plugins.js +++ b/src/upgrades/1.0.0/theme_to_active_plugins.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { diff --git a/src/upgrades/1.0.0/user_best_posts.js b/src/upgrades/1.0.0/user_best_posts.js index a45e2b4741..51dd55492f 100644 --- a/src/upgrades/1.0.0/user_best_posts.js +++ b/src/upgrades/1.0.0/user_best_posts.js @@ -1,16 +1,16 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Creating user best post sorted sets', timestamp: Date.UTC(2016, 0, 14), method: function (callback) { - var batch = require('../../batch'); - var progress = this.progress; + const batch = require('../../batch'); + const progress = this.progress; batch.processSortedSet('posts:pid', (ids, next) => { async.eachSeries(ids, (id, next) => { diff --git a/src/upgrades/1.0.0/users_notvalidated.js b/src/upgrades/1.0.0/users_notvalidated.js index 7909a939bc..e8a7c8d318 100644 --- a/src/upgrades/1.0.0/users_notvalidated.js +++ b/src/upgrades/1.0.0/users_notvalidated.js @@ -1,16 +1,16 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Creating users:notvalidated', timestamp: Date.UTC(2016, 0, 20), method: function (callback) { - var batch = require('../../batch'); - var now = Date.now(); + const batch = require('../../batch'); + const now = Date.now(); batch.processSortedSet('users:joindate', (ids, next) => { async.eachSeries(ids, (id, next) => { db.getObjectFields(`user:${id}`, ['uid', 'email:confirmed'], (err, userData) => { diff --git a/src/upgrades/1.1.0/assign_topic_read_privilege.js b/src/upgrades/1.1.0/assign_topic_read_privilege.js index f2835da778..1232afdacb 100644 --- a/src/upgrades/1.1.0/assign_topic_read_privilege.js +++ b/src/upgrades/1.1.0/assign_topic_read_privilege.js @@ -1,16 +1,16 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Giving topics:read privs to any group that was previously allowed to Find & Access Category', timestamp: Date.UTC(2016, 4, 28), method: function (callback) { - var groupsAPI = require('../../groups'); - var privilegesAPI = require('../../privileges'); + const groupsAPI = require('../../groups'); + const privilegesAPI = require('../../privileges'); db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { @@ -23,8 +23,8 @@ module.exports = { return next(err); } - var groups = data.groups; - var users = data.users; + const groups = data.groups; + const users = data.users; async.waterfall([ function (next) { diff --git a/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js b/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js index 489cba777b..b8f0325e31 100644 --- a/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js +++ b/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js @@ -1,19 +1,19 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Dismiss flags from deleted topics', timestamp: Date.UTC(2016, 3, 29), method: function (callback) { - var posts = require('../../posts'); - var topics = require('../../topics'); + const posts = require('../../posts'); + const topics = require('../../topics'); - var pids; - var tids; + let pids; + let tids; async.waterfall([ async.apply(db.getSortedSetRange, 'posts:flagged', 0, -1), @@ -27,7 +27,7 @@ module.exports = { topics.getTopicsFields(tids, ['deleted'], next); }, function (state, next) { - var toDismiss = state.map((a, idx) => (parseInt(a.deleted, 10) === 1 ? pids[idx] : null)).filter(Boolean); + const toDismiss = state.map((a, idx) => (parseInt(a.deleted, 10) === 1 ? pids[idx] : null)).filter(Boolean); winston.verbose(`[2016/04/29] ${toDismiss.length} dismissable flags found`); async.each(toDismiss, dismissFlag, next); @@ -78,7 +78,7 @@ function dismissFlag(pid, callback) { } async.each(uids, (uid, next) => { - var nid = `post_flag:${pid}:uid:${uid}`; + const nid = `post_flag:${pid}:uid:${uid}`; async.parallel([ async.apply(db.delete, `notifications:${nid}`), async.apply(db.sortedSetRemove, 'notifications', `post_flag:${pid}:uid:${uid}`), diff --git a/src/upgrades/1.1.0/group_title_update.js b/src/upgrades/1.1.0/group_title_update.js index 72215de139..2db036c17f 100644 --- a/src/upgrades/1.1.0/group_title_update.js +++ b/src/upgrades/1.1.0/group_title_update.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Group title from settings to user profile', timestamp: Date.UTC(2016, 3, 14), method: function (callback) { - var user = require('../../user'); - var batch = require('../../batch'); - var count = 0; + const user = require('../../user'); + const batch = require('../../batch'); + let count = 0; batch.processSortedSet('users:joindate', (uids, next) => { winston.verbose(`upgraded ${count} users`); user.getMultipleUserSettings(uids, (err, settings) => { diff --git a/src/upgrades/1.1.0/separate_upvote_downvote.js b/src/upgrades/1.1.0/separate_upvote_downvote.js index ae93a820b8..876adb0e40 100644 --- a/src/upgrades/1.1.0/separate_upvote_downvote.js +++ b/src/upgrades/1.1.0/separate_upvote_downvote.js @@ -1,18 +1,18 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Store upvotes/downvotes separately', timestamp: Date.UTC(2016, 5, 13), method: function (callback) { - var batch = require('../../batch'); - var posts = require('../../posts'); - var count = 0; - var progress = this.progress; + const batch = require('../../batch'); + const posts = require('../../posts'); + let count = 0; + const progress = this.progress; batch.processSortedSet('posts:pid', (pids, next) => { winston.verbose(`upgraded ${count} posts`); @@ -29,7 +29,7 @@ module.exports = { if (err) { return next(err); } - var data = {}; + const data = {}; if (parseInt(results.upvotes, 10) > 0) { data.upvotes = results.upvotes; diff --git a/src/upgrades/1.1.0/user_post_count_per_tid.js b/src/upgrades/1.1.0/user_post_count_per_tid.js index ddc32759af..b6e31f3307 100644 --- a/src/upgrades/1.1.0/user_post_count_per_tid.js +++ b/src/upgrades/1.1.0/user_post_count_per_tid.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Users post count per tid', timestamp: Date.UTC(2016, 3, 19), method: function (callback) { - var batch = require('../../batch'); - var topics = require('../../topics'); - var count = 0; + const batch = require('../../batch'); + const topics = require('../../topics'); + let count = 0; batch.processSortedSet('topics:tid', (tids, next) => { winston.verbose(`upgraded ${count} topics`); count += tids.length; diff --git a/src/upgrades/1.1.1/remove_negative_best_posts.js b/src/upgrades/1.1.1/remove_negative_best_posts.js index c80704f69c..d1a8a479cf 100644 --- a/src/upgrades/1.1.1/remove_negative_best_posts.js +++ b/src/upgrades/1.1.1/remove_negative_best_posts.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Removing best posts with negative scores', timestamp: Date.UTC(2016, 7, 5), method: function (callback) { - var batch = require('../../batch'); + const batch = require('../../batch'); batch.processSortedSet('users:joindate', (ids, next) => { async.each(ids, (id, next) => { winston.verbose(`processing uid ${id}`); diff --git a/src/upgrades/1.1.1/upload_privileges.js b/src/upgrades/1.1.1/upload_privileges.js index d1668a95cf..d343f4ebfa 100644 --- a/src/upgrades/1.1.1/upload_privileges.js +++ b/src/upgrades/1.1.1/upload_privileges.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Giving upload privileges', timestamp: Date.UTC(2016, 6, 12), method: function (callback) { - var privilegesAPI = require('../../privileges'); - var meta = require('../../meta'); + const privilegesAPI = require('../../privileges'); + const meta = require('../../meta'); db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { diff --git a/src/upgrades/1.10.0/hash_recent_ip_addresses.js b/src/upgrades/1.10.0/hash_recent_ip_addresses.js index 38ae98f798..ac165d7fe4 100644 --- a/src/upgrades/1.10.0/hash_recent_ip_addresses.js +++ b/src/upgrades/1.10.0/hash_recent_ip_addresses.js @@ -1,18 +1,18 @@ 'use strict'; -var async = require('async'); -var crypto = require('crypto'); -var nconf = require('nconf'); -var batch = require('../../batch'); -var db = require('../../database'); +const async = require('async'); +const crypto = require('crypto'); +const nconf = require('nconf'); +const batch = require('../../batch'); +const db = require('../../database'); module.exports = { name: 'Hash all IP addresses stored in Recent IPs zset', timestamp: Date.UTC(2018, 5, 22), method: function (callback) { const progress = this.progress; - var hashed = /[a-f0-9]{32}/; + const hashed = /[a-f0-9]{32}/; let hash; batch.processSortedSet('ip:recent', (ips, next) => { diff --git a/src/upgrades/1.10.0/post_history_privilege.js b/src/upgrades/1.10.0/post_history_privilege.js index 64b515e5fa..fb4600d705 100644 --- a/src/upgrades/1.10.0/post_history_privilege.js +++ b/src/upgrades/1.10.0/post_history_privilege.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var privileges = require('../../privileges'); -var db = require('../../database'); +const privileges = require('../../privileges'); +const db = require('../../database'); module.exports = { name: 'Give post history viewing privilege to registered-users on all categories', diff --git a/src/upgrades/1.10.0/search_privileges.js b/src/upgrades/1.10.0/search_privileges.js index a6b4b9ceb7..0d53aa07b6 100644 --- a/src/upgrades/1.10.0/search_privileges.js +++ b/src/upgrades/1.10.0/search_privileges.js @@ -1,21 +1,21 @@ 'use strict'; -var async = require('async'); +const async = require('async'); module.exports = { name: 'Give global search privileges', timestamp: Date.UTC(2018, 4, 28), method: function (callback) { - var meta = require('../../meta'); - var privileges = require('../../privileges'); - var allowGuestSearching = parseInt(meta.config.allowGuestSearching, 10) === 1; - var allowGuestUserSearching = parseInt(meta.config.allowGuestUserSearching, 10) === 1; + const meta = require('../../meta'); + const privileges = require('../../privileges'); + const allowGuestSearching = parseInt(meta.config.allowGuestSearching, 10) === 1; + const allowGuestUserSearching = parseInt(meta.config.allowGuestUserSearching, 10) === 1; async.waterfall([ function (next) { privileges.global.give(['groups:search:content', 'groups:search:users', 'groups:search:tags'], 'registered-users', next); }, function (next) { - var guestPrivs = []; + const guestPrivs = []; if (allowGuestSearching) { guestPrivs.push('groups:search:content'); } diff --git a/src/upgrades/1.10.0/view_deleted_privilege.js b/src/upgrades/1.10.0/view_deleted_privilege.js index fdeb3f38d3..ddf4b9c3fc 100644 --- a/src/upgrades/1.10.0/view_deleted_privilege.js +++ b/src/upgrades/1.10.0/view_deleted_privilege.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var groups = require('../../groups'); -var db = require('../../database'); +const groups = require('../../groups'); +const db = require('../../database'); module.exports = { name: 'Give deleted post viewing privilege to moderators on all categories', diff --git a/src/upgrades/1.10.2/event_filters.js b/src/upgrades/1.10.2/event_filters.js index 96b2341aa1..46a81a970e 100644 --- a/src/upgrades/1.10.2/event_filters.js +++ b/src/upgrades/1.10.2/event_filters.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); -var batch = require('../../batch'); +const batch = require('../../batch'); module.exports = { name: 'add filters to events', diff --git a/src/upgrades/1.10.2/fix_category_post_zsets.js b/src/upgrades/1.10.2/fix_category_post_zsets.js index fc4bf54dc1..d45f2024ac 100644 --- a/src/upgrades/1.10.2/fix_category_post_zsets.js +++ b/src/upgrades/1.10.2/fix_category_post_zsets.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); -var batch = require('../../batch'); +const batch = require('../../batch'); module.exports = { name: 'Fix category post zsets', @@ -15,14 +15,14 @@ module.exports = { if (err) { return callback(err); } - var keys = cids.map(cid => `cid:${cid}:pids`); - var posts = require('../../posts'); + const keys = cids.map(cid => `cid:${cid}:pids`); + const posts = require('../../posts'); batch.processSortedSet('posts:pid', (postData, next) => { async.eachSeries(postData, (postData, next) => { progress.incr(); - var pid = postData.value; - var timestamp = postData.score; - var cid; + const pid = postData.value; + const timestamp = postData.score; + let cid; async.waterfall([ function (next) { posts.getCidByPid(pid, next); @@ -32,7 +32,7 @@ module.exports = { db.isMemberOfSortedSets(keys, pid, next); }, function (isMembers, next) { - var memberCids = []; + const memberCids = []; isMembers.forEach((isMember, index) => { if (isMember) { memberCids.push(cids[index]); diff --git a/src/upgrades/1.10.2/fix_category_topic_zsets.js b/src/upgrades/1.10.2/fix_category_topic_zsets.js index c06c11379b..b81a73211f 100644 --- a/src/upgrades/1.10.2/fix_category_topic_zsets.js +++ b/src/upgrades/1.10.2/fix_category_topic_zsets.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); -var batch = require('../../batch'); +const batch = require('../../batch'); module.exports = { name: 'Fix category topic zsets', @@ -11,7 +11,7 @@ module.exports = { method: function (callback) { const progress = this.progress; - var topics = require('../../topics'); + const topics = require('../../topics'); batch.processSortedSet('topics:tid', (tids, next) => { async.eachSeries(tids, (tid, next) => { progress.incr(); diff --git a/src/upgrades/1.10.2/local_login_privileges.js b/src/upgrades/1.10.2/local_login_privileges.js index 7b764a1525..0415ee1ae3 100644 --- a/src/upgrades/1.10.2/local_login_privileges.js +++ b/src/upgrades/1.10.2/local_login_privileges.js @@ -4,9 +4,9 @@ module.exports = { name: 'Give global local login privileges', timestamp: Date.UTC(2018, 8, 28), method: function (callback) { - var meta = require('../../meta'); - var privileges = require('../../privileges'); - var allowLocalLogin = parseInt(meta.config.allowLocalLogin, 10) !== 0; + const meta = require('../../meta'); + const privileges = require('../../privileges'); + const allowLocalLogin = parseInt(meta.config.allowLocalLogin, 10) !== 0; if (allowLocalLogin) { privileges.global.give(['groups:local:login'], 'registered-users', callback); diff --git a/src/upgrades/1.10.2/postgres_sessions.js b/src/upgrades/1.10.2/postgres_sessions.js index 222307fa4c..d5c18fa726 100644 --- a/src/upgrades/1.10.2/postgres_sessions.js +++ b/src/upgrades/1.10.2/postgres_sessions.js @@ -1,7 +1,7 @@ 'use strict'; -var nconf = require('nconf'); -var db = require('../../database'); +const nconf = require('nconf'); +const db = require('../../database'); module.exports = { name: 'Optimize PostgreSQL sessions', diff --git a/src/upgrades/1.10.2/upgrade_bans_to_hashes.js b/src/upgrades/1.10.2/upgrade_bans_to_hashes.js index cb8e883845..bb916ca826 100644 --- a/src/upgrades/1.10.2/upgrade_bans_to_hashes.js +++ b/src/upgrades/1.10.2/upgrade_bans_to_hashes.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); -var batch = require('../../batch'); +const batch = require('../../batch'); // var user = require('../../user'); module.exports = { @@ -60,7 +60,7 @@ module.exports = { } const reasonData = findReason(ban.score); const banKey = `uid:${uid}:ban:${ban.score}`; - var data = { + const data = { uid: uid, timestamp: ban.score, expire: parseInt(ban.value, 10), diff --git a/src/upgrades/1.10.2/username_email_history.js b/src/upgrades/1.10.2/username_email_history.js index d38d7eafdb..d07bdff0ca 100644 --- a/src/upgrades/1.10.2/username_email_history.js +++ b/src/upgrades/1.10.2/username_email_history.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); -var batch = require('../../batch'); -var user = require('../../user'); +const batch = require('../../batch'); +const user = require('../../user'); module.exports = { name: 'Record first entry in username/email history', diff --git a/src/upgrades/1.11.0/navigation_visibility_groups.js b/src/upgrades/1.11.0/navigation_visibility_groups.js index 53b3a1d9a7..0a5e0b733d 100644 --- a/src/upgrades/1.11.0/navigation_visibility_groups.js +++ b/src/upgrades/1.11.0/navigation_visibility_groups.js @@ -1,6 +1,6 @@ 'use strict'; -var async = require('async'); +const async = require('async'); module.exports = { name: 'Navigation item visibility groups', diff --git a/src/upgrades/1.11.0/resize_image_width.js b/src/upgrades/1.11.0/resize_image_width.js index 36881eeef3..faab4bb843 100644 --- a/src/upgrades/1.11.0/resize_image_width.js +++ b/src/upgrades/1.11.0/resize_image_width.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { diff --git a/src/upgrades/1.11.0/widget_visibility_groups.js b/src/upgrades/1.11.0/widget_visibility_groups.js index fecbfc3947..41db65a086 100644 --- a/src/upgrades/1.11.0/widget_visibility_groups.js +++ b/src/upgrades/1.11.0/widget_visibility_groups.js @@ -1,6 +1,6 @@ 'use strict'; -var async = require('async'); +const async = require('async'); module.exports = { name: 'Widget visibility groups', diff --git a/src/upgrades/1.11.1/remove_ignored_cids_per_user.js b/src/upgrades/1.11.1/remove_ignored_cids_per_user.js index 991fcdd37e..528e236b7f 100644 --- a/src/upgrades/1.11.1/remove_ignored_cids_per_user.js +++ b/src/upgrades/1.11.1/remove_ignored_cids_per_user.js @@ -1,8 +1,8 @@ 'use strict'; -var db = require('../../database'); +const db = require('../../database'); -var batch = require('../../batch'); +const batch = require('../../batch'); module.exports = { name: 'Remove uid::ignored:cids', diff --git a/src/upgrades/1.12.0/category_watch_state.js b/src/upgrades/1.12.0/category_watch_state.js index e178004cde..95c55c3906 100644 --- a/src/upgrades/1.12.0/category_watch_state.js +++ b/src/upgrades/1.12.0/category_watch_state.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var db = require('../../database'); -var batch = require('../../batch'); -var categories = require('../../categories'); +const db = require('../../database'); +const batch = require('../../batch'); +const categories = require('../../categories'); module.exports = { name: 'Update category watch data', diff --git a/src/upgrades/1.12.0/global_view_privileges.js b/src/upgrades/1.12.0/global_view_privileges.js index de39e86f3e..b4cdabd226 100644 --- a/src/upgrades/1.12.0/global_view_privileges.js +++ b/src/upgrades/1.12.0/global_view_privileges.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var privileges = require('../../privileges'); +const async = require('async'); +const privileges = require('../../privileges'); module.exports = { name: 'Global view privileges', timestamp: Date.UTC(2019, 0, 5), method: function (callback) { - var meta = require('../../meta'); + const meta = require('../../meta'); - var tasks = [ + const tasks = [ async.apply(privileges.global.give, ['groups:view:users', 'groups:view:tags', 'groups:view:groups'], 'registered-users'), ]; diff --git a/src/upgrades/1.12.0/group_create_privilege.js b/src/upgrades/1.12.0/group_create_privilege.js index 35f93d0f36..4fad7703a9 100644 --- a/src/upgrades/1.12.0/group_create_privilege.js +++ b/src/upgrades/1.12.0/group_create_privilege.js @@ -1,12 +1,12 @@ 'use strict'; -var privileges = require('../../privileges'); +const privileges = require('../../privileges'); module.exports = { name: 'Group create global privilege', timestamp: Date.UTC(2019, 0, 4), method: function (callback) { - var meta = require('../../meta'); + const meta = require('../../meta'); if (parseInt(meta.config.allowGroupCreation, 10) === 1) { privileges.global.give(['groups:group:create'], 'registered-users', callback); } else { diff --git a/src/upgrades/1.12.1/clear_username_email_history.js b/src/upgrades/1.12.1/clear_username_email_history.js index 200d2fc9eb..a2925826bd 100644 --- a/src/upgrades/1.12.1/clear_username_email_history.js +++ b/src/upgrades/1.12.1/clear_username_email_history.js @@ -9,7 +9,7 @@ module.exports = { timestamp: Date.UTC(2019, 2, 25), method: function (callback) { const progress = this.progress; - var currentUid = 1; + let currentUid = 1; db.getObjectField('global', 'nextUid', (err, nextUid) => { if (err) { return callback(err); diff --git a/src/upgrades/1.12.1/moderation_notes_refactor.js b/src/upgrades/1.12.1/moderation_notes_refactor.js index fe53083a88..ad6ab17720 100644 --- a/src/upgrades/1.12.1/moderation_notes_refactor.js +++ b/src/upgrades/1.12.1/moderation_notes_refactor.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); -var batch = require('../../batch'); +const async = require('async'); +const db = require('../../database'); +const batch = require('../../batch'); module.exports = { name: 'Update moderation notes to hashes', timestamp: Date.UTC(2019, 3, 5), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('users:joindate', (ids, next) => { async.each(ids, (uid, next) => { @@ -20,7 +20,7 @@ module.exports = { } async.eachSeries(notes, (note, next) => { - var noteData; + let noteData; async.waterfall([ function (next) { try { diff --git a/src/upgrades/1.12.1/post_upload_sizes.js b/src/upgrades/1.12.1/post_upload_sizes.js index ffd04bcdda..bd1e5c4b43 100644 --- a/src/upgrades/1.12.1/post_upload_sizes.js +++ b/src/upgrades/1.12.1/post_upload_sizes.js @@ -1,6 +1,6 @@ 'use strict'; -var async = require('async'); +const async = require('async'); const batch = require('../../batch'); const posts = require('../../posts'); diff --git a/src/upgrades/1.12.3/give_mod_info_privilege.js b/src/upgrades/1.12.3/give_mod_info_privilege.js index e66d53bdf4..c613bf6205 100644 --- a/src/upgrades/1.12.3/give_mod_info_privilege.js +++ b/src/upgrades/1.12.3/give_mod_info_privilege.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); -var privileges = require('../../privileges'); -var groups = require('../../groups'); +const async = require('async'); +const db = require('../../database'); +const privileges = require('../../privileges'); +const groups = require('../../groups'); module.exports = { name: 'give mod info privilege', diff --git a/src/upgrades/1.12.3/give_mod_privileges.js b/src/upgrades/1.12.3/give_mod_privileges.js index f2dcf1e9ca..03c6c6ff67 100644 --- a/src/upgrades/1.12.3/give_mod_privileges.js +++ b/src/upgrades/1.12.3/give_mod_privileges.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var privileges = require('../../privileges'); -var groups = require('../../groups'); -var db = require('../../database'); +const async = require('async'); +const privileges = require('../../privileges'); +const groups = require('../../groups'); +const db = require('../../database'); module.exports = { name: 'Give mods explicit privileges', timestamp: Date.UTC(2019, 4, 28), method: function (callback) { - var defaultPrivileges = [ + const defaultPrivileges = [ 'find', 'read', 'topics:read', diff --git a/src/upgrades/1.12.3/update_registration_type.js b/src/upgrades/1.12.3/update_registration_type.js index 431189ebc2..8eb5e754d3 100644 --- a/src/upgrades/1.12.3/update_registration_type.js +++ b/src/upgrades/1.12.3/update_registration_type.js @@ -1,6 +1,6 @@ 'use strict'; -var db = require('../../database'); +const db = require('../../database'); module.exports = { name: 'Update registration type', diff --git a/src/upgrades/1.2.0/category_recent_tids.js b/src/upgrades/1.2.0/category_recent_tids.js index 31a1da5ed8..4a216593c8 100644 --- a/src/upgrades/1.2.0/category_recent_tids.js +++ b/src/upgrades/1.2.0/category_recent_tids.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { diff --git a/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js b/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js index 9627f64271..b5d28f4a56 100644 --- a/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js +++ b/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js @@ -1,16 +1,16 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Granting edit/delete/delete topic on existing categories', timestamp: Date.UTC(2016, 7, 7), method: function (callback) { - var groupsAPI = require('../../groups'); - var privilegesAPI = require('../../privileges'); + const groupsAPI = require('../../groups'); + const privilegesAPI = require('../../privileges'); db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { @@ -23,8 +23,8 @@ module.exports = { return next(err); } - var groups = data.groups; - var users = data.users; + const groups = data.groups; + const users = data.users; async.waterfall([ function (next) { diff --git a/src/upgrades/1.3.0/favourites_to_bookmarks.js b/src/upgrades/1.3.0/favourites_to_bookmarks.js index 07071fee84..a61bbf3cce 100644 --- a/src/upgrades/1.3.0/favourites_to_bookmarks.js +++ b/src/upgrades/1.3.0/favourites_to_bookmarks.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Favourites to Bookmarks', timestamp: Date.UTC(2016, 9, 8), method: function (callback) { - var progress = this.progress; + const progress = this.progress; function upgradePosts(next) { - var batch = require('../../batch'); + const batch = require('../../batch'); batch.processSortedSet('posts:pid', (ids, next) => { async.each(ids, (id, next) => { @@ -42,7 +42,7 @@ module.exports = { } function upgradeUsers(next) { - var batch = require('../../batch'); + const batch = require('../../batch'); batch.processSortedSet('users:joindate', (ids, next) => { async.each(ids, (id, next) => { diff --git a/src/upgrades/1.3.0/sorted_sets_for_post_replies.js b/src/upgrades/1.3.0/sorted_sets_for_post_replies.js index 24cbf3b9e2..d34f30a60d 100644 --- a/src/upgrades/1.3.0/sorted_sets_for_post_replies.js +++ b/src/upgrades/1.3.0/sorted_sets_for_post_replies.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Sorted sets for post replies', timestamp: Date.UTC(2016, 9, 14), method: function (callback) { - var posts = require('../../posts'); - var batch = require('../../batch'); - var progress = this.progress; + const posts = require('../../posts'); + const batch = require('../../batch'); + const progress = this.progress; batch.processSortedSet('posts:pid', (ids, next) => { posts.getPostsFields(ids, ['pid', 'toPid', 'timestamp'], (err, data) => { diff --git a/src/upgrades/1.4.0/global_and_user_language_keys.js b/src/upgrades/1.4.0/global_and_user_language_keys.js index 862a86cbbf..f565d6c423 100644 --- a/src/upgrades/1.4.0/global_and_user_language_keys.js +++ b/src/upgrades/1.4.0/global_and_user_language_keys.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Update global and user language keys', timestamp: Date.UTC(2016, 10, 22), method: function (callback) { - var user = require('../../user'); - var meta = require('../../meta'); - var batch = require('../../batch'); - var newLanguage; + const user = require('../../user'); + const meta = require('../../meta'); + const batch = require('../../batch'); + let newLanguage; async.parallel([ function (next) { meta.configs.get('defaultLang', (err, defaultLang) => { diff --git a/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js b/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js index b699a0ef8f..042dc6c948 100644 --- a/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js +++ b/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js @@ -1,16 +1,16 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); -var db = require('../../database'); +const async = require('async'); +const winston = require('winston'); +const db = require('../../database'); module.exports = { name: 'Sorted set for pinned topics', timestamp: Date.UTC(2016, 10, 25), method: function (callback) { - var topics = require('../../topics'); - var batch = require('../../batch'); + const topics = require('../../topics'); + const batch = require('../../batch'); batch.processSortedSet('topics:tid', (ids, next) => { topics.getTopicsFields(ids, ['tid', 'cid', 'pinned', 'lastposttime'], (err, data) => { if (err) { diff --git a/src/upgrades/1.4.4/config_urls_update.js b/src/upgrades/1.4.4/config_urls_update.js index 64f24ed525..5bf80c14fa 100644 --- a/src/upgrades/1.4.4/config_urls_update.js +++ b/src/upgrades/1.4.4/config_urls_update.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { @@ -17,10 +17,10 @@ module.exports = { return cb(); } - var keys = ['brand:favicon', 'brand:touchicon', 'og:image', 'brand:logo:url', 'defaultAvatar', 'profile:defaultCovers']; + const keys = ['brand:favicon', 'brand:touchicon', 'og:image', 'brand:logo:url', 'defaultAvatar', 'profile:defaultCovers']; keys.forEach((key) => { - var oldValue = config[key]; + const oldValue = config[key]; if (!oldValue || typeof oldValue !== 'string') { return; diff --git a/src/upgrades/1.4.4/sound_settings.js b/src/upgrades/1.4.4/sound_settings.js index 25efa2f0ad..ae0a6d8fa3 100644 --- a/src/upgrades/1.4.4/sound_settings.js +++ b/src/upgrades/1.4.4/sound_settings.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Update global and user sound settings', timestamp: Date.UTC(2017, 1, 25), method: function (callback) { - var meta = require('../../meta'); - var batch = require('../../batch'); + const meta = require('../../meta'); + const batch = require('../../batch'); - var map = { + const map = { 'notification.mp3': 'Default | Deedle-dum', 'waterdrop-high.mp3': 'Default | Water drop (high)', 'waterdrop-low.mp3': 'Default | Water drop (low)', @@ -19,7 +19,7 @@ module.exports = { async.parallel([ function (cb) { - var keys = ['chat-incoming', 'chat-outgoing', 'notification']; + const keys = ['chat-incoming', 'chat-outgoing', 'notification']; db.getObject('settings:sounds', (err, settings) => { if (err || !settings) { @@ -36,7 +36,7 @@ module.exports = { }); }, function (cb) { - var keys = ['notificationSound', 'incomingChatSound', 'outgoingChatSound']; + const keys = ['notificationSound', 'incomingChatSound', 'outgoingChatSound']; batch.processSortedSet('users:joindate', (ids, next) => { async.each(ids, (uid, next) => { @@ -44,7 +44,7 @@ module.exports = { if (err || !settings) { return next(err); } - var newSettings = {}; + const newSettings = {}; keys.forEach((key) => { if (settings[key] && !settings[key].includes(' | ')) { newSettings[key] = map[settings[key]] || ''; diff --git a/src/upgrades/1.4.6/delete_sessions.js b/src/upgrades/1.4.6/delete_sessions.js index 1fe6d0b6bc..aadf00b0ba 100644 --- a/src/upgrades/1.4.6/delete_sessions.js +++ b/src/upgrades/1.4.6/delete_sessions.js @@ -1,30 +1,30 @@ 'use strict'; -var async = require('async'); +const async = require('async'); const nconf = require('nconf'); -var db = require('../../database'); -var batch = require('../../batch'); +const db = require('../../database'); +const batch = require('../../batch'); module.exports = { name: 'Delete accidentally long-lived sessions', timestamp: Date.UTC(2017, 3, 16), method: function (callback) { - var configJSON; + let configJSON; try { configJSON = require('../../../config.json') || { [process.env.database]: true }; } catch (err) { configJSON = { [process.env.database]: true }; } - var isRedisSessionStore = configJSON.hasOwnProperty('redis'); - var progress = this.progress; + const isRedisSessionStore = configJSON.hasOwnProperty('redis'); + const progress = this.progress; async.waterfall([ function (next) { if (isRedisSessionStore) { - var connection = require('../../database/redis/connection'); - var client; + const connection = require('../../database/redis/connection'); + let client; async.waterfall([ function (next) { connection.connect(nconf.get('redis'), next); @@ -37,7 +37,7 @@ module.exports = { progress.total = sessionKeys.length; batch.processArray(sessionKeys, (keys, next) => { - var multi = client.multi(); + const multi = client.multi(); keys.forEach((key) => { progress.incr(); multi.del(key); diff --git a/src/upgrades/1.5.0/allowed_file_extensions.js b/src/upgrades/1.5.0/allowed_file_extensions.js index 7f1af2a5c3..5f7ee7c268 100644 --- a/src/upgrades/1.5.0/allowed_file_extensions.js +++ b/src/upgrades/1.5.0/allowed_file_extensions.js @@ -1,6 +1,6 @@ 'use strict'; -var db = require('../../database'); +const db = require('../../database'); module.exports = { name: 'Set default allowed file extensions', diff --git a/src/upgrades/1.5.0/flags_refactor.js b/src/upgrades/1.5.0/flags_refactor.js index b19fdfa30d..55a2553882 100644 --- a/src/upgrades/1.5.0/flags_refactor.js +++ b/src/upgrades/1.5.0/flags_refactor.js @@ -1,17 +1,17 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Migrating flags to new schema', timestamp: Date.UTC(2016, 11, 7), method: function (callback) { - var batch = require('../../batch'); - var posts = require('../../posts'); - var flags = require('../../flags'); - var progress = this.progress; + const batch = require('../../batch'); + const posts = require('../../posts'); + const flags = require('../../flags'); + const progress = this.progress; batch.processSortedSet('posts:pid', (ids, next) => { posts.getPostsByPids(ids, 1, (err, posts) => { @@ -38,9 +38,9 @@ module.exports = { } // Just take the first entry - var datetime = data.uids[0].score; - var reason = data.reasons[0].split(':')[1]; - var flagObj; + const datetime = data.uids[0].score; + const reason = data.reasons[0].split(':')[1]; + let flagObj; async.waterfall([ async.apply(flags.create, 'post', post.pid, data.uids[0].value, reason, datetime), @@ -59,7 +59,7 @@ module.exports = { function (next) { if (post.hasOwnProperty('flag:notes') && post['flag:notes'].length) { try { - var history = JSON.parse(post['flag:history']); + let history = JSON.parse(post['flag:history']); history = history.filter(event => event.type === 'notes')[0]; flags.appendNote(flagObj.flagId, history.uid, post['flag:notes'], history.timestamp, next); diff --git a/src/upgrades/1.5.0/moderation_history_refactor.js b/src/upgrades/1.5.0/moderation_history_refactor.js index eb112bf5e7..e06b3318b4 100644 --- a/src/upgrades/1.5.0/moderation_history_refactor.js +++ b/src/upgrades/1.5.0/moderation_history_refactor.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); -var batch = require('../../batch'); +const async = require('async'); +const db = require('../../database'); +const batch = require('../../batch'); module.exports = { name: 'Update moderation notes to zset', timestamp: Date.UTC(2017, 2, 22), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('users:joindate', (ids, next) => { async.each(ids, (uid, next) => { @@ -18,7 +18,7 @@ module.exports = { progress.incr(); return next(err); } - var note = { + const note = { uid: 1, note: moderationNote, timestamp: Date.now(), diff --git a/src/upgrades/1.5.0/post_votes_zset.js b/src/upgrades/1.5.0/post_votes_zset.js index dd81bf2663..9a84bfddaa 100644 --- a/src/upgrades/1.5.0/post_votes_zset.js +++ b/src/upgrades/1.5.0/post_votes_zset.js @@ -1,14 +1,14 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'New sorted set posts:votes', timestamp: Date.UTC(2017, 1, 27), method: function (callback) { - var progress = this.progress; + const progress = this.progress; require('../../batch').processSortedSet('posts:pid', (pids, next) => { async.each(pids, (pid, next) => { @@ -18,7 +18,7 @@ module.exports = { } progress.incr(); - var votes = parseInt(postData.upvotes || 0, 10) - parseInt(postData.downvotes || 0, 10); + const votes = parseInt(postData.upvotes || 0, 10) - parseInt(postData.downvotes || 0, 10); db.sortedSetAdd('posts:votes', votes, pid, next); }); }, next); diff --git a/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js b/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js index 93a891b501..5cbe49996b 100644 --- a/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js +++ b/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); -var batch = require('../../batch'); +const async = require('async'); +const db = require('../../database'); +const batch = require('../../batch'); module.exports = { name: 'Remove relative_path from uploaded profile cover urls', timestamp: Date.UTC(2017, 3, 26), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('users:joindate', (ids, done) => { async.each(ids, (uid, cb) => { @@ -24,7 +24,7 @@ module.exports = { return next(); } - var newUrl = url.replace(/^.*?\/uploads\//, '/assets/uploads/'); + const newUrl = url.replace(/^.*?\/uploads\//, '/assets/uploads/'); db.setObjectField(`user:${uid}`, 'cover:url', newUrl, next); }, ], cb); diff --git a/src/upgrades/1.5.1/rename_mods_group.js b/src/upgrades/1.5.1/rename_mods_group.js index cd43a7925c..5bdaa45c91 100644 --- a/src/upgrades/1.5.1/rename_mods_group.js +++ b/src/upgrades/1.5.1/rename_mods_group.js @@ -1,21 +1,21 @@ 'use strict'; -var async = require('async'); -var winston = require('winston'); +const async = require('async'); +const winston = require('winston'); -var batch = require('../../batch'); -var groups = require('../../groups'); +const batch = require('../../batch'); +const groups = require('../../groups'); module.exports = { name: 'rename user mod privileges group', timestamp: Date.UTC(2017, 4, 26), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('categories:cid', (cids, next) => { async.eachSeries(cids, (cid, next) => { - var groupName = `cid:${cid}:privileges:mods`; - var newName = `cid:${cid}:privileges:moderate`; + const groupName = `cid:${cid}:privileges:mods`; + const newName = `cid:${cid}:privileges:moderate`; groups.exists(groupName, (err, exists) => { if (err || !exists) { progress.incr(); diff --git a/src/upgrades/1.5.2/rss_token_wipe.js b/src/upgrades/1.5.2/rss_token_wipe.js index 76a0915c4f..e8b992dd33 100644 --- a/src/upgrades/1.5.2/rss_token_wipe.js +++ b/src/upgrades/1.5.2/rss_token_wipe.js @@ -1,14 +1,14 @@ 'use strict'; -var async = require('async'); -var batch = require('../../batch'); -var db = require('../../database'); +const async = require('async'); +const batch = require('../../batch'); +const db = require('../../database'); module.exports = { name: 'Wipe all existing RSS tokens', timestamp: Date.UTC(2017, 6, 5), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('users:joindate', (uids, next) => { async.eachLimit(uids, 500, (uid, next) => { diff --git a/src/upgrades/1.5.2/tags_privilege.js b/src/upgrades/1.5.2/tags_privilege.js index 80733d1d9f..44217acbc8 100644 --- a/src/upgrades/1.5.2/tags_privilege.js +++ b/src/upgrades/1.5.2/tags_privilege.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var batch = require('../../batch'); +const batch = require('../../batch'); module.exports = { name: 'Give tag privilege to registered-users on all categories', timestamp: Date.UTC(2017, 5, 16), method: function (callback) { - var progress = this.progress; - var privileges = require('../../privileges'); + const progress = this.progress; + const privileges = require('../../privileges'); batch.processSortedSet('categories:cid', (cids, next) => { async.eachSeries(cids, (cid, next) => { progress.incr(); diff --git a/src/upgrades/1.6.0/clear-stale-digest-template.js b/src/upgrades/1.6.0/clear-stale-digest-template.js index 76370443bb..ff34668691 100644 --- a/src/upgrades/1.6.0/clear-stale-digest-template.js +++ b/src/upgrades/1.6.0/clear-stale-digest-template.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var crypto = require('crypto'); -var meta = require('../../meta'); +const async = require('async'); +const crypto = require('crypto'); +const meta = require('../../meta'); module.exports = { name: 'Clearing stale digest templates that were accidentally saved as custom', timestamp: Date.UTC(2017, 8, 6), method: function (callback) { - var matches = [ + const matches = [ '112e541b40023d6530dd44df4b0d9c5d', // digest @ 75917e25b3b5ad7bed8ed0c36433fb35c9ab33eb '110b8805f70395b0282fd10555059e9f', // digest @ 9b02bb8f51f0e47c6e335578f776ffc17bc03537 '9538e7249edb369b2a25b03f2bd3282b', // digest @ 3314ab4b83138c7ae579ac1f1f463098b8c2d414 @@ -18,7 +18,7 @@ module.exports = { async.waterfall([ async.apply(meta.configs.getFields, ['email:custom:digest']), function (fieldset, next) { - var hash = fieldset['email:custom:digest'] ? crypto.createHash('md5').update(fieldset['email:custom:digest']).digest('hex') : null; + const hash = fieldset['email:custom:digest'] ? crypto.createHash('md5').update(fieldset['email:custom:digest']).digest('hex') : null; if (matches.includes(hash)) { meta.configs.remove('email:custom:digest', next); diff --git a/src/upgrades/1.6.0/generate-email-logo.js b/src/upgrades/1.6.0/generate-email-logo.js index 6e307f2a61..069f1aa723 100644 --- a/src/upgrades/1.6.0/generate-email-logo.js +++ b/src/upgrades/1.6.0/generate-email-logo.js @@ -1,24 +1,24 @@ 'use strict'; -var async = require('async'); -var path = require('path'); -var nconf = require('nconf'); -var fs = require('fs'); -var meta = require('../../meta'); -var image = require('../../image'); +const async = require('async'); +const path = require('path'); +const nconf = require('nconf'); +const fs = require('fs'); +const meta = require('../../meta'); +const image = require('../../image'); module.exports = { name: 'Generate email logo for use in email header', timestamp: Date.UTC(2017, 6, 17), method: function (callback) { - var skip = false; + let skip = false; async.series([ function (next) { // Resize existing logo (if present) to email header size - var uploadPath = path.join(nconf.get('upload_path'), 'system', 'site-logo-x50.png'); - var sourcePath = meta.config['brand:logo'] ? path.join(nconf.get('upload_path'), 'system', path.basename(meta.config['brand:logo'])) : null; + const uploadPath = path.join(nconf.get('upload_path'), 'system', 'site-logo-x50.png'); + const sourcePath = meta.config['brand:logo'] ? path.join(nconf.get('upload_path'), 'system', path.basename(meta.config['brand:logo'])) : null; if (!sourcePath) { skip = true; diff --git a/src/upgrades/1.6.0/ipblacklist-fix.js b/src/upgrades/1.6.0/ipblacklist-fix.js index 27afd49d97..7e3f13d506 100644 --- a/src/upgrades/1.6.0/ipblacklist-fix.js +++ b/src/upgrades/1.6.0/ipblacklist-fix.js @@ -1,14 +1,14 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var db = require('../../database'); +const db = require('../../database'); module.exports = { name: 'Changing ip blacklist storage to object', timestamp: Date.UTC(2017, 8, 7), method: function (callback) { - var rules; + let rules; async.waterfall([ function (next) { db.get('ip-blacklist-rules', next); diff --git a/src/upgrades/1.6.0/robots-config-change.js b/src/upgrades/1.6.0/robots-config-change.js index 3a18872bbc..7efc789357 100644 --- a/src/upgrades/1.6.0/robots-config-change.js +++ b/src/upgrades/1.6.0/robots-config-change.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Fix incorrect robots.txt schema', diff --git a/src/upgrades/1.6.2/topics_lastposttime_zset.js b/src/upgrades/1.6.2/topics_lastposttime_zset.js index b7b614b8c9..071901199a 100644 --- a/src/upgrades/1.6.2/topics_lastposttime_zset.js +++ b/src/upgrades/1.6.2/topics_lastposttime_zset.js @@ -1,14 +1,14 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var db = require('../../database'); +const db = require('../../database'); module.exports = { name: 'New sorted set cid::tids:lastposttime', timestamp: Date.UTC(2017, 9, 30), method: function (callback) { - var progress = this.progress; + const progress = this.progress; require('../../batch').processSortedSet('topics:tid', (tids, next) => { async.eachSeries(tids, (tid, next) => { @@ -18,7 +18,7 @@ module.exports = { } progress.incr(); - var timestamp = topicData.lastposttime || topicData.timestamp || Date.now(); + const timestamp = topicData.lastposttime || topicData.timestamp || Date.now(); db.sortedSetAdd(`cid:${topicData.cid}:tids:lastposttime`, timestamp, tid, next); }, next); }, next); diff --git a/src/upgrades/1.7.0/generate-custom-html.js b/src/upgrades/1.7.0/generate-custom-html.js index 795327af20..769633e80b 100644 --- a/src/upgrades/1.7.0/generate-custom-html.js +++ b/src/upgrades/1.7.0/generate-custom-html.js @@ -1,7 +1,7 @@ 'use strict'; -var db = require('../../database'); -var meta = require('../../meta'); +const db = require('../../database'); +const meta = require('../../meta'); module.exports = { name: 'Generate customHTML block from old customJS setting', @@ -12,11 +12,11 @@ module.exports = { return callback(err); } - var newJS = []; + let newJS = []; // Forgive me for parsing HTML with regex... - var scriptMatch = /^([\s\S]+?)<\/script>/m; - var match = scriptMatch.exec(newHTML); + const scriptMatch = /^([\s\S]+?)<\/script>/m; + let match = scriptMatch.exec(newHTML); while (match) { if (match[1]) { diff --git a/src/upgrades/1.7.1/notification-settings.js b/src/upgrades/1.7.1/notification-settings.js index 5076bbd92b..7ee78f244e 100644 --- a/src/upgrades/1.7.1/notification-settings.js +++ b/src/upgrades/1.7.1/notification-settings.js @@ -1,14 +1,14 @@ 'use strict'; -var async = require('async'); -var batch = require('../../batch'); -var db = require('../../database'); +const async = require('async'); +const batch = require('../../batch'); +const db = require('../../database'); module.exports = { name: 'Convert old notification digest settings', timestamp: Date.UTC(2017, 10, 15), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('users:joindate', (uids, next) => { async.eachLimit(uids, 500, (uid, next) => { @@ -21,7 +21,7 @@ module.exports = { if (!userSettings) { return next(); } - var tasks = []; + const tasks = []; if (parseInt(userSettings.sendChatNotifications, 10) === 1) { tasks.push(async.apply(db.setObjectField, `user:${uid}:settings`, 'notificationType_new-chat', 'notificationemail')); } diff --git a/src/upgrades/1.7.3/key_value_schema_change.js b/src/upgrades/1.7.3/key_value_schema_change.js index ccbb24874e..1904baf917 100644 --- a/src/upgrades/1.7.3/key_value_schema_change.js +++ b/src/upgrades/1.7.3/key_value_schema_change.js @@ -1,26 +1,26 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var db = require('../../database'); +const db = require('../../database'); module.exports = { name: 'Change the schema of simple keys so they don\'t use value field (mongodb only)', timestamp: Date.UTC(2017, 11, 18), method: function (callback) { - var configJSON; + let configJSON; try { configJSON = require('../../../config.json') || { [process.env.database]: true, database: process.env.database }; } catch (err) { configJSON = { [process.env.database]: true, database: process.env.database }; } - var isMongo = configJSON.hasOwnProperty('mongo') && configJSON.database === 'mongo'; - var progress = this.progress; + const isMongo = configJSON.hasOwnProperty('mongo') && configJSON.database === 'mongo'; + const progress = this.progress; if (!isMongo) { return callback(); } - var client = db.client; - var cursor; + const client = db.client; + let cursor; async.waterfall([ function (next) { client.collection('objects').countDocuments({ @@ -37,7 +37,7 @@ module.exports = { score: { $exists: false }, }).batchSize(1000); - var done = false; + let done = false; async.whilst( (next) => { next(null, !done); diff --git a/src/upgrades/1.7.3/topic_votes.js b/src/upgrades/1.7.3/topic_votes.js index cfd8132a0d..e28f0a8b27 100644 --- a/src/upgrades/1.7.3/topic_votes.js +++ b/src/upgrades/1.7.3/topic_votes.js @@ -1,19 +1,19 @@ 'use strict'; -var async = require('async'); -var batch = require('../../batch'); -var db = require('../../database'); +const async = require('async'); +const batch = require('../../batch'); +const db = require('../../database'); module.exports = { name: 'Add votes to topics', timestamp: Date.UTC(2017, 11, 8), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('topics:tid', (tids, next) => { async.eachLimit(tids, 500, (tid, _next) => { progress.incr(); - var topicData; + let topicData; async.waterfall([ function (next) { db.getObjectFields(`topic:${tid}`, ['mainPid', 'cid', 'pinned'], next); @@ -29,13 +29,13 @@ module.exports = { if (!postData) { return _next(); } - var upvotes = parseInt(postData.upvotes, 10) || 0; - var downvotes = parseInt(postData.downvotes, 10) || 0; - var data = { + const upvotes = parseInt(postData.upvotes, 10) || 0; + const downvotes = parseInt(postData.downvotes, 10) || 0; + const data = { upvotes: upvotes, downvotes: downvotes, }; - var votes = upvotes - downvotes; + const votes = upvotes - downvotes; async.parallel([ function (next) { db.setObject(`topic:${tid}`, data, next); diff --git a/src/upgrades/1.7.4/chat_privilege.js b/src/upgrades/1.7.4/chat_privilege.js index c4bd2ff8d1..360a7b8c57 100644 --- a/src/upgrades/1.7.4/chat_privilege.js +++ b/src/upgrades/1.7.4/chat_privilege.js @@ -1,7 +1,7 @@ 'use strict'; -var groups = require('../../groups'); +const groups = require('../../groups'); module.exports = { name: 'Give chat privilege to registered-users', diff --git a/src/upgrades/1.7.4/fix_moved_topics_byvotes.js b/src/upgrades/1.7.4/fix_moved_topics_byvotes.js index 9a6b1c8697..4d607c386a 100644 --- a/src/upgrades/1.7.4/fix_moved_topics_byvotes.js +++ b/src/upgrades/1.7.4/fix_moved_topics_byvotes.js @@ -1,19 +1,19 @@ 'use strict'; -var async = require('async'); -var batch = require('../../batch'); -var db = require('../../database'); +const async = require('async'); +const batch = require('../../batch'); +const db = require('../../database'); module.exports = { name: 'Fix sort by votes for moved topics', timestamp: Date.UTC(2018, 0, 8), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('topics:tid', (tids, next) => { async.eachLimit(tids, 500, (tid, _next) => { progress.incr(); - var topicData; + let topicData; async.waterfall([ function (next) { db.getObjectFields(`topic:${tid}`, ['cid', 'oldCid', 'upvotes', 'downvotes', 'pinned'], next); @@ -24,9 +24,9 @@ module.exports = { return _next(); } - var upvotes = parseInt(topicData.upvotes, 10) || 0; - var downvotes = parseInt(topicData.downvotes, 10) || 0; - var votes = upvotes - downvotes; + const upvotes = parseInt(topicData.upvotes, 10) || 0; + const downvotes = parseInt(topicData.downvotes, 10) || 0; + const votes = upvotes - downvotes; async.series([ function (next) { diff --git a/src/upgrades/1.7.4/fix_user_topics_per_category.js b/src/upgrades/1.7.4/fix_user_topics_per_category.js index df5534554f..0be8d81692 100644 --- a/src/upgrades/1.7.4/fix_user_topics_per_category.js +++ b/src/upgrades/1.7.4/fix_user_topics_per_category.js @@ -1,19 +1,19 @@ 'use strict'; -var async = require('async'); -var batch = require('../../batch'); -var db = require('../../database'); +const async = require('async'); +const batch = require('../../batch'); +const db = require('../../database'); module.exports = { name: 'Fix topics in categories per user if they were moved', timestamp: Date.UTC(2018, 0, 22), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('topics:tid', (tids, next) => { async.eachLimit(tids, 500, (tid, _next) => { progress.incr(); - var topicData; + let topicData; async.waterfall([ function (next) { db.getObjectFields(`topic:${tid}`, ['cid', 'tid', 'uid', 'oldCid', 'timestamp'], next); diff --git a/src/upgrades/1.7.4/global_upload_privilege.js b/src/upgrades/1.7.4/global_upload_privilege.js index e25392f599..b2db7813c6 100644 --- a/src/upgrades/1.7.4/global_upload_privilege.js +++ b/src/upgrades/1.7.4/global_upload_privilege.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); -var groups = require('../../groups'); -var privileges = require('../../privileges'); -var db = require('../../database'); +const async = require('async'); +const groups = require('../../groups'); +const privileges = require('../../privileges'); +const db = require('../../database'); module.exports = { name: 'Give upload privilege to registered-users globally if it is given on a category', @@ -20,7 +20,7 @@ module.exports = { return next(err); } - var privs = []; + const privs = []; if (groupPrivileges['groups:upload:post:image']) { privs.push('groups:upload:post:image'); } @@ -35,7 +35,7 @@ module.exports = { }; function getGroupPrivileges(cid, callback) { - var tasks = {}; + const tasks = {}; ['groups:upload:post:image', 'groups:upload:post:file'].forEach((privilege) => { tasks[privilege] = async.apply(groups.isMember, 'registered-users', `cid:${cid}:privileges:${privilege}`); diff --git a/src/upgrades/1.7.4/rename_min_reputation_settings.js b/src/upgrades/1.7.4/rename_min_reputation_settings.js index 782f92c40e..6edb9d7e46 100644 --- a/src/upgrades/1.7.4/rename_min_reputation_settings.js +++ b/src/upgrades/1.7.4/rename_min_reputation_settings.js @@ -1,6 +1,6 @@ 'use strict'; -var db = require('../../database'); +const db = require('../../database'); module.exports = { name: 'Rename privileges:downvote and privileges:flag to min:rep:downvote, min:rep:flag respectively', diff --git a/src/upgrades/1.7.4/vote_privilege.js b/src/upgrades/1.7.4/vote_privilege.js index be14cc7ef9..12eda4b8e6 100644 --- a/src/upgrades/1.7.4/vote_privilege.js +++ b/src/upgrades/1.7.4/vote_privilege.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); +const async = require('async'); -var privileges = require('../../privileges'); -var db = require('../../database'); +const privileges = require('../../privileges'); +const db = require('../../database'); module.exports = { name: 'Give vote privilege to registered-users on all categories', diff --git a/src/upgrades/1.7.6/flatten_navigation_data.js b/src/upgrades/1.7.6/flatten_navigation_data.js index 52e5e38519..e5cb5932b8 100644 --- a/src/upgrades/1.7.6/flatten_navigation_data.js +++ b/src/upgrades/1.7.6/flatten_navigation_data.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Flatten navigation data', @@ -12,11 +12,11 @@ module.exports = { db.getSortedSetRangeWithScores('navigation:enabled', 0, -1, next); }, function (data, next) { - var order = []; - var items = []; + const order = []; + const items = []; data.forEach((item) => { - var navItem = JSON.parse(item.value); - var keys = Object.keys(navItem); + let navItem = JSON.parse(item.value); + const keys = Object.keys(navItem); if (keys.length && parseInt(keys[0], 10) >= 0) { navItem = navItem[keys[0]]; } diff --git a/src/upgrades/1.7.6/notification_types.js b/src/upgrades/1.7.6/notification_types.js index 7064a7ac24..8d022a157b 100644 --- a/src/upgrades/1.7.6/notification_types.js +++ b/src/upgrades/1.7.6/notification_types.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { name: 'Add default settings for notification delivery types', @@ -12,8 +12,8 @@ module.exports = { db.getObject('config', next); }, function (config, next) { - var postNotifications = parseInt(config.sendPostNotifications, 10) === 1 ? 'notification' : 'none'; - var chatNotifications = parseInt(config.sendChatNotifications, 10) === 1 ? 'notification' : 'none'; + const postNotifications = parseInt(config.sendPostNotifications, 10) === 1 ? 'notification' : 'none'; + const chatNotifications = parseInt(config.sendChatNotifications, 10) === 1 ? 'notification' : 'none'; db.setObject('config', { notificationType_upvote: config.notificationType_upvote || 'notification', 'notificationType_new-topic': config['notificationType_new-topic'] || 'notification', diff --git a/src/upgrades/1.7.6/update_min_pass_strength.js b/src/upgrades/1.7.6/update_min_pass_strength.js index 238d152843..5afdb4f3ec 100644 --- a/src/upgrades/1.7.6/update_min_pass_strength.js +++ b/src/upgrades/1.7.6/update_min_pass_strength.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); module.exports = { diff --git a/src/upgrades/1.8.0/give_signature_privileges.js b/src/upgrades/1.8.0/give_signature_privileges.js index 03b387a676..adcc80e96f 100644 --- a/src/upgrades/1.8.0/give_signature_privileges.js +++ b/src/upgrades/1.8.0/give_signature_privileges.js @@ -1,6 +1,6 @@ 'use strict'; -var privileges = require('../../privileges'); +const privileges = require('../../privileges'); module.exports = { name: 'Give registered users signature privilege', diff --git a/src/upgrades/1.8.0/give_spiders_privileges.js b/src/upgrades/1.8.0/give_spiders_privileges.js index 9e5d13573a..1dc9055753 100644 --- a/src/upgrades/1.8.0/give_spiders_privileges.js +++ b/src/upgrades/1.8.0/give_spiders_privileges.js @@ -1,10 +1,10 @@ 'use strict'; -var async = require('async'); -var groups = require('../../groups'); -var privileges = require('../../privileges'); -var db = require('../../database'); +const async = require('async'); +const groups = require('../../groups'); +const privileges = require('../../privileges'); +const db = require('../../database'); module.exports = { name: 'Give category access privileges to spiders system group', @@ -20,7 +20,7 @@ module.exports = { return next(err); } - var privs = []; + const privs = []; if (groupPrivileges['groups:find']) { privs.push('groups:find'); } @@ -39,7 +39,7 @@ module.exports = { }; function getGroupPrivileges(cid, callback) { - var tasks = {}; + const tasks = {}; ['groups:find', 'groups:read', 'groups:topics:read'].forEach((privilege) => { tasks[privilege] = async.apply(groups.isMember, 'guests', `cid:${cid}:privileges:${privilege}`); diff --git a/src/upgrades/1.8.1/diffs_zset_to_listhash.js b/src/upgrades/1.8.1/diffs_zset_to_listhash.js index ea2a4ddd55..b69252acd6 100644 --- a/src/upgrades/1.8.1/diffs_zset_to_listhash.js +++ b/src/upgrades/1.8.1/diffs_zset_to_listhash.js @@ -1,7 +1,7 @@ 'use strict'; -var async = require('async'); -var db = require('../../database'); +const async = require('async'); +const db = require('../../database'); const batch = require('../../batch'); @@ -9,7 +9,7 @@ module.exports = { name: 'Reformatting post diffs to be stored in lists and hash instead of single zset', timestamp: Date.UTC(2018, 2, 15), method: function (callback) { - var progress = this.progress; + const progress = this.progress; batch.processSortedSet('posts:pid', (pids, next) => { async.each(pids, (pid, next) => { diff --git a/src/upgrades/1.9.0/refresh_post_upload_associations.js b/src/upgrades/1.9.0/refresh_post_upload_associations.js index 1e5fc84450..3c44431a0f 100644 --- a/src/upgrades/1.9.0/refresh_post_upload_associations.js +++ b/src/upgrades/1.9.0/refresh_post_upload_associations.js @@ -1,13 +1,13 @@ 'use strict'; -var async = require('async'); -var posts = require('../../posts'); +const async = require('async'); +const posts = require('../../posts'); module.exports = { name: 'Refresh post-upload associations', timestamp: Date.UTC(2018, 3, 16), method: function (callback) { - var progress = this.progress; + const progress = this.progress; require('../../batch').processSortedSet('posts:pid', (pids, next) => { async.each(pids, (pid, next) => { diff --git a/src/user/digest.js b/src/user/digest.js index 14da55e953..5889883f09 100644 --- a/src/user/digest.js +++ b/src/user/digest.js @@ -70,7 +70,7 @@ Digest.getUsersInterval = async (uids) => { }; Digest.getSubscribers = async function (interval) { - var subscribers = []; + let subscribers = []; await batch.processSortedSet('users:joindate', async (uids) => { const settings = await user.getMultipleUserSettings(uids); diff --git a/src/user/follow.js b/src/user/follow.js index 3c152219fd..f3b031a582 100644 --- a/src/user/follow.js +++ b/src/user/follow.js @@ -1,8 +1,8 @@ 'use strict'; -var plugins = require('../plugins'); -var db = require('../database'); +const plugins = require('../plugins'); +const db = require('../database'); module.exports = function (User) { User.follow = async function (uid, followuid) { diff --git a/src/user/info.js b/src/user/info.js index 4e113432f4..9e37660ac7 100644 --- a/src/user/info.js +++ b/src/user/info.js @@ -1,12 +1,12 @@ 'use strict'; -var _ = require('lodash'); -var validator = require('validator'); +const _ = require('lodash'); +const validator = require('validator'); -var db = require('../database'); -var posts = require('../posts'); -var topics = require('../topics'); -var utils = require('../../public/src/utils'); +const db = require('../database'); +const posts = require('../posts'); +const topics = require('../topics'); +const utils = require('../../public/src/utils'); module.exports = function (User) { User.getLatestBanInfo = async function (uid) { diff --git a/src/user/invite.js b/src/user/invite.js index 13c8163e76..5a221cae11 100644 --- a/src/user/invite.js +++ b/src/user/invite.js @@ -1,16 +1,16 @@ 'use strict'; -var async = require('async'); -var nconf = require('nconf'); -var validator = require('validator'); - -var db = require('../database'); -var meta = require('../meta'); -var emailer = require('../emailer'); -var groups = require('../groups'); -var translator = require('../translator'); -var utils = require('../utils'); +const async = require('async'); +const nconf = require('nconf'); +const validator = require('validator'); + +const db = require('../database'); +const meta = require('../meta'); +const emailer = require('../emailer'); +const groups = require('../groups'); +const translator = require('../translator'); +const utils = require('../utils'); module.exports = function (User) { User.getInvites = async function (uid) { diff --git a/src/user/jobs.js b/src/user/jobs.js index 1ef3c95377..9090d6b51e 100644 --- a/src/user/jobs.js +++ b/src/user/jobs.js @@ -1,18 +1,18 @@ 'use strict'; -var winston = require('winston'); -var cronJob = require('cron').CronJob; +const winston = require('winston'); +const cronJob = require('cron').CronJob; -var meta = require('../meta'); +const meta = require('../meta'); -var jobs = {}; +const jobs = {}; module.exports = function (User) { User.startJobs = function () { winston.verbose('[user/jobs] (Re-)starting jobs...'); - var started = 0; - var digestHour = meta.config.digestHour; + let started = 0; + let digestHour = meta.config.digestHour; // Fix digest hour if invalid if (isNaN(digestHour)) { @@ -44,9 +44,9 @@ module.exports = function (User) { } User.stopJobs = function () { - var terminated = 0; + let terminated = 0; // Terminate any active cron jobs - for (var jobId in jobs) { + for (const jobId in jobs) { if (jobs.hasOwnProperty(jobId)) { winston.verbose(`[user/jobs] Terminating job (${jobId})`); jobs[jobId].stop(); diff --git a/src/user/jobs/export-profile.js b/src/user/jobs/export-profile.js index 8fb2dce0c7..465400a280 100644 --- a/src/user/jobs/export-profile.js +++ b/src/user/jobs/export-profile.js @@ -50,7 +50,7 @@ process.on('message', async (msg) => { let chatData = []; await batch.processSortedSet(`uid:${targetUid}:chat:rooms`, async (roomIds) => { - var result = await Promise.all(roomIds.map(roomId => getRoomMessages(targetUid, roomId))); + const result = await Promise.all(roomIds.map(roomId => getRoomMessages(targetUid, roomId))); chatData = chatData.concat(_.flatten(result)); }, { batch: 100, interval: 1000 }); diff --git a/src/user/notifications.js b/src/user/notifications.js index 46fd795206..dcfa29f421 100644 --- a/src/user/notifications.js +++ b/src/user/notifications.js @@ -1,17 +1,17 @@ 'use strict'; -var winston = require('winston'); -var _ = require('lodash'); +const winston = require('winston'); +const _ = require('lodash'); -var db = require('../database'); -var meta = require('../meta'); -var notifications = require('../notifications'); -var privileges = require('../privileges'); -var plugins = require('../plugins'); -var utils = require('../utils'); +const db = require('../database'); +const meta = require('../meta'); +const notifications = require('../notifications'); +const privileges = require('../privileges'); +const plugins = require('../plugins'); +const utils = require('../utils'); -var UserNotifications = module.exports; +const UserNotifications = module.exports; UserNotifications.get = async function (uid) { if (parseInt(uid, 10) <= 0) { @@ -46,7 +46,7 @@ UserNotifications.getAll = async function (uid, filter) { ], 0, -1); nids = _.uniq(nids); const exists = await db.isSortedSetMembers('notifications', nids); - var deleteNids = []; + const deleteNids = []; nids = nids.filter((nid, index) => { if (!nid || !exists[index]) { @@ -199,7 +199,7 @@ UserNotifications.sendWelcomeNotification = async function (uid) { return; } - var path = meta.config.welcomeLink ? meta.config.welcomeLink : '#'; + const path = meta.config.welcomeLink ? meta.config.welcomeLink : '#'; const notifObj = await notifications.create({ bodyShort: meta.config.welcomeNotification, path: path, diff --git a/src/user/online.js b/src/user/online.js index ea4c3aea84..ffba4c9a94 100644 --- a/src/user/online.js +++ b/src/user/online.js @@ -1,9 +1,9 @@ 'use strict'; -var db = require('../database'); -var topics = require('../topics'); -var plugins = require('../plugins'); -var meta = require('../meta'); +const db = require('../database'); +const topics = require('../topics'); +const plugins = require('../plugins'); +const meta = require('../meta'); module.exports = function (User) { User.updateLastOnlineTime = async function (uid) { diff --git a/src/user/password.js b/src/user/password.js index 584533d68f..6761ed372d 100644 --- a/src/user/password.js +++ b/src/user/password.js @@ -17,7 +17,7 @@ module.exports = function (User) { User.isPasswordCorrect = async function (uid, password, ip) { password = password || ''; - var { + let { password: hashedPassword, 'password:shaWrapped': shaWrapped, } = await db.getObjectFields(`user:${uid}`, ['password', 'password:shaWrapped']); diff --git a/src/user/reset.js b/src/user/reset.js index 507cac674e..1fa3ff9082 100644 --- a/src/user/reset.js +++ b/src/user/reset.js @@ -131,7 +131,7 @@ UserReset.cleanByUid = async function (uid) { await batch.processSortedSet('reset:issueDate', async (tokens) => { const results = await db.getObjectFields('reset:uid', tokens); - for (var code in results) { + for (const code in results) { if (results.hasOwnProperty(code) && parseInt(results[code], 10) === uid) { tokensToClean.push(code); } diff --git a/src/webserver.js b/src/webserver.js index d23318024d..6ea5b44fba 100644 --- a/src/webserver.js +++ b/src/webserver.js @@ -1,40 +1,40 @@ 'use strict'; -var fs = require('fs'); +const fs = require('fs'); const util = require('util'); -var path = require('path'); -var os = require('os'); -var nconf = require('nconf'); -var express = require('express'); +const path = require('path'); +const os = require('os'); +const nconf = require('nconf'); +const express = require('express'); -var app = express(); +const app = express(); app.renderAsync = util.promisify((tpl, data, callback) => app.render(tpl, data, callback)); -var server; -var winston = require('winston'); -var async = require('async'); -var flash = require('connect-flash'); -var bodyParser = require('body-parser'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); -var useragent = require('express-useragent'); -var favicon = require('serve-favicon'); -var detector = require('spider-detector'); -var helmet = require('helmet'); - -var Benchpress = require('benchpressjs'); -var db = require('./database'); -var analytics = require('./analytics'); -var file = require('./file'); -var emailer = require('./emailer'); -var meta = require('./meta'); -var logger = require('./logger'); -var plugins = require('./plugins'); -var flags = require('./flags'); -var routes = require('./routes'); -var auth = require('./routes/authentication'); - -var helpers = require('../public/src/modules/helpers'); +let server; +const winston = require('winston'); +const async = require('async'); +const flash = require('connect-flash'); +const bodyParser = require('body-parser'); +const cookieParser = require('cookie-parser'); +const session = require('express-session'); +const useragent = require('express-useragent'); +const favicon = require('serve-favicon'); +const detector = require('spider-detector'); +const helmet = require('helmet'); + +const Benchpress = require('benchpressjs'); +const db = require('./database'); +const analytics = require('./analytics'); +const file = require('./file'); +const emailer = require('./emailer'); +const meta = require('./meta'); +const logger = require('./logger'); +const plugins = require('./plugins'); +const flags = require('./flags'); +const routes = require('./routes'); +const auth = require('./routes/authentication'); + +const helpers = require('../public/src/modules/helpers'); if (nconf.get('ssl')) { server = require('https').createServer({ @@ -59,9 +59,9 @@ server.on('error', (err) => { }); // see https://github.com/isaacs/server-destroy/blob/master/index.js -var connections = {}; +const connections = {}; server.on('connection', (conn) => { - var key = `${conn.remoteAddress}:${conn.remotePort}`; + const key = `${conn.remoteAddress}:${conn.remotePort}`; connections[key] = conn; conn.on('close', () => { delete connections[key]; @@ -70,7 +70,7 @@ server.on('connection', (conn) => { exports.destroy = function (callback) { server.close(callback); - for (var key in connections) { + for (const key in connections) { if (connections.hasOwnProperty(key)) { connections[key].destroy(); } @@ -174,7 +174,7 @@ function setupExpressApp(app) { auth.initialize(app, middleware); app.use(middleware.autoLocale); // must be added after auth middlewares are added - var toobusy = require('toobusy-js'); + const toobusy = require('toobusy-js'); toobusy.maxLag(meta.config.eventLoopLagThreshold); toobusy.interval(meta.config.eventLoopInterval); } @@ -201,7 +201,7 @@ function setupHelmet(app) { function setupFavicon(app) { - var faviconPath = meta.config['brand:favicon'] || 'favicon.ico'; + let faviconPath = meta.config['brand:favicon'] || 'favicon.ico'; faviconPath = path.join(nconf.get('base_dir'), 'public', faviconPath.replace(/assets\/uploads/, 'uploads')); if (file.existsSync(faviconPath)) { app.use(nconf.get('relative_path'), favicon(faviconPath)); @@ -229,9 +229,9 @@ function setupCookie() { function listen(callback) { callback = callback || function () { }; - var port = nconf.get('port'); - var isSocket = isNaN(port) && !Array.isArray(port); - var socketPath = isSocket ? nconf.get('port') : ''; + let port = nconf.get('port'); + const isSocket = isNaN(port) && !Array.isArray(port); + const socketPath = isSocket ? nconf.get('port') : ''; if (Array.isArray(port)) { if (!port.length) { @@ -257,9 +257,9 @@ function listen(callback) { winston.info('Using ports 80 and 443 is not recommend; use a proxy instead. See README.md'); } - var bind_address = ((nconf.get('bind_address') === '0.0.0.0' || !nconf.get('bind_address')) ? '0.0.0.0' : nconf.get('bind_address')); - var args = isSocket ? [socketPath] : [port, bind_address]; - var oldUmask; + const bind_address = ((nconf.get('bind_address') === '0.0.0.0' || !nconf.get('bind_address')) ? '0.0.0.0' : nconf.get('bind_address')); + const args = isSocket ? [socketPath] : [port, bind_address]; + let oldUmask; args.push((err) => { if (err) { @@ -294,8 +294,8 @@ exports.testSocket = function (socketPath, callback) { if (typeof socketPath !== 'string') { return callback(new Error(`invalid socket path : ${socketPath}`)); } - var net = require('net'); - var file = require('./file'); + const net = require('net'); + const file = require('./file'); async.series([ function (next) { file.exists(socketPath, (err, exists) => { @@ -307,7 +307,7 @@ exports.testSocket = function (socketPath, callback) { }); }, function (next) { - var testSocket = new net.Socket(); + const testSocket = new net.Socket(); testSocket.on('error', (err) => { next(err.code !== 'ECONNREFUSED' ? err : null); }); diff --git a/src/widgets/index.js b/src/widgets/index.js index 2c38436144..54cecfac07 100644 --- a/src/widgets/index.js +++ b/src/widgets/index.js @@ -198,7 +198,7 @@ widgets.reset = async function () { widgets.resetTemplate = async function (template) { let toBeDrafted = []; const area = await db.getObject(`widgets:${template}.tpl`); - for (var location in area) { + for (const location in area) { if (area.hasOwnProperty(location)) { toBeDrafted = toBeDrafted.concat(JSON.parse(area[location])); } diff --git a/test/authentication.js b/test/authentication.js index bbe2567d3f..96c353ab61 100644 --- a/test/authentication.js +++ b/test/authentication.js @@ -1,22 +1,22 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var nconf = require('nconf'); -var request = require('request'); +const assert = require('assert'); +const async = require('async'); +const nconf = require('nconf'); +const request = require('request'); const util = require('util'); -var db = require('./mocks/databasemock'); -var user = require('../src/user'); -var utils = require('../src/utils'); -var meta = require('../src/meta'); -var privileges = require('../src/privileges'); -var helpers = require('./helpers'); +const db = require('./mocks/databasemock'); +const user = require('../src/user'); +const utils = require('../src/utils'); +const meta = require('../src/meta'); +const privileges = require('../src/privileges'); +const helpers = require('./helpers'); describe('authentication', () => { function loginUser(username, password, callback) { - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, @@ -44,7 +44,7 @@ describe('authentication', () => { const loginUserPromisified = util.promisify(loginUser); function registerUser(email, username, password, callback) { - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, @@ -73,8 +73,8 @@ describe('authentication', () => { }); } - var jar = request.jar(); - var regularUid; + const jar = request.jar(); + let regularUid; before((done) => { user.create({ username: 'regular', password: 'regularpwd', email: 'regular@nodebb.org' }, (err, uid) => { assert.ifError(err); @@ -225,7 +225,7 @@ describe('authentication', () => { }); it('should revoke all sessions', (done) => { - var socketAdmin = require('../src/socket.io/admin'); + const socketAdmin = require('../src/socket.io/admin'); db.sortedSetCard(`uid:${regularUid}:sessions`, (err, count) => { assert.ifError(err); assert(count); @@ -241,7 +241,7 @@ describe('authentication', () => { }); it('should fail to login if ip address is invalid', (done) => { - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, @@ -319,8 +319,8 @@ describe('authentication', () => { }); it('should fail to login if password is longer than 4096', (done) => { - var longPassword; - for (var i = 0; i < 5000; i++) { + let longPassword; + for (let i = 0; i < 5000; i++) { longPassword += 'a'; } loginUser('someuser', longPassword, (err, response, body) => { @@ -431,7 +431,7 @@ describe('authentication', () => { }); it('should send 200 if not logged in', (done) => { - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, @@ -475,7 +475,7 @@ describe('authentication', () => { assert.equal(body, '[[error:user-banned-reason, spammer]]'); user.bans.unban(bannedUser.uid, (err) => { assert.ifError(err); - var expiry = Date.now() + 10000; + const expiry = Date.now() + 10000; user.bans.ban(bannedUser.uid, expiry, '', (err) => { assert.ifError(err); loginUser(bannedUser.username, bannedUser.pw, (err, res, body) => { @@ -506,7 +506,7 @@ describe('authentication', () => { it('should lockout account on 3 failed login attempts', (done) => { meta.config.loginAttempts = 3; - var uid; + let uid; async.waterfall([ function (next) { user.create({ username: 'lockme', password: '123456' }, next); diff --git a/test/batch.js b/test/batch.js index 6d54431bfb..fe11b72883 100644 --- a/test/batch.js +++ b/test/batch.js @@ -1,11 +1,11 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); +const async = require('async'); +const assert = require('assert'); -var db = require('./mocks/databasemock'); +const db = require('./mocks/databasemock'); -var batch = require('../src/batch'); +const batch = require('../src/batch'); describe('batch', () => { const scores = []; diff --git a/test/blacklist.js b/test/blacklist.js index 19850aeb61..f682ccd16c 100644 --- a/test/blacklist.js +++ b/test/blacklist.js @@ -1,15 +1,15 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); +const async = require('async'); +const assert = require('assert'); -var db = require('./mocks/databasemock'); -var groups = require('../src/groups'); -var user = require('../src/user'); -var blacklist = require('../src/meta/blacklist'); +const db = require('./mocks/databasemock'); +const groups = require('../src/groups'); +const user = require('../src/user'); +const blacklist = require('../src/meta/blacklist'); describe('blacklist', () => { - var adminUid; + let adminUid; before((done) => { user.create({ username: 'admin' }, (err, uid) => { @@ -19,8 +19,8 @@ describe('blacklist', () => { }); }); - var socketBlacklist = require('../src/socket.io/blacklist'); - var rules = '1.1.1.1\n2.2.2.2\n::ffff:0:2.2.2.2\n127.0.0.1\n192.168.100.0/22'; + const socketBlacklist = require('../src/socket.io/blacklist'); + const rules = '1.1.1.1\n2.2.2.2\n::ffff:0:2.2.2.2\n127.0.0.1\n192.168.100.0/22'; it('should validate blacklist', (done) => { socketBlacklist.validate({ uid: adminUid }, { diff --git a/test/build.js b/test/build.js index 02b5e85254..41bc2f24c9 100644 --- a/test/build.js +++ b/test/build.js @@ -1,22 +1,22 @@ 'use strict'; -var path = require('path'); -var fs = require('fs'); -var assert = require('assert'); -var mkdirp = require('mkdirp'); -var rimraf = require('rimraf'); -var async = require('async'); +const path = require('path'); +const fs = require('fs'); +const assert = require('assert'); +const mkdirp = require('mkdirp'); +const rimraf = require('rimraf'); +const async = require('async'); -var db = require('./mocks/databasemock'); -var file = require('../src/file'); +const db = require('./mocks/databasemock'); +const file = require('../src/file'); describe('minifier', () => { before(async () => { await mkdirp(path.join(__dirname, '../build/test')); }); - var minifier = require('../src/meta/minifier'); - var scripts = [ + const minifier = require('../src/meta/minifier'); + const scripts = [ path.resolve(__dirname, './files/1.js'), path.resolve(__dirname, './files/2.js'), ].map(script => ({ @@ -26,7 +26,7 @@ describe('minifier', () => { })); it('.js.bundle() should concat scripts', (done) => { - var destPath = path.resolve(__dirname, '../build/test/concatenated.js'); + const destPath = path.resolve(__dirname, '../build/test/concatenated.js'); minifier.js.bundle({ files: scripts, @@ -54,7 +54,7 @@ describe('minifier', () => { }); }); it('.js.bundle() should minify scripts', (done) => { - var destPath = path.resolve(__dirname, '../build/test/minified.js'); + const destPath = path.resolve(__dirname, '../build/test/minified.js'); minifier.js.bundle({ files: scripts, @@ -93,11 +93,11 @@ describe('minifier', () => { }); }); - var styles = [ + const styles = [ '@import (inline) "./1.css";', '@import "./2.less";', ].join('\n'); - var paths = [ + const paths = [ path.resolve(__dirname, './files'), ]; it('.css.bundle() should concat styles', (done) => { @@ -118,7 +118,7 @@ describe('minifier', () => { }); describe('Build', (done) => { - var build = require('../src/meta/build'); + const build = require('../src/meta/build'); before((done) => { async.parallel([ @@ -138,7 +138,7 @@ describe('Build', (done) => { it('should build requirejs modules', (done) => { build.build(['requirejs modules'], (err) => { assert.ifError(err); - var filename = path.join(__dirname, '../build/public/src/modules/Chart.js'); + const filename = path.join(__dirname, '../build/public/src/modules/Chart.js'); assert(file.existsSync(filename)); assert(fs.readFileSync(filename).toString().startsWith('/*!\n * Chart.js')); done(); @@ -148,7 +148,7 @@ describe('Build', (done) => { it('should build client js bundle', (done) => { build.build(['client js bundle'], (err) => { assert.ifError(err); - var filename = path.join(__dirname, '../build/public/nodebb.min.js'); + const filename = path.join(__dirname, '../build/public/nodebb.min.js'); assert(file.existsSync(filename)); assert(fs.readFileSync(filename).length > 1000); done(); @@ -158,7 +158,7 @@ describe('Build', (done) => { it('should build admin js bundle', (done) => { build.build(['admin js bundle'], (err) => { assert.ifError(err); - var filename = path.join(__dirname, '../build/public/acp.min.js'); + const filename = path.join(__dirname, '../build/public/acp.min.js'); assert(file.existsSync(filename)); assert(fs.readFileSync(filename).length > 1000); done(); @@ -168,7 +168,7 @@ describe('Build', (done) => { it('should build client side styles', (done) => { build.build(['client side styles'], (err) => { assert.ifError(err); - var filename = path.join(__dirname, '../build/public/client.css'); + const filename = path.join(__dirname, '../build/public/client.css'); assert(file.existsSync(filename)); assert(fs.readFileSync(filename).toString().startsWith('/*! normalize.css')); done(); @@ -178,9 +178,9 @@ describe('Build', (done) => { it('should build admin control panel styles', (done) => { build.build(['admin control panel styles'], (err) => { assert.ifError(err); - var filename = path.join(__dirname, '../build/public/admin.css'); + const filename = path.join(__dirname, '../build/public/admin.css'); assert(file.existsSync(filename)); - var adminCSS = fs.readFileSync(filename).toString(); + const adminCSS = fs.readFileSync(filename).toString(); if (global.env === 'production') { assert(adminCSS.startsWith('@charset "UTF-8";') || adminCSS.startsWith('@import url')); } else { @@ -194,7 +194,7 @@ describe('Build', (done) => { this.timeout(0); build.build(['templates'], (err) => { assert.ifError(err); - var filename = path.join(__dirname, '../build/public/templates/admin/header.tpl'); + const filename = path.join(__dirname, '../build/public/templates/admin/header.tpl'); assert(file.existsSync(filename)); assert(fs.readFileSync(filename).toString().startsWith('')); done(); @@ -205,14 +205,14 @@ describe('Build', (done) => { build.build(['languages'], (err) => { assert.ifError(err); - var globalFile = path.join(__dirname, '../build/public/language/en-GB/global.json'); + const globalFile = path.join(__dirname, '../build/public/language/en-GB/global.json'); assert(file.existsSync(globalFile), 'global.json exists'); - var global = fs.readFileSync(globalFile).toString(); + const global = fs.readFileSync(globalFile).toString(); assert.strictEqual(JSON.parse(global).home, 'Home', 'global.json contains correct translations'); - var mdFile = path.join(__dirname, '../build/public/language/en-GB/markdown.json'); + const mdFile = path.join(__dirname, '../build/public/language/en-GB/markdown.json'); assert(file.existsSync(mdFile), 'markdown.json exists'); - var md = fs.readFileSync(mdFile).toString(); + const md = fs.readFileSync(mdFile).toString(); assert.strictEqual(JSON.parse(md).bold, 'bolded text', 'markdown.json contains correct translations'); done(); diff --git a/test/categories.js b/test/categories.js index 2dbe70e65c..b690c7dfb5 100644 --- a/test/categories.js +++ b/test/categories.js @@ -1,22 +1,22 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var nconf = require('nconf'); -var request = require('request'); - -var db = require('./mocks/databasemock'); -var Categories = require('../src/categories'); -var Topics = require('../src/topics'); -var User = require('../src/user'); -var groups = require('../src/groups'); -var privileges = require('../src/privileges'); +const async = require('async'); +const assert = require('assert'); +const nconf = require('nconf'); +const request = require('request'); + +const db = require('./mocks/databasemock'); +const Categories = require('../src/categories'); +const Topics = require('../src/topics'); +const User = require('../src/user'); +const groups = require('../src/groups'); +const privileges = require('../src/privileges'); describe('Categories', () => { - var categoryObj; - var posterUid; - var adminUid; + let categoryObj; + let posterUid; + let adminUid; before((done) => { async.series({ @@ -154,8 +154,8 @@ describe('Categories', () => { }); describe('Categories.moveRecentReplies', () => { - var moveCid; - var moveTid; + let moveCid; + let moveTid; before((done) => { async.parallel({ category: function (next) { @@ -201,7 +201,7 @@ describe('Categories', () => { }); describe('socket methods', () => { - var socketCategories = require('../src/socket.io/categories'); + const socketCategories = require('../src/socket.io/categories'); before((done) => { Topics.post({ @@ -330,8 +330,8 @@ describe('Categories', () => { }); describe('admin socket methods', () => { - var socketCategories = require('../src/socket.io/admin/categories'); - var cid; + const socketCategories = require('../src/socket.io/admin/categories'); + let cid; before((done) => { socketCategories.create({ uid: adminUid }, { name: 'update name', @@ -355,7 +355,7 @@ describe('Categories', () => { }); it('should error if you try to set parent as self', (done) => { - var updateData = {}; + const updateData = {}; updateData[cid] = { parentCid: cid, }; @@ -366,8 +366,8 @@ describe('Categories', () => { }); it('should error if you try to set child as parent', (done) => { - var child1Cid; - var parentCid; + let child1Cid; + let parentCid; async.waterfall([ function (next) { Categories.create({ name: 'parent 1', description: 'poor parent' }, next); @@ -378,7 +378,7 @@ describe('Categories', () => { }, function (category, next) { child1Cid = category.cid; - var updateData = {}; + const updateData = {}; updateData[parentCid] = { parentCid: child1Cid, }; @@ -391,7 +391,7 @@ describe('Categories', () => { }); it('should update category data', (done) => { - var updateData = {}; + const updateData = {}; updateData[cid] = { name: 'new name', description: 'new description', @@ -481,9 +481,9 @@ describe('Categories', () => { }); it('should copy privileges to children', (done) => { - var parentCid; - var child1Cid; - var child2Cid; + let parentCid; + let child1Cid; + let child2Cid; async.waterfall([ function (next) { Categories.create({ name: 'parent' }, next); @@ -514,8 +514,8 @@ describe('Categories', () => { }); it('should create category with settings from', (done) => { - var child1Cid; - var parentCid; + let child1Cid; + let parentCid; async.waterfall([ function (next) { Categories.create({ name: 'copy from', description: 'copy me' }, next); @@ -533,8 +533,8 @@ describe('Categories', () => { }); it('should copy settings from', (done) => { - var child1Cid; - var parentCid; + let child1Cid; + let parentCid; async.waterfall([ function (next) { Categories.create({ name: 'parent', description: 'copy me' }, next); @@ -558,8 +558,8 @@ describe('Categories', () => { }); it('should copy privileges from another category', (done) => { - var child1Cid; - var parentCid; + let child1Cid; + let parentCid; async.waterfall([ function (next) { Categories.create({ name: 'parent', description: 'copy me' }, next); @@ -586,8 +586,8 @@ describe('Categories', () => { }); it('should copy privileges from another category for a single group', (done) => { - var child1Cid; - var parentCid; + let child1Cid; + let parentCid; async.waterfall([ function (next) { Categories.create({ name: 'parent', description: 'copy me' }, next); @@ -636,8 +636,8 @@ describe('Categories', () => { }); describe('tag whitelist', () => { - var cid; - var socketTopics = require('../src/socket.io/topics'); + let cid; + const socketTopics = require('../src/socket.io/topics'); before((done) => { Categories.create({ name: 'test', @@ -664,7 +664,7 @@ describe('Categories', () => { }); it('should add tags to category whitelist', (done) => { - var data = {}; + const data = {}; data[cid] = { tagWhitelist: 'nodebb,jquery,javascript', }; @@ -711,7 +711,7 @@ describe('Categories', () => { describe('privileges', () => { - var privileges = require('../src/privileges'); + const privileges = require('../src/privileges'); it('should return empty array if uids is empty array', (done) => { privileges.categories.filterUids('find', categoryObj.cid, [], (err, uids) => { @@ -884,7 +884,7 @@ describe('Categories', () => { describe('getTopicIds', () => { - var plugins = require('../src/plugins'); + const plugins = require('../src/plugins'); it('should get topic ids with filter', (done) => { function method(data, callback) { data.tids = [1, 2, 3]; diff --git a/test/controllers-admin.js b/test/controllers-admin.js index 61eec1529c..bcc6377245 100644 --- a/test/controllers-admin.js +++ b/test/controllers-admin.js @@ -1,28 +1,28 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var nconf = require('nconf'); -var request = require('request'); - -var db = require('./mocks/databasemock'); -var categories = require('../src/categories'); -var topics = require('../src/topics'); -var user = require('../src/user'); -var groups = require('../src/groups'); -var helpers = require('./helpers'); -var meta = require('../src/meta'); +const async = require('async'); +const assert = require('assert'); +const nconf = require('nconf'); +const request = require('request'); + +const db = require('./mocks/databasemock'); +const categories = require('../src/categories'); +const topics = require('../src/topics'); +const user = require('../src/user'); +const groups = require('../src/groups'); +const helpers = require('./helpers'); +const meta = require('../src/meta'); describe('Admin Controllers', () => { - var tid; - var cid; - var pid; + let tid; + let cid; + let pid; let regularPid; - var adminUid; - var regularUid; + let adminUid; + let regularUid; let regular2Uid; - var moderatorUid; - var jar; + let moderatorUid; + let jar; before((done) => { async.series({ @@ -360,7 +360,7 @@ describe('Admin Controllers', () => { }); it('should load /admin/advanced/logs', (done) => { - var fs = require('fs'); + const fs = require('fs'); fs.appendFile(meta.logs.path, 'dummy log', (err) => { assert.ifError(err); request(`${nconf.get('url')}/api/admin/advanced/logs`, { jar: jar, json: true }, (err, res, body) => { @@ -373,8 +373,8 @@ describe('Admin Controllers', () => { }); it('should load /admin/settings/navigation', (done) => { - var navigation = require('../src/navigation/admin'); - var data = require('../install/data/navigation.json'); + const navigation = require('../src/navigation/admin'); + const data = require('../install/data/navigation.json'); navigation.save(data, (err) => { assert.ifError(err); @@ -470,7 +470,7 @@ describe('Admin Controllers', () => { }); it('should load /admin/settings/social', (done) => { - var socketAdmin = require('../src/socket.io/admin'); + const socketAdmin = require('../src/socket.io/admin'); socketAdmin.social.savePostSharingNetworks({ uid: adminUid }, ['facebook', 'twitter'], (err) => { assert.ifError(err); request(`${nconf.get('url')}/api/admin/settings/social`, { jar: jar, json: true }, (err, res, body) => { @@ -559,7 +559,7 @@ describe('Admin Controllers', () => { }); describe('mods page', () => { - var moderatorJar; + let moderatorJar; before((done) => { helpers.loginUser('moderator', 'modmod', (err, _jar) => { @@ -598,8 +598,8 @@ describe('Admin Controllers', () => { }); it('should error when you attempt to flag a privileged user\'s post', async () => { - var socketFlags = require('../src/socket.io/flags'); - var oldValue = meta.config['min:rep:flag']; + const socketFlags = require('../src/socket.io/flags'); + const oldValue = meta.config['min:rep:flag']; try { await socketFlags.create({ uid: regularUid }, { id: pid, type: 'post', reason: 'spam' }); } catch (err) { @@ -608,8 +608,8 @@ describe('Admin Controllers', () => { }); it('should error with not enough reputation to flag', (done) => { - var socketFlags = require('../src/socket.io/flags'); - var oldValue = meta.config['min:rep:flag']; + const socketFlags = require('../src/socket.io/flags'); + const oldValue = meta.config['min:rep:flag']; meta.config['min:rep:flag'] = 1000; socketFlags.create({ uid: regularUid }, { id: regularPid, type: 'post', reason: 'spam' }, (err) => { assert.strictEqual(err.message, '[[error:not-enough-reputation-to-flag]]'); @@ -619,8 +619,8 @@ describe('Admin Controllers', () => { }); it('should return flag details', (done) => { - var socketFlags = require('../src/socket.io/flags'); - var oldValue = meta.config['min:rep:flag']; + const socketFlags = require('../src/socket.io/flags'); + const oldValue = meta.config['min:rep:flag']; meta.config['min:rep:flag'] = 0; socketFlags.create({ uid: regularUid }, { id: regularPid, type: 'post', reason: 'spam' }, (err, flagId) => { meta.config['min:rep:flag'] = oldValue; @@ -638,7 +638,7 @@ describe('Admin Controllers', () => { }); it('should escape special characters in config', (done) => { - var plugins = require('../src/plugins'); + const plugins = require('../src/plugins'); function onConfigGet(config, callback) { config.someValue = '"foo"'; config.otherValue = "'123'"; diff --git a/test/controllers.js b/test/controllers.js index b4a83db293..3acdf3a089 100644 --- a/test/controllers.js +++ b/test/controllers.js @@ -1,31 +1,31 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var nconf = require('nconf'); -var request = require('request'); -var fs = require('fs'); -var path = require('path'); - -var db = require('./mocks/databasemock'); -var categories = require('../src/categories'); -var topics = require('../src/topics'); -var posts = require('../src/posts'); -var user = require('../src/user'); -var groups = require('../src/groups'); -var meta = require('../src/meta'); -var translator = require('../src/translator'); -var privileges = require('../src/privileges'); -var plugins = require('../src/plugins'); -var utils = require('../src/utils'); -var helpers = require('./helpers'); +const async = require('async'); +const assert = require('assert'); +const nconf = require('nconf'); +const request = require('request'); +const fs = require('fs'); +const path = require('path'); + +const db = require('./mocks/databasemock'); +const categories = require('../src/categories'); +const topics = require('../src/topics'); +const posts = require('../src/posts'); +const user = require('../src/user'); +const groups = require('../src/groups'); +const meta = require('../src/meta'); +const translator = require('../src/translator'); +const privileges = require('../src/privileges'); +const plugins = require('../src/plugins'); +const utils = require('../src/utils'); +const helpers = require('./helpers'); describe('Controllers', () => { - var tid; - var cid; - var pid; - var fooUid; - var category; + let tid; + let cid; + let pid; + let fooUid; + let category; before((done) => { async.series({ @@ -39,8 +39,8 @@ describe('Controllers', () => { user.create({ username: 'foo', password: 'barbar', email: 'foo@test.com' }, next); }, navigation: function (next) { - var navigation = require('../src/navigation/admin'); - var data = require('../install/data/navigation.json'); + const navigation = require('../src/navigation/admin'); + const data = require('../install/data/navigation.json'); navigation.save(data, next); }, @@ -99,9 +99,9 @@ describe('Controllers', () => { works: true, }); } - var message = utils.generateUUID(); - var name = 'mycustompage.tpl'; - var tplPath = path.join(nconf.get('views_dir'), name); + const message = utils.generateUUID(); + const name = 'mycustompage.tpl'; + const tplPath = path.join(nconf.get('views_dir'), name); before(async () => { plugins.hooks.register('myTestPlugin', { @@ -308,14 +308,14 @@ describe('Controllers', () => { method: hookMethod, }); - var data = { + const data = { username: 'interstitial', password: '123456', 'password-confirm': '123456', email: 'test@me.com', }; - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, @@ -729,7 +729,7 @@ describe('Controllers', () => { }); it('should 404 when trying to load group members of hidden group', (done) => { - var groups = require('../src/groups'); + const groups = require('../src/groups'); groups.create({ name: 'hidden-group', description: 'Foobar!', @@ -782,9 +782,9 @@ describe('Controllers', () => { describe('revoke session', () => { - var uid; - var jar; - var csrf_token; + let uid; + let jar; + let csrf_token; before((done) => { user.create({ username: 'revokeme', password: 'barbar' }, (err, _uid) => { @@ -834,7 +834,7 @@ describe('Controllers', () => { it('should revoke user session', (done) => { db.getSortedSetRange(`uid:${uid}:sessions`, 0, -1, (err, sids) => { assert.ifError(err); - var sid = sids[0]; + const sid = sids[0]; db.sessionStore.get(sid, (err, sessionObj) => { assert.ifError(err); @@ -861,7 +861,7 @@ describe('Controllers', () => { }); describe('widgets', () => { - var widgets = require('../src/widgets'); + const widgets = require('../src/widgets'); before((done) => { async.waterfall([ @@ -869,7 +869,7 @@ describe('Controllers', () => { widgets.reset(next); }, function (next) { - var data = { + const data = { template: 'categories.tpl', location: 'sidebar', widgets: [ @@ -900,7 +900,7 @@ describe('Controllers', () => { }); it('should render templates', (done) => { - var url = `${nconf.get('url')}/api/categories`; + const url = `${nconf.get('url')}/api/categories`; request(url, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); @@ -926,7 +926,7 @@ describe('Controllers', () => { }); describe('tags', () => { - var tid; + let tid; before((done) => { topics.post({ uid: fooUid, @@ -1013,7 +1013,7 @@ describe('Controllers', () => { }); describe('account pages', () => { - var jar; + let jar; before((done) => { helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); @@ -1266,8 +1266,8 @@ describe('Controllers', () => { }); it('should load notifications page', (done) => { - var notifications = require('../src/notifications'); - var notifData = { + const notifications = require('../src/notifications'); + const notifData = { bodyShort: '[[notifications:user_posted_to, test1, test2]]', bodyLong: 'some post content', pid: 1, @@ -1294,7 +1294,7 @@ describe('Controllers', () => { function (res, body, next) { assert.equal(res.statusCode, 200); assert(body); - var notif = body.notifications[0]; + const notif = body.notifications[0]; assert.equal(notif.bodyShort, notifData.bodyShort); assert.equal(notif.bodyLong, notifData.bodyLong); assert.equal(notif.pid, notifData.pid); @@ -1472,8 +1472,8 @@ describe('Controllers', () => { }); it('should only return posts that are not deleted', (done) => { - var topicData; - var pidToDelete; + let topicData; + let pidToDelete; async.waterfall([ function (next) { topics.post({ uid: fooUid, title: 'visible', content: 'some content', cid: cid }, next); @@ -1493,7 +1493,7 @@ describe('Controllers', () => { request(`${nconf.get('url')}/api/user/foo`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); - var contents = body.posts.map(p => p.content); + const contents = body.posts.map(p => p.content); assert(!contents.includes('1st reply')); done(); }); @@ -1559,8 +1559,8 @@ describe('Controllers', () => { }); describe('account follow page', () => { - var socketUser = require('../src/socket.io/user'); - var uid; + const socketUser = require('../src/socket.io/user'); + let uid; before((done) => { user.create({ username: 'follower' }, (err, _uid) => { assert.ifError(err); @@ -1608,7 +1608,7 @@ describe('Controllers', () => { }); describe('post redirect', () => { - var jar; + let jar; before((done) => { helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); @@ -1650,7 +1650,7 @@ describe('Controllers', () => { describe('cookie consent', () => { it('should return relevant data in configs API route', (done) => { request(`${nconf.get('url')}/api/config`, (err, res, body) => { - var parsed; + let parsed; assert.ifError(err); assert.equal(res.statusCode, 200); @@ -1674,7 +1674,7 @@ describe('Controllers', () => { assert.ifError(err); request(`${nconf.get('url')}/api/config`, (err, res, body) => { - var parsed; + let parsed; assert.ifError(err); assert.equal(res.statusCode, 200); @@ -1701,7 +1701,7 @@ describe('Controllers', () => { }); describe('handle errors', () => { - var plugins = require('../src/plugins'); + const plugins = require('../src/plugins'); after((done) => { plugins.loadedHooks['filter:router.page'] = undefined; done(); @@ -1747,7 +1747,7 @@ describe('Controllers', () => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { - var err = new Error('csrf-error'); + const err = new Error('csrf-error'); err.code = 'EBADCSRFTOKEN'; next(err); }, @@ -1765,7 +1765,7 @@ describe('Controllers', () => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { - var err = new Error('blacklist error message'); + const err = new Error('blacklist error message'); err.code = 'blacklisted-ip'; next(err); }, @@ -1784,7 +1784,7 @@ describe('Controllers', () => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { - var err = new Error('redirect'); + const err = new Error('redirect'); err.status = 302; err.path = '/popular'; plugins.loadedHooks['filter:router.page'] = []; @@ -1804,7 +1804,7 @@ describe('Controllers', () => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { - var err = new Error('redirect'); + const err = new Error('redirect'); err.status = 308; err.path = '/api/popular'; plugins.loadedHooks['filter:router.page'] = []; @@ -1825,7 +1825,7 @@ describe('Controllers', () => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { - var err = new Error('regular error'); + const err = new Error('regular error'); next(err); }, }); @@ -1868,7 +1868,7 @@ describe('Controllers', () => { }); describe('category', () => { - var jar; + let jar; before((done) => { helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); @@ -2065,9 +2065,9 @@ describe('Controllers', () => { }); it('should get recent topic replies from children categories', (done) => { - var parentCategory; - var childCategory1; - var childCategory2; + let parentCategory; + let childCategory1; + let childCategory2; async.waterfall([ function (next) { @@ -2108,8 +2108,8 @@ describe('Controllers', () => { categories.create({ name: 'category with 2 pages' }, next); }, function (category, next) { - var titles = []; - for (var i = 0; i < 30; i++) { + const titles = []; + for (let i = 0; i < 30; i++) { titles.push(`topic title ${i}`); } @@ -2140,7 +2140,7 @@ describe('Controllers', () => { }); describe('unread', () => { - var jar; + let jar; before((done) => { helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); @@ -2205,8 +2205,8 @@ describe('Controllers', () => { }); describe('composer', () => { - var csrf_token; - var jar; + let csrf_token; + let jar; before((done) => { helpers.loginUser('foo', 'barbar', (err, _jar) => { @@ -2308,7 +2308,7 @@ describe('Controllers', () => { }); it('should create a new topic and reply by composer route', (done) => { - var data = { + const data = { cid: cid, title: 'no js is good', content: 'a topic with noscript', @@ -2341,7 +2341,7 @@ describe('Controllers', () => { }); after((done) => { - var analytics = require('../src/analytics'); + const analytics = require('../src/analytics'); analytics.writeData(done); }); }); diff --git a/test/coverPhoto.js b/test/coverPhoto.js index 498a5d56dd..3b8cc0ce60 100644 --- a/test/coverPhoto.js +++ b/test/coverPhoto.js @@ -1,23 +1,23 @@ 'use strict'; -var assert = require('assert'); -var nconf = require('nconf'); +const assert = require('assert'); +const nconf = require('nconf'); -var db = require('./mocks/databasemock'); -var coverPhoto = require('../src/coverPhoto'); -var meta = require('../src/meta'); +const db = require('./mocks/databasemock'); +const coverPhoto = require('../src/coverPhoto'); +const meta = require('../src/meta'); describe('coverPhoto', () => { it('should get default group cover', (done) => { meta.config['groups:defaultCovers'] = '/assets/image1.png, /assets/image2.png'; - var result = coverPhoto.getDefaultGroupCover('registered-users'); + const result = coverPhoto.getDefaultGroupCover('registered-users'); assert.equal(result, `${nconf.get('relative_path')}/assets/image2.png`); done(); }); it('should get default default profile cover', (done) => { meta.config['profile:defaultCovers'] = ' /assets/image1.png, /assets/image2.png '; - var result = coverPhoto.getDefaultProfileCover(1); + const result = coverPhoto.getDefaultProfileCover(1); assert.equal(result, `${nconf.get('relative_path')}/assets/image2.png`); done(); }); diff --git a/test/database.js b/test/database.js index 0440c7602d..0d3f73b34e 100644 --- a/test/database.js +++ b/test/database.js @@ -1,9 +1,9 @@ 'use strict'; -var assert = require('assert'); -var nconf = require('nconf'); -var db = require('./mocks/databasemock'); +const assert = require('assert'); +const nconf = require('nconf'); +const db = require('./mocks/databasemock'); describe('Test database', () => { @@ -37,7 +37,7 @@ describe('Test database', () => { }); it('should return error with a too low version', (done) => { - var dbName = nconf.get('database'); + const dbName = nconf.get('database'); if (dbName === 'redis') { db.checkCompatibilityVersion('2.4.0', (err) => { assert.equal(err.message, 'Your Redis version is not new enough to support NodeBB, please upgrade Redis to v2.8.9 or higher.'); diff --git a/test/database/hash.js b/test/database/hash.js index c92e42798e..8d46c723b9 100644 --- a/test/database/hash.js +++ b/test/database/hash.js @@ -1,12 +1,12 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var db = require('../mocks/databasemock'); +const async = require('async'); +const assert = require('assert'); +const db = require('../mocks/databasemock'); describe('Hash methods', () => { - var testData = { + const testData = { name: 'baris', lastname: 'usakli', age: 99, diff --git a/test/database/keys.js b/test/database/keys.js index 1d21d2ecd2..ef4afc8857 100644 --- a/test/database/keys.js +++ b/test/database/keys.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var db = require('../mocks/databasemock'); +const async = require('async'); +const assert = require('assert'); +const db = require('../mocks/databasemock'); describe('Key methods', () => { beforeEach((done) => { diff --git a/test/database/list.js b/test/database/list.js index 008dc98384..ae2c8744ad 100644 --- a/test/database/list.js +++ b/test/database/list.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var db = require('../mocks/databasemock'); +const async = require('async'); +const assert = require('assert'); +const db = require('../mocks/databasemock'); describe('List methods', () => { describe('listAppend()', () => { @@ -172,7 +172,7 @@ describe('List methods', () => { describe('listTrim()', () => { it('should trim list to a certain range', (done) => { - var list = ['1', '2', '3', '4', '5']; + const list = ['1', '2', '3', '4', '5']; async.eachSeries(list, (value, next) => { db.listAppend('testList6', value, next); }, (err) => { diff --git a/test/database/sets.js b/test/database/sets.js index 8f2e8d3832..35608c018b 100644 --- a/test/database/sets.js +++ b/test/database/sets.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var db = require('../mocks/databasemock'); +const async = require('async'); +const assert = require('assert'); +const db = require('../mocks/databasemock'); describe('Set methods', () => { describe('setAdd()', () => { diff --git a/test/database/sorted.js b/test/database/sorted.js index 11750aba70..9548b602bd 100644 --- a/test/database/sorted.js +++ b/test/database/sorted.js @@ -1,9 +1,9 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var db = require('../mocks/databasemock'); +const async = require('async'); +const assert = require('assert'); +const db = require('../mocks/databasemock'); describe('Sorted Set methods', () => { before((done) => { diff --git a/test/defer-logger.js b/test/defer-logger.js index 7a07fd1c4a..2340f35a0f 100644 --- a/test/defer-logger.js +++ b/test/defer-logger.js @@ -1,9 +1,9 @@ 'use strict'; -var winston = require('winston'); -var Transport = require('winston-transport'); +const winston = require('winston'); +const Transport = require('winston-transport'); -var winstonLogged = []; +const winstonLogged = []; class DeferLogger extends Transport { constructor(opts) { diff --git a/test/emailer.js b/test/emailer.js index f9412d0769..2cb1b52896 100644 --- a/test/emailer.js +++ b/test/emailer.js @@ -1,28 +1,28 @@ 'use strict'; -var SMTPServer = require('smtp-server').SMTPServer; -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const SMTPServer = require('smtp-server').SMTPServer; +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); -var db = require('./mocks/databasemock'); -var Plugins = require('../src/plugins'); -var Emailer = require('../src/emailer'); -var Meta = require('../src/meta'); +const db = require('./mocks/databasemock'); +const Plugins = require('../src/plugins'); +const Emailer = require('../src/emailer'); +const Meta = require('../src/meta'); describe('emailer', () => { - var onMail = function (address, session, callback) { callback(); }; - var onTo = function (address, session, callback) { callback(); }; + let onMail = function (address, session, callback) { callback(); }; + let onTo = function (address, session, callback) { callback(); }; - var template = 'test'; - var email = 'test@example.org'; - var language = 'en-GB'; - var params = { + const template = 'test'; + const email = 'test@example.org'; + const language = 'en-GB'; + const params = { subject: 'Welcome to NodeBB', }; before((done) => { - var server = new SMTPServer({ + const server = new SMTPServer({ allowInsecureAuth: true, onAuth: function (auth, session, callback) { callback(null, { @@ -46,7 +46,7 @@ describe('emailer', () => { // TODO: test sendmail here at some point it('plugin hook should work', (done) => { - var error = new Error(); + const error = new Error(); Plugins.hooks.register('emailer-test', { hook: 'filter:email.send', @@ -68,7 +68,7 @@ describe('emailer', () => { }); it('should build custom template on config change', (done) => { - var text = 'a random string of text'; + const text = 'a random string of text'; // make sure it's not already set Emailer.renderAndTranslate('test', {}, 'en-GB', (err, output) => { @@ -93,8 +93,8 @@ describe('emailer', () => { }); it('should send via SMTP', (done) => { - var from = 'admin@example.org'; - var username = 'another@example.com'; + const from = 'admin@example.org'; + const username = 'another@example.com'; onMail = function (address, session, callback) { assert.equal(address.address, from); diff --git a/test/feeds.js b/test/feeds.js index 06aa208f6a..3e3780b210 100644 --- a/test/feeds.js +++ b/test/feeds.js @@ -1,24 +1,24 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var request = require('request'); -var nconf = require('nconf'); - -var db = require('./mocks/databasemock'); -var topics = require('../src/topics'); -var categories = require('../src/categories'); -var groups = require('../src/groups'); -var user = require('../src/user'); -var meta = require('../src/meta'); -var privileges = require('../src/privileges'); -var helpers = require('./helpers'); +const assert = require('assert'); +const async = require('async'); +const request = require('request'); +const nconf = require('nconf'); + +const db = require('./mocks/databasemock'); +const topics = require('../src/topics'); +const categories = require('../src/categories'); +const groups = require('../src/groups'); +const user = require('../src/user'); +const meta = require('../src/meta'); +const privileges = require('../src/privileges'); +const helpers = require('./helpers'); describe('feeds', () => { - var tid; - var pid; - var fooUid; - var cid; + let tid; + let pid; + let fooUid; + let cid; before((done) => { meta.config['feeds:disableRSS'] = 1; async.series({ @@ -48,7 +48,7 @@ describe('feeds', () => { it('should 404', (done) => { - var feedUrls = [ + const feedUrls = [ `${nconf.get('url')}/topic/${tid}.rss`, `${nconf.get('url')}/category/${cid}.rss`, `${nconf.get('url')}/topics.rss`, @@ -125,8 +125,8 @@ describe('feeds', () => { }); describe('private feeds and tokens', () => { - var jar; - var rssToken; + let jar; + let rssToken; before((done) => { helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); diff --git a/test/file.js b/test/file.js index 479202d7e8..becd7b44d6 100644 --- a/test/file.js +++ b/test/file.js @@ -1,18 +1,18 @@ 'use strict'; -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var nconf = require('nconf'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const nconf = require('nconf'); -var utils = require('../src/utils'); -var file = require('../src/file'); +const utils = require('../src/utils'); +const file = require('../src/file'); describe('file', () => { - var filename = `${utils.generateUUID()}.png`; - var folder = 'files'; - var uploadPath = path.join(nconf.get('upload_path'), folder, filename); - var tempPath = path.join(__dirname, './files/test.png'); + const filename = `${utils.generateUUID()}.png`; + const folder = 'files'; + const uploadPath = path.join(nconf.get('upload_path'), folder, filename); + const tempPath = path.join(__dirname, './files/test.png'); afterEach((done) => { fs.unlink(uploadPath, () => { @@ -27,8 +27,8 @@ describe('file', () => { assert(file.existsSync(uploadPath)); - var srcContent = fs.readFileSync(tempPath, 'utf8'); - var destContent = fs.readFileSync(uploadPath, 'utf8'); + const srcContent = fs.readFileSync(tempPath, 'utf8'); + const destContent = fs.readFileSync(uploadPath, 'utf8'); assert.strictEqual(srcContent, destContent); done(); @@ -43,8 +43,8 @@ describe('file', () => { assert(file.existsSync(uploadPath)); - var srcContent = fs.readFileSync(tempPath, 'utf8'); - var destContent = fs.readFileSync(uploadPath, 'utf8'); + const srcContent = fs.readFileSync(tempPath, 'utf8'); + const destContent = fs.readFileSync(uploadPath, 'utf8'); assert.strictEqual(srcContent, destContent); done(); @@ -80,8 +80,8 @@ describe('file', () => { assert(file.existsSync(uploadPath)); - var oldFile = fs.readFileSync(tempPath, 'utf8'); - var newFile = fs.readFileSync(uploadPath, 'utf8'); + const oldFile = fs.readFileSync(tempPath, 'utf8'); + const newFile = fs.readFileSync(uploadPath, 'utf8'); assert.strictEqual(oldFile, newFile); done(); diff --git a/test/flags.js b/test/flags.js index 7d197b41ea..f2bf1e5cc0 100644 --- a/test/flags.js +++ b/test/flags.js @@ -47,7 +47,7 @@ describe('Flags', () => { it('should create a flag and return its data', (done) => { Flags.create('post', 1, 1, 'Test flag', (err, flagData) => { assert.ifError(err); - var compare = { + const compare = { flagId: 1, targetId: 1, type: 'post', @@ -55,7 +55,7 @@ describe('Flags', () => { target_readable: 'Post 1', }; assert(flagData); - for (var key in compare) { + for (const key in compare) { if (compare.hasOwnProperty(key)) { assert.ok(flagData[key], `undefined key ${key}`); assert.equal(flagData[key], compare[key]); @@ -123,7 +123,7 @@ describe('Flags', () => { it('should retrieve and display a flag\'s data', (done) => { Flags.get(1, (err, flagData) => { assert.ifError(err); - var compare = { + const compare = { flagId: 1, targetId: 1, type: 'post', @@ -131,7 +131,7 @@ describe('Flags', () => { target_readable: 'Post 1', }; assert(flagData); - for (var key in compare) { + for (const key in compare) { if (compare.hasOwnProperty(key)) { assert.ok(flagData[key], `undefined key ${key}`); assert.equal(flagData[key], compare[key]); @@ -477,13 +477,13 @@ describe('Flags', () => { it('should return a post\'s data if queried with type "post"', (done) => { Flags.getTarget('post', 1, 1, (err, data) => { assert.ifError(err); - var compare = { + const compare = { uid: 1, pid: 1, content: 'This is flaggable content', }; - for (var key in compare) { + for (const key in compare) { if (compare.hasOwnProperty(key)) { assert.ok(data[key]); assert.equal(data[key], compare[key]); @@ -497,13 +497,13 @@ describe('Flags', () => { it('should return a user\'s data if queried with type "user"', (done) => { Flags.getTarget('user', 1, 1, (err, data) => { assert.ifError(err); - var compare = { + const compare = { uid: 1, username: 'testUser', email: 'b@c.com', }; - for (var key in compare) { + for (const key in compare) { if (compare.hasOwnProperty(key)) { assert.ok(data[key]); assert.equal(data[key], compare[key]); @@ -559,9 +559,9 @@ describe('Flags', () => { }); it('should not error if user blocked target', (done) => { - var SocketFlags = require('../src/socket.io/flags.js'); - var reporterUid; - var reporteeUid; + const SocketFlags = require('../src/socket.io/flags.js'); + let reporterUid; + let reporteeUid; async.waterfall([ function (next) { User.create({ username: 'reporter' }, next); @@ -638,13 +638,13 @@ describe('Flags', () => { it('return should match a predefined spec', (done) => { Flags.getNotes(1, (err, notes) => { assert.ifError(err); - var compare = { + const compare = { uid: 1, content: 'this is my note', }; - var data = notes[1]; - for (var key in compare) { + const data = notes[1]; + for (const key in compare) { if (compare.hasOwnProperty(key)) { assert.ok(data[key]); assert.strictEqual(data[key], compare[key]); @@ -666,7 +666,7 @@ describe('Flags', () => { }); describe('.appendHistory()', () => { - var entries; + let entries; before((done) => { db.sortedSetCard('flag:1:history', (err, count) => { entries = count; @@ -704,8 +704,8 @@ describe('Flags', () => { }); describe('(websockets)', () => { - var SocketFlags = require('../src/socket.io/flags.js'); - var pid; + const SocketFlags = require('../src/socket.io/flags.js'); + let pid; before((done) => { Topics.post({ diff --git a/test/groups.js b/test/groups.js index bc591be310..87d6c8fb69 100644 --- a/test/groups.js +++ b/test/groups.js @@ -1,22 +1,22 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var path = require('path'); -var nconf = require('nconf'); +const assert = require('assert'); +const async = require('async'); +const path = require('path'); +const nconf = require('nconf'); -var db = require('./mocks/databasemock'); -var helpers = require('./helpers'); -var Groups = require('../src/groups'); -var User = require('../src/user'); -var socketGroups = require('../src/socket.io/groups'); -var meta = require('../src/meta'); -var navigation = require('../src/navigation/admin'); +const db = require('./mocks/databasemock'); +const helpers = require('./helpers'); +const Groups = require('../src/groups'); +const User = require('../src/user'); +const socketGroups = require('../src/socket.io/groups'); +const meta = require('../src/meta'); +const navigation = require('../src/navigation/admin'); describe('Groups', () => { - var adminUid; - var testUid; + let adminUid; + let testUid; before(async () => { const navData = require('../install/data/navigation.json'); await navigation.save(navData); @@ -113,7 +113,7 @@ describe('Groups', () => { }); describe('.search()', () => { - var socketGroups = require('../src/socket.io/groups'); + const socketGroups = require('../src/socket.io/groups'); it('should return empty array if query is falsy', (done) => { Groups.search(null, {}, (err, groups) => { @@ -663,7 +663,7 @@ describe('Groups', () => { }); it('should add user to multiple groups', (done) => { - var groupNames = ['test-hidden1', 'Test', 'test-hidden2', 'empty group']; + const groupNames = ['test-hidden1', 'Test', 'test-hidden2', 'empty group']; Groups.create({ name: 'empty group' }, (err) => { assert.ifError(err); Groups.join(groupNames, testUid, (err) => { @@ -683,7 +683,7 @@ describe('Groups', () => { }); it('should set group title when user joins the group', (done) => { - var groupName = 'this will be title'; + const groupName = 'this will be title'; User.create({ username: 'needstitle' }, (err, uid) => { assert.ifError(err); Groups.create({ name: groupName }, (err) => { @@ -745,7 +745,7 @@ describe('Groups', () => { Groups.leaveAllGroups(testUid, (err) => { assert.ifError(err); - var groups = ['Test', 'Hidden']; + const groups = ['Test', 'Hidden']; async.every(groups, (group, next) => { Groups.isMember(testUid, group, (err, isMember) => { next(err, !isMember); @@ -946,7 +946,7 @@ describe('Groups', () => { callback(err); }); } - var uids; + let uids; async.waterfall([ function (next) { async.parallel({ @@ -1146,7 +1146,7 @@ describe('Groups', () => { socketGroups.create({ uid: adminUid }, { name: 'createupdategroup' }, (err, groupData) => { assert.ifError(err); assert(groupData); - var data = { + const data = { groupName: 'createupdategroup', values: { name: 'renamedupdategroup', @@ -1182,7 +1182,7 @@ describe('Groups', () => { }); it('should fail to rename guests group', (done) => { - var data = { + const data = { groupName: 'guests', values: { name: 'guests2', @@ -1265,7 +1265,7 @@ describe('Groups', () => { }); describe('admin socket methods', () => { - var socketGroups = require('../src/socket.io/admin/groups'); + const socketGroups = require('../src/socket.io/admin/groups'); it('should fail to create group with invalid data', (done) => { socketGroups.create({ uid: adminUid }, null, (err) => { @@ -1365,7 +1365,7 @@ describe('Groups', () => { }); it('should update group', (done) => { - var data = { + const data = { groupName: 'newgroup', values: { name: 'renamedgroup', @@ -1394,10 +1394,10 @@ describe('Groups', () => { }); describe('groups cover', () => { - var socketGroups = require('../src/socket.io/groups'); - var regularUid; - var logoPath = path.join(__dirname, '../test/files/test.png'); - var imagePath = path.join(__dirname, '../test/files/groupcover.png'); + const socketGroups = require('../src/socket.io/groups'); + let regularUid; + const logoPath = path.join(__dirname, '../test/files/test.png'); + const imagePath = path.join(__dirname, '../test/files/groupcover.png'); before((done) => { User.create({ username: 'regularuser', password: '123456' }, (err, uid) => { assert.ifError(err); @@ -1427,7 +1427,7 @@ describe('Groups', () => { }); it('should upload group cover image from file', (done) => { - var data = { + const data = { groupName: 'Test', file: { path: imagePath, @@ -1450,7 +1450,7 @@ describe('Groups', () => { it('should upload group cover image from data', (done) => { - var data = { + const data = { groupName: 'Test', imageData: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSK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tra2WG+i63iKH53m4rku1WqVcLmNZFu3t7S2x7+/vJ51O89prr7VYfenSpcPAP1UqFeSHH36YeDxOKpW6eP/9988Bv9d09nw+T7VapVKptJjZnE2tVmNtbY1cLke5XGZra4vNzU16enp49tlnGRgYaD7iTxqNxgexWIzDhw+jNEPQHV87NT8/f+PChQtnR0ZGqFarrUVuOsDds2u2b2FhgVQqRSQSYWFhgStXrtDf308ymcwBf3nw4EEOHjx4O5c2lURVVRzHYXp6+t8uX7785IULFz7LZDLous59991HOBy+h31N9xgdHSWTyVCtVhkaGmLfvn1MT08zPz/PzMzM6c8//9xr+uE9QViWZer1OhsbGxiG8fns7OzPc7ncx729vXR3d1OpVNi2bRuhUAhZljEMA9/3sW0bVVVZWlri4sWLjI+P8/rrr/P111/z5JNPXrIs69cn76ZeGoaBpmm0tbX9Q6FQeHhubu7fC4UCkUiE1dVVstks8Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/xZBEHCHred83x/b3Nz8l/X19aRlWWxsbNDZ2cnw8DDhcBjf96lWq/T09HD06FGeeuopXnrpJc6ePUs6nb4hhPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC', }; @@ -1465,7 +1465,7 @@ describe('Groups', () => { }); it('should fail to upload group cover with invalid image', (done) => { - var data = { + const data = { groupName: 'Test', file: { path: imagePath, @@ -1479,7 +1479,7 @@ describe('Groups', () => { }); it('should fail to upload group cover with invalid image', (done) => { - var data = { + const data = { groupName: 'Test', imageData: 'data:image/svg;base64,iVBORw0KGgoAAAANSUhEUgAAABwA', }; @@ -1490,7 +1490,7 @@ describe('Groups', () => { }); it('should update group cover position', (done) => { - var data = { + const data = { groupName: 'Test', position: '50% 50%', }; diff --git a/test/helpers/index.js b/test/helpers/index.js index 4d83e7c0cd..0e38e23c5d 100644 --- a/test/helpers/index.js +++ b/test/helpers/index.js @@ -1,17 +1,17 @@ 'use strict'; -var request = require('request'); +const request = require('request'); const requestAsync = require('request-promise-native'); -var nconf = require('nconf'); -var fs = require('fs'); -var winston = require('winston'); +const nconf = require('nconf'); +const fs = require('fs'); +const winston = require('winston'); -var utils = require('../../public/src/utils'); +const utils = require('../../public/src/utils'); -var helpers = module.exports; +const helpers = module.exports; helpers.loginUser = function (username, password, callback) { - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, @@ -66,11 +66,11 @@ helpers.logoutUser = function (jar, callback) { }; helpers.connectSocketIO = function (res, callback) { - var io = require('socket.io-client'); + const io = require('socket.io-client'); let cookies = res.headers['set-cookie']; cookies = cookies.filter(c => /express.sid=[^;]+;/.test(c)); const cookie = cookies[0]; - var socket = io(nconf.get('base_url'), { + const socket = io(nconf.get('base_url'), { path: `${nconf.get('relative_path')}/socket.io`, extraHeaders: { Origin: nconf.get('url'), @@ -88,7 +88,7 @@ helpers.connectSocketIO = function (res, callback) { }; helpers.uploadFile = function (uploadEndPoint, filePath, body, jar, csrf_token, callback) { - var formData = { + let formData = { files: [ fs.createReadStream(filePath), fs.createReadStream(filePath), // see https://github.com/request/request/issues/2445 @@ -115,7 +115,7 @@ helpers.uploadFile = function (uploadEndPoint, filePath, body, jar, csrf_token, }; helpers.registerUser = function (data, callback) { - var jar = request.jar(); + const jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, @@ -140,13 +140,13 @@ helpers.registerUser = function (data, callback) { // http://stackoverflow.com/a/14387791/583363 helpers.copyFile = function (source, target, callback) { - var cbCalled = false; + let cbCalled = false; - var rd = fs.createReadStream(source); + const rd = fs.createReadStream(source); rd.on('error', (err) => { done(err); }); - var wr = fs.createWriteStream(target); + const wr = fs.createWriteStream(target); wr.on('error', (err) => { done(err); }); diff --git a/test/image.js b/test/image.js index f2c2c06941..0c7d5785a0 100644 --- a/test/image.js +++ b/test/image.js @@ -1,11 +1,11 @@ 'use strict'; -var assert = require('assert'); -var path = require('path'); +const assert = require('assert'); +const path = require('path'); -var db = require('./mocks/databasemock'); -var image = require('../src/image'); -var file = require('../src/file'); +const db = require('./mocks/databasemock'); +const image = require('../src/image'); +const file = require('../src/file'); describe('image', () => { it('should normalise image', (done) => { diff --git a/test/locale-detect.js b/test/locale-detect.js index 5b76d70fdb..3f6bfaf5db 100644 --- a/test/locale-detect.js +++ b/test/locale-detect.js @@ -1,11 +1,11 @@ 'use strict'; -var assert = require('assert'); -var nconf = require('nconf'); -var request = require('request'); +const assert = require('assert'); +const nconf = require('nconf'); +const request = require('request'); -var db = require('./mocks/databasemock'); -var meta = require('../src/meta'); +const db = require('./mocks/databasemock'); +const meta = require('../src/meta'); describe('Language detection', () => { it('should detect the language for a guest', (done) => { diff --git a/test/messaging.js b/test/messaging.js index f5a069ba97..c3223c980e 100644 --- a/test/messaging.js +++ b/test/messaging.js @@ -1,23 +1,23 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var request = require('request'); -var nconf = require('nconf'); - -var db = require('./mocks/databasemock'); -var meta = require('../src/meta'); -var User = require('../src/user'); -var Groups = require('../src/groups'); -var Messaging = require('../src/messaging'); -var helpers = require('./helpers'); -var socketModules = require('../src/socket.io/modules'); +const assert = require('assert'); +const async = require('async'); +const request = require('request'); +const nconf = require('nconf'); + +const db = require('./mocks/databasemock'); +const meta = require('../src/meta'); +const User = require('../src/user'); +const Groups = require('../src/groups'); +const Messaging = require('../src/messaging'); +const helpers = require('./helpers'); +const socketModules = require('../src/socket.io/modules'); describe('Messaging Library', () => { - var fooUid; // the admin - var bazUid; // the user with chat restriction enabled - var herpUid; - var roomId; + let fooUid; // the admin + let bazUid; // the user with chat restriction enabled + let herpUid; + let roomId; before((done) => { // Create 3 users: 1 admin, 2 regular @@ -88,8 +88,8 @@ describe('Messaging Library', () => { }); it('should return rate limit error on second try', (done) => { - var socketMock = { uid: fooUid }; - var oldValue = meta.config.chatMessageDelay; + const socketMock = { uid: fooUid }; + const oldValue = meta.config.chatMessageDelay; meta.config.chatMessageDelay = 1000; socketModules.chats.newRoom(socketMock, { touid: bazUid }, (err) => { assert.ifError(err); @@ -345,8 +345,8 @@ describe('Messaging Library', () => { }); it('should fail to send second message due to rate limit', (done) => { - var socketMock = { uid: fooUid }; - var oldValue = meta.config.chatMessageDelay; + const socketMock = { uid: fooUid }; + const oldValue = meta.config.chatMessageDelay; meta.config.chatMessageDelay = 1000; socketModules.chats.send(socketMock, { roomId: roomId, message: 'first chat message' }, (err) => { assert.ifError(err); @@ -369,7 +369,7 @@ describe('Messaging Library', () => { }); it('should return not allowed error if mid is not in room', (done) => { - var myRoomId; + let myRoomId; User.create({ username: 'dummy' }, (err, uid) => { assert.ifError(err); socketModules.chats.newRoom({ uid: bazUid }, { touid: uid }, (err, _roomId) => { @@ -404,7 +404,7 @@ describe('Messaging Library', () => { User.notifications.get(herpUid, (err, data) => { assert.ifError(err); assert(data.unread[0]); - var notification = data.unread[0]; + const notification = data.unread[0]; assert.equal(notification.bodyShort, '[[notifications:new_message_from, foo]]'); assert.equal(notification.nid, `chat_${fooUid}_${roomId}`); assert.equal(notification.path, `${nconf.get('relative_path')}/chats/${roomId}`); @@ -595,8 +595,8 @@ describe('Messaging Library', () => { }); describe('edit/delete', () => { - var socketModules = require('../src/socket.io/modules'); - var mid; + const socketModules = require('../src/socket.io/modules'); + let mid; let mid2; before(async () => { await socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'baz' }); @@ -682,7 +682,7 @@ describe('Messaging Library', () => { assert.ifError(err); // Reduce messages to their mids - var mids = messages.reduce((mids, cur) => { + const mids = messages.reduce((mids, cur) => { mids.push(cur.messageId); return mids; }, []); @@ -790,7 +790,7 @@ describe('Messaging Library', () => { }); describe('logged in chat controller', () => { - var jar; + let jar; before((done) => { helpers.loginUser('herp', 'derpderp', (err, _jar) => { assert.ifError(err); diff --git a/test/meta.js b/test/meta.js index 82f1e60988..841d7b11ef 100644 --- a/test/meta.js +++ b/test/meta.js @@ -1,19 +1,19 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var request = require('request'); -var nconf = require('nconf'); +const assert = require('assert'); +const async = require('async'); +const request = require('request'); +const nconf = require('nconf'); -var db = require('./mocks/databasemock'); -var meta = require('../src/meta'); -var User = require('../src/user'); -var Groups = require('../src/groups'); +const db = require('./mocks/databasemock'); +const meta = require('../src/meta'); +const User = require('../src/user'); +const Groups = require('../src/groups'); describe('meta', () => { - var fooUid; - var bazUid; - var herpUid; + let fooUid; + let bazUid; + let herpUid; before((done) => { Groups.cache.reset(); @@ -36,7 +36,7 @@ describe('meta', () => { }); describe('settings', () => { - var socketAdmin = require('../src/socket.io/admin'); + const socketAdmin = require('../src/socket.io/admin'); it('it should set setting', (done) => { socketAdmin.settings.set({ uid: fooUid }, { hash: 'some:hash', values: { foo: '1', derp: 'value' } }, (err) => { assert.ifError(err); @@ -187,7 +187,7 @@ describe('meta', () => { describe('config', () => { - var socketAdmin = require('../src/socket.io/admin'); + const socketAdmin = require('../src/socket.io/admin'); before((done) => { db.setObject('config', { minimumTagLength: 3, maximumTagLength: 15 }, done); }); @@ -436,13 +436,13 @@ describe('meta', () => { }); it('should parse json package data', (done) => { - var pkgData = meta.dependencies.parseModuleData('nodebb-plugin-test', '{"a": 1}'); + const pkgData = meta.dependencies.parseModuleData('nodebb-plugin-test', '{"a": 1}'); assert.equal(pkgData.a, 1); done(); }); it('should return null data with invalid json', (done) => { - var pkgData = meta.dependencies.parseModuleData('nodebb-plugin-test', 'asdasd'); + const pkgData = meta.dependencies.parseModuleData('nodebb-plugin-test', 'asdasd'); assert.strictEqual(pkgData, null); done(); }); @@ -464,17 +464,17 @@ describe('meta', () => { }); describe('debugFork', () => { - var oldArgv; + let oldArgv; before(() => { oldArgv = process.execArgv; process.execArgv = ['--debug=5858', '--foo=1']; }); it('should detect debugging', (done) => { - var debugFork = require('../src/meta/debugFork'); + let debugFork = require('../src/meta/debugFork'); assert(!debugFork.debugging); - var debugForkPath = require.resolve('../src/meta/debugFork'); + const debugForkPath = require.resolve('../src/meta/debugFork'); delete require.cache[debugForkPath]; debugFork = require('../src/meta/debugFork'); @@ -490,7 +490,7 @@ describe('meta', () => { describe('Access-Control-Allow-Origin', () => { it('Access-Control-Allow-Origin header should be empty', (done) => { - var jar = request.jar(); + const jar = request.jar(); request.get(`${nconf.get('url')}/api/search?term=bug`, { form: {}, json: true, @@ -503,8 +503,8 @@ describe('meta', () => { }); it('should set proper Access-Control-Allow-Origin header', (done) => { - var jar = request.jar(); - var oldValue = meta.config['access-control-allow-origin']; + const jar = request.jar(); + const oldValue = meta.config['access-control-allow-origin']; meta.config['access-control-allow-origin'] = 'test.com, mydomain.com'; request.get(`${nconf.get('url')}/api/search?term=bug`, { form: { @@ -523,8 +523,8 @@ describe('meta', () => { }); it('Access-Control-Allow-Origin header should be empty if origin does not match', (done) => { - var jar = request.jar(); - var oldValue = meta.config['access-control-allow-origin']; + const jar = request.jar(); + const oldValue = meta.config['access-control-allow-origin']; meta.config['access-control-allow-origin'] = 'test.com, mydomain.com'; request.get(`${nconf.get('url')}/api/search?term=bug`, { form: { @@ -543,8 +543,8 @@ describe('meta', () => { }); it('should set proper Access-Control-Allow-Origin header', (done) => { - var jar = request.jar(); - var oldValue = meta.config['access-control-allow-origin-regex']; + const jar = request.jar(); + const oldValue = meta.config['access-control-allow-origin-regex']; meta.config['access-control-allow-origin-regex'] = 'match\\.this\\..+\\.domain.com, mydomain\\.com'; request.get(`${nconf.get('url')}/api/search?term=bug`, { form: { @@ -563,8 +563,8 @@ describe('meta', () => { }); it('Access-Control-Allow-Origin header should be empty if origin does not match', (done) => { - var jar = request.jar(); - var oldValue = meta.config['access-control-allow-origin-regex']; + const jar = request.jar(); + const oldValue = meta.config['access-control-allow-origin-regex']; meta.config['access-control-allow-origin-regex'] = 'match\\.this\\..+\\.domain.com, mydomain\\.com'; request.get(`${nconf.get('url')}/api/search?term=bug`, { form: { @@ -583,8 +583,8 @@ describe('meta', () => { }); it('should not error with invalid regexp', (done) => { - var jar = request.jar(); - var oldValue = meta.config['access-control-allow-origin-regex']; + const jar = request.jar(); + const oldValue = meta.config['access-control-allow-origin-regex']; meta.config['access-control-allow-origin-regex'] = '[match\\.this\\..+\\.domain.com, mydomain\\.com'; request.get(`${nconf.get('url')}/api/search?term=bug`, { form: { diff --git a/test/notifications.js b/test/notifications.js index c595eeff7c..7de0f93347 100644 --- a/test/notifications.js +++ b/test/notifications.js @@ -1,22 +1,22 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var nconf = require('nconf'); - -var db = require('./mocks/databasemock'); -var meta = require('../src/meta'); -var user = require('../src/user'); -var topics = require('../src/topics'); -var categories = require('../src/categories'); -var groups = require('../src/groups'); -var notifications = require('../src/notifications'); -var socketNotifications = require('../src/socket.io/notifications'); +const assert = require('assert'); +const async = require('async'); +const nconf = require('nconf'); + +const db = require('./mocks/databasemock'); +const meta = require('../src/meta'); +const user = require('../src/user'); +const topics = require('../src/topics'); +const categories = require('../src/categories'); +const groups = require('../src/groups'); +const notifications = require('../src/notifications'); +const socketNotifications = require('../src/socket.io/notifications'); describe('Notifications', () => { - var uid; - var notification; + let uid; + let notification; before((done) => { user.create({ username: 'poster' }, (err, _uid) => { @@ -227,12 +227,12 @@ describe('Notifications', () => { }); it('should link to the first unread post in a watched topic', (done) => { - var categories = require('../src/categories'); - var topics = require('../src/topics'); - var watcherUid; - var cid; - var tid; - var pid; + const categories = require('../src/categories'); + const topics = require('../src/topics'); + let watcherUid; + let cid; + let tid; + let pid; async.waterfall([ function (next) { @@ -343,7 +343,7 @@ describe('Notifications', () => { }); it('should get all notifications and filter', (done) => { - var nid = 'willbefiltered'; + const nid = 'willbefiltered'; notifications.create({ bodyShort: 'bodyShort', nid: nid, @@ -404,7 +404,7 @@ describe('Notifications', () => { }); it('should send notification to followers of user when he posts', (done) => { - var followerUid; + let followerUid; async.waterfall([ function (next) { user.create({ username: 'follower' }, next); @@ -467,7 +467,7 @@ describe('Notifications', () => { assert.ifError(err); notifications.prune((err) => { assert.ifError(err); - var week = 604800000; + const week = 604800000; db.sortedSetAdd('notifications', Date.now() - (2 * week), notification.nid, (err) => { assert.ifError(err); notifications.prune((err) => { diff --git a/test/package-install.js b/test/package-install.js index da0d2f8a1f..3305c2e532 100644 --- a/test/package-install.js +++ b/test/package-install.js @@ -5,7 +5,7 @@ const { execSync } = require('child_process'); const path = require('path'); const { readFileSync } = require('fs'); -var assert = require('assert'); +const assert = require('assert'); describe('Package install', () => { it('should remove non-`nodebb-` modules not specified in `install/package.json`', () => { diff --git a/test/pagination.js b/test/pagination.js index 2952748f62..ef86871014 100644 --- a/test/pagination.js +++ b/test/pagination.js @@ -1,12 +1,12 @@ 'use strict'; -var assert = require('assert'); -var pagination = require('../src/pagination'); +const assert = require('assert'); +const pagination = require('../src/pagination'); describe('Pagination', () => { it('should create empty pagination for 1 page', (done) => { - var data = pagination.create(1, 1); + const data = pagination.create(1, 1); assert.equal(data.pages.length, 0); assert.equal(data.rel.length, 0); assert.equal(data.pageCount, 1); @@ -16,7 +16,7 @@ describe('Pagination', () => { }); it('should create pagination for 10 pages', (done) => { - var data = pagination.create(2, 10); + const data = pagination.create(2, 10); // [1, (2), 3, 4, 5, separator, 9, 10] assert.equal(data.pages.length, 8); assert.equal(data.rel.length, 2); @@ -27,7 +27,7 @@ describe('Pagination', () => { }); it('should create pagination for 3 pages with query params', (done) => { - var data = pagination.create(1, 3, { key: 'value' }); + const data = pagination.create(1, 3, { key: 'value' }); assert.equal(data.pages.length, 3); assert.equal(data.rel.length, 1); assert.equal(data.pageCount, 3); diff --git a/test/plugins.js b/test/plugins.js index 9fed358e77..df90b982ed 100644 --- a/test/plugins.js +++ b/test/plugins.js @@ -1,18 +1,18 @@ 'use strict'; -var assert = require('assert'); -var path = require('path'); -var nconf = require('nconf'); -var request = require('request'); -var fs = require('fs'); +const assert = require('assert'); +const path = require('path'); +const nconf = require('nconf'); +const request = require('request'); +const fs = require('fs'); -var db = require('./mocks/databasemock'); -var plugins = require('../src/plugins'); +const db = require('./mocks/databasemock'); +const plugins = require('../src/plugins'); describe('Plugins', () => { it('should load plugin data', (done) => { - var pluginId = 'nodebb-plugin-markdown'; + const pluginId = 'nodebb-plugin-markdown'; plugins.loadPlugin(path.join(nconf.get('base_dir'), `node_modules/${pluginId}`), (err) => { assert.ifError(err); assert(plugins.libraries[pluginId]); @@ -153,7 +153,7 @@ describe('Plugins', () => { it('should get plugin data from nbbpm', (done) => { plugins.get('nodebb-plugin-markdown', (err, data) => { assert.ifError(err); - var keys = ['id', 'name', 'url', 'description', 'latest', 'installed', 'active', 'latest']; + const keys = ['id', 'name', 'url', 'description', 'latest', 'installed', 'active', 'latest']; assert.equal(data.name, 'nodebb-plugin-markdown'); assert.equal(data.id, 'nodebb-plugin-markdown'); keys.forEach((key) => { @@ -166,7 +166,7 @@ describe('Plugins', () => { it('should get a list of plugins', (done) => { plugins.list((err, data) => { assert.ifError(err); - var keys = ['id', 'name', 'url', 'description', 'latest', 'installed', 'active', 'latest']; + const keys = ['id', 'name', 'url', 'description', 'latest', 'installed', 'active', 'latest']; assert(Array.isArray(data)); keys.forEach((key) => { assert(data[0].hasOwnProperty(key)); @@ -176,12 +176,12 @@ describe('Plugins', () => { }); it('should show installed plugins', (done) => { - var nodeModulesPath = plugins.nodeModulesPath; + const nodeModulesPath = plugins.nodeModulesPath; plugins.nodeModulesPath = path.join(__dirname, './mocks/plugin_modules'); plugins.showInstalled((err, pluginsData) => { assert.ifError(err); - var paths = pluginsData.map(plugin => path.relative(plugins.nodeModulesPath, plugin.path).replace(/\\/g, '/')); + const paths = pluginsData.map(plugin => path.relative(plugins.nodeModulesPath, plugin.path).replace(/\\/g, '/')); assert(paths.indexOf('nodebb-plugin-xyz') > -1); assert(paths.indexOf('@nodebb/nodebb-plugin-abc') > -1); @@ -191,8 +191,8 @@ describe('Plugins', () => { }); describe('install/activate/uninstall', () => { - var latest; - var pluginName = 'nodebb-plugin-imgur'; + let latest; + const pluginName = 'nodebb-plugin-imgur'; it('should install a plugin', function (done) { this.timeout(0); plugins.toggleInstall(pluginName, '1.0.16', (err, pluginData) => { @@ -206,7 +206,7 @@ describe('Plugins', () => { assert.equal(pluginData.active, false); assert.equal(pluginData.installed, true); - var packageFile = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8')); + const packageFile = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8')); assert(packageFile.dependencies[pluginName]); done(); @@ -244,7 +244,7 @@ describe('Plugins', () => { assert.equal(pluginData.installed, false); assert.equal(pluginData.active, false); - var packageFile = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8')); + const packageFile = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8')); assert(!packageFile.dependencies[pluginName]); done(); diff --git a/test/posts.js b/test/posts.js index 1527089217..de431a2b44 100644 --- a/test/posts.js +++ b/test/posts.js @@ -1,33 +1,33 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var request = require('request'); -var nconf = require('nconf'); -var crypto = require('crypto'); -var fs = require('fs'); -var path = require('path'); - -var db = require('./mocks/databasemock'); -var topics = require('../src/topics'); -var posts = require('../src/posts'); -var categories = require('../src/categories'); -var privileges = require('../src/privileges'); -var user = require('../src/user'); -var groups = require('../src/groups'); -var socketPosts = require('../src/socket.io/posts'); -var socketTopics = require('../src/socket.io/topics'); -var meta = require('../src/meta'); -var helpers = require('./helpers'); +const assert = require('assert'); +const async = require('async'); +const request = require('request'); +const nconf = require('nconf'); +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const db = require('./mocks/databasemock'); +const topics = require('../src/topics'); +const posts = require('../src/posts'); +const categories = require('../src/categories'); +const privileges = require('../src/privileges'); +const user = require('../src/user'); +const groups = require('../src/groups'); +const socketPosts = require('../src/socket.io/posts'); +const socketTopics = require('../src/socket.io/topics'); +const meta = require('../src/meta'); +const helpers = require('./helpers'); describe('Post\'s', () => { - var voterUid; - var voteeUid; - var globalModUid; - var postData; - var topicData; - var cid; + let voterUid; + let voteeUid; + let globalModUid; + let postData; + let topicData; + let cid; before((done) => { async.series({ @@ -347,9 +347,9 @@ describe('Post\'s', () => { }); } - var tid; - var mainPid; - var replyPid; + let tid; + let mainPid; + let replyPid; before((done) => { createTopicWithReply((topicPostData, replyData) => { @@ -392,7 +392,7 @@ describe('Post\'s', () => { function (next) { helpers.loginUser('global mod', '123456', (err, _jar) => { assert.ifError(err); - var jar = _jar; + const jar = _jar; request(`${nconf.get('url')}/api/topic/${tid}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); @@ -463,9 +463,9 @@ describe('Post\'s', () => { }); describe('edit', () => { - var pid; - var replyPid; - var tid; + let pid; + let replyPid; + let tid; before((done) => { topics.post({ uid: voterUid, @@ -511,7 +511,7 @@ describe('Post\'s', () => { }); it('should error if title is too long', (done) => { - var longTitle = new Array(meta.config.maximumTitleLength + 2).join('a'); + const longTitle = new Array(meta.config.maximumTitleLength + 2).join('a'); socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', title: longTitle }, (err) => { assert.equal(err.message, `[[error:title-too-long, ${meta.config.maximumTitleLength}]]`); done(); @@ -519,7 +519,7 @@ describe('Post\'s', () => { }); it('should error with too few tags', (done) => { - var oldValue = meta.config.minimumTagsPerTopic; + const oldValue = meta.config.minimumTagsPerTopic; meta.config.minimumTagsPerTopic = 1; socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', tags: [] }, (err) => { assert.equal(err.message, `[[error:not-enough-tags, ${meta.config.minimumTagsPerTopic}]]`); @@ -529,8 +529,8 @@ describe('Post\'s', () => { }); it('should error with too many tags', (done) => { - var tags = []; - for (var i = 0; i < meta.config.maximumTagsPerTopic + 1; i += 1) { + const tags = []; + for (let i = 0; i < meta.config.maximumTagsPerTopic + 1; i += 1) { tags.push(`tag${i}`); } socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', tags: tags }, (err) => { @@ -547,7 +547,7 @@ describe('Post\'s', () => { }); it('should error if content is too long', (done) => { - var longContent = new Array(meta.config.maximumPostLength + 2).join('a'); + const longContent = new Array(meta.config.maximumPostLength + 2).join('a'); socketPosts.edit({ uid: voterUid }, { pid: pid, content: longContent }, (err) => { assert.equal(err.message, `[[error:content-too-long, ${meta.config.maximumPostLength}]]`); done(); @@ -673,9 +673,9 @@ describe('Post\'s', () => { }); describe('move', () => { - var replyPid; - var tid; - var moveTid; + let replyPid; + let tid; + let moveTid; before((done) => { async.waterfall([ @@ -809,9 +809,9 @@ describe('Post\'s', () => { }); it('should store post content in cache', (done) => { - var oldValue = global.env; + const oldValue = global.env; global.env = 'production'; - var postData = { + const postData = { pid: 9999, content: 'some post content', }; @@ -828,7 +828,7 @@ describe('Post\'s', () => { it('should parse signature and remove links and images', (done) => { meta.config['signatures:disableLinks'] = 1; meta.config['signatures:disableImages'] = 1; - var userData = { + const userData = { signature: 'test derp', }; @@ -842,17 +842,17 @@ describe('Post\'s', () => { }); it('should turn relative links in post body to absolute urls', (done) => { - var nconf = require('nconf'); - var content = 'test youtube'; - var parsedContent = posts.relativeToAbsolute(content, posts.urlRegex); + const nconf = require('nconf'); + const content = 'test youtube'; + const parsedContent = posts.relativeToAbsolute(content, posts.urlRegex); assert.equal(parsedContent, `test youtube`); done(); }); it('should turn relative links in post body to absolute urls', (done) => { - var nconf = require('nconf'); - var content = 'test youtube some test '; - var parsedContent = posts.relativeToAbsolute(content, posts.urlRegex); + const nconf = require('nconf'); + const content = 'test youtube some test '; + let parsedContent = posts.relativeToAbsolute(content, posts.urlRegex); parsedContent = posts.relativeToAbsolute(parsedContent, posts.imgRegex); assert.equal(parsedContent, `test youtube some test `); done(); @@ -860,7 +860,7 @@ describe('Post\'s', () => { }); describe('socket methods', () => { - var pid; + let pid; before((done) => { topics.reply({ uid: voterUid, @@ -1053,10 +1053,10 @@ describe('Post\'s', () => { }); describe('post queue', () => { - var uid; - var queueId; - var topicQueueId; - var jar; + let uid; + let queueId; + let topicQueueId; + let jar; before((done) => { meta.config.postQueue = 1; user.create({ username: 'newuser' }, (err, _uid) => { @@ -1169,7 +1169,7 @@ describe('Post\'s', () => { }); it('should accept queued posts and submit', (done) => { - var ids; + let ids; async.waterfall([ function (next) { db.getSortedSetRange('post:queue', 0, -1, next); diff --git a/test/pubsub.js b/test/pubsub.js index 512dd3bd85..cb81b49bf1 100644 --- a/test/pubsub.js +++ b/test/pubsub.js @@ -1,10 +1,10 @@ 'use strict'; -var assert = require('assert'); -var nconf = require('nconf'); +const assert = require('assert'); +const nconf = require('nconf'); -var db = require('./mocks/databasemock'); -var pubsub = require('../src/pubsub'); +const db = require('./mocks/databasemock'); +const pubsub = require('../src/pubsub'); describe('pubsub', () => { it('should use the plain event emitter', (done) => { @@ -29,7 +29,7 @@ describe('pubsub', () => { }); it('should use singleHostCluster', (done) => { - var oldValue = nconf.get('singleHostCluster'); + const oldValue = nconf.get('singleHostCluster'); nconf.set('singleHostCluster', true); pubsub.on('testEvent', (message) => { assert.equal(message.foo, 3); @@ -41,7 +41,7 @@ describe('pubsub', () => { }); it('should use same event emitter', (done) => { - var oldValue = nconf.get('singleHostCluster'); + const oldValue = nconf.get('singleHostCluster'); pubsub.on('dummyEvent', (message) => { assert.equal(message.foo, 4); nconf.set('singleHostCluster', oldValue); diff --git a/test/rewards.js b/test/rewards.js index 5ca090188f..2a6cc0a14b 100644 --- a/test/rewards.js +++ b/test/rewards.js @@ -1,17 +1,17 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); +const assert = require('assert'); +const async = require('async'); -var db = require('./mocks/databasemock'); -var meta = require('../src/meta'); -var User = require('../src/user'); -var Groups = require('../src/groups'); +const db = require('./mocks/databasemock'); +const meta = require('../src/meta'); +const User = require('../src/user'); +const Groups = require('../src/groups'); describe('rewards', () => { - var adminUid; - var bazUid; - var herpUid; + let adminUid; + let bazUid; + let herpUid; before((done) => { // Create 3 users: 1 admin, 2 regular @@ -40,10 +40,10 @@ describe('rewards', () => { }); describe('rewards create', () => { - var socketAdmin = require('../src/socket.io/admin'); - var rewards = require('../src/rewards'); + const socketAdmin = require('../src/socket.io/admin'); + const rewards = require('../src/rewards'); it('it should save a reward', (done) => { - var data = [ + const data = [ { rewards: { groupname: 'Gamers' }, condition: 'essentials/user.postcount', diff --git a/test/search-admin.js b/test/search-admin.js index ec4163c9e1..dff93c9beb 100644 --- a/test/search-admin.js +++ b/test/search-admin.js @@ -1,8 +1,8 @@ 'use strict'; -var assert = require('assert'); -var search = require('../src/admin/search'); +const assert = require('assert'); +const search = require('../src/admin/search'); describe('admin search', () => { describe('filterDirectories', () => { diff --git a/test/search.js b/test/search.js index 880695a4b4..61dbf35901 100644 --- a/test/search.js +++ b/test/search.js @@ -1,30 +1,30 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var request = require('request'); -var nconf = require('nconf'); - -var db = require('./mocks/databasemock'); -var topics = require('../src/topics'); -var categories = require('../src/categories'); -var user = require('../src/user'); -var search = require('../src/search'); -var privileges = require('../src/privileges'); +const assert = require('assert'); +const async = require('async'); +const request = require('request'); +const nconf = require('nconf'); + +const db = require('./mocks/databasemock'); +const topics = require('../src/topics'); +const categories = require('../src/categories'); +const user = require('../src/user'); +const search = require('../src/search'); +const privileges = require('../src/privileges'); describe('Search', () => { - var phoebeUid; - var gingerUid; - - var topic1Data; - var topic2Data; - var post1Data; - var post2Data; - var post3Data; - var cid1; - var cid2; - var cid3; + let phoebeUid; + let gingerUid; + + let topic1Data; + let topic2Data; + let post1Data; + let post2Data; + let post3Data; + let cid1; + let cid2; + let cid3; before((done) => { async.waterfall([ @@ -105,8 +105,8 @@ describe('Search', () => { }); it('should search term in titles and posts', (done) => { - var meta = require('../src/meta'); - var qs = `/api/search?term=cucumber&in=titlesposts&categories[]=${cid1}&by=phoebe&replies=1&repliesFilter=atleast&sortBy=timestamp&sortDirection=desc&showAs=posts`; + const meta = require('../src/meta'); + const qs = `/api/search?term=cucumber&in=titlesposts&categories[]=${cid1}&by=phoebe&replies=1&repliesFilter=atleast&sortBy=timestamp&sortDirection=desc&showAs=posts`; privileges.global.give(['groups:search:content'], 'guests', (err) => { assert.ifError(err); request({ @@ -229,7 +229,7 @@ describe('Search', () => { }); it('should return json search data with no categories', (done) => { - var qs = '/api/search?term=cucumber&in=titlesposts&searchOnly=1'; + const qs = '/api/search?term=cucumber&in=titlesposts&searchOnly=1'; privileges.global.give(['groups:search:content'], 'guests', (err) => { assert.ifError(err); request({ diff --git a/test/settings.js b/test/settings.js index 6f58dd020b..68ac9f8e09 100644 --- a/test/settings.js +++ b/test/settings.js @@ -1,14 +1,14 @@ 'use strict'; -var assert = require('assert'); -var nconf = require('nconf'); +const assert = require('assert'); +const nconf = require('nconf'); -var db = require('./mocks/databasemock'); -var settings = require('../src/settings'); +const db = require('./mocks/databasemock'); +const settings = require('../src/settings'); describe('settings v3', () => { - var settings1; - var settings2; + let settings1; + let settings2; it('should create a new settings object', (done) => { settings1 = new settings('my-plugin', '1.0', { foo: 1, bar: { derp: 2 } }, done); @@ -52,7 +52,7 @@ describe('settings v3', () => { }); it('should get value from default value', (done) => { - var newSettings = new settings('some-plugin', '1.0', { default: { value: 1 } }); + const newSettings = new settings('some-plugin', '1.0', { default: { value: 1 } }); assert.equal(newSettings.get('default.value'), 1); done(); }); diff --git a/test/socket.io.js b/test/socket.io.js index 5b537db991..99258801dd 100644 --- a/test/socket.io.js +++ b/test/socket.io.js @@ -8,29 +8,29 @@ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; const util = require('util'); const sleep = util.promisify(setTimeout); -var assert = require('assert'); -var async = require('async'); -var nconf = require('nconf'); -var request = require('request'); - -var cookies = request.jar(); - -var db = require('./mocks/databasemock'); -var user = require('../src/user'); -var groups = require('../src/groups'); -var categories = require('../src/categories'); -var helpers = require('./helpers'); -var meta = require('../src/meta'); +const assert = require('assert'); +const async = require('async'); +const nconf = require('nconf'); +const request = require('request'); + +const cookies = request.jar(); + +const db = require('./mocks/databasemock'); +const user = require('../src/user'); +const groups = require('../src/groups'); +const categories = require('../src/categories'); +const helpers = require('./helpers'); +const meta = require('../src/meta'); const events = require('../src/events'); -var socketAdmin = require('../src/socket.io/admin'); +const socketAdmin = require('../src/socket.io/admin'); describe('socket.io', () => { - var io; - var cid; - var tid; - var adminUid; - var regularUid; + let io; + let cid; + let tid; + let adminUid; + let regularUid; before((done) => { async.series([ @@ -93,11 +93,11 @@ describe('socket.io', () => { }); it('should get installed themes', (done) => { - var themes = ['nodebb-theme-lavender', 'nodebb-theme-persona', 'nodebb-theme-vanilla']; + const themes = ['nodebb-theme-lavender', 'nodebb-theme-persona', 'nodebb-theme-vanilla']; io.emit('admin.themes.getInstalled', (err, data) => { assert.ifError(err); assert(data); - var installed = data.map(theme => theme.id); + const installed = data.map(theme => theme.id); themes.forEach((theme) => { assert.notEqual(installed.indexOf(theme), -1); }); @@ -135,7 +135,7 @@ describe('socket.io', () => { }); it('should ban a user', (done) => { - var socketUser = require('../src/socket.io/user'); + const socketUser = require('../src/socket.io/user'); socketUser.banUsers({ uid: adminUid }, { uids: [regularUid], reason: 'spammer' }, (err) => { assert.ifError(err); user.getLatestBanInfo(regularUid, (err, data) => { @@ -159,7 +159,7 @@ describe('socket.io', () => { }); it('should unban a user', (done) => { - var socketUser = require('../src/socket.io/user'); + const socketUser = require('../src/socket.io/user'); socketUser.unbanUsers({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); user.bans.isBanned(regularUid, (err, isBanned) => { @@ -239,8 +239,8 @@ describe('socket.io', () => { }); describe('validation emails', () => { - var meta = require('../src/meta'); - var plugins = require('../src/plugins'); + const meta = require('../src/meta'); + const plugins = require('../src/plugins'); async function dummyEmailerHook(data) { // pretend to handle sending emails @@ -292,7 +292,7 @@ describe('socket.io', () => { }); it('should push unread notifications on reconnect', (done) => { - var socketMeta = require('../src/socket.io/meta'); + const socketMeta = require('../src/socket.io/meta'); socketMeta.reconnected({ uid: 1 }, {}, (err) => { assert.ifError(err); done(); @@ -308,7 +308,7 @@ describe('socket.io', () => { }); it('should return if uid is 0', (done) => { - var socketMeta = require('../src/socket.io/meta'); + const socketMeta = require('../src/socket.io/meta'); socketMeta.rooms.enter({ uid: 0 }, null, (err) => { assert.ifError(err); done(); @@ -498,7 +498,7 @@ describe('socket.io', () => { }); it('should order active plugins', (done) => { - var data = [ + const data = [ { name: 'nodebb-theme-persona', order: 0 }, { name: 'nodebb-plugin-dbsearch', order: 1 }, { name: 'nodebb-plugin-markdown', order: 2 }, @@ -530,7 +530,7 @@ describe('socket.io', () => { }); it('should error with invalid data', (done) => { - var data = [{ template: 'global', location: 'sidebar', widgets: [{ widget: 'html', data: { html: 'test', title: 'test', container: '' } }] }]; + const data = [{ template: 'global', location: 'sidebar', widgets: [{ widget: 'html', data: { html: 'test', title: 'test', container: '' } }] }]; socketAdmin.widgets.set({ uid: adminUid }, data, (err) => { assert.ifError(err); db.getObjectField('widgets:global', 'sidebar', (err, widgetData) => { @@ -557,8 +557,8 @@ describe('socket.io', () => { }); it('should get logs', (done) => { - var fs = require('fs'); - var path = require('path'); + const fs = require('fs'); + const path = require('path'); meta.logs.path = path.join(nconf.get('base_dir'), 'test/files', 'output.log'); fs.appendFile(meta.logs.path, 'some logs', (err) => { assert.ifError(err); @@ -619,15 +619,15 @@ describe('socket.io', () => { }); describe('logger', () => { - var logger = require('../src/logger'); - var index = require('../src/socket.io'); - var fs = require('fs'); - var path = require('path'); + const logger = require('../src/logger'); + const index = require('../src/socket.io'); + const fs = require('fs'); + const path = require('path'); it('should enable logging', (done) => { meta.config.loggerStatus = 1; meta.config.loggerIOStatus = 1; - var loggerPath = path.join(__dirname, '..', 'logs', 'logger.log'); + const loggerPath = path.join(__dirname, '..', 'logs', 'logger.log'); logger.monitorConfig({ io: index.server }, { key: 'loggerPath', value: loggerPath }); setTimeout(() => { io.emit('meta.rooms.enter', { enter: 'recent_topics' }, (err) => { diff --git a/test/template-helpers.js b/test/template-helpers.js index 8d10ddba5e..535bdcffe9 100644 --- a/test/template-helpers.js +++ b/test/template-helpers.js @@ -1,20 +1,20 @@ 'use strict'; -var nconf = require('nconf'); -var assert = require('assert'); +const nconf = require('nconf'); +const assert = require('assert'); -var db = require('./mocks/databasemock'); -var helpers = require('../public/src/modules/helpers'); +const db = require('./mocks/databasemock'); +const helpers = require('../public/src/modules/helpers'); describe('helpers', () => { it('should return false if item doesn\'t exist', (done) => { - var flag = helpers.displayMenuItem({ navigation: [] }, 0); + const flag = helpers.displayMenuItem({ navigation: [] }, 0); assert(!flag); done(); }); it('should return false if route is /users and user does not have view:users privilege', (done) => { - var flag = helpers.displayMenuItem({ + const flag = helpers.displayMenuItem({ navigation: [{ route: '/users' }], user: { privileges: { @@ -27,7 +27,7 @@ describe('helpers', () => { }); it('should return false if route is /tags and user does not have view:tags privilege', (done) => { - var flag = helpers.displayMenuItem({ + const flag = helpers.displayMenuItem({ navigation: [{ route: '/tags' }], user: { privileges: { @@ -40,7 +40,7 @@ describe('helpers', () => { }); it('should return false if route is /groups and user does not have view:groups privilege', (done) => { - var flag = helpers.displayMenuItem({ + const flag = helpers.displayMenuItem({ navigation: [{ route: '/groups' }], user: { privileges: { @@ -53,13 +53,13 @@ describe('helpers', () => { }); it('should stringify object', (done) => { - var str = helpers.stringify({ a: 'herp < derp > and & quote "' }); + const str = helpers.stringify({ a: 'herp < derp > and & quote "' }); assert.equal(str, '{"a":"herp < derp > and & quote \\""}'); done(); }); it('should escape html', (done) => { - var str = helpers.escape('gdkfhgk < some > and &'); + const str = helpers.escape('gdkfhgk < some > and &'); assert.equal(str, 'gdkfhgk < some > and &'); done(); }); @@ -70,28 +70,28 @@ describe('helpers', () => { }); it('should generate category background', (done) => { - var category = { + const category = { bgColor: '#ff0000', color: '#00ff00', backgroundImage: '/assets/uploads/image.png', imageClass: 'auto', }; - var bg = helpers.generateCategoryBackground(category); + const bg = helpers.generateCategoryBackground(category); assert.equal(bg, 'background-color: #ff0000; color: #00ff00; background-image: url(/assets/uploads/image.png); background-size: auto;'); done(); }); it('should return empty string if category has no children', (done) => { - var category = { + const category = { children: [], }; - var bg = helpers.generateChildrenCategories(category); + const bg = helpers.generateChildrenCategories(category); assert.equal(bg, ''); done(); }); it('should generate html for children', (done) => { - var category = { + const category = { children: [ { link: '', @@ -101,137 +101,137 @@ describe('helpers', () => { }, ], }; - var html = helpers.generateChildrenCategories(category); + const html = helpers.generateChildrenCategories(category); assert.equal(html, `children`); done(); }); it('should generate topic class', (done) => { - var className = helpers.generateTopicClass({ locked: true, pinned: true, deleted: true, unread: true }); + const className = helpers.generateTopicClass({ locked: true, pinned: true, deleted: true, unread: true }); assert.equal(className, 'locked pinned deleted unread'); done(); }); it('should show leave button if isMember and group is not administrators', (done) => { - var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isMember: true }); + const btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isMember: true }); assert.equal(btn, ''); done(); }); it('should show pending button if isPending and group is not administrators', (done) => { - var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isPending: true }); + const btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isPending: true }); assert.equal(btn, ''); done(); }); it('should show reject invite button if isInvited', (done) => { - var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isInvited: true }); + const btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isInvited: true }); assert.equal(btn, ''); done(); }); it('should show join button if join requests are not disabled and group is not administrators', (done) => { - var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', disableJoinRequests: false }); + const btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', disableJoinRequests: false }); assert.equal(btn, ''); done(); }); it('should show nothing if group is administrators ', (done) => { - var btn = helpers.membershipBtn({ displayName: 'administrators', name: 'administrators' }); + const btn = helpers.membershipBtn({ displayName: 'administrators', name: 'administrators' }); assert.equal(btn, ''); done(); }); it('should spawn privilege states', (done) => { - var privs = { + const privs = { find: true, read: true, }; - var html = helpers.spawnPrivilegeStates('guests', privs); + const html = helpers.spawnPrivilegeStates('guests', privs); assert.equal(html, ''); done(); }); it('should render thumb as topic image', (done) => { - var topicObj = { thumb: '/uploads/1.png', user: { username: 'baris' } }; - var html = helpers.renderTopicImage(topicObj); + const topicObj = { thumb: '/uploads/1.png', user: { username: 'baris' } }; + const html = helpers.renderTopicImage(topicObj); assert.equal(html, ``); done(); }); it('should render user picture as topic image', (done) => { - var topicObj = { thumb: '', user: { uid: 1, username: 'baris', picture: '/uploads/2.png' } }; - var html = helpers.renderTopicImage(topicObj); + const topicObj = { thumb: '', user: { uid: 1, username: 'baris', picture: '/uploads/2.png' } }; + const html = helpers.renderTopicImage(topicObj); assert.equal(html, ``); done(); }); it('should render digest avatar', (done) => { - var block = { teaser: { user: { username: 'baris', picture: '/uploads/1.png' } } }; - var html = helpers.renderDigestAvatar(block); + const block = { teaser: { user: { username: 'baris', picture: '/uploads/1.png' } } }; + const html = helpers.renderDigestAvatar(block); assert.equal(html, ``); done(); }); it('should render digest avatar', (done) => { - var block = { teaser: { user: { username: 'baris', 'icon:text': 'B', 'icon:bgColor': '#ff000' } } }; - var html = helpers.renderDigestAvatar(block); + const block = { teaser: { user: { username: 'baris', 'icon:text': 'B', 'icon:bgColor': '#ff000' } } }; + const html = helpers.renderDigestAvatar(block); assert.equal(html, `
${block.teaser.user['icon:text']}
`); done(); }); it('should render digest avatar', (done) => { - var block = { user: { username: 'baris', picture: '/uploads/1.png' } }; - var html = helpers.renderDigestAvatar(block); + const block = { user: { username: 'baris', picture: '/uploads/1.png' } }; + const html = helpers.renderDigestAvatar(block); assert.equal(html, ``); done(); }); it('should render digest avatar', (done) => { - var block = { user: { username: 'baris', 'icon:text': 'B', 'icon:bgColor': '#ff000' } }; - var html = helpers.renderDigestAvatar(block); + const block = { user: { username: 'baris', 'icon:text': 'B', 'icon:bgColor': '#ff000' } }; + const html = helpers.renderDigestAvatar(block); assert.equal(html, `
${block.user['icon:text']}
`); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'Linux', browser: 'Chrome' }); + const html = helpers.userAgentIcons({ platform: 'Linux', browser: 'Chrome' }); assert.equal(html, ''); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'Microsoft Windows', browser: 'Firefox' }); + const html = helpers.userAgentIcons({ platform: 'Microsoft Windows', browser: 'Firefox' }); assert.equal(html, ''); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'Apple Mac', browser: 'Safari' }); + const html = helpers.userAgentIcons({ platform: 'Apple Mac', browser: 'Safari' }); assert.equal(html, ''); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'Android', browser: 'IE' }); + const html = helpers.userAgentIcons({ platform: 'Android', browser: 'IE' }); assert.equal(html, ''); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'iPad', browser: 'Edge' }); + const html = helpers.userAgentIcons({ platform: 'iPad', browser: 'Edge' }); assert.equal(html, ''); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'iPhone', browser: 'unknow' }); + const html = helpers.userAgentIcons({ platform: 'iPhone', browser: 'unknow' }); assert.equal(html, ''); done(); }); it('shoud render user agent/browser icons', (done) => { - var html = helpers.userAgentIcons({ platform: 'unknow', browser: 'unknown' }); + const html = helpers.userAgentIcons({ platform: 'unknow', browser: 'unknown' }); assert.equal(html, ''); done(); }); diff --git a/test/topicEvents.js b/test/topicEvents.js index d3ec62c730..84cd9701f0 100644 --- a/test/topicEvents.js +++ b/test/topicEvents.js @@ -2,7 +2,7 @@ const assert = require('assert'); -var db = require('./mocks/databasemock'); +const db = require('./mocks/databasemock'); const plugins = require('../src/plugins'); const categories = require('../src/categories'); diff --git a/test/topicThumbs.js b/test/topicThumbs.js index 9b17cecd90..7a7f7e3530 100644 --- a/test/topicThumbs.js +++ b/test/topicThumbs.js @@ -6,7 +6,7 @@ const assert = require('assert'); const nconf = require('nconf'); const request = require('request-promise-native'); -var db = require('./mocks/databasemock'); +const db = require('./mocks/databasemock'); const meta = require('../src/meta'); const user = require('../src/user'); diff --git a/test/topics.js b/test/topics.js index 27a9e84b5d..6d84fee933 100644 --- a/test/topics.js +++ b/test/topics.js @@ -25,11 +25,11 @@ const requestType = util.promisify((type, url, opts, cb) => { }); describe('Topic\'s', () => { - var topic; - var categoryObj; - var adminUid; - var adminJar; - var fooUid; + let topic; + let categoryObj; + let adminUid; + let adminJar; + let fooUid; before(async () => { adminUid = await User.create({ username: 'admin', password: '123456' }); @@ -166,8 +166,8 @@ describe('Topic\'s', () => { }); describe('.reply', () => { - var newTopic; - var newPost; + let newTopic; + let newPost; before((done) => { topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { @@ -261,8 +261,8 @@ describe('Topic\'s', () => { }); describe('Get methods', () => { - var newTopic; - var newPost; + let newTopic; + let newPost; before((done) => { topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { @@ -449,8 +449,8 @@ describe('Topic\'s', () => { describe('Title escaping', () => { it('should properly escape topic title', (done) => { - var title = '" new topic test'; - var titleEscaped = validator.escape(title); + const title = '" new topic test'; + const titleEscaped = validator.escape(title); topics.post({ uid: topic.userId, title: title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); topics.getTopicData(result.topicData.tid, (err, topicData) => { @@ -464,9 +464,9 @@ describe('Topic\'s', () => { }); describe('tools/delete/restore/purge', () => { - var newTopic; - var followerUid; - var moveCid; + let newTopic; + let followerUid; + let moveCid; before((done) => { async.waterfall([ @@ -588,13 +588,13 @@ describe('Topic\'s', () => { }); it('should properly update sets when post is moved', (done) => { - var movedPost; - var previousPost; - var topic2LastReply; - var tid1; - var tid2; - var cid1 = topic.categoryId; - var cid2; + let movedPost; + let previousPost; + let topic2LastReply; + let tid1; + let tid2; + const cid1 = topic.categoryId; + let cid2; function checkCidSets(post1, post2, callback) { async.waterfall([ function (next) { @@ -625,7 +625,7 @@ describe('Topic\'s', () => { }, next); }, function (results, next) { - var assertMsg = `${JSON.stringify(results.posts1)}\n${JSON.stringify(results.posts2)}`; + const assertMsg = `${JSON.stringify(results.posts1)}\n${JSON.stringify(results.posts2)}`; assert.equal(results.topicData[0].postcount, results.scores1[2], assertMsg); assert.equal(results.topicData[1].postcount, results.scores2[2], assertMsg); assert.equal(results.topicData[0].lastposttime, post1.timestamp, assertMsg); @@ -702,8 +702,8 @@ describe('Topic\'s', () => { }); it('should fail to purge topic if user does not have privilege', (done) => { - var globalModUid; - var tid; + let globalModUid; + let tid; async.waterfall([ function (next) { topics.post({ @@ -761,9 +761,9 @@ describe('Topic\'s', () => { }); describe('order pinned topics', () => { - var tid1; - var tid2; - var tid3; + let tid1; + let tid2; + let tid3; before((done) => { function createTopic(callback) { topics.post({ @@ -802,7 +802,7 @@ describe('Topic\'s', () => { }); }); - var socketTopics = require('../src/socket.io/topics'); + const socketTopics = require('../src/socket.io/topics'); it('should error with invalid data', (done) => { socketTopics.orderPinnedTopics({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); @@ -855,9 +855,9 @@ describe('Topic\'s', () => { describe('.ignore', () => { - var newTid; - var uid; - var newTopic; + let newTid; + let uid; + let newTopic; before((done) => { uid = topic.userId; async.waterfall([ @@ -887,8 +887,8 @@ describe('Topic\'s', () => { topics.getUnreadTopics({ cid: 0, uid: uid, start: 0, stop: -1, filter: '' }, done); }, function (results, done) { - var topics = results.topics; - var tids = topics.map(topic => topic.tid); + const topics = results.topics; + const tids = topics.map(topic => topic.tid); assert.equal(tids.indexOf(newTid), -1, 'The topic appeared in the unread list.'); done(); }, @@ -909,9 +909,9 @@ describe('Topic\'s', () => { }, done); }, function (results, done) { - var topics = results.topics; - var topic; - var i; + const topics = results.topics; + let topic; + let i; for (i = 0; i < topics.length; i += 1) { if (topics[i].tid === parseInt(newTid, 10)) { assert.equal(false, topics[i].unread, 'ignored topic was marked as unread in recent list'); @@ -936,8 +936,8 @@ describe('Topic\'s', () => { topics.getUnreadTopics({ cid: 0, uid: uid, start: 0, stop: -1, filter: '' }, done); }, function (results, done) { - var topics = results.topics; - var tids = topics.map(topic => topic.tid); + const topics = results.topics; + const tids = topics.map(topic => topic.tid); assert.notEqual(tids.indexOf(newTid), -1, 'The topic did not appear in the unread list.'); done(); }, @@ -956,8 +956,8 @@ describe('Topic\'s', () => { topics.getUnreadTopics({ cid: 0, uid: uid, start: 0, stop: -1, filter: '' }, done); }, function (results, done) { - var topics = results.topics; - var tids = topics.map(topic => topic.tid); + const topics = results.topics; + const tids = topics.map(topic => topic.tid); assert.notEqual(tids.indexOf(newTid), -1, 'The topic did not appear in the unread list.'); done(); }, @@ -966,10 +966,10 @@ describe('Topic\'s', () => { }); describe('.fork', () => { - var newTopic; - var replies = []; - var topicPids; - var originalBookmark = 6; + let newTopic; + const replies = []; + let topicPids; + const originalBookmark = 6; function postReply(next) { topics.reply({ uid: topic.userId, content: `test post ${replies.length}`, tid: newTopic.tid }, (err, result) => { assert.equal(err, null, 'was created with error'); @@ -1094,7 +1094,7 @@ describe('Topic\'s', () => { }); describe('controller', () => { - var topicData; + let topicData; before((done) => { topics.post({ @@ -1147,7 +1147,7 @@ describe('Topic\'s', () => { }); it('should 401 if not allowed to read as guest', (done) => { - var privileges = require('../src/privileges'); + const privileges = require('../src/privileges'); privileges.categories.rescind(['groups:topics:read'], topicData.cid, 'guests', (err) => { assert.ifError(err); request(`${nconf.get('url')}/api/topic/${topicData.slug}`, (err, response, body) => { @@ -1179,7 +1179,7 @@ describe('Topic\'s', () => { }); it('should 404 if page is out of bounds', (done) => { - var meta = require('../src/meta'); + const meta = require('../src/meta'); meta.config.usePagination = 1; request(`${nconf.get('url')}/topic/${topicData.slug}?page=100`, (err, response) => { assert.ifError(err); @@ -1273,8 +1273,8 @@ describe('Topic\'s', () => { describe('infinitescroll', () => { - var socketTopics = require('../src/socket.io/topics'); - var tid; + const socketTopics = require('../src/socket.io/topics'); + let tid; before((done) => { topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); @@ -1354,8 +1354,8 @@ describe('Topic\'s', () => { }); describe('suggested topics', () => { - var tid1; - var tid3; + let tid1; + let tid3; before((done) => { async.series({ topic1: function (next) { @@ -1393,10 +1393,10 @@ describe('Topic\'s', () => { }); describe('unread', () => { - var socketTopics = require('../src/socket.io/topics'); - var tid; - var mainPid; - var uid; + const socketTopics = require('../src/socket.io/topics'); + let tid; + let mainPid; + let uid; before((done) => { async.parallel({ topic: function (next) { @@ -1586,8 +1586,8 @@ describe('Topic\'s', () => { }); it('should not return topics in category you cant read', (done) => { - var privateCid; - var privateTid; + let privateCid; + let privateTid; async.waterfall([ function (next) { categories.create({ @@ -1615,8 +1615,8 @@ describe('Topic\'s', () => { }); it('should not return topics in category you ignored/not watching', (done) => { - var ignoredCid; - var tid; + let ignoredCid; + let tid; async.waterfall([ function (next) { categories.create({ @@ -1647,8 +1647,8 @@ describe('Topic\'s', () => { }); it('should not return topic as unread if new post is from blocked user', (done) => { - var blockedUid; - var topic; + let blockedUid; + let topic; async.waterfall([ function (next) { topics.post({ uid: adminUid, title: 'will not get as unread', content: 'not unread', cid: categoryObj.cid }, next); @@ -1684,8 +1684,8 @@ describe('Topic\'s', () => { }); describe('tags', () => { - var socketTopics = require('../src/socket.io/topics'); - var socketAdmin = require('../src/socket.io/admin'); + const socketTopics = require('../src/socket.io/topics'); + const socketAdmin = require('../src/socket.io/admin'); before((done) => { async.series([ @@ -1752,7 +1752,7 @@ describe('Topic\'s', () => { assert.ifError(err); assert.equal(data.matchCount, 3); assert.equal(data.pageCount, 1); - var tagData = [ + const tagData = [ { value: 'nodebb', valueEscaped: 'nodebb', color: '', bgColor: '', score: 3 }, { value: 'nodejs', valueEscaped: 'nodejs', color: '', bgColor: '', score: 1 }, { value: 'nosql', valueEscaped: 'nosql', color: '', bgColor: '', score: 1 }, @@ -1885,9 +1885,9 @@ describe('Topic\'s', () => { }); it('should return related topics', (done) => { - var meta = require('../src/meta'); + const meta = require('../src/meta'); meta.config.maximumRelatedTopics = 2; - var topicData = { + const topicData = { tags: [{ value: 'javascript' }], }; topics.getRelatedTopics(topicData, 0, (err, data) => { @@ -2090,9 +2090,9 @@ describe('Topic\'s', () => { }); describe('follow/unfollow', () => { - var socketTopics = require('../src/socket.io/topics'); - var tid; - var followerUid; + const socketTopics = require('../src/socket.io/topics'); + let tid; + let followerUid; before((done) => { User.create({ username: 'follower' }, (err, uid) => { if (err) { @@ -2164,7 +2164,7 @@ describe('Topic\'s', () => { }); it('should return results', (done) => { - var plugins = require('../src/plugins'); + const plugins = require('../src/plugins'); plugins.hooks.register('myTestPlugin', { hook: 'filter:topic.search', method: function (data, callback) { @@ -2188,8 +2188,8 @@ describe('Topic\'s', () => { }); describe('teasers', () => { - var topic1; - var topic2; + let topic1; + let topic2; before((done) => { async.series([ function (next) { @@ -2298,7 +2298,7 @@ describe('Topic\'s', () => { }); it('should not return teaser if user is blocked', (done) => { - var blockedUid; + let blockedUid; async.waterfall([ function (next) { User.create({ username: 'blocked' }, next); @@ -2322,8 +2322,8 @@ describe('Topic\'s', () => { }); describe('tag privilege', () => { - var uid; - var cid; + let uid; + let cid; before((done) => { async.waterfall([ function (next) { @@ -2353,7 +2353,7 @@ describe('Topic\'s', () => { it('should fail to edit if user does not have tag privilege', (done) => { topics.post({ uid: uid, cid: cid, title: 'topic with tags', content: 'some content here' }, (err, result) => { assert.ifError(err); - var pid = result.postData.pid; + const pid = result.postData.pid; posts.edit({ pid: pid, uid: uid, content: 'edited content', tags: ['tag2'] }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); @@ -2368,7 +2368,7 @@ describe('Topic\'s', () => { assert.ifError(err); posts.edit({ pid: result.postData.pid, uid: uid, content: 'edited content', tags: ['tag1', 'tag2'] }, (err, result) => { assert.ifError(err); - var tags = result.topic.tags.map(tag => tag.value); + const tags = result.topic.tags.map(tag => tag.value); assert(tags.includes('tag1')); assert(tags.includes('tag2')); done(); @@ -2379,9 +2379,9 @@ describe('Topic\'s', () => { }); describe('topic merge', () => { - var uid; - var topic1Data; - var topic2Data; + let uid; + let topic1Data; + let topic2Data; async function getTopic(tid) { const topicData = await topics.getTopicData(tid); @@ -2518,7 +2518,7 @@ describe('Topic\'s', () => { describe('sorted topics', () => { it('should get sorted topics in category', (done) => { - var filters = ['', 'watched', 'unreplied', 'new']; + const filters = ['', 'watched', 'unreplied', 'new']; async.map(filters, (filter, next) => { topics.getSortedTopics({ cids: [topic.categoryId], diff --git a/test/translator.js b/test/translator.js index d33b326e15..b3c80eedad 100644 --- a/test/translator.js +++ b/test/translator.js @@ -1,11 +1,11 @@ 'use strict'; -var assert = require('assert'); -var shim = require('../public/src/modules/translator.js'); +const assert = require('assert'); +const shim = require('../public/src/modules/translator.js'); -var Translator = shim.Translator; -var db = require('./mocks/databasemock'); +const Translator = shim.Translator; +const db = require('./mocks/databasemock'); describe('Translator shim', () => { describe('.translate()', () => { @@ -47,7 +47,7 @@ describe('new Translator(language)', () => { describe('.translate()', () => { it('should handle basic translations', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[global:home]]').then((translated) => { assert.strictEqual(translated, 'Home'); @@ -55,7 +55,7 @@ describe('new Translator(language)', () => { }); it('should handle language keys in regular text', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('Let\'s go [[global:home]]').then((translated) => { assert.strictEqual(translated, 'Let\'s go Home'); @@ -63,7 +63,7 @@ describe('new Translator(language)', () => { }); it('should handle language keys in regular text with another language specified', () => { - var translator = Translator.create('de'); + const translator = Translator.create('de'); return translator.translate('[[global:home]] test').then((translated) => { assert.strictEqual(translated, 'Übersicht test'); @@ -71,7 +71,7 @@ describe('new Translator(language)', () => { }); it('should handle language keys with parameters', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[global:pagination.out_of, 1, 5]]').then((translated) => { assert.strictEqual(translated, '1 out of 5'); @@ -79,7 +79,7 @@ describe('new Translator(language)', () => { }); it('should handle language keys inside language keys', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[notifications:outgoing_link_message, [[global:guest]]]]').then((translated) => { assert.strictEqual(translated, 'You are now leaving Guest'); @@ -87,7 +87,7 @@ describe('new Translator(language)', () => { }); it('should handle language keys inside language keys with multiple parameters', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[notifications:user_posted_to, [[global:guest]], My Topic]]').then((translated) => { assert.strictEqual(translated, 'Guest has posted a reply to: My Topic'); @@ -95,7 +95,7 @@ describe('new Translator(language)', () => { }); it('should handle language keys inside language keys with all parameters as language keys', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[notifications:user_posted_to, [[global:guest]], [[global:guest]]]]').then((translated) => { assert.strictEqual(translated, 'Guest has posted a reply to: Guest'); @@ -103,7 +103,7 @@ describe('new Translator(language)', () => { }); it('should properly handle parameters that contain square brackets', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[global:pagination.out_of, [guest], [[global:home]]]]').then((translated) => { assert.strictEqual(translated, '[guest] out of Home'); @@ -111,7 +111,7 @@ describe('new Translator(language)', () => { }); it('should properly handle parameters that contain parentheses', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[global:pagination.out_of, (foobar), [[global:home]]]]').then((translated) => { assert.strictEqual(translated, '(foobar) out of Home'); @@ -119,18 +119,18 @@ describe('new Translator(language)', () => { }); it('should escape language key parameters with HTML in them', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); - var key = '[[global:403.login, test]]'; + const key = '[[global:403.login, test]]'; return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Perhaps you should try logging in?'); }); }); it('should not unescape html in parameters', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); - var key = '[[pages:tag, some&tag]]'; + const key = '[[pages:tag, some&tag]]'; return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Topics tagged under "some&tag"'); }); @@ -138,78 +138,78 @@ describe('new Translator(language)', () => { it('should translate escaped translation arguments properly', () => { // https://github.com/NodeBB/NodeBB/issues/9206 - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); - var key = '[[notifications:upvoted_your_post_in, test1, error: Error: [[error:group-name-too-long]] on NodeBB Upgrade]]'; + const key = '[[notifications:upvoted_your_post_in, test1, error: Error: [[error:group-name-too-long]] on NodeBB Upgrade]]'; return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'test1 has upvoted your post in error: Error: [[error:group-name-too-long]] on NodeBB Upgrade.'); }); }); it('should properly escape and ignore % and \\, in arguments', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); - var title = 'Test 1\\, 2\\, 3 %2 salmon'; - var key = `[[topic:composer.replying_to, ${title}]]`; + const title = 'Test 1\\, 2\\, 3 %2 salmon'; + const key = `[[topic:composer.replying_to, ${title}]]`; return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Replying to Test 1, 2, 3 %2 salmon'); }); }); it('should not escape regular %', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); - var title = '3 % salmon'; - var key = `[[topic:composer.replying_to, ${title}]]`; + const title = '3 % salmon'; + const key = `[[topic:composer.replying_to, ${title}]]`; return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Replying to 3 % salmon'); }); }); it('should not translate [[derp] some text', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[derp] some text').then((translated) => { assert.strictEqual('[[derp] some text', translated); }); }); it('should not translate [[derp]] some text', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[derp]] some text').then((translated) => { assert.strictEqual('[[derp]] some text', translated); }); }); it('should not translate [[derp:xyz] some text', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[derp:xyz] some text').then((translated) => { assert.strictEqual('[[derp:xyz] some text', translated); }); }); it('should translate keys with slashes properly', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[pages:users/latest]]').then((translated) => { assert.strictEqual(translated, 'Latest Users'); }); }); it('should use key for unknown keys without arguments', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[unknown:key.without.args]]').then((translated) => { assert.strictEqual(translated, 'key.without.args'); }); }); it('should use backup for unknown keys with arguments', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('[[unknown:key.with.args, arguments are here, derpity, derp]]').then((translated) => { assert.strictEqual(translated, 'unknown:key.with.args, arguments are here, derpity, derp'); }); }); it('should ignore unclosed tokens', () => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); return translator.translate('here is some stuff and other things [[abc:xyz, other random stuff should be fine here [[global:home]] and more things [[pages:users/latest]]').then((translated) => { assert.strictEqual(translated, 'here is some stuff and other things abc:xyz, other random stuff should be fine here Home and more things Latest Users'); }); @@ -219,20 +219,20 @@ describe('new Translator(language)', () => { describe('Translator.create()', () => { it('should return an instance of Translator', (done) => { - var translator = Translator.create('en-GB'); + const translator = Translator.create('en-GB'); assert(translator instanceof Translator); done(); }); it('should return the same object for the same language', (done) => { - var one = Translator.create('de'); - var two = Translator.create('de'); + const one = Translator.create('de'); + const two = Translator.create('de'); assert.strictEqual(one, two); done(); }); it('should default to defaultLang', (done) => { - var translator = Translator.create(); + const translator = Translator.create(); assert.strictEqual(translator.lang, 'en-GB'); done(); @@ -241,10 +241,10 @@ describe('Translator.create()', () => { describe('Translator modules', () => { it('should work before registered', () => { - var translator = Translator.create(); + const translator = Translator.create(); Translator.registerModule('test-custom-integer-format', lang => function (key, args) { - var num = parseInt(args[0], 10) || 0; + const num = parseInt(args[0], 10) || 0; if (key === 'binary') { return num.toString(2); } @@ -263,7 +263,7 @@ describe('Translator modules', () => { }); it('should work after registered', () => { - var translator = Translator.create('de'); + const translator = Translator.create('de'); return translator.translate('[[test-custom-integer-format:octal, 23]]').then((translation) => { assert.strictEqual(translation, '27'); @@ -275,7 +275,7 @@ describe('Translator modules', () => { assert.ok(lang); }); - var translator = Translator.create('fr_FR'); + const translator = Translator.create('fr_FR'); done(); }); }); diff --git a/test/uploads.js b/test/uploads.js index fd85900a59..9f3177e005 100644 --- a/test/uploads.js +++ b/test/uploads.js @@ -1,29 +1,29 @@ 'use strict'; -var async = require('async'); -var assert = require('assert'); -var nconf = require('nconf'); -var path = require('path'); -var request = require('request'); - -var db = require('./mocks/databasemock'); -var categories = require('../src/categories'); -var topics = require('../src/topics'); -var user = require('../src/user'); -var groups = require('../src/groups'); -var privileges = require('../src/privileges'); -var meta = require('../src/meta'); -var socketUser = require('../src/socket.io/user'); -var helpers = require('./helpers'); -var file = require('../src/file'); -var image = require('../src/image'); +const async = require('async'); +const assert = require('assert'); +const nconf = require('nconf'); +const path = require('path'); +const request = require('request'); + +const db = require('./mocks/databasemock'); +const categories = require('../src/categories'); +const topics = require('../src/topics'); +const user = require('../src/user'); +const groups = require('../src/groups'); +const privileges = require('../src/privileges'); +const meta = require('../src/meta'); +const socketUser = require('../src/socket.io/user'); +const helpers = require('./helpers'); +const file = require('../src/file'); +const image = require('../src/image'); describe('Upload Controllers', () => { - var tid; - var cid; - var pid; - var adminUid; - var regularUid; + let tid; + let cid; + let pid; + let adminUid; + let regularUid; before((done) => { async.series({ @@ -59,8 +59,8 @@ describe('Upload Controllers', () => { }); describe('regular user uploads', () => { - var jar; - var csrf_token; + let jar; + let csrf_token; before((done) => { helpers.loginUser('regular', 'zugzug', (err, _jar, _csrf_token) => { @@ -89,7 +89,7 @@ describe('Upload Controllers', () => { assert(body && body.status && body.response && body.response.images); assert(Array.isArray(body.response.images)); assert(body.response.images[0].url); - var name = body.response.images[0].url.replace(nconf.get('relative_path') + nconf.get('upload_url'), ''); + const name = body.response.images[0].url.replace(nconf.get('relative_path') + nconf.get('upload_url'), ''); socketUser.deleteUpload({ uid: regularUid }, { uid: regularUid, name: name }, (err) => { assert.ifError(err); db.getSortedSetRange(`uid:${regularUid}:uploads`, 0, -1, (err, uploads) => { @@ -116,7 +116,7 @@ describe('Upload Controllers', () => { }); it('should resize and upload an image to a post', (done) => { - var oldValue = meta.config.resizeImageWidth; + const oldValue = meta.config.resizeImageWidth; meta.config.resizeImageWidth = 10; meta.config.resizeImageWidthThreshold = 10; helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { @@ -134,7 +134,7 @@ describe('Upload Controllers', () => { it('should upload a file to a post', (done) => { - var oldValue = meta.config.allowedFileExtensions; + const oldValue = meta.config.allowedFileExtensions; meta.config.allowedFileExtensions = 'png,jpg,bmp,html'; helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/503.html'), {}, jar, csrf_token, (err, res, body) => { meta.config.allowedFileExtensions = oldValue; @@ -271,10 +271,10 @@ describe('Upload Controllers', () => { }); it('should delete users uploads if account is deleted', (done) => { - var jar; - var uid; - var url; - var file = require('../src/file'); + let jar; + let uid; + let url; + const file = require('../src/file'); async.waterfall([ function (next) { @@ -296,7 +296,7 @@ describe('Upload Controllers', () => { user.delete(1, uid, next); }, function (userData, next) { - var filePath = path.join(nconf.get('upload_path'), url.replace('/assets/uploads', '')); + const filePath = path.join(nconf.get('upload_path'), url.replace('/assets/uploads', '')); file.exists(filePath, next); }, function (exists, next) { @@ -308,8 +308,8 @@ describe('Upload Controllers', () => { }); describe('admin uploads', () => { - var jar; - var csrf_token; + let jar; + let csrf_token; before((done) => { helpers.loginUser('admin', 'barbar', (err, _jar, _csrf_token) => { @@ -385,7 +385,7 @@ describe('Upload Controllers', () => { }); it('should upload touch icon', (done) => { - var touchiconAssetPath = '/assets/uploads/system/touchicon-orig.png'; + const touchiconAssetPath = '/assets/uploads/system/touchicon-orig.png'; helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadTouchIcon`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); diff --git a/test/user.js b/test/user.js index bae85e74d7..e87f0923b5 100644 --- a/test/user.js +++ b/test/user.js @@ -1,31 +1,31 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var path = require('path'); -var nconf = require('nconf'); -var request = require('request'); +const assert = require('assert'); +const async = require('async'); +const path = require('path'); +const nconf = require('nconf'); +const request = require('request'); const requestAsync = require('request-promise-native'); -var jwt = require('jsonwebtoken'); - -var db = require('./mocks/databasemock'); -var User = require('../src/user'); -var Topics = require('../src/topics'); -var Categories = require('../src/categories'); -var Posts = require('../src/posts'); -var Password = require('../src/password'); -var groups = require('../src/groups'); -var helpers = require('./helpers'); -var meta = require('../src/meta'); -var plugins = require('../src/plugins'); -var socketUser = require('../src/socket.io/user'); +const jwt = require('jsonwebtoken'); + +const db = require('./mocks/databasemock'); +const User = require('../src/user'); +const Topics = require('../src/topics'); +const Categories = require('../src/categories'); +const Posts = require('../src/posts'); +const Password = require('../src/password'); +const groups = require('../src/groups'); +const helpers = require('./helpers'); +const meta = require('../src/meta'); +const plugins = require('../src/plugins'); +const socketUser = require('../src/socket.io/user'); describe('User', () => { - var userData; - var testUid; - var testCid; + let userData; + let testUid; + let testCid; - var plugins = require('../src/plugins'); + const plugins = require('../src/plugins'); async function dummyEmailerHook(data) { // pretend to handle sending emails @@ -106,8 +106,8 @@ describe('User', () => { }); it('should error with a too long password', (done) => { - var toolong = ''; - for (var i = 0; i < 5000; i++) { + let toolong = ''; + for (let i = 0; i < 5000; i++) { toolong += 'a'; } User.create({ username: 'test', password: toolong }, (err) => { @@ -161,8 +161,8 @@ describe('User', () => { describe('.uniqueUsername()', () => { it('should deal with collisions', (done) => { - var users = []; - for (var i = 0; i < 10; i += 1) { + const users = []; + for (let i = 0; i < 10; i += 1) { users.push({ username: 'Jane Doe', email: `jane.doe${i}@example.com`, @@ -488,7 +488,7 @@ describe('User', () => { }); describe('.delete()', () => { - var uid; + let uid; before((done) => { User.create({ username: 'usertodelete', password: '123456', email: 'delete@me.com' }, (err, newUid) => { assert.ifError(err); @@ -544,8 +544,8 @@ describe('User', () => { }); describe('passwordReset', () => { - var uid; - var code; + let uid; + let code; before((done) => { User.create({ username: 'resetuser', password: '123456', email: 'reset@me.com' }, (err, newUid) => { assert.ifError(err); @@ -613,9 +613,9 @@ describe('User', () => { }); it('.commit() should invalidate old codes', (done) => { - var code1; - var code2; - var uid; + let code1; + let code2; + let uid; async.waterfall([ function (next) { User.create({ username: 'doublereseter', email: 'sorry@forgot.com', password: '123456' }, next); @@ -810,8 +810,8 @@ describe('User', () => { }); describe('profile methods', () => { - var uid; - var jar; + let uid; + let jar; before((done) => { User.create({ username: 'updateprofile', email: 'update@me.com', password: '123456' }, (err, newUid) => { @@ -842,7 +842,7 @@ describe('User', () => { it('should update a user\'s profile', (done) => { User.create({ username: 'justforupdate', email: 'just@for.updated', password: '123456' }, (err, uid) => { assert.ifError(err); - var data = { + const data = { uid: uid, username: 'updatedUserName', email: 'updatedEmail@me.com', @@ -1026,8 +1026,8 @@ describe('User', () => { }); it('should update cover image', (done) => { - var imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEB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ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC'; - var position = '50.0301% 19.2464%'; + const imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTK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VapVKptJjZnE2tVmNtbY1cLke5XGZra4vNzU16enp49tlnGRgYaD7iTxqNxgexWIzDhw+jNEPQHV87NT8/f+PChQtnR0ZGqFarrUVuOsDds2u2b2FhgVQqRSQSYWFhgStXrtDf308ymcwBf3nw4EEOHjx4O5c2lURVVRzHYXp6+t8uX7785IULFz7LZDLous59991HOBy+h31N9xgdHSWTyVCtVhkaGmLfvn1MT08zPz/PzMzM6c8//9xr+uE9QViWZer1OhsbGxiG8fns7OzPc7ncx729vXR3d1OpVNi2bRuhUAhZljEMA9/3sW0bVVVZWlri4sWLjI+P8/rrr/P111/z5JNPXrIs69cn76ZeGoaBpmm0tbX9Q6FQeHhubu7fC4UCkUiE1dVVstks8Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/xZBEHCHred83x/b3Nz8l/X19aRlWWxsbNDZ2cnw8DDhcBjf96lWq/T09HD06FGeeuopXnrpJc6ePUs6nb4hhPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC'; + const position = '50.0301% 19.2464%'; socketUser.updateCover({ uid: uid }, { uid: uid, imageData: imageData, position: position }, (err, result) => { assert.ifError(err); assert(result.url); @@ -1041,7 +1041,7 @@ describe('User', () => { }); it('should upload cropped profile picture', (done) => { - var imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfAC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tra2WG+i63iKH53m4rku1WqVcLmNZFu3t7S2x7+/vJ51O89prr7VYfenSpcPAP1UqFeSHH36YeDxOKpW6eP/9988Bv9d09nw+T7VapVKptJjZnE2tVmNtbY1cLke5XGZra4vNzU16enp49tlnGRgYaD7iTxqNxgexWIzDhw+jNEPQHV87NT8/f+PChQtnR0ZGqFarrUVuOsDds2u2b2FhgVQqRSQSYWFhgStXrtDf308ymcwBf3nw4EEOHjx4O5c2lURVVRzHYXp6+t8uX7785IULFz7LZDLous59991HOBy+h31N9xgdHSWTyVCtVhkaGmLfvn1MT08zPz/PzMzM6c8//9xr+uE9QViWZer1OhsbGxiG8fns7OzPc7ncx729vXR3d1OpVNi2bRuhUAhZljEMA9/3sW0bVVVZWlri4sWLjI+P8/rrr/P111/z5JNPXrIs69cn76ZeGoaBpmm0tbX9Q6FQeHhubu7fC4UCkUiE1dVVstks8Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/xZBEHCHred83x/b3Nz8l/X19aRlWWxsbNDZ2cnw8DDhcBjf96lWq/T09HD06FGeeuopXnrpJc6ePUs6nb4hhPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC'; socketUser.uploadCroppedPicture({ uid: uid }, { uid: uid, imageData: imageData }, (err, result) => { assert.ifError(err); assert(result.url); @@ -1130,7 +1130,7 @@ describe('User', () => { it('should return error if profile image uploads disabled', (done) => { meta.config.allowProfileImageUploads = 0; - var picture = { + const picture = { path: path.join(nconf.get('base_dir'), 'test/files/test_copy.png'), size: 7189, name: 'test.png', @@ -1157,8 +1157,8 @@ describe('User', () => { }); describe('user.uploadCroppedPicture', () => { - var goodImage = 'data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//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bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw=='; it('should error if both file and imageData are missing', (done) => { User.uploadCroppedPicture({}, (err) => { assert.equal('[[error:invalid-data]]', err.message); @@ -1167,7 +1167,7 @@ describe('User', () => { }); it('should error if file size is too big', (done) => { - var temp = meta.config.maximumProfileImageSize; + const temp = meta.config.maximumProfileImageSize; meta.config.maximumProfileImageSize = 1; User.uploadCroppedPicture({ uid: 1, @@ -1433,10 +1433,10 @@ describe('User', () => { }); describe('Digest.getSubscribers', (done) => { - var uidIndex = {}; + const uidIndex = {}; before((done) => { - var testUsers = ['daysub', 'offsub', 'nullsub', 'weeksub']; + const testUsers = ['daysub', 'offsub', 'nullsub', 'weeksub']; async.each(testUsers, (username, next) => { async.waterfall([ async.apply(User.create, { username: username, email: `${username}@example.com` }), @@ -1447,7 +1447,7 @@ describe('User', () => { uidIndex[username] = uid; - var sub = username.slice(0, -3); + const sub = username.slice(0, -3); async.parallel([ async.apply(User.updateDigestSetting, uid, sub), async.apply(User.setSetting, uid, 'dailyDigestFreq', sub), @@ -1514,7 +1514,7 @@ describe('User', () => { }); describe('digests', () => { - var uid; + let uid; before((done) => { async.waterfall([ function (next) { @@ -1653,7 +1653,7 @@ describe('User', () => { }); describe('socket methods', () => { - var socketUser = require('../src/socket.io/user'); + const socketUser = require('../src/socket.io/user'); it('should fail with invalid data', (done) => { socketUser.exists({ uid: testUid }, null, (err) => { @@ -1786,7 +1786,7 @@ describe('User', () => { it('should commit reset', (done) => { db.getObject('reset:uid', (err, data) => { assert.ifError(err); - var code = Object.keys(data).find(code => parseInt(data[code], 10) === parseInt(testUid, 10)); + const code = Object.keys(data).find(code => parseInt(data[code], 10) === parseInt(testUid, 10)); socketUser.reset.commit({ uid: 0 }, { code: code, password: 'pwdchange' }, (err) => { assert.ifError(err); done(); @@ -1795,7 +1795,7 @@ describe('User', () => { }); it('should save user settings', (done) => { - var data = { + const data = { uid: testUid, settings: { bootswatchSkin: 'default', @@ -1825,7 +1825,7 @@ describe('User', () => { }); it('should properly escape homePageRoute', (done) => { - var data = { + const data = { uid: testUid, settings: { bootswatchSkin: 'default', @@ -1856,7 +1856,7 @@ describe('User', () => { it('should error if language is invalid', (done) => { - var data = { + const data = { uid: testUid, settings: { userLang: '', @@ -1871,7 +1871,7 @@ describe('User', () => { }); it('should set moderation note', (done) => { - var adminUid; + let adminUid; async.waterfall([ function (next) { User.create({ username: 'noteadmin' }, next); @@ -1904,8 +1904,8 @@ describe('User', () => { }); describe('approval queue', () => { - var oldRegistrationApprovalType; - var adminUid; + let oldRegistrationApprovalType; + let adminUid; before((done) => { oldRegistrationApprovalType = meta.config.registrationApprovalType; meta.config.registrationApprovalType = 'admin-approval'; @@ -2024,16 +2024,16 @@ describe('User', () => { }); describe('invites', () => { - var notAnInviterUid; - var inviterUid; - var adminUid; + let notAnInviterUid; + let inviterUid; + let adminUid; - var PUBLIC_GROUP = 'publicGroup'; - var PRIVATE_GROUP = 'privateGroup'; - var OWN_PRIVATE_GROUP = 'ownPrivateGroup'; - var HIDDEN_GROUP = 'hiddenGroup'; + const PUBLIC_GROUP = 'publicGroup'; + const PRIVATE_GROUP = 'privateGroup'; + const OWN_PRIVATE_GROUP = 'ownPrivateGroup'; + const HIDDEN_GROUP = 'hiddenGroup'; - var COMMON_PW = '123456'; + const COMMON_PW = '123456'; before((done) => { async.parallel({ @@ -2057,8 +2057,8 @@ describe('User', () => { }); describe('when inviter is not an admin and does not have invite privilege', () => { - var csrf_token; - var jar; + let csrf_token; + let jar; before((done) => { helpers.loginUser('notAnInviter', COMMON_PW, (err, _jar) => { @@ -2093,8 +2093,8 @@ describe('User', () => { }); describe('when inviter has invite privilege', () => { - var csrf_token; - var jar; + let csrf_token; + let jar; before((done) => { helpers.loginUser('inviter', COMMON_PW, (err, _jar) => { @@ -2193,8 +2193,8 @@ describe('User', () => { }); describe('when inviter is an admin', () => { - var csrf_token; - var jar; + let csrf_token; + let jar; before((done) => { helpers.loginUser('adminInvite', COMMON_PW, (err, _jar) => { @@ -2241,10 +2241,10 @@ describe('User', () => { User.getAllInvites((err, data) => { assert.ifError(err); - var adminData = data.filter(d => parseInt(d.uid, 10) === adminUid)[0]; + const adminData = data.filter(d => parseInt(d.uid, 10) === adminUid)[0]; assert.notEqual(adminData.invitations.indexOf('invite99@test.com'), -1); - var inviterData = data.filter(d => parseInt(d.uid, 10) === inviterUid)[0]; + const inviterData = data.filter(d => parseInt(d.uid, 10) === inviterUid)[0]; Array.from(Array(6)).forEach((_, i) => { assert.notEqual(inviterData.invitations.indexOf(`invite${i + 1}@test.com`), -1); }); @@ -2268,7 +2268,7 @@ describe('User', () => { }); it('should verify installation with no errors', (done) => { - var email = 'invite1@test.com'; + const email = 'invite1@test.com'; db.getObjectField(`invitation:email:${email}`, 'token', (err, token) => { assert.ifError(err); User.verifyInvitation({ token: token, email: 'invite1@test.com' }, (err) => { @@ -2286,7 +2286,7 @@ describe('User', () => { }); it('should delete invitation', (done) => { - var socketUser = require('../src/socket.io/user'); + const socketUser = require('../src/socket.io/user'); socketUser.deleteInvitation({ uid: adminUid }, { invitedBy: 'inviter', email: 'invite1@test.com' }, (err) => { assert.ifError(err); db.isSetMember(`invitation:uid:${inviterUid}`, 'invite1@test.com', (err, isMember) => { @@ -2313,9 +2313,9 @@ describe('User', () => { }); it('should joined the groups from invitation after registration', async () => { - var email = 'invite5@test.com'; - var groupsToJoin = [PUBLIC_GROUP, OWN_PRIVATE_GROUP]; - var token = await db.getObjectField(`invitation:email:${email}`, 'token'); + const email = 'invite5@test.com'; + const groupsToJoin = [PUBLIC_GROUP, OWN_PRIVATE_GROUP]; + const token = await db.getObjectField(`invitation:email:${email}`, 'token'); await new Promise((resolve, reject) => { helpers.registerUser({ @@ -2330,8 +2330,8 @@ describe('User', () => { reject(err); } - var memberships = await groups.isMemberOfGroups(body.uid, groupsToJoin); - var joinedToAll = memberships.filter(Boolean); + const memberships = await groups.isMemberOfGroups(body.uid, groupsToJoin); + const joinedToAll = memberships.filter(Boolean); if (joinedToAll.length !== groupsToJoin.length) { reject(new Error('Not joined to the groups')); @@ -2344,8 +2344,8 @@ describe('User', () => { }); describe('invite groups', () => { - var csrf_token; - var jar; + let csrf_token; + let jar; before((done) => { helpers.loginUser('inviter', COMMON_PW, (err, _jar) => { @@ -2466,7 +2466,7 @@ describe('User', () => { }); describe('hideEmail/hideFullname', () => { - var uid; + let uid; after((done) => { meta.config.hideEmail = 0; meta.config.hideFullname = 0; @@ -2709,7 +2709,7 @@ describe('User', () => { describe('status/online', () => { it('should return offline if user is guest', (done) => { - var status = User.getStatus({ uid: 0 }); + const status = User.getStatus({ uid: 0 }); assert.strictEqual(status, 'offline'); done(); }); diff --git a/test/utils.js b/test/utils.js index 4a65508e4c..d765c15e8a 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,21 +1,21 @@ 'use strict'; -var assert = require('assert'); -var JSDOM = require('jsdom').JSDOM; -var utils = require('../public/src/utils.js'); -var slugify = require('../src/slugify'); +const assert = require('assert'); +const JSDOM = require('jsdom').JSDOM; +const utils = require('../public/src/utils.js'); +const slugify = require('../src/slugify'); const db = require('./mocks/databasemock'); describe('Utility Methods', () => { // https://gist.github.com/robballou/9ee108758dc5e0e2d028 // create some jsdom magic to allow jQuery to work - var dom = new JSDOM(''); - var window = dom.window; + const dom = new JSDOM(''); + const window = dom.window; global.window = window; global.jQuery = require('jquery'); global.$ = global.jQuery; - var $ = global.$; + const $ = global.$; require('jquery-deserialize'); require('jquery-serializeobject'); @@ -91,12 +91,12 @@ describe('Utility Methods', () => { describe('username validation', () => { it('accepts latin-1 characters', () => { - var username = "John\"'-. Doeäâèéë1234"; + const username = "John\"'-. Doeäâèéë1234"; assert(utils.isUserNameValid(username), 'invalid username'); }); it('rejects empty string', () => { - var username = ''; + const username = ''; assert.equal(utils.isUserNameValid(username), false, 'accepted as valid username'); }); @@ -113,7 +113,7 @@ describe('Utility Methods', () => { }); it('accepts square brackets', () => { - var username = '[best clan] julian'; + const username = '[best clan] julian'; assert(utils.isUserNameValid(username), 'invalid username'); }); @@ -128,26 +128,26 @@ describe('Utility Methods', () => { describe('email validation', () => { it('accepts sample address', () => { - var email = 'sample@example.com'; + const email = 'sample@example.com'; assert(utils.isEmailValid(email), 'invalid email'); }); it('rejects empty address', () => { - var email = ''; + const email = ''; assert.equal(utils.isEmailValid(email), false, 'accepted as valid email'); }); }); describe('UUID generation', () => { it('return unique random value every time', () => { - var uuid1 = utils.generateUUID(); - var uuid2 = utils.generateUUID(); + const uuid1 = utils.generateUUID(); + const uuid2 = utils.generateUUID(); assert.notEqual(uuid1, uuid2, 'matches'); }); }); describe('cleanUpTag', () => { it('should cleanUp a tag', (done) => { - var cleanedTag = utils.cleanUpTag(',/#!$%^*;TaG1:{}=_`<>\'"~()?|'); + const cleanedTag = utils.cleanUpTag(',/#!$%^*;TaG1:{}=_`<>\'"~()?|'); assert.equal(cleanedTag, 'tag1'); done(); }); @@ -163,7 +163,7 @@ describe('Utility Methods', () => { }); it('should remove punctuation', (done) => { - var removed = utils.removePunctuation('some text with , ! punctuation inside "'); + const removed = utils.removePunctuation('some text with , ! punctuation inside "'); assert.equal(removed, 'some text with punctuation inside '); done(); }); @@ -179,9 +179,9 @@ describe('Utility Methods', () => { }); it('should shallow merge two objects', (done) => { - var a = { foo: 1, cat1: 'ginger' }; - var b = { baz: 2, cat2: 'phoebe' }; - var obj = utils.merge(a, b); + const a = { foo: 1, cat1: 'ginger' }; + const b = { baz: 2, cat2: 'phoebe' }; + const obj = utils.merge(a, b); assert.strictEqual(obj.foo, 1); assert.strictEqual(obj.baz, 2); assert.strictEqual(obj.cat1, 'ginger'); @@ -230,7 +230,7 @@ describe('Utility Methods', () => { }); it('should make numbers human readable on elements', (done) => { - var el = $('
'); + const el = $('
'); utils.makeNumbersHumanReadable(el); assert.equal(el.html(), '100.0k'); done(); @@ -252,15 +252,15 @@ describe('Utility Methods', () => { }); it('should add commas to elements', (done) => { - var el = $('
1000000
'); + const el = $('
1000000
'); utils.addCommasToNumbers(el); assert.equal(el.html(), '1,000,000'); done(); }); it('should return passed in value if invalid', (done) => { - var bigInt = -111111111111111111; - var result = utils.toISOString(bigInt); + const bigInt = -111111111111111111; + const result = utils.toISOString(bigInt); assert.equal(bigInt, result); done(); }); @@ -297,20 +297,20 @@ describe('Utility Methods', () => { }); it('should check if element is in viewport', (done) => { - var el = $('
some text
'); + const el = $('
some text
'); assert(utils.isElementInViewport(el)); done(); }); it('should get empty object for url params', (done) => { global.document = window.document; - var params = utils.params(); + const params = utils.params(); assert.equal(Object.keys(params), 0); done(); }); it('should get url params', (done) => { - var params = utils.params({ url: 'http://nodebb.org?foo=1&bar=test&herp=2' }); + const params = utils.params({ url: 'http://nodebb.org?foo=1&bar=test&herp=2' }); assert.equal(params.foo, 1); assert.equal(params.bar, 'test'); assert.equal(params.herp, 2); @@ -345,20 +345,20 @@ describe('Utility Methods', () => { }); it('should parse json', (done) => { - var data = utils.toType('{"a":"1"}'); + const data = utils.toType('{"a":"1"}'); assert.equal(data.a, '1'); done(); }); it('should return string as is if its not json,true,false or number', (done) => { - var regularStr = 'this is a regular string'; + const regularStr = 'this is a regular string'; assert.equal(regularStr, utils.toType(regularStr)); done(); }); }); describe('utils.props', () => { - var data = {}; + const data = {}; it('should set nested data', (done) => { assert.equal(10, utils.props(data, 'a.b.c.d', 10)); @@ -366,7 +366,7 @@ describe('Utility Methods', () => { }); it('should return nested object', (done) => { - var obj = utils.props(data, 'a.b.c'); + const obj = utils.props(data, 'a.b.c'); assert.equal(obj.d, 10); done(); }); @@ -383,8 +383,8 @@ describe('Utility Methods', () => { }); describe('isInternalURI', () => { - var target = { host: '', protocol: 'https' }; - var reference = { host: '', protocol: 'https' }; + const target = { host: '', protocol: 'https' }; + const reference = { host: '', protocol: 'https' }; it('should return true if they match', (done) => { assert(utils.isInternalURI(target, reference, '')); @@ -413,23 +413,23 @@ describe('Utility Methods', () => { }); it('escape html', (done) => { - var escaped = utils.escapeHTML('&<>'); + const escaped = utils.escapeHTML('&<>'); assert.equal(escaped, '&<>'); done(); }); it('should escape regex chars', (done) => { - var escaped = utils.escapeRegexChars('some text {}'); + const escaped = utils.escapeRegexChars('some text {}'); assert.equal(escaped, 'some\\ text\\ \\{\\}'); done(); }); it('should get hours array', (done) => { - var currentHour = new Date().getHours(); - var hours = utils.getHoursArray(); - var index = hours.length - 1; - for (var i = currentHour, ii = currentHour - 24; i > ii; i -= 1) { - var hour = i < 0 ? 24 + i : i; + const currentHour = new Date().getHours(); + const hours = utils.getHoursArray(); + let index = hours.length - 1; + for (let i = currentHour, ii = currentHour - 24; i > ii; i -= 1) { + const hour = i < 0 ? 24 + i : i; assert.equal(hours[index], `${hour}:00`); index -= 1; } @@ -437,12 +437,12 @@ describe('Utility Methods', () => { }); it('should get days array', (done) => { - var currentDay = new Date(Date.now()).getTime(); - var days = utils.getDaysArray(); - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var index = 0; - for (var x = 29; x >= 0; x -= 1) { - var tmpDate = new Date(currentDay - (1000 * 60 * 60 * 24 * x)); + const currentDay = new Date(Date.now()).getTime(); + const days = utils.getDaysArray(); + const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + let index = 0; + for (let x = 29; x >= 0; x -= 1) { + const tmpDate = new Date(currentDay - (1000 * 60 * 60 * 24 * x)); assert.equal(`${months[tmpDate.getMonth()]} ${tmpDate.getDate()}`, days[index]); index += 1; } @@ -457,7 +457,7 @@ describe('Utility Methods', () => { }); it('should profile function', (done) => { - var st = process.hrtime(); + const st = process.hrtime(); setTimeout(() => { process.profile('it took', st); done();