From dab3b23575002c361d5a97a2a0b6245740d55133 Mon Sep 17 00:00:00 2001
From: Peter Jaszkowiak
Date: Thu, 4 Feb 2021 00:06:15 -0700
Subject: [PATCH] chore: eslint no-var, vars-on-top
---
.eslintrc | 2 -
Gruntfile.js | 10 +-
install/databases.js | 2 +-
install/web.js | 20 +--
loader.js | 62 +++----
src/admin/search.js | 4 +-
src/api/helpers.js | 2 +-
src/api/topics.js | 2 +-
src/categories/delete.js | 16 +-
src/categories/recentreplies.js | 1 -
src/categories/update.js | 4 +-
src/cli/colors.js | 44 ++---
src/cli/running.js | 2 +-
src/cli/setup.js | 6 +-
src/cli/upgrade.js | 24 +--
src/controllers/accounts.js | 2 +-
src/controllers/accounts/helpers.js | 2 +-
src/controllers/accounts/profile.js | 2 +-
src/controllers/accounts/settings.js | 4 +-
src/controllers/admin.js | 2 +-
src/controllers/admin/uploads.js | 12 +-
src/controllers/admin/users.js | 2 +-
src/controllers/authentication.js | 10 +-
src/controllers/errors.js | 22 +--
src/controllers/helpers.js | 2 +-
src/controllers/home.js | 2 +-
src/database/index.js | 6 +-
src/database/mongo/connection.js | 14 +-
src/database/mongo/hash.js | 8 +-
src/database/mongo/helpers.js | 4 +-
src/database/mongo/list.js | 2 +-
src/database/mongo/main.js | 4 +-
src/database/mongo/sets.js | 16 +-
src/database/mongo/sorted.js | 28 +--
src/database/mongo/sorted/add.js | 14 +-
src/database/mongo/sorted/remove.js | 6 +-
src/database/mongo/sorted/union.js | 8 +-
src/database/postgres.js | 6 +-
src/database/postgres/connection.js | 2 +-
src/database/postgres/hash.js | 4 +-
src/database/postgres/helpers.js | 12 +-
src/database/postgres/list.js | 2 +-
src/database/postgres/sets.js | 4 +-
src/database/postgres/sorted.js | 26 +--
src/database/postgres/sorted/add.js | 4 +-
src/database/postgres/sorted/intersect.js | 12 +-
src/database/postgres/sorted/remove.js | 2 +-
src/database/postgres/sorted/union.js | 12 +-
src/database/redis/hash.js | 2 +-
src/database/redis/helpers.js | 4 +-
src/database/redis/main.js | 2 +-
src/database/redis/pubsub.js | 2 +-
src/database/redis/sets.js | 6 +-
src/database/redis/sorted.js | 16 +-
src/database/redis/sorted/add.js | 10 +-
src/database/redis/sorted/intersect.js | 22 +--
src/database/redis/sorted/remove.js | 4 +-
src/database/redis/sorted/union.js | 10 +-
src/flags.js | 4 +-
src/groups/index.js | 4 +-
src/install.js | 6 +-
src/logger.js | 28 +--
src/messaging/data.js | 4 +-
src/messaging/index.js | 4 +-
src/messaging/rooms.js | 14 +-
src/messaging/unread.js | 4 +-
src/meta/aliases.js | 6 +-
src/meta/blacklist.js | 28 ++-
src/meta/build.js | 2 +-
src/meta/configs.js | 2 +-
src/meta/debugFork.js | 10 +-
src/meta/index.js | 6 +-
src/meta/languages.js | 6 +-
src/meta/minifier.js | 18 +-
src/meta/tags.js | 10 +-
src/meta/templates.js | 14 +-
src/meta/themes.js | 8 +-
src/middleware/admin.js | 38 ++--
src/middleware/index.js | 52 +++---
src/notifications.js | 12 +-
src/pagination.js | 20 +--
src/plugins/data.js | 8 +-
src/plugins/hooks.js | 2 +-
src/plugins/index.js | 14 +-
src/plugins/load.js | 2 +-
src/posts/create.js | 18 +-
src/posts/parse.js | 22 +--
src/posts/summary.js | 4 +-
src/posts/topics.js | 4 +-
src/prestart.js | 16 +-
src/privileges/helpers.js | 4 +-
src/privileges/index.js | 2 +-
src/privileges/posts.js | 6 +-
src/pubsub.js | 12 +-
src/routes/accounts.js | 8 +-
src/routes/api.js | 12 +-
src/routes/authentication.js | 24 +--
src/routes/debug.js | 6 +-
src/routes/feeds.js | 2 +-
src/routes/index.js | 48 +++---
src/routes/write/topics.js | 4 +-
src/search.js | 2 +-
src/settings.js | 44 ++---
src/sitemap.js | 2 +-
src/socket.io/admin/rooms.js | 22 +--
src/socket.io/groups.js | 2 +-
src/socket.io/index.js | 4 +-
src/socket.io/meta.js | 6 +-
src/socket.io/plugins.js | 2 +-
src/socket.io/posts.js | 2 +-
src/socket.io/posts/tools.js | 4 +-
src/socket.io/single-host-cluster.js | 4 +-
src/topics/bookmarks.js | 10 +-
src/topics/create.js | 6 +-
src/topics/data.js | 10 +-
src/topics/delete.js | 20 +--
src/topics/index.js | 24 +--
src/topics/posts.js | 28 +--
src/topics/suggested.js | 6 +-
src/topics/teaser.js | 26 +--
src/topics/user.js | 2 +-
src/upgrade.js | 6 +-
src/upgrades/1.0.0/chat_room_hashes.js | 6 +-
src/upgrades/1.0.0/chat_upgrade.js | 30 ++--
src/upgrades/1.0.0/global_moderators.js | 4 +-
src/upgrades/1.0.0/social_post_sharing.js | 6 +-
src/upgrades/1.0.0/theme_to_active_plugins.js | 4 +-
src/upgrades/1.0.0/user_best_posts.js | 10 +-
src/upgrades/1.0.0/users_notvalidated.js | 10 +-
.../1.1.0/assign_topic_read_privilege.js | 14 +-
.../dismiss_flags_from_deleted_topics.js | 18 +-
src/upgrades/1.1.0/group_title_update.js | 12 +-
.../1.1.0/separate_upvote_downvote.js | 16 +-
src/upgrades/1.1.0/user_post_count_per_tid.js | 12 +-
.../1.1.1/remove_negative_best_posts.js | 8 +-
src/upgrades/1.1.1/upload_privileges.js | 8 +-
.../1.10.0/hash_recent_ip_addresses.js | 12 +-
src/upgrades/1.10.0/post_history_privilege.js | 6 +-
src/upgrades/1.10.0/search_privileges.js | 12 +-
src/upgrades/1.10.0/view_deleted_privilege.js | 6 +-
src/upgrades/1.10.2/event_filters.js | 6 +-
.../1.10.2/fix_category_post_zsets.js | 18 +-
.../1.10.2/fix_category_topic_zsets.js | 8 +-
src/upgrades/1.10.2/local_login_privileges.js | 6 +-
src/upgrades/1.10.2/postgres_sessions.js | 4 +-
src/upgrades/1.10.2/upgrade_bans_to_hashes.js | 8 +-
src/upgrades/1.10.2/username_email_history.js | 8 +-
.../1.11.0/navigation_visibility_groups.js | 2 +-
src/upgrades/1.11.0/resize_image_width.js | 4 +-
.../1.11.0/widget_visibility_groups.js | 2 +-
.../1.11.1/remove_ignored_cids_per_user.js | 4 +-
src/upgrades/1.12.0/category_watch_state.js | 8 +-
src/upgrades/1.12.0/global_view_privileges.js | 8 +-
src/upgrades/1.12.0/group_create_privilege.js | 4 +-
.../1.12.1/clear_username_email_history.js | 2 +-
.../1.12.1/moderation_notes_refactor.js | 10 +-
src/upgrades/1.12.1/post_upload_sizes.js | 2 +-
.../1.12.3/give_mod_info_privilege.js | 8 +-
src/upgrades/1.12.3/give_mod_privileges.js | 10 +-
.../1.12.3/update_registration_type.js | 2 +-
src/upgrades/1.2.0/category_recent_tids.js | 4 +-
.../edit_delete_deletetopic_privileges.js | 14 +-
src/upgrades/1.3.0/favourites_to_bookmarks.js | 10 +-
.../1.3.0/sorted_sets_for_post_replies.js | 12 +-
.../1.4.0/global_and_user_language_keys.js | 12 +-
.../1.4.0/sorted_set_for_pinned_topics.js | 10 +-
src/upgrades/1.4.4/config_urls_update.js | 8 +-
src/upgrades/1.4.4/sound_settings.js | 16 +-
src/upgrades/1.4.6/delete_sessions.js | 18 +-
src/upgrades/1.5.0/allowed_file_extensions.js | 2 +-
src/upgrades/1.5.0/flags_refactor.js | 20 +--
.../1.5.0/moderation_history_refactor.js | 10 +-
src/upgrades/1.5.0/post_votes_zset.js | 8 +-
.../remove_relative_uploaded_profile_cover.js | 10 +-
src/upgrades/1.5.1/rename_mods_group.js | 14 +-
src/upgrades/1.5.2/rss_token_wipe.js | 8 +-
src/upgrades/1.5.2/tags_privilege.js | 8 +-
.../1.6.0/clear-stale-digest-template.js | 10 +-
src/upgrades/1.6.0/generate-email-logo.js | 18 +-
src/upgrades/1.6.0/ipblacklist-fix.js | 6 +-
src/upgrades/1.6.0/robots-config-change.js | 4 +-
.../1.6.2/topics_lastposttime_zset.js | 8 +-
src/upgrades/1.7.0/generate-custom-html.js | 10 +-
src/upgrades/1.7.1/notification-settings.js | 10 +-
src/upgrades/1.7.3/key_value_schema_change.js | 16 +-
src/upgrades/1.7.3/topic_votes.js | 18 +-
src/upgrades/1.7.4/chat_privilege.js | 2 +-
.../1.7.4/fix_moved_topics_byvotes.js | 16 +-
.../1.7.4/fix_user_topics_per_category.js | 10 +-
src/upgrades/1.7.4/global_upload_privilege.js | 12 +-
.../1.7.4/rename_min_reputation_settings.js | 2 +-
src/upgrades/1.7.4/vote_privilege.js | 6 +-
src/upgrades/1.7.6/flatten_navigation_data.js | 12 +-
src/upgrades/1.7.6/notification_types.js | 8 +-
.../1.7.6/update_min_pass_strength.js | 4 +-
.../1.8.0/give_signature_privileges.js | 2 +-
src/upgrades/1.8.0/give_spiders_privileges.js | 12 +-
src/upgrades/1.8.1/diffs_zset_to_listhash.js | 6 +-
.../1.9.0/refresh_post_upload_associations.js | 6 +-
src/user/digest.js | 2 +-
src/user/follow.js | 4 +-
src/user/info.js | 12 +-
src/user/invite.js | 20 +--
src/user/jobs.js | 16 +-
src/user/jobs/export-profile.js | 2 +-
src/user/notifications.js | 22 +--
src/user/online.js | 8 +-
src/user/password.js | 2 +-
src/user/reset.js | 2 +-
src/webserver.js | 90 +++++-----
src/widgets/index.js | 2 +-
test/authentication.js | 42 ++---
test/batch.js | 8 +-
test/blacklist.js | 18 +-
test/build.js | 52 +++---
test/categories.js | 80 ++++-----
test/controllers-admin.js | 62 +++----
test/controllers.js | 138 +++++++--------
test/coverPhoto.js | 14 +-
test/database.js | 8 +-
test/database/hash.js | 8 +-
test/database/keys.js | 6 +-
test/database/list.js | 8 +-
test/database/sets.js | 6 +-
test/database/sorted.js | 6 +-
test/defer-logger.js | 6 +-
test/emailer.js | 38 ++--
test/feeds.js | 40 ++---
test/file.js | 32 ++--
test/flags.js | 34 ++--
test/groups.js | 62 +++----
test/helpers/index.js | 28 +--
test/image.js | 10 +-
test/locale-detect.js | 10 +-
test/messaging.js | 52 +++---
test/meta.js | 58 +++----
test/notifications.js | 46 ++---
test/package-install.js | 2 +-
test/pagination.js | 10 +-
test/plugins.js | 32 ++--
test/posts.js | 110 ++++++------
test/pubsub.js | 12 +-
test/rewards.js | 24 +--
test/search-admin.js | 4 +-
test/search.js | 50 +++---
test/settings.js | 14 +-
test/socket.io.js | 72 ++++----
test/template-helpers.js | 86 +++++-----
test/topicEvents.js | 2 +-
test/topicThumbs.js | 2 +-
test/topics.js | 162 +++++++++---------
test/translator.js | 80 ++++-----
test/uploads.js | 70 ++++----
test/user.js | 162 +++++++++---------
test/utils.js | 92 +++++-----
255 files changed, 2010 insertions(+), 2017 deletions(-)
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 = /^ 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/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWH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51O89prr7VYfenSpcPAP1UqFeSHH36YeDxOKpW6eP/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';
- var position = '50.0301% 19.2464%';
+ const imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIs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q/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/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/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VotDIKghc7zPCzLolKpsLW1RVtbG0EQ4DgOmqbR09NDM1qUSiWAPwdQ7ujjmf7+/kQymfxrSZJQVZWtra2WG+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';
+ const imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsD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Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/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//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJ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EC/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();