style(eslint): match operator-linebreak preferences

This commit is contained in:
Peter Jaszkowiak
2018-11-28 20:29:43 -07:00
committed by Julian Lam
parent 89c025d102
commit ba619c7ec8
40 changed files with 241 additions and 238 deletions

View File

@@ -40,6 +40,7 @@
"allowTemplateLiterals": true "allowTemplateLiterals": true
}], }],
"no-else-return": [ "error", { "allowElseIf": true } ], "no-else-return": [ "error", { "allowElseIf": true } ],
"operator-linebreak": [ "error", "after" ],
// ES6 // ES6
"prefer-rest-params": "off", "prefer-rest-params": "off",

View File

@@ -99,9 +99,9 @@
} else { } else {
var matches = url.match(/admin\/(.+?)\/(.+?)$/); var matches = url.match(/admin\/(.+?)\/(.+?)$/);
mainTitle = '[[admin/menu:' + matches[1] + '/' + matches[2] + ']]'; mainTitle = '[[admin/menu:' + matches[1] + '/' + matches[2] + ']]';
pageTitle = '[[admin/menu:section-' pageTitle = '[[admin/menu:section-' +
+ (matches[1] === 'development' ? 'advanced' : matches[1]) (matches[1] === 'development' ? 'advanced' : matches[1]) +
+ ']]' + (matches[2] ? (' > ' + mainTitle) : ''); ']]' + (matches[2] ? (' > ' + mainTitle) : '');
if (matches[2] === 'settings') { if (matches[2] === 'settings') {
mainTitle = translator.compile('admin/menu:settings.page-title', mainTitle); mainTitle = translator.compile('admin/menu:settings.page-title', mainTitle);
} }

View File

@@ -62,22 +62,22 @@ define('admin/general/dashboard', ['semver', 'Chart', 'translator', 'benchpress'
graphData.rooms = data; graphData.rooms = data;
var html = '<div class="text-center pull-left">' var html = '<div class="text-center pull-left">' +
+ '<span class="formatted-number">' + data.onlineRegisteredCount + '</span>' '<span class="formatted-number">' + data.onlineRegisteredCount + '</span>' +
+ '<div class="stat">[[admin/general/dashboard:active-users.users]]</div>' '<div class="stat">[[admin/general/dashboard:active-users.users]]</div>' +
+ '</div>' '</div>' +
+ '<div class="text-center pull-left">' '<div class="text-center pull-left">' +
+ '<span class="formatted-number">' + data.onlineGuestCount + '</span>' '<span class="formatted-number">' + data.onlineGuestCount + '</span>' +
+ '<div class="stat">[[admin/general/dashboard:active-users.guests]]</div>' '<div class="stat">[[admin/general/dashboard:active-users.guests]]</div>' +
+ '</div>' '</div>' +
+ '<div class="text-center pull-left">' '<div class="text-center pull-left">' +
+ '<span class="formatted-number">' + (data.onlineRegisteredCount + data.onlineGuestCount) + '</span>' '<span class="formatted-number">' + (data.onlineRegisteredCount + data.onlineGuestCount) + '</span>' +
+ '<div class="stat">[[admin/general/dashboard:active-users.total]]</div>' '<div class="stat">[[admin/general/dashboard:active-users.total]]</div>' +
+ '</div>' '</div>' +
+ '<div class="text-center pull-left">' '<div class="text-center pull-left">' +
+ '<span class="formatted-number">' + data.socketCount + '</span>' '<span class="formatted-number">' + data.socketCount + '</span>' +
+ '<div class="stat">[[admin/general/dashboard:active-users.connections]]</div>' '<div class="stat">[[admin/general/dashboard:active-users.connections]]</div>' +
+ '</div>'; '</div>';
updateRegisteredGraph(data.onlineRegisteredCount, data.onlineGuestCount); updateRegisteredGraph(data.onlineRegisteredCount, data.onlineGuestCount);
updatePresenceGraph(data.users); updatePresenceGraph(data.users);
@@ -513,10 +513,10 @@ define('admin/general/dashboard', ['semver', 'Chart', 'translator', 'benchpress'
topics.forEach(function (topic, i) { topics.forEach(function (topic, i) {
var label = topic.count === '0' ? topic.title : '<a title="' + topic.title + '"href="' + RELATIVE_PATH + '/topic/' + topic.tid + '" target="_blank"> ' + topic.title + '</a>'; var label = topic.count === '0' ? topic.title : '<a title="' + topic.title + '"href="' + RELATIVE_PATH + '/topic/' + topic.tid + '" target="_blank"> ' + topic.title + '</a>';
html += '<li>' html += '<li>' +
+ '<div style="background-color: ' + topicColors[i] + ';"></div>' '<div style="background-color: ' + topicColors[i] + ';"></div>' +
+ '<span> (' + topic.count + ') ' + label + '</span>' '<span> (' + topic.count + ') ' + label + '</span>' +
+ '</li>'; '</li>';
}); });
legend.translateHtml(html); legend.translateHtml(html);
} }

View File

@@ -32,15 +32,15 @@ define('admin/modules/search', ['mousetrap'], function (mousetrap) {
'$1<span class="search-match">$2</span>$3' '$1<span class="search-match">$2</span>$3'
); );
return '<li role="presentation" class="result">' return '<li role="presentation" class="result">' +
+ '<a role= "menuitem" href= "' + config.relative_path + '/' + namespace + '" >' '<a role= "menuitem" href= "' + config.relative_path + '/' + namespace + '" >' +
+ title title +
+ '<br>' + (!results ? '' '<br>' + (!results ? '' :
: ('<small><code>' ('<small><code>' +
+ results results +
+ '</small></code>')) '</small></code>')) +
+ '</a>' '</a>' +
+ '</li>'; '</li>';
}).join(''); }).join('');
return html; return html;
} }

View File

@@ -70,8 +70,8 @@ define('forum/chats/messages', ['components', 'sounds', 'translator', 'benchpres
var lastSpeaker = parseInt(chatContentEl.find('.chat-message').last().attr('data-uid'), 10); var lastSpeaker = parseInt(chatContentEl.find('.chat-message').last().attr('data-uid'), 10);
var lasttimestamp = parseInt(chatContentEl.find('.chat-message').last().attr('data-timestamp'), 10); var lasttimestamp = parseInt(chatContentEl.find('.chat-message').last().attr('data-timestamp'), 10);
if (!Array.isArray(data)) { if (!Array.isArray(data)) {
data.newSet = lastSpeaker !== parseInt(data.fromuid, 10) data.newSet = lastSpeaker !== parseInt(data.fromuid, 10) ||
|| parseInt(data.timestamp, 10) > parseInt(lasttimestamp, 10) + (1000 * 60 * 3); parseInt(data.timestamp, 10) > parseInt(lasttimestamp, 10) + (1000 * 60 * 3);
} }
messages.parseMessage(data, function (html) { messages.parseMessage(data, function (html) {

View File

@@ -58,10 +58,10 @@ define('forum/chats/search', ['components'], function (components) {
function displayUser(chatsListEl, userObj) { function displayUser(chatsListEl, userObj) {
function createUserImage() { function createUserImage() {
return (userObj.picture return (userObj.picture ?
? '<img src="' + userObj.picture + '" title="' + userObj.username + '" />' '<img src="' + userObj.picture + '" title="' + userObj.username + '" />' :
: '<div class="user-icon" style="background-color: ' + userObj['icon:bgColor'] + '">' + userObj['icon:text'] + '</div>') '<div class="user-icon" style="background-color: ' + userObj['icon:bgColor'] + '">' + userObj['icon:text'] + '</div>') +
+ '<i class="fa fa-circle status ' + userObj.status + '"></i> ' + userObj.username; '<i class="fa fa-circle status ' + userObj.status + '"></i> ' + userObj.username;
} }
var chatEl = $('<li component="chat/search/user" />') var chatEl = $('<li component="chat/search/user" />')

View File

@@ -23,9 +23,9 @@ define('forum/topic/images', [], function () {
var altExt = altFilename.split('.').slice(1).pop(); var altExt = altFilename.split('.').slice(1).pop();
if (!$this.parent().is('a')) { if (!$this.parent().is('a')) {
$this.wrap('<a href="' + src + '" ' $this.wrap('<a href="' + src + '" ' +
+ (!srcExt && altExt ? ' download="' + altFilename + '" ' : '') (!srcExt && altExt ? ' download="' + altFilename + '" ' : '') +
+ ' target="_blank" >'); ' target="_blank" >');
} }
}); });
}; };

View File

@@ -70,8 +70,8 @@ define('forum/topic/posts', [
ajaxify.data.pagination.pageCount = Math.max(1, Math.ceil(posts[0].topic.postcount / config.postsPerPage)); ajaxify.data.pagination.pageCount = Math.max(1, Math.ceil(posts[0].topic.postcount / config.postsPerPage));
var direction = config.topicPostSort === 'oldest_to_newest' || config.topicPostSort === 'most_votes' ? 1 : -1; var direction = config.topicPostSort === 'oldest_to_newest' || config.topicPostSort === 'most_votes' ? 1 : -1;
var isPostVisible = (ajaxify.data.pagination.currentPage === ajaxify.data.pagination.pageCount && direction === 1) var isPostVisible = (ajaxify.data.pagination.currentPage === ajaxify.data.pagination.pageCount && direction === 1) ||
|| (ajaxify.data.pagination.currentPage === 1 && direction === -1); (ajaxify.data.pagination.currentPage === 1 && direction === -1);
if (isPostVisible) { if (isPostVisible) {
createNewPosts(data, components.get('post').not('[data-index=0]'), direction, scrollToPost); createNewPosts(data, components.get('post').not('[data-index=0]'), direction, scrollToPost);

View File

@@ -118,11 +118,11 @@
category.children.forEach(function (child) { category.children.forEach(function (child) {
if (child && !child.isSection) { if (child && !child.isSection) {
var link = child.link ? child.link : (relative_path + '/category/' + child.slug); var link = child.link ? child.link : (relative_path + '/category/' + child.slug);
html += '<span class="category-children-item pull-left">' html += '<span class="category-children-item pull-left">' +
+ '<div class="icon pull-left" style="' + generateCategoryBackground(child) + '">' '<div class="icon pull-left" style="' + generateCategoryBackground(child) + '">' +
+ '<i class="fa fa-fw ' + child.icon + '"></i>' '<i class="fa fa-fw ' + child.icon + '"></i>' +
+ '</div>' '</div>' +
+ '<a href="' + link + '"><small>' + child.name + '</small></a></span>'; '<a href="' + link + '"><small>' + child.name + '</small></a></span>';
} }
}); });
html = html ? ('<span class="category-children">' + html + '</span>') : html; html = html ? ('<span class="category-children">' + html + '</span>') : html;

View File

@@ -19,8 +19,8 @@ define('scrollStop', function () {
var elementHeight = Math.round(this.getBoundingClientRect().height); var elementHeight = Math.round(this.getBoundingClientRect().height);
if ( if (
(e.originalEvent.deltaY < 0 && scrollTop === 0) // scroll up (e.originalEvent.deltaY < 0 && scrollTop === 0) || // scroll up
|| (e.originalEvent.deltaY > 0 && (elementHeight + scrollTop) >= scrollHeight) // scroll down (e.originalEvent.deltaY > 0 && (elementHeight + scrollTop) >= scrollHeight) // scroll down
) { ) {
return false; return false;
} }

View File

@@ -116,11 +116,11 @@ define('taskbar', ['benchpress', 'translator'], function (Benchpress, translator
var taskbarEl = $('<li />') var taskbarEl = $('<li />')
.addClass(data.options.className) .addClass(data.options.className)
.html('<a href="#">' .html('<a href="#">' +
+ (data.options.icon ? '<i class="fa ' + data.options.icon + '"></i> ' : '') (data.options.icon ? '<i class="fa ' + data.options.icon + '"></i> ' : '') +
+ (data.options.image ? '<img src="' + data.options.image + '"/> ' : '') (data.options.image ? '<img src="' + data.options.image + '"/> ' : '') +
+ '<span component="taskbar/title">' + title + '</span>' '<span component="taskbar/title">' + title + '</span>' +
+ '</a>') '</a>')
.attr({ .attr({
title: title, title: title,
'data-module': data.module, 'data-module': data.module,

View File

@@ -74,9 +74,9 @@ define('topicList', [
}; };
function onNewTopic(data) { function onNewTopic(data) {
if ((ajaxify.data.selectedCids && ajaxify.data.selectedCids.indexOf(parseInt(data.cid, 10)) === -1) if ((ajaxify.data.selectedCids && ajaxify.data.selectedCids.indexOf(parseInt(data.cid, 10)) === -1) ||
|| (ajaxify.data.selectedFilter && ajaxify.data.selectedFilter.filter === 'watched') (ajaxify.data.selectedFilter && ajaxify.data.selectedFilter.filter === 'watched') ||
|| (ajaxify.data.template.category && parseInt(ajaxify.data.cid, 10) !== parseInt(data.cid, 10))) { (ajaxify.data.template.category && parseInt(ajaxify.data.cid, 10) !== parseInt(data.cid, 10))) {
return; return;
} }
@@ -91,11 +91,13 @@ define('topicList', [
} }
var post = data.posts[0]; var post = data.posts[0];
if ((!post || !post.topic) if (
|| (parseInt(post.topic.mainPid, 10) === parseInt(post.pid, 10)) (!post || !post.topic) ||
|| (ajaxify.data.selectedCids && ajaxify.data.selectedCids.length && ajaxify.data.selectedCids.indexOf(parseInt(post.topic.cid, 10)) === -1) (parseInt(post.topic.mainPid, 10) === parseInt(post.pid, 10)) ||
|| (ajaxify.data.selectedFilter && ajaxify.data.selectedFilter.filter === 'new') (ajaxify.data.selectedCids && ajaxify.data.selectedCids.length && ajaxify.data.selectedCids.indexOf(parseInt(post.topic.cid, 10)) === -1) ||
|| (ajaxify.data.template.category && parseInt(ajaxify.data.cid, 10) !== parseInt(post.topic.cid, 10))) { (ajaxify.data.selectedFilter && ajaxify.data.selectedFilter.filter === 'new') ||
(ajaxify.data.template.category && parseInt(ajaxify.data.cid, 10) !== parseInt(post.topic.cid, 10))
) {
return; return;
} }

View File

@@ -181,8 +181,8 @@
cursor += 1; cursor += 1;
// a space or comma was found before the name // a space or comma was found before the name
// this isn't a translation string, so back out // this isn't a translation string, so back out
} else if (!(textBeforeColonFound && colonFound && textAfterColonFound && commaAfterNameFound) } else if (!(textBeforeColonFound && colonFound && textAfterColonFound && commaAfterNameFound) &&
&& invalidTextRegex.test(char0)) { invalidTextRegex.test(char0)) {
cursor += 1; cursor += 1;
lastBreak -= 2; lastBreak -= 2;
// no longer in a token // no longer in a token

View File

@@ -152,14 +152,14 @@ app.isConnected = false;
} }
if ( if (
config.socketioOrigins config.socketioOrigins &&
&& config.socketioOrigins !== '*' config.socketioOrigins !== '*' &&
&& config.socketioOrigins.indexOf(location.hostname) === -1 config.socketioOrigins.indexOf(location.hostname) === -1
) { ) {
console.error( console.error(
'You are accessing the forum from an unknown origin. This will likely result in websockets failing to connect. \n' 'You are accessing the forum from an unknown origin. This will likely result in websockets failing to connect. \n' +
+ 'To fix this, set the `"url"` value in `config.json` to the URL at which you access the site. \n' 'To fix this, set the `"url"` value in `config.json` to the URL at which you access the site. \n' +
+ 'For more information, see this FAQ topic: https://community.nodebb.org/topic/13388' 'For more information, see this FAQ topic: https://community.nodebb.org/topic/13388'
); );
} }
}()); }());

View File

@@ -625,10 +625,10 @@
var rect = el.getBoundingClientRect(); var rect = el.getBoundingClientRect();
return ( return (
rect.top >= 0 rect.top >= 0 &&
&& rect.left >= 0 rect.left >= 0 &&
&& rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */ rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
&& rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
); );
}, },
@@ -731,10 +731,10 @@
}, },
isInternalURI: function (targetLocation, referenceLocation, relative_path) { isInternalURI: function (targetLocation, referenceLocation, relative_path) {
return targetLocation.host === '' // Relative paths are always internal links return targetLocation.host === '' || // Relative paths are always internal links
|| ( (
targetLocation.host === referenceLocation.host && targetLocation.protocol === referenceLocation.protocol // Otherwise need to check if protocol and host match targetLocation.host === referenceLocation.host && targetLocation.protocol === referenceLocation.protocol && // Otherwise need to check if protocol and host match
&& (relative_path.length > 0 ? targetLocation.pathname.indexOf(relative_path) === 0 : true) // Subfolder installs need this additional check (relative_path.length > 0 ? targetLocation.pathname.indexOf(relative_path) === 0 : true) // Subfolder installs need this additional check
); );
}, },

View File

@@ -18,10 +18,10 @@ function filterDirectories(directories) {
// exclude partials // exclude partials
// only include subpaths // only include subpaths
// exclude category.tpl, group.tpl, category-analytics.tpl // exclude category.tpl, group.tpl, category-analytics.tpl
return !dir.endsWith('.js') return !dir.endsWith('.js') &&
&& !dir.includes('/partials/') !dir.includes('/partials/') &&
&& /\/.*\//.test(dir) /\/.*\//.test(dir) &&
&& !/manage\/(category|group|category-analytics)$/.test(dir); !/manage\/(category|group|category-analytics)$/.test(dir);
}); });
} }
@@ -139,10 +139,10 @@ function initDict(language, callback) {
title = '[[admin/menu:general/dashboard]]'; title = '[[admin/menu:general/dashboard]]';
} else { } else {
title = title.match(/admin\/(.+?)\/(.+?)$/); title = title.match(/admin\/(.+?)\/(.+?)$/);
title = '[[admin/menu:section-' title = '[[admin/menu:section-' +
+ (title[1] === 'development' ? 'advanced' : title[1]) (title[1] === 'development' ? 'advanced' : title[1]) +
+ ']]' + (title[2] ? (' > [[admin/menu:' ']]' + (title[2] ? (' > [[admin/menu:' +
+ title[1] + '/' + title[2] + ']]') : ''); title[1] + '/' + title[2] + ']]') : '');
} }
translator.translate(title).then(function (title) { translator.translate(title).then(function (title) {

View File

@@ -65,9 +65,9 @@ Command.prototype.usage = function () {
return humanReadableArgName(arg); return humanReadableArgName(arg);
}); });
var usage = '[options]'[optionColor] var usage = '[options]'[optionColor] +
+ (this.commands.length ? ' [command]' : '')[subCommandColor] (this.commands.length ? ' [command]' : '')[subCommandColor] +
+ (this._args.length ? ' ' + args.join(' ') : '')[argColor]; (this._args.length ? ' ' + args.join(' ') : '')[argColor];
return usage; return usage;
}; };
@@ -90,10 +90,10 @@ Command.prototype.commandHelp = function () {
}).join(' '); }).join(' ');
return [ return [
cmd._name[subCommandColor] cmd._name[subCommandColor] +
+ (cmd._alias ? ' | ' + cmd._alias : '')[subCommandColor] (cmd._alias ? ' | ' + cmd._alias : '')[subCommandColor] +
+ (cmd.options.length ? ' [options]' : '')[subOptionColor] (cmd.options.length ? ' [options]' : '')[subOptionColor] +
+ ' ' + args[subArgColor], ' ' + args[subArgColor],
cmd._description, cmd._description,
]; ];
}); });

View File

@@ -27,10 +27,10 @@ function buildTargets() {
return ' ' + _.padEnd('"' + tuple[0] + '"', length + 2).magenta + ' | ' + tuple[1]; return ' ' + _.padEnd('"' + tuple[0] + '"', length + 2).magenta + ' | ' + tuple[1];
}).join('\n'); }).join('\n');
console.log( console.log(
'\n\n Build targets:\n' '\n\n Build targets:\n' +
+ ('\n ' + _.padEnd('Target', length + 2) + ' | Aliases').green ('\n ' + _.padEnd('Target', length + 2) + ' | Aliases').green +
+ '\n ------------------------------------------------------\n'.blue '\n ------------------------------------------------------\n'.blue +
+ output + '\n' output + '\n'
); );
} }

View File

@@ -88,8 +88,8 @@ function runUpgrade(upgrades, options) {
if (upgrades === true) { if (upgrades === true) {
var tasks = Object.keys(steps); var tasks = Object.keys(steps);
if (options.package || options.install if (options.package || options.install ||
|| options.plugins || options.schema || options.build) { options.plugins || options.schema || options.build) {
tasks = tasks.filter(function (key) { tasks = tasks.filter(function (key) {
return options[key]; return options[key];
}); });

View File

@@ -88,9 +88,9 @@ function buildBreadcrumbs(currentFolder) {
var dir = path.join(currentPath, part); var dir = path.join(currentPath, part);
crumbs.push({ crumbs.push({
text: part || 'Uploads', text: part || 'Uploads',
url: part url: part ?
? (nconf.get('relative_path') + '/admin/manage/uploads?dir=' + dir) (nconf.get('relative_path') + '/admin/manage/uploads?dir=' + dir) :
: nconf.get('relative_path') + '/admin/manage/uploads', nconf.get('relative_path') + '/admin/manage/uploads',
}); });
currentPath = dir; currentPath = dir;
}); });

View File

@@ -249,10 +249,10 @@ Controllers.robots = function (req, res) {
if (meta.config['robots:txt']) { if (meta.config['robots:txt']) {
res.send(meta.config['robots:txt']); res.send(meta.config['robots:txt']);
} else { } else {
res.send('User-agent: *\n' res.send('User-agent: *\n' +
+ 'Disallow: ' + nconf.get('relative_path') + '/admin/\n' 'Disallow: ' + nconf.get('relative_path') + '/admin/\n' +
+ 'Disallow: ' + nconf.get('relative_path') + '/reset/\n' 'Disallow: ' + nconf.get('relative_path') + '/reset/\n' +
+ 'Sitemap: ' + nconf.get('url') + '/sitemap.xml'); 'Sitemap: ' + nconf.get('url') + '/sitemap.xml');
} }
}; };

View File

@@ -77,9 +77,9 @@ module.exports = function (Groups) {
}; };
function isSystemGroup(data) { function isSystemGroup(data) {
return data.system === true || parseInt(data.system, 10) === 1 return data.system === true || parseInt(data.system, 10) === 1 ||
|| data.name === 'administrators' || data.name === 'registered-users' || data.name === 'Global Moderators' data.name === 'administrators' || data.name === 'registered-users' || data.name === 'Global Moderators' ||
|| Groups.isPrivilegeGroup(data.name); Groups.isPrivilegeGroup(data.name);
} }
function validateGroupName(name, callback) { function validateGroupName(name, callback) {

View File

@@ -134,8 +134,8 @@ module.exports = function (Messaging) {
Messaging.getMessageFields(mid, ['fromuid', 'timestamp'], next); Messaging.getMessageFields(mid, ['fromuid', 'timestamp'], next);
}, },
function (fields, next) { function (fields, next) {
if ((messages[0].timestamp > fields.timestamp + Messaging.newMessageCutoff) if ((messages[0].timestamp > fields.timestamp + Messaging.newMessageCutoff) ||
|| (messages[0].fromuid !== fields.fromuid)) { (messages[0].fromuid !== fields.fromuid)) {
// If it's been 5 minutes, this is a new set of messages // If it's been 5 minutes, this is a new set of messages
messages[0].newSet = true; messages[0].newSet = true;
} }

View File

@@ -80,9 +80,9 @@ Blacklist.test = function (clientIp, callback) {
} }
if ( if (
!Blacklist._rules.ipv4.includes(clientIp) // not explicitly specified in ipv4 list !Blacklist._rules.ipv4.includes(clientIp) && // not explicitly specified in ipv4 list
&& !Blacklist._rules.ipv6.includes(clientIp) // not explicitly specified in ipv6 list !Blacklist._rules.ipv6.includes(clientIp) && // not explicitly specified in ipv6 list
&& !Blacklist._rules.cidr.some(function (subnet) { !Blacklist._rules.cidr.some(function (subnet) {
var cidr = ipaddr.parseCIDR(subnet); var cidr = ipaddr.parseCIDR(subnet);
if (addr.kind() !== cidr[0].kind()) { if (addr.kind() !== cidr[0].kind()) {
return false; return false;

View File

@@ -89,11 +89,11 @@ module.exports = function (middleware) {
}, next); }, next);
}, },
function (results, next) { function (results, next) {
var str = results.header var str = results.header +
+ (res.locals.postHeader || '') (res.locals.postHeader || '') +
+ results.content + '<script id="ajaxify-data"></script>' results.content + '<script id="ajaxify-data"></script>' +
+ (res.locals.preFooter || '') (res.locals.preFooter || '') +
+ results.footer; results.footer;
translate(str, req, res, next); translate(str, req, res, next);
}, },

View File

@@ -106,16 +106,16 @@ function getStaticDirectories(pluginData, callback) {
async.each(dirs, function (route, next) { async.each(dirs, function (route, next) {
if (!validMappedPath.test(route)) { if (!validMappedPath.test(route)) {
winston.warn('[plugins/' + pluginData.id + '] Invalid mapped path specified: ' winston.warn('[plugins/' + pluginData.id + '] Invalid mapped path specified: ' +
+ route + '. Path must adhere to: ' + validMappedPath.toString()); route + '. Path must adhere to: ' + validMappedPath.toString());
return next(); return next();
} }
var dirPath = path.join(pluginData.path, pluginData.staticDirs[route]); var dirPath = path.join(pluginData.path, pluginData.staticDirs[route]);
fs.stat(dirPath, function (err, stats) { fs.stat(dirPath, function (err, stats) {
if (err && err.code === 'ENOENT') { if (err && err.code === 'ENOENT') {
winston.warn('[plugins/' + pluginData.id + '] Mapped path \'' winston.warn('[plugins/' + pluginData.id + '] Mapped path \'' +
+ route + ' => ' + dirPath + '\' not found.'); route + ' => ' + dirPath + '\' not found.');
return next(); return next();
} }
if (err) { if (err) {
@@ -123,8 +123,8 @@ function getStaticDirectories(pluginData, callback) {
} }
if (!stats.isDirectory()) { if (!stats.isDirectory()) {
winston.warn('[plugins/' + pluginData.id + '] Mapped path \'' winston.warn('[plugins/' + pluginData.id + '] Mapped path \'' +
+ route + ' => ' + dirPath + '\' is not a directory.'); route + ' => ' + dirPath + '\' is not a directory.');
return next(); return next();
} }
@@ -135,8 +135,8 @@ function getStaticDirectories(pluginData, callback) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
winston.verbose('[plugins] found ' + Object.keys(staticDirs).length winston.verbose('[plugins] found ' + Object.keys(staticDirs).length +
+ ' static directories for ' + pluginData.id); ' static directories for ' + pluginData.id);
callback(null, staticDirs); callback(null, staticDirs);
}); });
} }

View File

@@ -34,10 +34,10 @@ module.exports = function (Plugins) {
var method; var method;
if (Object.keys(Plugins.deprecatedHooks).includes(data.hook)) { if (Object.keys(Plugins.deprecatedHooks).includes(data.hook)) {
winston.warn('[plugins/' + id + '] Hook `' + data.hook + '` is deprecated, ' winston.warn('[plugins/' + id + '] Hook `' + data.hook + '` is deprecated, ' +
+ (Plugins.deprecatedHooks[data.hook] (Plugins.deprecatedHooks[data.hook] ?
? 'please use `' + Plugins.deprecatedHooks[data.hook] + '` instead.' 'please use `' + Plugins.deprecatedHooks[data.hook] + '` instead.' :
: 'there is no alternative.' 'there is no alternative.'
)); ));
} }

View File

@@ -141,8 +141,8 @@ module.exports = function (privileges) {
}, },
function (results, next) { function (results, next) {
cids = cids.filter(function (cid, index) { cids = cids.filter(function (cid, index) {
return !results.categories[index].disabled return !results.categories[index].disabled &&
&& (results.allowedTo[index] || results.isAdmin || results.isModerators[index]); (results.allowedTo[index] || results.isAdmin || results.isModerators[index]);
}); });
next(null, cids.filter(Boolean)); next(null, cids.filter(Boolean));

View File

@@ -115,15 +115,15 @@ module.exports = function (privileges) {
var isModOf = {}; var isModOf = {};
cids = cids.filter(function (cid, index) { cids = cids.filter(function (cid, index) {
isModOf[cid] = results.isModerators[index]; isModOf[cid] = results.isModerators[index];
return !results.categories[index].disabled return !results.categories[index].disabled &&
&& (results.allowedTo[index] || results.isAdmin || results.isModerators[index]); (results.allowedTo[index] || results.isAdmin || results.isModerators[index]);
}); });
const cidsSet = new Set(cids); const cidsSet = new Set(cids);
pids = postData.filter(function (post) { pids = postData.filter(function (post) {
return post.topic && cidsSet.has(post.topic.cid) return post.topic && cidsSet.has(post.topic.cid) &&
&& ((!post.topic.deleted && !post.deleted) || results.isAdmin || isModOf[post.cid]); ((!post.topic.deleted && !post.deleted) || results.isAdmin || isModOf[post.cid]);
}).map(post => post.pid); }).map(post => post.pid);
plugins.fireHook('filter:privileges.posts.filter', { plugins.fireHook('filter:privileges.posts.filter', {

View File

@@ -96,15 +96,15 @@ module.exports = function (privileges) {
var isModOf = {}; var isModOf = {};
cids = cids.filter(function (cid, index) { cids = cids.filter(function (cid, index) {
isModOf[cid] = results.isModerators[index]; isModOf[cid] = results.isModerators[index];
return !results.categories[index].disabled return !results.categories[index].disabled &&
&& (results.allowedTo[index] || results.isAdmin || results.isModerators[index]); (results.allowedTo[index] || results.isAdmin || results.isModerators[index]);
}); });
const cidsSet = new Set(cids); const cidsSet = new Set(cids);
tids = topicsData.filter(function (topic) { tids = topicsData.filter(function (topic) {
return cidsSet.has(topic.cid) return cidsSet.has(topic.cid) &&
&& (!topic.deleted || results.isAdmin || isModOf[topic.cid]); (!topic.deleted || results.isAdmin || isModOf[topic.cid]);
}).map(topic => topic.tid); }).map(topic => topic.tid);
plugins.fireHook('filter:privileges.topics.filter', { plugins.fireHook('filter:privileges.topics.filter', {
@@ -148,8 +148,8 @@ module.exports = function (privileges) {
}, },
function (results, next) { function (results, next) {
uids = uids.filter(function (uid, index) { uids = uids.filter(function (uid, index) {
return !results.disabled return !results.disabled &&
&& ((results.allowedTo[index] && !topicData.deleted) || results.isAdmins[index] || results.isModerators[index]); ((results.allowedTo[index] && !topicData.deleted) || results.isAdmins[index] || results.isModerators[index]);
}); });
next(null, uids); next(null, uids);
@@ -197,9 +197,9 @@ module.exports = function (privileges) {
var preventTopicDeleteAfterReplies = meta.config.preventTopicDeleteAfterReplies; var preventTopicDeleteAfterReplies = meta.config.preventTopicDeleteAfterReplies;
if (preventTopicDeleteAfterReplies && (topicData.postcount - 1) >= preventTopicDeleteAfterReplies) { if (preventTopicDeleteAfterReplies && (topicData.postcount - 1) >= preventTopicDeleteAfterReplies) {
var langKey = preventTopicDeleteAfterReplies > 1 var langKey = preventTopicDeleteAfterReplies > 1 ?
? '[[error:cant-delete-topic-has-replies, ' + meta.config.preventTopicDeleteAfterReplies + ']]' '[[error:cant-delete-topic-has-replies, ' + meta.config.preventTopicDeleteAfterReplies + ']]' :
: '[[error:cant-delete-topic-has-reply]]'; '[[error:cant-delete-topic-has-reply]]';
return next(new Error(langKey)); return next(new Error(langKey));
} }

View File

@@ -173,8 +173,8 @@ module.exports = function (app, middleware, callback) {
// DEPRECATED (v1.12.0) // DEPRECATED (v1.12.0)
app.use(relativePath + '/assets/stylesheet.css', function (req, res) { app.use(relativePath + '/assets/stylesheet.css', function (req, res) {
if (!warned.has(req.path)) { if (!warned.has(req.path)) {
winston.warn('[deprecated] Accessing `/assets/stylesheet.css` is deprecated to be REMOVED in NodeBB v1.12.0. ' winston.warn('[deprecated] Accessing `/assets/stylesheet.css` is deprecated to be REMOVED in NodeBB v1.12.0. ' +
+ 'Use `/assets/client.css` to access this file'); 'Use `/assets/client.css` to access this file');
warned.add(req.path); warned.add(req.path);
} }
res.redirect(relativePath + '/assets/client.css?' + meta.config['cache-buster']); res.redirect(relativePath + '/assets/client.css?' + meta.config['cache-buster']);

View File

@@ -42,8 +42,8 @@ sitemap.render = function (callback) {
sitemap.getPages = function (callback) { sitemap.getPages = function (callback) {
if ( if (
sitemap.maps.pages sitemap.maps.pages &&
&& Date.now() < parseInt(sitemap.maps.pages.cacheSetTimestamp, 10) + parseInt(sitemap.maps.pages.cacheResetPeriod, 10) Date.now() < parseInt(sitemap.maps.pages.cacheSetTimestamp, 10) + parseInt(sitemap.maps.pages.cacheResetPeriod, 10)
) { ) {
return sitemap.maps.pages.toXML(callback); return sitemap.maps.pages.toXML(callback);
} }
@@ -82,8 +82,8 @@ sitemap.getPages = function (callback) {
sitemap.getCategories = function (callback) { sitemap.getCategories = function (callback) {
if ( if (
sitemap.maps.categories sitemap.maps.categories &&
&& Date.now() < parseInt(sitemap.maps.categories.cacheSetTimestamp, 10) + parseInt(sitemap.maps.categories.cacheResetPeriod, 10) Date.now() < parseInt(sitemap.maps.categories.cacheSetTimestamp, 10) + parseInt(sitemap.maps.categories.cacheResetPeriod, 10)
) { ) {
return sitemap.maps.categories.toXML(callback); return sitemap.maps.categories.toXML(callback);
} }
@@ -124,8 +124,8 @@ sitemap.getTopicPage = function (page, callback) {
var max = min + numTopics; var max = min + numTopics;
if ( if (
sitemap.maps.topics[page - 1] sitemap.maps.topics[page - 1] &&
&& Date.now() < parseInt(sitemap.maps.topics[page - 1].cacheSetTimestamp, 10) + parseInt(sitemap.maps.topics[page - 1].cacheResetPeriod, 10) Date.now() < parseInt(sitemap.maps.topics[page - 1].cacheSetTimestamp, 10) + parseInt(sitemap.maps.topics[page - 1].cacheResetPeriod, 10)
) { ) {
return sitemap.maps.topics[page - 1].toXML(callback); return sitemap.maps.topics[page - 1].toXML(callback);
} }

View File

@@ -249,10 +249,10 @@ SocketGroups.create = function (socket, data, callback) {
}; };
SocketGroups.delete = isOwner(function (socket, data, callback) { SocketGroups.delete = isOwner(function (socket, data, callback) {
if (data.groupName === 'administrators' if (data.groupName === 'administrators' ||
|| data.groupName === 'registered-users' data.groupName === 'registered-users' ||
|| data.groupName === 'guests' data.groupName === 'guests' ||
|| data.groupName === 'Global Moderators') { data.groupName === 'Global Moderators') {
return callback(new Error('[[error:not-allowed]]')); return callback(new Error('[[error:not-allowed]]'));
} }

View File

@@ -70,8 +70,8 @@ function filterTidCidIgnorers(uids, tid, cid, callback) {
}, },
function (results, next) { function (results, next) {
uids = uids.filter(function (uid, index) { uids = uids.filter(function (uid, index) {
return results.topicFollowed[index] return results.topicFollowed[index] ||
|| (!results.topicFollowed[index] && !results.topicIgnored[index] && !results.categoryIgnored[index]); (!results.topicFollowed[index] && !results.topicIgnored[index] && !results.categoryIgnored[index]);
}); });
next(null, uids); next(null, uids);
}, },

View File

@@ -464,9 +464,9 @@ module.exports = function (Topics) {
function (results, next) { function (results, next) {
var cutoff = Topics.unreadCutoff(); var cutoff = Topics.unreadCutoff();
var result = tids.map(function (tid, index) { var result = tids.map(function (tid, index) {
var read = !results.tids_unread[index] var read = !results.tids_unread[index] &&
&& (results.topicScores[index] < cutoff (results.topicScores[index] < cutoff ||
|| !!(results.userScores[index] && results.userScores[index] >= results.topicScores[index])); !!(results.userScores[index] && results.userScores[index] >= results.topicScores[index]));
return { tid: tid, read: read, index: index }; return { tid: tid, read: read, index: index };
}); });

View File

@@ -240,11 +240,11 @@ module.exports = function (User) {
function (next) { function (next) {
request({ request({
method: 'get', method: 'get',
url: 'http://api.stopforumspam.org/api' url: 'http://api.stopforumspam.org/api' +
+ '?ip=' + encodeURIComponent(user.ip) '?ip=' + encodeURIComponent(user.ip) +
+ '&email=' + encodeURIComponent(user.email) '&email=' + encodeURIComponent(user.email) +
+ '&username=' + encodeURIComponent(user.username) '&username=' + encodeURIComponent(user.username) +
+ '&f=json', '&f=json',
json: true, json: true,
}, next); }, next);
}, },

View File

@@ -109,9 +109,9 @@ module.exports = function (User) {
var expired; var expired;
sessions = sessions.filter(function (sessionObj, idx) { sessions = sessions.filter(function (sessionObj, idx) {
expired = !sessionObj || !sessionObj.hasOwnProperty('passport') expired = !sessionObj || !sessionObj.hasOwnProperty('passport') ||
|| !sessionObj.passport.hasOwnProperty('user') !sessionObj.passport.hasOwnProperty('user') ||
|| parseInt(sessionObj.passport.user, 10) !== parseInt(uid, 10); parseInt(sessionObj.passport.user, 10) !== parseInt(uid, 10);
if (expired) { if (expired) {
expiredSids.push(_sids[idx]); expiredSids.push(_sids[idx]);

View File

@@ -41,16 +41,16 @@ describe('minifier', function () {
assert.strictEqual( assert.strictEqual(
fs.readFileSync(destPath).toString().replace(/\r\n/g, '\n'), fs.readFileSync(destPath).toString().replace(/\r\n/g, '\n'),
'(function (window, document) {' '(function (window, document) {' +
+ '\n\twindow.doStuff = function () {' '\n\twindow.doStuff = function () {' +
+ '\n\t\tdocument.body.innerHTML = \'Stuff has been done\';' '\n\t\tdocument.body.innerHTML = \'Stuff has been done\';' +
+ '\n\t};' '\n\t};' +
+ '\n})(window, document);' '\n})(window, document);' +
+ '\n' '\n' +
+ '\n;function foo(name, age) {' '\n;function foo(name, age) {' +
+ '\n\treturn \'The person known as "\' + name + \'" is \' + age + \' years old\';' '\n\treturn \'The person known as "\' + name + \'" is \' + age + \' years old\';' +
+ '\n}' '\n}' +
+ '\n' '\n'
); );
done(); done();
}); });
@@ -69,8 +69,8 @@ describe('minifier', function () {
assert.strictEqual( assert.strictEqual(
fs.readFileSync(destPath).toString(), fs.readFileSync(destPath).toString(),
'(function(n,o){n.doStuff=function(){o.body.innerHTML="Stuff has been done"}})(window,document);function foo(n,o){return\'The person known as "\'+n+\'" is \'+o+" years old"}' '(function(n,o){n.doStuff=function(){o.body.innerHTML="Stuff has been done"}})(window,document);function foo(n,o){return\'The person known as "\'+n+\'" is \'+o+" years old"}' +
+ '\n//# sourceMappingURL=minified.js.map' '\n//# sourceMappingURL=minified.js.map'
); );
done(); done();
}); });
@@ -87,8 +87,8 @@ describe('minifier', function () {
assert.ifError(err); assert.ifError(err);
assert.strictEqual( assert.strictEqual(
buffer.toString(), buffer.toString(),
'(function(n,o){n.doStuff=function(){o.body.innerHTML="Stuff has been done"}})(window,document);' '(function(n,o){n.doStuff=function(){o.body.innerHTML="Stuff has been done"}})(window,document);' +
+ '\n//# sourceMappingURL=1.js.map' '\n//# sourceMappingURL=1.js.map'
); );
done(); done();
}); });

View File

@@ -45,47 +45,47 @@ var productionDbConfig = nconf.get(dbType);
if (!testDbConfig) { if (!testDbConfig) {
const errorText = 'test_database is not defined'; const errorText = 'test_database is not defined';
winston.info( winston.info(
'\n===========================================================\n' '\n===========================================================\n' +
+ 'Please, add parameters for test database in config.json\n' 'Please, add parameters for test database in config.json\n' +
+ 'For example (redis):\n' 'For example (redis):\n' +
+ '"test_database": {\n' '"test_database": {\n' +
+ ' "host": "127.0.0.1",\n' ' "host": "127.0.0.1",\n' +
+ ' "port": "6379",\n' ' "port": "6379",\n' +
+ ' "password": "",\n' ' "password": "",\n' +
+ ' "database": "1"\n' ' "database": "1"\n' +
+ '}\n' '}\n' +
+ ' or (mongo):\n' ' or (mongo):\n' +
+ '"test_database": {\n' '"test_database": {\n' +
+ ' "host": "127.0.0.1",\n' ' "host": "127.0.0.1",\n' +
+ ' "port": "27017",\n' ' "port": "27017",\n' +
+ ' "password": "",\n' ' "password": "",\n' +
+ ' "database": "1"\n' ' "database": "1"\n' +
+ '}\n' '}\n' +
+ ' or (mongo) in a replicaset\n' ' or (mongo) in a replicaset\n' +
+ '"test_database": {\n' '"test_database": {\n' +
+ ' "host": "127.0.0.1,127.0.0.1,127.0.0.1",\n' ' "host": "127.0.0.1,127.0.0.1,127.0.0.1",\n' +
+ ' "port": "27017,27018,27019",\n' ' "port": "27017,27018,27019",\n' +
+ ' "username": "",\n' ' "username": "",\n' +
+ ' "password": "",\n' ' "password": "",\n' +
+ ' "database": "nodebb_test"\n' ' "database": "nodebb_test"\n' +
+ '}\n' '}\n' +
+ ' or (postgres):\n' ' or (postgres):\n' +
+ '"test_database": {\n' '"test_database": {\n' +
+ ' "host": "127.0.0.1",\n' ' "host": "127.0.0.1",\n' +
+ ' "port": "5432",\n' ' "port": "5432",\n' +
+ ' "username": "postgres",\n' ' "username": "postgres",\n' +
+ ' "password": "",\n' ' "password": "",\n' +
+ ' "database": "nodebb_test"\n' ' "database": "nodebb_test"\n' +
+ '}\n' '}\n' +
+ '===========================================================' '==========================================================='
); );
winston.error(errorText); winston.error(errorText);
throw new Error(errorText); throw new Error(errorText);
} }
if (testDbConfig.database === productionDbConfig.database if (testDbConfig.database === productionDbConfig.database &&
&& testDbConfig.host === productionDbConfig.host testDbConfig.host === productionDbConfig.host &&
&& testDbConfig.port === productionDbConfig.port) { testDbConfig.port === productionDbConfig.port) {
const errorText = 'test_database has the same config as production db'; const errorText = 'test_database has the same config as production db';
winston.error(errorText); winston.error(errorText);
throw new Error(errorText); throw new Error(errorText);

View File

@@ -46,19 +46,19 @@ describe('admin search', function () {
describe('sanitize', function () { describe('sanitize', function () {
it('should strip out scripts', function (done) { it('should strip out scripts', function (done) {
assert.equal( assert.equal(
search.sanitize('Pellentesque tristique senectus' search.sanitize('Pellentesque tristique senectus' +
+ '<script>alert("nope");</script> habitant morbi'), '<script>alert("nope");</script> habitant morbi'),
'Pellentesque tristique senectus' 'Pellentesque tristique senectus' +
+ ' habitant morbi' ' habitant morbi'
); );
done(); done();
}); });
it('should remove all tags', function (done) { it('should remove all tags', function (done) {
assert.equal( assert.equal(
search.sanitize('<p>Pellentesque <b>habitant morbi</b> tristique senectus' search.sanitize('<p>Pellentesque <b>habitant morbi</b> tristique senectus' +
+ 'Aenean <i>vitae</i> est.Mauris <a href="placerat">eleifend</a> leo.</p>'), 'Aenean <i>vitae</i> est.Mauris <a href="placerat">eleifend</a> leo.</p>'),
'Pellentesque habitant morbi tristique senectus' 'Pellentesque habitant morbi tristique senectus' +
+ 'Aenean vitae est.Mauris eleifend leo.' 'Aenean vitae est.Mauris eleifend leo.'
); );
done(); done();
}); });
@@ -67,19 +67,19 @@ describe('admin search', function () {
describe('simplify', function () { describe('simplify', function () {
it('should remove all mustaches', function (done) { it('should remove all mustaches', function (done) {
assert.equal( assert.equal(
search.simplify('Pellentesque tristique {{senectus}}habitant morbi' search.simplify('Pellentesque tristique {{senectus}}habitant morbi' +
+ 'liquam tincidunt {mauris.eu}risus'), 'liquam tincidunt {mauris.eu}risus'),
'Pellentesque tristique habitant morbi' 'Pellentesque tristique habitant morbi' +
+ 'liquam tincidunt risus' 'liquam tincidunt risus'
); );
done(); done();
}); });
it('should collapse all whitespace', function (done) { it('should collapse all whitespace', function (done) {
assert.equal( assert.equal(
search.simplify('Pellentesque tristique habitant morbi' search.simplify('Pellentesque tristique habitant morbi' +
+ ' \n\n liquam tincidunt mauris eu risus.'), ' \n\n liquam tincidunt mauris eu risus.'),
'Pellentesque tristique habitant morbi' 'Pellentesque tristique habitant morbi' +
+ '\nliquam tincidunt mauris eu risus.' '\nliquam tincidunt mauris eu risus.'
); );
done(); done();
}); });