');
+ // http://stackoverflow.com/questions/14441456/how-to-detect-which-device-view-youre-on-using-twitter-bootstrap-api
+ var envs = ['xs', 'sm', 'md', 'lg'];
+ var $el = $('
');
$el.appendTo($('body'));
- for (var i = envs.length - 1; i >= 0; i--) {
+ for (var i = envs.length - 1; i >= 0; i -= 1) {
var env = envs[i];
$el.addClass('hidden-' + env);
@@ -292,10 +296,10 @@
},
getHoursArray: function () {
- var currentHour = new Date().getHours(),
- labels = [];
+ var currentHour = new Date().getHours();
+ var labels = [];
- for (var i = currentHour, ii = currentHour - 24; i > ii; i--) {
+ for (var i = currentHour, ii = currentHour - 24; i > ii; i -= 1) {
var hour = i < 0 ? 24 + i : i;
labels.push(hour + ':00');
}
@@ -304,12 +308,12 @@
},
getDaysArray: function (from) {
- var currentDay = new Date(from || Date.now()).getTime(),
- months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
- labels = [],
- tmpDate;
+ var currentDay = new Date(from || Date.now()).getTime();
+ var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+ var labels = [];
+ var tmpDate;
- for(var x = 29; x >= 0; x--) {
+ for (var x = 29; x >= 0; x -= 1) {
tmpDate = new Date(currentDay - (1000 * 60 * 60 * 24 * x));
labels.push(months[tmpDate.getMonth()] + ' ' + tmpDate.getDate());
}
@@ -319,8 +323,8 @@
/* Retrieved from http://stackoverflow.com/a/7557433 @ 27 Mar 2016 */
isElementInViewport: function (el) {
- //special bonus for those using jQuery
- if (typeof jQuery === "function" && el instanceof jQuery) {
+ // special bonus for those using jQuery
+ if (typeof jQuery === 'function' && el instanceof jQuery) {
el = el[0];
}
@@ -329,14 +333,16 @@
return (
rect.top >= 0 &&
rect.left >= 0 &&
- rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
- rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
+ rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
+ rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
);
},
// get all the url params in a single key/value hash
params: function (options) {
- var a, hash = {}, params;
+ var a;
+ var hash = {};
+ var params;
options = options || {};
options.skipToType = options.skipToType || {};
@@ -344,12 +350,12 @@
if (options.url) {
a = utils.urlToLocation(options.url);
}
- params = (a ? a.search : window.location.search).substring(1).split("&");
+ params = (a ? a.search : window.location.search).substring(1).split('&');
params.forEach(function (param) {
- var val = param.split('='),
- key = decodeURI(val[0]),
- value = options.skipToType[key] ? decodeURI(val[1]) : utils.toType(decodeURI(val[1]));
+ var val = param.split('=');
+ var key = decodeURI(val[0]);
+ var value = options.skipToType[key] ? decodeURI(val[1]) : utils.toType(decodeURI(val[1]));
if (key) {
if (key.substr(-2, 2) === '[]') {
@@ -383,25 +389,24 @@
toType: function (str) {
var type = typeof str;
if (type !== 'string') {
- return str;
- } else {
- var nb = parseFloat(str);
- if (!isNaN(nb) && isFinite(str)) {
- return nb;
- }
- if (str === 'false') {
- return false;
- }
- if (str === 'true') {
- return true;
- }
-
- try {
- str = JSON.parse(str);
- } catch (e) {}
-
return str;
}
+ var nb = parseFloat(str);
+ if (!isNaN(nb) && isFinite(str)) {
+ return nb;
+ }
+ if (str === 'false') {
+ return false;
+ }
+ if (str === 'true') {
+ return true;
+ }
+
+ try {
+ str = JSON.parse(str);
+ } catch (e) {}
+
+ return str;
},
// Safely get/set chained properties on an object
@@ -410,23 +415,23 @@
// get example: utils.props(A, 'a.b.c.foo.bar') // returns undefined without throwing a TypeError
// credits to github.com/gkindel
props: function (obj, props, value) {
- if(obj === undefined) {
+ if (obj === undefined) {
obj = window;
}
- if(props == null) {
+ if (props == null) {
return undefined;
}
var i = props.indexOf('.');
- if( i == -1 ) {
- if(value !== undefined) {
+ if (i === -1) {
+ if (value !== undefined) {
obj[props] = value;
}
return obj[props];
}
- var prop = props.slice(0, i),
- newProps = props.slice(i + 1);
+ var prop = props.slice(0, i);
+ var newProps = props.slice(i + 1);
- if(props !== undefined && !(obj[prop] instanceof Object) ) {
+ if (props !== undefined && !(obj[prop] instanceof Object)) {
obj[prop] = {};
}
@@ -439,47 +444,43 @@
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
);
- }
+ },
};
- if (typeof String.prototype.startsWith != 'function') {
+ module.exports = utils;
+ if (typeof window !== 'undefined') {
+ window.utils = module.exports;
+ }
+
+ /* eslint "no-extend-native": "off" */
+ if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function (prefix) {
if (this.length < prefix.length) {
return false;
}
- for (var i = prefix.length - 1; (i >= 0) && (this[i] === prefix[i]); --i) {
- continue;
- }
- return i < 0;
+ return this.slice(0, prefix.length) === prefix;
};
}
- if (typeof String.prototype.endsWith != 'function') {
+ if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
if (this.length < suffix.length) {
return false;
}
- var len = this.length;
- var suffixLen = suffix.length;
- for (var i = 1; (i <= suffixLen && this[len - i] === suffix[suffixLen - i]); ++i) {
- continue;
+ if (suffix.length === 0) {
+ return true;
}
- return i > suffixLen;
+ return this.slice(-suffix.length) === suffix;
};
}
- if (typeof String.prototype.rtrim != 'function') {
+ if (typeof String.prototype.rtrim !== 'function') {
String.prototype.rtrim = function () {
return this.replace(/\s+$/g, '');
};
}
-
- if ('undefined' !== typeof window) {
- window.utils = module.exports;
- }
-
-}('undefined' === typeof module ? {
+}(typeof module === 'undefined' ? {
module: {
- exports: {}
- }
+ exports: {},
+ },
} : module));
diff --git a/public/src/widgets.js b/public/src/widgets.js
index 377ccb2c53..f5f667d2a7 100644
--- a/public/src/widgets.js
+++ b/public/src/widgets.js
@@ -1,5 +1,5 @@
-"use strict";
-/*global ajaxify, templates, config, utils*/
+'use strict';
+
(function (ajaxify) {
ajaxify.widgets = {};
@@ -29,19 +29,19 @@
}
});
- $.get(config.relative_path + '/api/widgets/render' + '?' + config['cache-buster'], {
+ $.get(config.relative_path + '/api/widgets/render?' + config['cache-buster'], {
locations: widgetLocations,
template: template + '.tpl',
url: url,
cid: ajaxify.data.cid,
- isMobile: utils.isMobile()
+ isMobile: utils.isMobile(),
}, function (renderedAreas) {
- for (var x = 0; x < renderedAreas.length; ++x) {
+ for (var x = 0; x < renderedAreas.length; x += 1) {
var renderedWidgets = renderedAreas[x].widgets;
var location = renderedAreas[x].location;
var html = '';
- for (var i = 0; i < renderedWidgets.length; ++i) {
+ for (var i = 0; i < renderedWidgets.length; i += 1) {
html += templates.parse(renderedWidgets[i].html, {});
}
@@ -79,7 +79,7 @@
widgetAreas.find('img[title].teaser-pic,img[title].user-img').each(function () {
$(this).tooltip({
placement: 'top',
- title: $(this).attr('title')
+ title: $(this).attr('title'),
});
});
$(window).trigger('action:widgets.loaded', {});
diff --git a/public/vendor/fontawesome/fonts/FontAwesome.otf b/public/vendor/fontawesome/fonts/FontAwesome.otf
index d4de13e832..401ec0f36e 100644
Binary files a/public/vendor/fontawesome/fonts/FontAwesome.otf and b/public/vendor/fontawesome/fonts/FontAwesome.otf differ
diff --git a/public/vendor/fontawesome/fonts/fontawesome-webfont.eot b/public/vendor/fontawesome/fonts/fontawesome-webfont.eot
index c7b00d2ba8..e9f60ca953 100644
Binary files a/public/vendor/fontawesome/fonts/fontawesome-webfont.eot and b/public/vendor/fontawesome/fonts/fontawesome-webfont.eot differ
diff --git a/public/vendor/fontawesome/fonts/fontawesome-webfont.svg b/public/vendor/fontawesome/fonts/fontawesome-webfont.svg
index 8b66187fe0..855c845e53 100644
--- a/public/vendor/fontawesome/fonts/fontawesome-webfont.svg
+++ b/public/vendor/fontawesome/fonts/fontawesome-webfont.svg
@@ -1,685 +1,2671 @@
-
diff --git a/public/vendor/fontawesome/fonts/fontawesome-webfont.ttf b/public/vendor/fontawesome/fonts/fontawesome-webfont.ttf
index f221e50a2e..35acda2fa1 100644
Binary files a/public/vendor/fontawesome/fonts/fontawesome-webfont.ttf and b/public/vendor/fontawesome/fonts/fontawesome-webfont.ttf differ
diff --git a/public/vendor/fontawesome/fonts/fontawesome-webfont.woff b/public/vendor/fontawesome/fonts/fontawesome-webfont.woff
index 6e7483cf61..400014a4b0 100644
Binary files a/public/vendor/fontawesome/fonts/fontawesome-webfont.woff and b/public/vendor/fontawesome/fonts/fontawesome-webfont.woff differ
diff --git a/public/vendor/fontawesome/fonts/fontawesome-webfont.woff2 b/public/vendor/fontawesome/fonts/fontawesome-webfont.woff2
index 7eb74fd127..4d13fc6040 100644
Binary files a/public/vendor/fontawesome/fonts/fontawesome-webfont.woff2 and b/public/vendor/fontawesome/fonts/fontawesome-webfont.woff2 differ
diff --git a/public/vendor/fontawesome/less/font-awesome.less b/public/vendor/fontawesome/less/font-awesome.less
index c44e5f466a..c3677def31 100644
--- a/public/vendor/fontawesome/less/font-awesome.less
+++ b/public/vendor/fontawesome/less/font-awesome.less
@@ -1,5 +1,5 @@
/*!
- * Font Awesome 4.6.3 by @davegandy - http://fontawesome.io - @fontawesome
+ * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/
diff --git a/public/vendor/fontawesome/less/icons.less b/public/vendor/fontawesome/less/icons.less
index ba21b222d6..159d600425 100644
--- a/public/vendor/fontawesome/less/icons.less
+++ b/public/vendor/fontawesome/less/icons.less
@@ -605,6 +605,7 @@
.@{fa-css-prefix}-opencart:before { content: @fa-var-opencart; }
.@{fa-css-prefix}-expeditedssl:before { content: @fa-var-expeditedssl; }
.@{fa-css-prefix}-battery-4:before,
+.@{fa-css-prefix}-battery:before,
.@{fa-css-prefix}-battery-full:before { content: @fa-var-battery-full; }
.@{fa-css-prefix}-battery-3:before,
.@{fa-css-prefix}-battery-three-quarters:before { content: @fa-var-battery-three-quarters; }
@@ -731,3 +732,58 @@
.@{fa-css-prefix}-google-plus-official:before { content: @fa-var-google-plus-official; }
.@{fa-css-prefix}-fa:before,
.@{fa-css-prefix}-font-awesome:before { content: @fa-var-font-awesome; }
+.@{fa-css-prefix}-handshake-o:before { content: @fa-var-handshake-o; }
+.@{fa-css-prefix}-envelope-open:before { content: @fa-var-envelope-open; }
+.@{fa-css-prefix}-envelope-open-o:before { content: @fa-var-envelope-open-o; }
+.@{fa-css-prefix}-linode:before { content: @fa-var-linode; }
+.@{fa-css-prefix}-address-book:before { content: @fa-var-address-book; }
+.@{fa-css-prefix}-address-book-o:before { content: @fa-var-address-book-o; }
+.@{fa-css-prefix}-vcard:before,
+.@{fa-css-prefix}-address-card:before { content: @fa-var-address-card; }
+.@{fa-css-prefix}-vcard-o:before,
+.@{fa-css-prefix}-address-card-o:before { content: @fa-var-address-card-o; }
+.@{fa-css-prefix}-user-circle:before { content: @fa-var-user-circle; }
+.@{fa-css-prefix}-user-circle-o:before { content: @fa-var-user-circle-o; }
+.@{fa-css-prefix}-user-o:before { content: @fa-var-user-o; }
+.@{fa-css-prefix}-id-badge:before { content: @fa-var-id-badge; }
+.@{fa-css-prefix}-drivers-license:before,
+.@{fa-css-prefix}-id-card:before { content: @fa-var-id-card; }
+.@{fa-css-prefix}-drivers-license-o:before,
+.@{fa-css-prefix}-id-card-o:before { content: @fa-var-id-card-o; }
+.@{fa-css-prefix}-quora:before { content: @fa-var-quora; }
+.@{fa-css-prefix}-free-code-camp:before { content: @fa-var-free-code-camp; }
+.@{fa-css-prefix}-telegram:before { content: @fa-var-telegram; }
+.@{fa-css-prefix}-thermometer-4:before,
+.@{fa-css-prefix}-thermometer:before,
+.@{fa-css-prefix}-thermometer-full:before { content: @fa-var-thermometer-full; }
+.@{fa-css-prefix}-thermometer-3:before,
+.@{fa-css-prefix}-thermometer-three-quarters:before { content: @fa-var-thermometer-three-quarters; }
+.@{fa-css-prefix}-thermometer-2:before,
+.@{fa-css-prefix}-thermometer-half:before { content: @fa-var-thermometer-half; }
+.@{fa-css-prefix}-thermometer-1:before,
+.@{fa-css-prefix}-thermometer-quarter:before { content: @fa-var-thermometer-quarter; }
+.@{fa-css-prefix}-thermometer-0:before,
+.@{fa-css-prefix}-thermometer-empty:before { content: @fa-var-thermometer-empty; }
+.@{fa-css-prefix}-shower:before { content: @fa-var-shower; }
+.@{fa-css-prefix}-bathtub:before,
+.@{fa-css-prefix}-s15:before,
+.@{fa-css-prefix}-bath:before { content: @fa-var-bath; }
+.@{fa-css-prefix}-podcast:before { content: @fa-var-podcast; }
+.@{fa-css-prefix}-window-maximize:before { content: @fa-var-window-maximize; }
+.@{fa-css-prefix}-window-minimize:before { content: @fa-var-window-minimize; }
+.@{fa-css-prefix}-window-restore:before { content: @fa-var-window-restore; }
+.@{fa-css-prefix}-times-rectangle:before,
+.@{fa-css-prefix}-window-close:before { content: @fa-var-window-close; }
+.@{fa-css-prefix}-times-rectangle-o:before,
+.@{fa-css-prefix}-window-close-o:before { content: @fa-var-window-close-o; }
+.@{fa-css-prefix}-bandcamp:before { content: @fa-var-bandcamp; }
+.@{fa-css-prefix}-grav:before { content: @fa-var-grav; }
+.@{fa-css-prefix}-etsy:before { content: @fa-var-etsy; }
+.@{fa-css-prefix}-imdb:before { content: @fa-var-imdb; }
+.@{fa-css-prefix}-ravelry:before { content: @fa-var-ravelry; }
+.@{fa-css-prefix}-eercast:before { content: @fa-var-eercast; }
+.@{fa-css-prefix}-microchip:before { content: @fa-var-microchip; }
+.@{fa-css-prefix}-snowflake-o:before { content: @fa-var-snowflake-o; }
+.@{fa-css-prefix}-superpowers:before { content: @fa-var-superpowers; }
+.@{fa-css-prefix}-wpexplorer:before { content: @fa-var-wpexplorer; }
+.@{fa-css-prefix}-meetup:before { content: @fa-var-meetup; }
diff --git a/public/vendor/fontawesome/less/variables.less b/public/vendor/fontawesome/less/variables.less
index a2019dcadc..1620d22dd7 100644
--- a/public/vendor/fontawesome/less/variables.less
+++ b/public/vendor/fontawesome/less/variables.less
@@ -4,14 +4,18 @@
@fa-font-path: "./vendor/fontawesome/fonts";
@fa-font-size-base: 14px;
@fa-line-height-base: 1;
-//@fa-font-path: "//netdna.bootstrapcdn.com/font-awesome/4.6.3/fonts"; // for referencing Bootstrap CDN font files directly
+//@fa-font-path: "//netdna.bootstrapcdn.com/font-awesome/4.7.0/fonts"; // for referencing Bootstrap CDN font files directly
@fa-css-prefix: fa;
-@fa-version: "4.6.3";
+@fa-version: "4.7.0";
@fa-border-color: #eee;
@fa-inverse: #fff;
@fa-li-width: (30em / 14);
@fa-var-500px: "\f26e";
+@fa-var-address-book: "\f2b9";
+@fa-var-address-book-o: "\f2ba";
+@fa-var-address-card: "\f2bb";
+@fa-var-address-card-o: "\f2bc";
@fa-var-adjust: "\f042";
@fa-var-adn: "\f170";
@fa-var-align-center: "\f037";
@@ -60,11 +64,15 @@
@fa-var-backward: "\f04a";
@fa-var-balance-scale: "\f24e";
@fa-var-ban: "\f05e";
+@fa-var-bandcamp: "\f2d5";
@fa-var-bank: "\f19c";
@fa-var-bar-chart: "\f080";
@fa-var-bar-chart-o: "\f080";
@fa-var-barcode: "\f02a";
@fa-var-bars: "\f0c9";
+@fa-var-bath: "\f2cd";
+@fa-var-bathtub: "\f2cd";
+@fa-var-battery: "\f240";
@fa-var-battery-0: "\f244";
@fa-var-battery-1: "\f243";
@fa-var-battery-2: "\f242";
@@ -214,19 +222,25 @@
@fa-var-dot-circle-o: "\f192";
@fa-var-download: "\f019";
@fa-var-dribbble: "\f17d";
+@fa-var-drivers-license: "\f2c2";
+@fa-var-drivers-license-o: "\f2c3";
@fa-var-dropbox: "\f16b";
@fa-var-drupal: "\f1a9";
@fa-var-edge: "\f282";
@fa-var-edit: "\f044";
+@fa-var-eercast: "\f2da";
@fa-var-eject: "\f052";
@fa-var-ellipsis-h: "\f141";
@fa-var-ellipsis-v: "\f142";
@fa-var-empire: "\f1d1";
@fa-var-envelope: "\f0e0";
@fa-var-envelope-o: "\f003";
+@fa-var-envelope-open: "\f2b6";
+@fa-var-envelope-open-o: "\f2b7";
@fa-var-envelope-square: "\f199";
@fa-var-envira: "\f299";
@fa-var-eraser: "\f12d";
+@fa-var-etsy: "\f2d7";
@fa-var-eur: "\f153";
@fa-var-euro: "\f153";
@fa-var-exchange: "\f0ec";
@@ -294,6 +308,7 @@
@fa-var-forumbee: "\f211";
@fa-var-forward: "\f04e";
@fa-var-foursquare: "\f180";
+@fa-var-free-code-camp: "\f2c5";
@fa-var-frown-o: "\f119";
@fa-var-futbol-o: "\f1e3";
@fa-var-gamepad: "\f11b";
@@ -326,6 +341,7 @@
@fa-var-google-wallet: "\f1ee";
@fa-var-graduation-cap: "\f19d";
@fa-var-gratipay: "\f184";
+@fa-var-grav: "\f2d6";
@fa-var-group: "\f0c0";
@fa-var-h-square: "\f0fd";
@fa-var-hacker-news: "\f1d4";
@@ -342,6 +358,7 @@
@fa-var-hand-scissors-o: "\f257";
@fa-var-hand-spock-o: "\f259";
@fa-var-hand-stop-o: "\f256";
+@fa-var-handshake-o: "\f2b5";
@fa-var-hard-of-hearing: "\f2a4";
@fa-var-hashtag: "\f292";
@fa-var-hdd-o: "\f0a0";
@@ -365,8 +382,12 @@
@fa-var-houzz: "\f27c";
@fa-var-html5: "\f13b";
@fa-var-i-cursor: "\f246";
+@fa-var-id-badge: "\f2c1";
+@fa-var-id-card: "\f2c2";
+@fa-var-id-card-o: "\f2c3";
@fa-var-ils: "\f20b";
@fa-var-image: "\f03e";
+@fa-var-imdb: "\f2d8";
@fa-var-inbox: "\f01c";
@fa-var-indent: "\f03c";
@fa-var-industry: "\f275";
@@ -404,6 +425,7 @@
@fa-var-link: "\f0c1";
@fa-var-linkedin: "\f0e1";
@fa-var-linkedin-square: "\f08c";
+@fa-var-linode: "\f2b8";
@fa-var-linux: "\f17c";
@fa-var-list: "\f03a";
@fa-var-list-alt: "\f022";
@@ -436,8 +458,10 @@
@fa-var-meanpath: "\f20c";
@fa-var-medium: "\f23a";
@fa-var-medkit: "\f0fa";
+@fa-var-meetup: "\f2e0";
@fa-var-meh-o: "\f11a";
@fa-var-mercury: "\f223";
+@fa-var-microchip: "\f2db";
@fa-var-microphone: "\f130";
@fa-var-microphone-slash: "\f131";
@fa-var-minus: "\f068";
@@ -502,6 +526,7 @@
@fa-var-plus-circle: "\f055";
@fa-var-plus-square: "\f0fe";
@fa-var-plus-square-o: "\f196";
+@fa-var-podcast: "\f2ce";
@fa-var-power-off: "\f011";
@fa-var-print: "\f02f";
@fa-var-product-hunt: "\f288";
@@ -511,10 +536,12 @@
@fa-var-question: "\f128";
@fa-var-question-circle: "\f059";
@fa-var-question-circle-o: "\f29c";
+@fa-var-quora: "\f2c4";
@fa-var-quote-left: "\f10d";
@fa-var-quote-right: "\f10e";
@fa-var-ra: "\f1d0";
@fa-var-random: "\f074";
+@fa-var-ravelry: "\f2d9";
@fa-var-rebel: "\f1d0";
@fa-var-recycle: "\f1b8";
@fa-var-reddit: "\f1a1";
@@ -541,6 +568,7 @@
@fa-var-rub: "\f158";
@fa-var-ruble: "\f158";
@fa-var-rupee: "\f156";
+@fa-var-s15: "\f2cd";
@fa-var-safari: "\f267";
@fa-var-save: "\f0c7";
@fa-var-scissors: "\f0c4";
@@ -565,6 +593,7 @@
@fa-var-shopping-bag: "\f290";
@fa-var-shopping-basket: "\f291";
@fa-var-shopping-cart: "\f07a";
+@fa-var-shower: "\f2cc";
@fa-var-sign-in: "\f090";
@fa-var-sign-language: "\f2a7";
@fa-var-sign-out: "\f08b";
@@ -581,6 +610,7 @@
@fa-var-snapchat: "\f2ab";
@fa-var-snapchat-ghost: "\f2ac";
@fa-var-snapchat-square: "\f2ad";
+@fa-var-snowflake-o: "\f2dc";
@fa-var-soccer-ball-o: "\f1e3";
@fa-var-sort: "\f0dc";
@fa-var-sort-alpha-asc: "\f15d";
@@ -626,6 +656,7 @@
@fa-var-subway: "\f239";
@fa-var-suitcase: "\f0f2";
@fa-var-sun-o: "\f185";
+@fa-var-superpowers: "\f2dd";
@fa-var-superscript: "\f12b";
@fa-var-support: "\f1cd";
@fa-var-table: "\f0ce";
@@ -635,6 +666,7 @@
@fa-var-tags: "\f02c";
@fa-var-tasks: "\f0ae";
@fa-var-taxi: "\f1ba";
+@fa-var-telegram: "\f2c6";
@fa-var-television: "\f26c";
@fa-var-tencent-weibo: "\f1d5";
@fa-var-terminal: "\f120";
@@ -644,6 +676,17 @@
@fa-var-th-large: "\f009";
@fa-var-th-list: "\f00b";
@fa-var-themeisle: "\f2b2";
+@fa-var-thermometer: "\f2c7";
+@fa-var-thermometer-0: "\f2cb";
+@fa-var-thermometer-1: "\f2ca";
+@fa-var-thermometer-2: "\f2c9";
+@fa-var-thermometer-3: "\f2c8";
+@fa-var-thermometer-4: "\f2c7";
+@fa-var-thermometer-empty: "\f2cb";
+@fa-var-thermometer-full: "\f2c7";
+@fa-var-thermometer-half: "\f2c9";
+@fa-var-thermometer-quarter: "\f2ca";
+@fa-var-thermometer-three-quarters: "\f2c8";
@fa-var-thumb-tack: "\f08d";
@fa-var-thumbs-down: "\f165";
@fa-var-thumbs-o-down: "\f088";
@@ -653,6 +696,8 @@
@fa-var-times: "\f00d";
@fa-var-times-circle: "\f057";
@fa-var-times-circle-o: "\f05c";
+@fa-var-times-rectangle: "\f2d3";
+@fa-var-times-rectangle-o: "\f2d4";
@fa-var-tint: "\f043";
@fa-var-toggle-down: "\f150";
@fa-var-toggle-left: "\f191";
@@ -693,11 +738,16 @@
@fa-var-usb: "\f287";
@fa-var-usd: "\f155";
@fa-var-user: "\f007";
+@fa-var-user-circle: "\f2bd";
+@fa-var-user-circle-o: "\f2be";
@fa-var-user-md: "\f0f0";
+@fa-var-user-o: "\f2c0";
@fa-var-user-plus: "\f234";
@fa-var-user-secret: "\f21b";
@fa-var-user-times: "\f235";
@fa-var-users: "\f0c0";
+@fa-var-vcard: "\f2bb";
+@fa-var-vcard-o: "\f2bc";
@fa-var-venus: "\f221";
@fa-var-venus-double: "\f226";
@fa-var-venus-mars: "\f228";
@@ -722,10 +772,16 @@
@fa-var-wheelchair-alt: "\f29b";
@fa-var-wifi: "\f1eb";
@fa-var-wikipedia-w: "\f266";
+@fa-var-window-close: "\f2d3";
+@fa-var-window-close-o: "\f2d4";
+@fa-var-window-maximize: "\f2d0";
+@fa-var-window-minimize: "\f2d1";
+@fa-var-window-restore: "\f2d2";
@fa-var-windows: "\f17a";
@fa-var-won: "\f159";
@fa-var-wordpress: "\f19a";
@fa-var-wpbeginner: "\f297";
+@fa-var-wpexplorer: "\f2de";
@fa-var-wpforms: "\f298";
@fa-var-wrench: "\f0ad";
@fa-var-xing: "\f168";
diff --git a/src/admin/search.js b/src/admin/search.js
index 4c53815e48..3a6f52cfd0 100644
--- a/src/admin/search.js
+++ b/src/admin/search.js
@@ -19,7 +19,7 @@ function filterDirectories(directories) {
// exclude category.tpl, group.tpl, category-analytics.tpl
return !dir.includes('/partials/') &&
/\/.*\//.test(dir) &&
- !/manage\/(category|group|category\-analytics)$/.test(dir);
+ !/manage\/(category|group|category-analytics)$/.test(dir);
});
}
@@ -45,7 +45,7 @@ function sanitize(html) {
function simplify(translations) {
return translations
// remove all mustaches
- .replace(/(?:\{{1,2}[^\}]*?\}{1,2})/g, '')
+ .replace(/(?:\{{1,2}[^}]*?\}{1,2})/g, '')
// collapse whitespace
.replace(/(?:[ \t]*[\n\r]+[ \t]*)+/g, '\n')
.replace(/[\t ]+/g, ' ');
@@ -137,7 +137,7 @@ function initDict(language, callback) {
title = '[[admin/menu:general/dashboard]]';
} else {
title = title.match(/admin\/(.+?)\/(.+?)$/);
- title = '[[admin/menu:section-' +
+ title = '[[admin/menu:section-' +
(title[1] === 'development' ? 'advanced' : title[1]) +
']]' + (title[2] ? (' > [[admin/menu:' +
title[1] + '/' + title[2] + ']]') : '');
diff --git a/src/analytics.js b/src/analytics.js
index 6b248057da..6a733b1a5f 100644
--- a/src/analytics.js
+++ b/src/analytics.js
@@ -25,12 +25,12 @@ Analytics.increment = function (keys) {
keys.forEach(function (key) {
counters[key] = counters[key] || 0;
- ++counters[key];
+ counters[key] += 1;
});
};
Analytics.pageView = function (payload) {
- ++pageViews;
+ pageViews += 1;
if (payload.ip) {
db.sortedSetScore('ip:recent', payload.ip, function (err, score) {
@@ -38,20 +38,20 @@ Analytics.pageView = function (payload) {
return;
}
if (!score) {
- ++uniqueIPCount;
+ uniqueIPCount += 1;
}
var today = new Date();
today.setHours(today.getHours(), 0, 0, 0);
if (!score || score < today.getTime()) {
- ++uniquevisitors;
+ uniquevisitors += 1;
db.sortedSetAdd('ip:recent', Date.now(), payload.ip);
}
});
}
if (payload.path) {
- var categoryMatch = payload.path.match(isCategory),
- cid = categoryMatch ? parseInt(categoryMatch[1], 10) : null;
+ var categoryMatch = payload.path.match(isCategory);
+ var cid = categoryMatch ? parseInt(categoryMatch[1], 10) : null;
if (cid) {
Analytics.increment(['pageviews:byCid:' + cid]);
@@ -86,7 +86,7 @@ Analytics.writeData = function (callback) {
}
if (Object.keys(counters).length > 0) {
- for(var key in counters) {
+ for (var key in counters) {
if (counters.hasOwnProperty(key)) {
dbQueue.push(async.apply(db.sortedSetIncrBy, 'analytics:' + key, counters[key], today.getTime()));
delete counters[key];
@@ -103,13 +103,13 @@ Analytics.writeData = function (callback) {
};
Analytics.getHourlyStatsForSet = function (set, hour, numHours, callback) {
- var terms = {},
- hoursArr = [];
+ var terms = {};
+ var hoursArr = [];
hour = new Date(hour);
hour.setHours(hour.getHours(), 0, 0, 0);
- for (var i = 0, ii = numHours; i < ii; i++) {
+ for (var i = 0, ii = numHours; i < ii; i += 1) {
hoursArr.push(hour.getTime());
hour.setHours(hour.getHours() - 1, 0, 0, 0);
}
@@ -142,7 +142,8 @@ Analytics.getDailyStatsForSet = function (set, day, numDays, callback) {
day.setHours(0, 0, 0, 0);
async.whilst(function () {
- return numDays--;
+ numDays -= 1;
+ return numDays + 1;
}, function (next) {
Analytics.getHourlyStatsForSet(set, day.getTime() - (1000 * 60 * 60 * 24 * numDays), 24, function (err, day) {
if (err) {
@@ -177,7 +178,7 @@ Analytics.getMonthlyPageViews = function (callback) {
if (err) {
return callback(err);
}
- callback(null, {thisMonth: scores[0] || 0, lastMonth: scores[1] || 0});
+ callback(null, { thisMonth: scores[0] || 0, lastMonth: scores[1] || 0 });
});
};
@@ -193,7 +194,7 @@ Analytics.getCategoryAnalytics = function (cid, callback) {
Analytics.getErrorAnalytics = function (callback) {
async.parallel({
'not-found': async.apply(Analytics.getDailyStatsForSet, 'analytics:errors:404', Date.now(), 7),
- 'toobusy': async.apply(Analytics.getDailyStatsForSet, 'analytics:errors:503', Date.now(), 7)
+ toobusy: async.apply(Analytics.getDailyStatsForSet, 'analytics:errors:503', Date.now(), 7),
}, callback);
};
diff --git a/src/batch.js b/src/batch.js
index 19595df07e..cb3fd298a1 100644
--- a/src/batch.js
+++ b/src/batch.js
@@ -95,7 +95,7 @@ exports.processArray = function (array, process, options, callback) {
if (err) {
return next(err);
}
- start = start + batch;
+ start += batch;
if (options.interval) {
setTimeout(next, options.interval);
} else {
diff --git a/src/categories.js b/src/categories.js
index 5bb5222d38..815049ad4c 100644
--- a/src/categories.js
+++ b/src/categories.js
@@ -10,7 +10,6 @@ var plugins = require('./plugins');
var privileges = require('./privileges');
(function (Categories) {
-
require('./categories/data')(Categories);
require('./categories/create')(Categories);
require('./categories/delete')(Categories);
@@ -49,7 +48,7 @@ var privileges = require('./privileges');
},
isIgnored: function (next) {
Categories.isIgnored([data.cid], data.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -58,11 +57,11 @@ var privileges = require('./privileges');
category.isIgnored = results.isIgnored[0];
category.topic_count = results.topicCount;
- plugins.fireHook('filter:category.get', {category: category, uid: data.uid}, next);
+ plugins.fireHook('filter:category.get', { category: category, uid: data.uid }, next);
},
function (data, next) {
next(null, data.category);
- }
+ },
], callback);
};
@@ -73,7 +72,7 @@ var privileges = require('./privileges');
Categories.getPageCount = function (cid, uid, callback) {
async.parallel({
topicCount: async.apply(Categories.getCategoryField, cid, 'topic_count'),
- settings: async.apply(user.getSettings, uid)
+ settings: async.apply(user.getSettings, uid),
}, function (err, results) {
if (err) {
return callback(err);
@@ -107,7 +106,7 @@ var privileges = require('./privileges');
},
function (cids, next) {
Categories.getCategories(cids, uid, next);
- }
+ },
], callback);
};
@@ -146,7 +145,7 @@ var privileges = require('./privileges');
},
hasRead: function (next) {
Categories.hasReadCategories(cids, uid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -214,7 +213,7 @@ var privileges = require('./privileges');
});
if (!parentCids.length) {
- return callback(null, cids.map(function () {return null;}));
+ return callback(null, cids.map(function () { return null; }));
}
Categories.getCategoriesData(parentCids, next);
@@ -224,13 +223,13 @@ var privileges = require('./privileges');
return parentData[parentCids.indexOf(parseInt(category.parentCid, 10))];
});
next(null, parentData);
- }
+ },
], callback);
};
Categories.getChildren = function (cids, uid, callback) {
var categories = cids.map(function (cid) {
- return {cid: cid};
+ return { cid: cid };
});
async.each(categories, function (category, next) {
@@ -266,7 +265,7 @@ var privileges = require('./privileges');
async.each(category.children, function (child, next) {
getChildrenRecursive(child, uid, next);
}, next);
- }
+ },
], callback);
}
@@ -293,9 +292,12 @@ var privileges = require('./privileges');
* @param parentCid {number} start from 0 to build full tree
*/
Categories.getTree = function (categories, parentCid) {
- var tree = [], i = 0, len = categories.length, category;
+ var tree = [];
+ var i = 0;
+ var len = categories.length;
+ var category;
- for (i; i < len; ++i) {
+ for (i; i < len; i += 1) {
category = categories[i];
if (!category.hasOwnProperty('parentCid') || category.parentCid === null) {
category.parentCid = 0;
@@ -357,9 +359,7 @@ var privileges = require('./privileges');
return uid && !isIgnoring[index];
});
next(null, readingUids);
- }
+ },
], callback);
};
-
-
}(exports));
diff --git a/src/categories/activeusers.js b/src/categories/activeusers.js
index 15673939ae..5ce28c4b11 100644
--- a/src/categories/activeusers.js
+++ b/src/categories/activeusers.js
@@ -5,7 +5,6 @@ var posts = require('../posts');
var db = require('../database');
module.exports = function (Categories) {
-
Categories.getActiveUsers = function (cid, callback) {
async.waterfall([
function (next) {
@@ -22,7 +21,7 @@ module.exports = function (Categories) {
});
next(null, uids);
- }
+ },
], callback);
};
};
diff --git a/src/categories/create.js b/src/categories/create.js
index 508d8ab348..7be163bd5b 100644
--- a/src/categories/create.js
+++ b/src/categories/create.js
@@ -9,7 +9,6 @@ var privileges = require('../privileges');
var utils = require('../../public/src/utils');
module.exports = function (Categories) {
-
Categories.create = function (data, callback) {
var category;
var parentCid = data.parentCid ? data.parentCid : 0;
@@ -40,11 +39,11 @@ module.exports = function (Categories) {
order: order,
link: '',
numRecentReplies: 1,
- class: ( data.class ? data.class : 'col-md-3 col-xs-6' ),
- imageClass: 'cover'
+ class: (data.class ? data.class : 'col-md-3 col-xs-6'),
+ imageClass: 'cover',
};
- plugins.fireHook('filter:category.create', {category: category, data: data}, next);
+ plugins.fireHook('filter:category.create', { category: category, data: data }, next);
},
function (data, next) {
category = data.category;
@@ -63,7 +62,7 @@ module.exports = function (Categories) {
async.apply(db.sortedSetAdd, 'cid:' + parentCid + ':children', category.order, category.cid),
async.apply(privileges.categories.give, defaultPrivileges, category.cid, 'administrators'),
async.apply(privileges.categories.give, defaultPrivileges, category.cid, 'registered-users'),
- async.apply(privileges.categories.give, ['find', 'read', 'topics:read'], category.cid, 'guests')
+ async.apply(privileges.categories.give, ['find', 'read', 'topics:read'], category.cid, 'guests'),
], next);
},
function (results, next) {
@@ -75,7 +74,7 @@ module.exports = function (Categories) {
function (category, next) {
plugins.fireHook('action:category.create', category);
next(null, category);
- }
+ },
], callback);
};
@@ -93,7 +92,7 @@ module.exports = function (Categories) {
function (next) {
async.parallel({
source: async.apply(db.getObject, 'category:' + fromCid),
- destination: async.apply(db.getObject, 'category:' + toCid)
+ destination: async.apply(db.getObject, 'category:' + toCid),
}, next);
},
function (results, next) {
@@ -132,7 +131,7 @@ module.exports = function (Categories) {
},
function (results, next) {
Categories.copyPrivilegesFrom(fromCid, toCid, next);
- }
+ },
], function (err) {
callback(err, destination);
});
@@ -165,8 +164,7 @@ module.exports = function (Categories) {
async.eachSeries(members, function (member, next) {
groups.join('cid:' + toCid + ':privileges:' + privilege, member, next);
}, next);
- }
+ },
], callback);
}
-
};
diff --git a/src/categories/data.js b/src/categories/data.js
index ccc31343d9..25b7021610 100644
--- a/src/categories/data.js
+++ b/src/categories/data.js
@@ -7,7 +7,6 @@ var winston = require('winston');
var db = require('../database');
module.exports = function (Categories) {
-
Categories.getCategoryData = function (cid, callback) {
db.getObject('category:' + cid, function (err, category) {
if (err) {
@@ -46,11 +45,13 @@ module.exports = function (Categories) {
category.disabled = category.hasOwnProperty('disabled') ? parseInt(category.disabled, 10) === 1 : undefined;
category.icon = category.icon || 'hidden';
if (category.hasOwnProperty('post_count')) {
- category.post_count = category.totalPostCount = category.post_count || 0;
+ category.post_count = category.post_count || 0;
+ category.totalPostCount = category.post_count;
}
if (category.hasOwnProperty('topic_count')) {
- category.topic_count = category.totalTopicCount = category.topic_count || 0;
+ category.topic_count = category.topic_count || 0;
+ category.totalTopicCount = category.topic_count;
}
if (category.image) {
@@ -96,7 +97,7 @@ module.exports = function (Categories) {
async.apply(db.getSortedSetRange, 'categories:cid', 0, -1),
function (cids, next) {
Categories.getCategoriesFields(cids, fields, next);
- }
+ },
], callback);
};
@@ -111,5 +112,4 @@ module.exports = function (Categories) {
Categories.incrementCategoryFieldBy = function (cid, field, value, callback) {
db.incrObjectFieldBy('category:' + cid, field, value, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/categories/delete.js b/src/categories/delete.js
index 06d4931132..4aad25846f 100644
--- a/src/categories/delete.js
+++ b/src/categories/delete.js
@@ -9,7 +9,6 @@ var groups = require('../groups');
var privileges = require('../privileges');
module.exports = function (Categories) {
-
Categories.purge = function (cid, uid, callback) {
async.waterfall([
function (next) {
@@ -17,7 +16,7 @@ module.exports = function (Categories) {
async.eachLimit(tids, 10, function (tid, next) {
topics.purgePostsAndTopic(tid, uid, next);
}, next);
- }, {alwaysStartAt: 0}, next);
+ }, { alwaysStartAt: 0 }, next);
},
function (next) {
Categories.getPinnedTids('cid:' + cid + ':tids:pinned', 0, -1, next);
@@ -33,7 +32,7 @@ module.exports = function (Categories) {
function (next) {
plugins.fireHook('action:category.delete', cid);
next();
- }
+ },
], callback);
};
@@ -55,14 +54,14 @@ module.exports = function (Categories) {
'cid:' + cid + ':ignorers',
'cid:' + cid + ':children',
'cid:' + cid + ':tag:whitelist',
- 'category:' + cid
+ 'category:' + cid,
], next);
},
function (next) {
async.each(privileges.privilegeList, function (privilege, next) {
groups.destroy('cid:' + cid + ':privileges:' + privilege, next);
}, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -77,7 +76,7 @@ module.exports = function (Categories) {
},
children: function (next) {
db.getSortedSetRange('cid:' + cid + ':children', 0, -1, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -94,14 +93,14 @@ module.exports = function (Categories) {
},
function (next) {
db.sortedSetAdd('cid:0:children', cid, cid, next);
- }
+ },
], next);
}, next);
- }
+ },
], next);
- }
+ },
], function (err) {
callback(err);
});
}
-};
\ No newline at end of file
+};
diff --git a/src/categories/recentreplies.js b/src/categories/recentreplies.js
index 831991d61a..c38fec527e 100644
--- a/src/categories/recentreplies.js
+++ b/src/categories/recentreplies.js
@@ -14,7 +14,6 @@ var batch = require('../batch');
module.exports = function (Categories) {
-
Categories.getRecentReplies = function (cid, uid, count, callback) {
if (!parseInt(count, 10)) {
return callback(null, []);
@@ -28,8 +27,8 @@ module.exports = function (Categories) {
privileges.posts.filter('read', pids, uid, next);
},
function (pids, next) {
- posts.getPostSummaryByPids(pids, uid, {stripTags: true}, next);
- }
+ posts.getPostSummaryByPids(pids, uid, { stripTags: true }, next);
+ },
], callback);
};
@@ -40,7 +39,7 @@ module.exports = function (Categories) {
},
numRecentReplies: function (next) {
db.getObjectField('category:' + cid, 'numRecentReplies', next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -61,7 +60,7 @@ module.exports = function (Categories) {
},
function (next) {
db.sortedSetAdd('cid:' + cid + ':recent_tids', Date.now(), tid, next);
- }
+ },
], callback);
});
};
@@ -95,7 +94,7 @@ module.exports = function (Categories) {
bubbleUpChildrenPosts(categoryData);
next();
- }
+ },
], callback);
};
@@ -131,17 +130,19 @@ module.exports = function (Categories) {
results.teasers.forEach(function (teaser, index) {
if (teaser) {
teaser.cid = topicData[index].cid;
- teaser.parentCid = parseInt(parentCids[teaser.cid]) || 0;
- teaser.tid = teaser.uid = teaser.user.uid = undefined;
+ teaser.parentCid = parseInt(parentCids[teaser.cid], 10) || 0;
+ teaser.tid = undefined;
+ teaser.uid = undefined;
+ teaser.user.uid = undefined;
teaser.topic = {
slug: topicData[index].slug,
- title: validator.escape(String(topicData[index].title))
+ title: validator.escape(String(topicData[index].title)),
};
}
});
results.teasers = results.teasers.filter(Boolean);
next(null, results.teasers);
- }
+ },
], callback);
}
@@ -211,9 +212,9 @@ module.exports = function (Categories) {
},
function (next) {
db.sortedSetAdd('cid:' + cid + ':pids', timestamps, pids, next);
- }
+ },
], next);
- }
+ },
], next);
}, function (err) {
if (err) {
@@ -238,7 +239,7 @@ module.exports = function (Categories) {
},
function (next) {
db.incrObjectFieldBy('category:' + newCid, 'post_count', postCount, next);
- }
+ },
], function (err) {
if (err) {
winston.error(err.message);
@@ -248,4 +249,3 @@ module.exports = function (Categories) {
}
};
-
diff --git a/src/categories/topics.js b/src/categories/topics.js
index 9e477e51ef..a346307e9c 100644
--- a/src/categories/topics.js
+++ b/src/categories/topics.js
@@ -7,7 +7,6 @@ var topics = require('../topics');
var plugins = require('../plugins');
module.exports = function (Categories) {
-
Categories.getCategoryTopics = function (data, callback) {
async.waterfall([
function (next) {
@@ -21,23 +20,23 @@ module.exports = function (Categories) {
},
function (topics, next) {
if (!Array.isArray(topics) || !topics.length) {
- return next(null, {topics: [], uid: data.uid});
+ return next(null, { topics: [], uid: data.uid });
}
- for (var i = 0; i < topics.length; ++i) {
+ for (var i = 0; i < topics.length; i += 1) {
topics[i].index = data.start + i;
}
- plugins.fireHook('filter:category.topics.get', {cid: data.cid, topics: topics, uid: data.uid}, next);
+ plugins.fireHook('filter:category.topics.get', { cid: data.cid, topics: topics, uid: data.uid }, next);
},
function (results, next) {
- next(null, {topics: results.topics, nextStart: data.stop + 1});
- }
+ next(null, { topics: results.topics, nextStart: data.stop + 1 });
+ },
], callback);
};
Categories.getTopicIds = function (cid, set, reverse, start, stop, callback) {
- var pinnedTids;
+ var pinnedTids;
var pinnedCount;
var totalPinnedCount;
@@ -65,7 +64,7 @@ module.exports = function (Categories) {
stop = stop === -1 ? stop : start + normalTidsToGet - 1;
if (Array.isArray(set)) {
- db[reverse ? 'getSortedSetRevIntersect' : 'getSortedSetIntersect']({sets: set, start: start, stop: stop}, next);
+ db[reverse ? 'getSortedSetRevIntersect' : 'getSortedSetIntersect']({ sets: set, start: start, stop: stop }, next);
} else {
db[reverse ? 'getSortedSetRevRange' : 'getSortedSetRange'](set, start, stop, next);
}
@@ -76,7 +75,7 @@ module.exports = function (Categories) {
});
next(null, pinnedTids.concat(normalTids));
- }
+ },
], callback);
};
@@ -132,15 +131,14 @@ module.exports = function (Categories) {
},
function (next) {
db.sortedSetIncrBy('cid:' + cid + ':tids:posts', 1, postData.tid, next);
- }
+ },
], function (err) {
next(err);
});
},
function (next) {
Categories.updateRecentTid(cid, postData.tid, next);
- }
+ },
], callback);
};
-
};
diff --git a/src/categories/unread.js b/src/categories/unread.js
index 3a1ba27277..1ef6ee40b5 100644
--- a/src/categories/unread.js
+++ b/src/categories/unread.js
@@ -1,11 +1,8 @@
+'use strict';
-"use strict";
-
-var async = require('async');
var db = require('../database');
module.exports = function (Categories) {
-
Categories.markAsRead = function (cids, uid, callback) {
callback = callback || function () {};
if (!Array.isArray(cids) || !cids.length) {
@@ -43,7 +40,7 @@ module.exports = function (Categories) {
Categories.hasReadCategories = function (cids, uid, callback) {
var sets = [];
- for (var i = 0, ii = cids.length; i < ii; i++) {
+ for (var i = 0, ii = cids.length; i < ii; i += 1) {
sets.push('cid:' + cids[i] + ':read_by_uid');
}
@@ -53,5 +50,4 @@ module.exports = function (Categories) {
Categories.hasReadCategory = function (cid, uid, callback) {
db.isSetMember('cid:' + cid + ':read_by_uid', uid, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/categories/update.js b/src/categories/update.js
index afaad6d974..04bf0e2235 100644
--- a/src/categories/update.js
+++ b/src/categories/update.js
@@ -10,9 +10,7 @@ var translator = require('../../public/src/modules/translator');
var plugins = require('../plugins');
module.exports = function (Categories) {
-
Categories.update = function (modified, callback) {
-
var cids = Object.keys(modified);
async.each(cids, function (cid, next) {
@@ -43,7 +41,7 @@ module.exports = function (Categories) {
}
},
function (next) {
- plugins.fireHook('filter:category.update', {category: modifiedFields}, next);
+ plugins.fireHook('filter:category.update', { category: modifiedFields }, next);
},
function (categoryData, next) {
category = categoryData.category;
@@ -59,9 +57,9 @@ module.exports = function (Categories) {
}, next);
},
function (next) {
- plugins.fireHook('action:category.update', {cid: cid, modified: category});
+ plugins.fireHook('action:category.update', { cid: cid, modified: category });
next();
- }
+ },
], callback);
}
@@ -84,7 +82,7 @@ module.exports = function (Categories) {
} else {
next();
}
- }
+ },
], callback);
}
@@ -108,9 +106,9 @@ module.exports = function (Categories) {
},
function (next) {
db.setObjectField('category:' + cid, 'parentCid', newParent, next);
- }
+ },
], next);
- }
+ },
], function (err) {
callback(err);
});
@@ -131,7 +129,7 @@ module.exports = function (Categories) {
return index;
});
db.sortedSetAdd('cid:' + cid + ':tag:whitelist', scores, tags, next);
- }
+ },
], callback);
}
@@ -148,9 +146,9 @@ module.exports = function (Categories) {
function (next) {
parentCid = parseInt(parentCid, 10) || 0;
db.sortedSetAdd('cid:' + parentCid + ':children', order, cid, next);
- }
+ },
], next);
- }
+ },
], function (err) {
callback(err);
});
@@ -163,8 +161,7 @@ module.exports = function (Categories) {
},
function (parsedDescription, next) {
Categories.setCategoryField(cid, 'descriptionParsed', parsedDescription, next);
- }
+ },
], callback);
};
-
};
diff --git a/src/controllers/404.js b/src/controllers/404.js
new file mode 100644
index 0000000000..bc4e2e1d00
--- /dev/null
+++ b/src/controllers/404.js
@@ -0,0 +1,47 @@
+'use strict';
+
+var nconf = require('nconf');
+var winston = require('winston');
+var validator = require('validator');
+
+var meta = require('../meta');
+var plugins = require('../plugins');
+
+exports.handle404 = function (req, res) {
+ var relativePath = nconf.get('relative_path');
+ var isClientScript = new RegExp('^' + relativePath + '\\/assets\\/src\\/.+\\.js');
+
+ if (plugins.hasListeners('action:meta.override404')) {
+ return plugins.fireHook('action:meta.override404', {
+ req: req,
+ res: res,
+ error: {},
+ });
+ }
+
+ if (isClientScript.test(req.url)) {
+ res.type('text/javascript').status(200).send('');
+ } else if (req.path.startsWith(relativePath + '/assets/uploads') || (req.get('accept') && req.get('accept').indexOf('text/html') === -1) || req.path === '/favicon.ico') {
+ meta.errors.log404(req.path || '');
+ res.sendStatus(404);
+ } else if (req.accepts('html')) {
+ if (process.env.NODE_ENV === 'development') {
+ winston.warn('Route requested but not found: ' + req.url);
+ }
+
+ meta.errors.log404(req.path.replace(/^\/api/, '') || '');
+ res.status(404);
+
+ var path = String(req.path || '');
+
+ if (res.locals.isAPI) {
+ return res.json({ path: validator.escape(path.replace(/^\/api/, '')), title: '[[global:404.title]]' });
+ }
+ var middleware = require('../middleware');
+ middleware.buildHeader(req, res, function () {
+ res.render('404', { path: validator.escape(path), title: '[[global:404.title]]' });
+ });
+ } else {
+ res.status(404).type('txt').send('Not found');
+ }
+};
diff --git a/src/controllers/accounts.js b/src/controllers/accounts.js
index 2c99a981c3..a7aa1716b4 100644
--- a/src/controllers/accounts.js
+++ b/src/controllers/accounts.js
@@ -10,7 +10,7 @@ var accountsController = {
posts: require('./accounts/posts'),
notifications: require('./accounts/notifications'),
chats: require('./accounts/chats'),
- session: require('./accounts/session')
+ session: require('./accounts/session'),
};
module.exports = accountsController;
diff --git a/src/controllers/accounts/chats.js b/src/controllers/accounts/chats.js
index c951bafdbd..8ffac0a4dc 100644
--- a/src/controllers/accounts/chats.js
+++ b/src/controllers/accounts/chats.js
@@ -21,7 +21,7 @@ chatsController.get = function (req, res, callback) {
function (next) {
async.parallel({
uid: async.apply(user.getUidByUserslug, req.params.userslug),
- username: async.apply(user.getUsernameByUserslug, req.params.userslug)
+ username: async.apply(user.getUsernameByUserslug, req.params.userslug),
}, next);
},
function (results, next) {
@@ -45,7 +45,7 @@ chatsController.get = function (req, res, callback) {
nextStart: recentChats.nextStart,
allowed: true,
title: '[[pages:chats]]',
- breadcrumbs: helpers.buildBreadcrumbs([{text: username, url: '/user/' + req.params.userslug}, {text: '[[pages:chats]]'}])
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: username, url: '/user/' + req.params.userslug }, { text: '[[pages:chats]]' }]),
});
}
messaging.isUserInRoom(req.uid, req.params.roomid, next);
@@ -62,10 +62,10 @@ chatsController.get = function (req, res, callback) {
callerUid: req.uid,
uid: uid,
roomId: req.params.roomid,
- isNew: false
- })
+ isNew: false,
+ }),
}, next);
- }
+ },
], function (err, data) {
if (err) {
return callback(err);
@@ -87,9 +87,9 @@ chatsController.get = function (req, res, callback) {
room.usernames = messaging.generateUsernames(room.users, req.uid);
room.title = room.roomName || room.usernames || '[[pages:chats]]';
room.breadcrumbs = helpers.buildBreadcrumbs([
- {text: username, url: '/user/' + req.params.userslug},
- {text: '[[pages:chats]]', url: '/user/' + req.params.userslug + '/chats'},
- {text: room.roomName || room.usernames || '[[pages:chats]]'}
+ { text: username, url: '/user/' + req.params.userslug },
+ { text: '[[pages:chats]]', url: '/user/' + req.params.userslug + '/chats' },
+ { text: room.roomName || room.usernames || '[[pages:chats]]' },
]);
room.maximumUsersInChatRoom = parseInt(meta.config.maximumUsersInChatRoom, 10) || 0;
room.maximumChatMessageLength = parseInt(meta.config.maximumChatMessageLength, 10) || 1000;
@@ -114,5 +114,4 @@ chatsController.redirectToChat = function (req, res, next) {
};
-
-module.exports = chatsController;
\ No newline at end of file
+module.exports = chatsController;
diff --git a/src/controllers/accounts/edit.js b/src/controllers/accounts/edit.js
index 58409060e4..3c2e57bec4 100644
--- a/src/controllers/accounts/edit.js
+++ b/src/controllers/accounts/edit.js
@@ -2,7 +2,6 @@
var async = require('async');
var fs = require('fs');
-var nconf = require('nconf');
var winston = require('winston');
var db = require('../../database');
@@ -25,7 +24,7 @@ editController.get = function (req, res, callback) {
userData.maximumSignatureLength = parseInt(meta.config.maximumSignatureLength, 10) || 255;
userData.maximumAboutMeLength = parseInt(meta.config.maximumAboutMeLength, 10) || 1000;
userData.maximumProfileImageSize = parseInt(meta.config.maximumProfileImageSize, 10);
- userData.allowProfileImageUploads = parseInt(meta.config.allowProfileImageUploads) === 1;
+ userData.allowProfileImageUploads = parseInt(meta.config.allowProfileImageUploads, 10) === 1;
userData.allowAccountDelete = parseInt(meta.config.allowAccountDelete, 10) === 1;
userData.profileImageDimension = parseInt(meta.config.profileImageDimension, 10) || 128;
@@ -37,12 +36,15 @@ editController.get = function (req, res, callback) {
});
userData.title = '[[pages:account/edit, ' + userData.username + ']]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{
- text: userData.username,
- url: '/user/' + userData.userslug
- }, {
- text: '[[user:edit]]'
- }]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([
+ {
+ text: userData.username,
+ url: '/user/' + userData.userslug,
+ },
+ {
+ text: '[[user:edit]]',
+ },
+ ]);
userData.editButtons = [];
plugins.fireHook('filter:user.account.edit', userData, function (err, userData) {
@@ -81,15 +83,19 @@ function renderRoute(name, req, res, next) {
}
userData.title = '[[pages:account/edit/' + name + ', ' + userData.username + ']]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{
- text: userData.username,
- url: '/user/' + userData.userslug
- }, {
- text: '[[user:edit]]',
- url: '/user/' + userData.userslug + '/edit'
- }, {
- text: '[[user:' + name + ']]'
- }]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([
+ {
+ text: userData.username,
+ url: '/user/' + userData.userslug,
+ },
+ {
+ text: '[[user:edit]]',
+ url: '/user/' + userData.userslug + '/edit',
+ },
+ {
+ text: '[[user:' + name + ']]',
+ },
+ ]);
res.render('account/edit/' + name, userData);
});
@@ -107,7 +113,7 @@ function getUserData(req, next, callback) {
return callback();
}
db.getObjectField('user:' + userData.uid, 'password', next);
- }
+ },
], function (err, password) {
if (err) {
return callback(err);
@@ -138,7 +144,7 @@ editController.uploadPicture = function (req, res, next) {
}
user.uploadPicture(updateUid, userPhoto, next);
- }
+ },
], function (err, image) {
fs.unlink(userPhoto.path, function (err) {
if (err) {
@@ -151,7 +157,7 @@ editController.uploadPicture = function (req, res, next) {
res.json([{
name: userPhoto.name,
- url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url
+ url: image.url,
}]);
});
};
@@ -161,14 +167,14 @@ editController.uploadCoverPicture = function (req, res, next) {
user.updateCoverPicture({
file: req.files.files[0],
- uid: params.uid
+ uid: params.uid,
}, function (err, image) {
if (err) {
return next(err);
}
res.json([{
- url: image.url
+ url: image.url,
}]);
});
};
diff --git a/src/controllers/accounts/follow.js b/src/controllers/accounts/follow.js
index 7d1e91b5e2..eac274136d 100644
--- a/src/controllers/accounts/follow.js
+++ b/src/controllers/accounts/follow.js
@@ -36,7 +36,7 @@ function getFollow(tpl, name, req, res, callback) {
}
var method = name === 'following' ? 'getFollowing' : 'getFollowers';
user[method](userData.uid, start, stop, next);
- }
+ },
], function (err, users) {
if (err) {
return callback(err);
@@ -47,10 +47,10 @@ function getFollow(tpl, name, req, res, callback) {
var count = name === 'following' ? userData.followingCount : userData.followerCount;
var pageCount = Math.ceil(count / resultsPerPage);
userData.pagination = pagination.create(page, pageCount);
- userData.breadcrumbs = helpers.buildBreadcrumbs([{text: userData.username, url: '/user/' + userData.userslug}, {text: '[[user:' + name + ']]'}]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username, url: '/user/' + userData.userslug }, { text: '[[user:' + name + ']]' }]);
res.render(tpl, userData);
});
}
-module.exports = followController;
\ No newline at end of file
+module.exports = followController;
diff --git a/src/controllers/accounts/groups.js b/src/controllers/accounts/groups.js
index 038d63de1d..650c510fc9 100644
--- a/src/controllers/accounts/groups.js
+++ b/src/controllers/accounts/groups.js
@@ -38,7 +38,7 @@ groupsController.get = function (req, res, callback) {
group.members = members[index];
});
next();
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -46,9 +46,9 @@ groupsController.get = function (req, res, callback) {
userData.groups = groupsData;
userData.title = '[[pages:account/groups, ' + userData.username + ']]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{text: userData.username, url: '/user/' + userData.userslug}, {text: '[[global:header.groups]]'}]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username, url: '/user/' + userData.userslug }, { text: '[[global:header.groups]]' }]);
res.render('account/groups', userData);
});
};
-module.exports = groupsController;
\ No newline at end of file
+module.exports = groupsController;
diff --git a/src/controllers/accounts/helpers.js b/src/controllers/accounts/helpers.js
index 2ef476a4ef..1ee9a08678 100644
--- a/src/controllers/accounts/helpers.js
+++ b/src/controllers/accounts/helpers.js
@@ -52,14 +52,14 @@ helpers.getUserDataByUserSlug = function (userslug, callerUID, callback) {
plugins.fireHook('filter:user.profileLinks', [], next);
},
profile_menu: function (next) {
- plugins.fireHook('filter:user.profileMenu', {uid: uid, callerUID: callerUID, links: []}, next);
+ plugins.fireHook('filter:user.profileMenu', { uid: uid, callerUID: callerUID, links: [] }, next);
},
groups: function (next) {
groups.getUserGroups([uid], next);
},
sso: function (next) {
- plugins.fireHook('filter:auth.list', {uid: uid, associations: []}, next);
- }
+ plugins.fireHook('filter:auth.list', { uid: uid, associations: [] }, next);
+ },
}, next);
},
function (results, next) {
@@ -144,7 +144,7 @@ helpers.getUserDataByUserSlug = function (userslug, callerUID, callback) {
userData['email:disableEdit'] = !userData.isAdmin && parseInt(meta.config['email:disableEdit'], 10) === 1;
next(null, userData);
- }
+ },
], callback);
};
diff --git a/src/controllers/accounts/info.js b/src/controllers/accounts/info.js
index 77ab2f275e..e852ebc3df 100644
--- a/src/controllers/accounts/info.js
+++ b/src/controllers/accounts/info.js
@@ -23,9 +23,9 @@ infoController.get = function (req, res, callback) {
history: async.apply(user.getModerationHistory, userData.uid),
sessions: async.apply(user.auth.getSessions, userData.uid, req.sessionID),
usernames: async.apply(user.getHistory, 'user:' + userData.uid + ':usernames'),
- emails: async.apply(user.getHistory, 'user:' + userData.uid + ':emails')
+ emails: async.apply(user.getHistory, 'user:' + userData.uid + ':emails'),
}, next);
- }
+ },
], function (err, data) {
if (err) {
return callback(err);
@@ -36,10 +36,10 @@ infoController.get = function (req, res, callback) {
userData.usernames = data.usernames;
userData.emails = data.emails;
userData.title = '[[pages:account/info]]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{text: userData.username, url: '/user/' + userData.userslug}, {text: '[[user:account_info]]'}]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username, url: '/user/' + userData.userslug }, { text: '[[user:account_info]]' }]);
res.render('account/info', userData);
});
};
-module.exports = infoController;
\ No newline at end of file
+module.exports = infoController;
diff --git a/src/controllers/accounts/notifications.js b/src/controllers/accounts/notifications.js
index 50a5a5913b..6184ec056d 100644
--- a/src/controllers/accounts/notifications.js
+++ b/src/controllers/accounts/notifications.js
@@ -14,7 +14,7 @@ notificationsController.get = function (req, res, next) {
notifications: notifications,
nextStart: 40,
title: '[[pages:notifications]]',
- breadcrumbs: helpers.buildBreadcrumbs([{text: '[[pages:notifications]]'}])
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[pages:notifications]]' }]),
});
});
};
diff --git a/src/controllers/accounts/posts.js b/src/controllers/accounts/posts.js
index 9875387997..2f603b8015 100644
--- a/src/controllers/accounts/posts.js
+++ b/src/controllers/accounts/posts.js
@@ -18,44 +18,44 @@ var templateToData = {
set: 'bookmarks',
type: 'posts',
noItemsFoundKey: '[[topic:bookmarks.has_no_bookmarks]]',
- crumb: '[[user:bookmarks]]'
+ crumb: '[[user:bookmarks]]',
},
'account/posts': {
set: 'posts',
type: 'posts',
noItemsFoundKey: '[[user:has_no_posts]]',
- crumb: '[[global:posts]]'
+ crumb: '[[global:posts]]',
},
'account/upvoted': {
set: 'upvote',
type: 'posts',
noItemsFoundKey: '[[user:has_no_upvoted_posts]]',
- crumb: '[[global:upvoted]]'
+ crumb: '[[global:upvoted]]',
},
'account/downvoted': {
set: 'downvote',
type: 'posts',
noItemsFoundKey: '[[user:has_no_downvoted_posts]]',
- crumb: '[[global:downvoted]]'
+ crumb: '[[global:downvoted]]',
},
'account/best': {
set: 'posts:votes',
type: 'posts',
noItemsFoundKey: '[[user:has_no_voted_posts]]',
- crumb: '[[global:best]]'
+ crumb: '[[global:best]]',
},
'account/watched': {
set: 'followed_tids',
type: 'topics',
noItemsFoundKey: '[[user:has_no_watched_topics]]',
- crumb: '[[user:watched]]'
+ crumb: '[[user:watched]]',
},
'account/topics': {
set: 'topics',
type: 'topics',
noItemsFoundKey: '[[user:has_no_topics]]',
- crumb: '[[global:topics]]'
- }
+ crumb: '[[global:topics]]',
+ },
};
postsController.getBookmarks = function (req, res, next) {
@@ -101,7 +101,7 @@ function getFromUserSet(template, req, res, callback) {
},
userData: function (next) {
accountHelpers.getUserDataByUserSlug(req.params.userslug, req.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -127,9 +127,9 @@ function getFromUserSet(template, req, res, callback) {
var start = (page - 1) * itemsPerPage;
var stop = start + itemsPerPage - 1;
data.method(setName, req.uid, start, stop, next);
- }
+ },
}, next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -143,10 +143,10 @@ function getFromUserSet(template, req, res, callback) {
userData.noItemsFoundKey = data.noItemsFoundKey;
userData.title = '[[pages:' + data.template + ', ' + userData.username + ']]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{text: userData.username, url: '/user/' + userData.userslug}, {text: data.crumb}]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username, url: '/user/' + userData.userslug }, { text: data.crumb }]);
res.render(data.template, userData);
});
}
-module.exports = postsController;
\ No newline at end of file
+module.exports = postsController;
diff --git a/src/controllers/accounts/profile.js b/src/controllers/accounts/profile.js
index e95fedd0d1..1fc092a5f4 100644
--- a/src/controllers/accounts/profile.js
+++ b/src/controllers/accounts/profile.js
@@ -62,7 +62,7 @@ profileController.get = function (req, res, callback) {
} else {
next();
}
- }
+ },
}, next);
},
function (results, next) {
@@ -76,7 +76,7 @@ profileController.get = function (req, res, callback) {
userData.hasPrivateChat = results.hasPrivateChat;
userData.aboutme = results.aboutme;
userData.nextStart = results.posts.nextStart;
- userData.breadcrumbs = helpers.buildBreadcrumbs([{text: userData.username}]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username }]);
userData.title = userData.username;
var pageCount = Math.ceil(userData.postcount / itemsPerPage);
userData.pagination = pagination.create(page, pageCount, req.query);
@@ -92,21 +92,21 @@ profileController.get = function (req, res, callback) {
res.locals.metaTags = [
{
- name: "title",
- content: userData.fullname || userData.username
+ name: 'title',
+ content: userData.fullname || userData.username,
},
{
- name: "description",
- content: plainAboutMe
+ name: 'description',
+ content: plainAboutMe,
},
{
property: 'og:title',
- content: userData.fullname || userData.username
+ content: userData.fullname || userData.username,
},
{
property: 'og:description',
- content: plainAboutMe
- }
+ content: plainAboutMe,
+ },
];
if (userData.picture) {
@@ -114,12 +114,12 @@ profileController.get = function (req, res, callback) {
{
property: 'og:image',
content: userData.picture,
- noEscape: true
+ noEscape: true,
},
{
- property: "og:image:url",
+ property: 'og:image:url',
content: userData.picture,
- noEscape: true
+ noEscape: true,
}
);
}
@@ -127,8 +127,8 @@ profileController.get = function (req, res, callback) {
return group && group.name === userData.groupTitle;
});
- plugins.fireHook('filter:user.account', {userData: userData, uid: req.uid}, next);
- }
+ plugins.fireHook('filter:user.account', { userData: userData, uid: req.uid }, next);
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -137,4 +137,4 @@ profileController.get = function (req, res, callback) {
});
};
-module.exports = profileController;
\ No newline at end of file
+module.exports = profileController;
diff --git a/src/controllers/accounts/session.js b/src/controllers/accounts/session.js
index e8123820ee..809cdb6dad 100644
--- a/src/controllers/accounts/session.js
+++ b/src/controllers/accounts/session.js
@@ -42,14 +42,13 @@ sessionController.revoke = function (req, res, next) {
}
user.auth.revokeSession(_id, uid, next);
- }
+ },
], function (err) {
if (err) {
return res.status(500).send(err.message);
- } else {
- return res.sendStatus(200);
}
+ return res.sendStatus(200);
});
};
-module.exports = sessionController;
\ No newline at end of file
+module.exports = sessionController;
diff --git a/src/controllers/accounts/settings.js b/src/controllers/accounts/settings.js
index 68cef8be5f..2f360f883c 100644
--- a/src/controllers/accounts/settings.js
+++ b/src/controllers/accounts/settings.js
@@ -39,7 +39,7 @@ settingsController.get = function (req, res, callback) {
},
soundsMapping: function (next) {
meta.sounds.getUserSoundMap(userData.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -53,7 +53,7 @@ settingsController.get = function (req, res, callback) {
'chat-outgoing',
];
var aliases = {
- 'notification': 'notificationSound',
+ notification: 'notificationSound',
'chat-incoming': 'incomingChatSound',
'chat-outgoing': 'outgoingChatSound',
};
@@ -93,38 +93,39 @@ settingsController.get = function (req, res, callback) {
userData.customSettings = data.customSettings;
userData.disableEmailSubscriptions = parseInt(meta.config.disableEmailSubscriptions, 10) === 1;
next();
- }
+ },
], function (err) {
if (err) {
return callback(err);
}
userData.dailyDigestFreqOptions = [
- { value: 'off', name: '[[user:digest_off]]', selected: 'off' === userData.settings.dailyDigestFreq },
- { value: 'day', name: '[[user:digest_daily]]', selected: 'day' === userData.settings.dailyDigestFreq },
- { value: 'week', name: '[[user:digest_weekly]]', selected: 'week' === userData.settings.dailyDigestFreq },
- { value: 'month', name: '[[user:digest_monthly]]', selected: 'month' === userData.settings.dailyDigestFreq }
+ { value: 'off', name: '[[user:digest_off]]', selected: userData.settings.dailyDigestFreq === 'off' },
+ { value: 'day', name: '[[user:digest_daily]]', selected: userData.settings.dailyDigestFreq === 'day' },
+ { value: 'week', name: '[[user:digest_weekly]]', selected: userData.settings.dailyDigestFreq === 'week' },
+ { value: 'month', name: '[[user:digest_monthly]]', selected: userData.settings.dailyDigestFreq === 'month' },
];
userData.bootswatchSkinOptions = [
- { "name": "Default", "value": "default" },
- { "name": "Cerulean", "value": "cerulean" },
- { "name": "Cosmo", "value": "cosmo" },
- { "name": "Cyborg", "value": "cyborg" },
- { "name": "Darkly", "value": "darkly" },
- { "name": "Flatly", "value": "flatly" },
- { "name": "Journal", "value": "journal" },
- { "name": "Lumen", "value": "lumen" },
- { "name": "Paper", "value": "paper" },
- { "name": "Readable", "value": "readable" },
- { "name": "Sandstone", "value": "sandstone" },
- { "name": "Simplex", "value": "simplex" },
- { "name": "Slate", "value": "slate" },
- { "name": "Spacelab", "value": "spacelab" },
- { "name": "Superhero", "value": "superhero" },
- { "name": "United", "value": "united" },
- { "name": "Yeti", "value": "yeti" }
+ { name: 'No skin', value: 'noskin' },
+ { name: 'Default', value: 'default' },
+ { name: 'Cerulean', value: 'cerulean' },
+ { name: 'Cosmo', value: 'cosmo' },
+ { name: 'Cyborg', value: 'cyborg' },
+ { name: 'Darkly', value: 'darkly' },
+ { name: 'Flatly', value: 'flatly' },
+ { name: 'Journal', value: 'journal' },
+ { name: 'Lumen', value: 'lumen' },
+ { name: 'Paper', value: 'paper' },
+ { name: 'Readable', value: 'readable' },
+ { name: 'Sandstone', value: 'sandstone' },
+ { name: 'Simplex', value: 'simplex' },
+ { name: 'Slate', value: 'slate' },
+ { name: 'Spacelab', value: 'spacelab' },
+ { name: 'Superhero', value: 'superhero' },
+ { name: 'United', value: 'united' },
+ { name: 'Yeti', value: 'yeti' },
];
var isCustom = true;
@@ -140,9 +141,9 @@ settingsController.get = function (req, res, callback) {
}
userData.homePageRoutes.push({
- route: 'custom',
- name: 'Custom',
- selected: isCustom
+ route: 'custom',
+ name: 'Custom',
+ selected: isCustom,
});
userData.bootswatchSkinOptions.forEach(function (skin) {
@@ -160,7 +161,7 @@ settingsController.get = function (req, res, callback) {
userData.inTopicSearchAvailable = plugins.hasListeners('filter:topic.search');
userData.title = '[[pages:account/settings]]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{text: userData.username, url: '/user/' + userData.userslug}, {text: '[[user:settings]]'}]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username, url: '/user/' + userData.userslug }, { text: '[[user:settings]]' }]);
res.render('account/settings', userData);
});
@@ -182,36 +183,36 @@ function getHomePageRoutes(callback) {
categoryData = categoryData.map(function (category) {
return {
route: 'category/' + category.slug,
- name: 'Category: ' + category.name
+ name: 'Category: ' + category.name,
};
});
categoryData = categoryData || [];
- plugins.fireHook('filter:homepage.get', {routes: [
+ plugins.fireHook('filter:homepage.get', { routes: [
{
route: 'categories',
- name: 'Categories'
+ name: 'Categories',
},
{
route: 'unread',
- name: 'Unread'
+ name: 'Unread',
},
{
route: 'recent',
- name: 'Recent'
+ name: 'Recent',
},
{
route: 'popular',
- name: 'Popular'
- }
- ].concat(categoryData)}, next);
+ name: 'Popular',
+ },
+ ].concat(categoryData) }, next);
},
function (data, next) {
next(null, data.routes);
- }
+ },
], callback);
}
-module.exports = settingsController;
\ No newline at end of file
+module.exports = settingsController;
diff --git a/src/controllers/admin.js b/src/controllers/admin.js
index 7f622466cd..056a7025aa 100644
--- a/src/controllers/admin.js
+++ b/src/controllers/admin.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var adminController = {
dashboard: require('./admin/dashboard'),
@@ -10,7 +10,7 @@ var adminController = {
appearance: require('./admin/appearance'),
extend: {
widgets: require('./admin/widgets'),
- rewards: require('./admin/rewards')
+ rewards: require('./admin/rewards'),
},
events: require('./admin/events'),
logs: require('./admin/logs'),
@@ -28,7 +28,7 @@ var adminController = {
themes: require('./admin/themes'),
users: require('./admin/users'),
uploads: require('./admin/uploads'),
- info: require('./admin/info')
+ info: require('./admin/info'),
};
diff --git a/src/controllers/admin/appearance.js b/src/controllers/admin/appearance.js
index 8956bd175d..021733d417 100644
--- a/src/controllers/admin/appearance.js
+++ b/src/controllers/admin/appearance.js
@@ -1,8 +1,8 @@
-"use strict";
+'use strict';
var appearanceController = {};
-appearanceController.get = function (req, res, next) {
+appearanceController.get = function (req, res) {
var term = req.params.term ? req.params.term : 'themes';
res.render('admin/appearance/' + term, {});
diff --git a/src/controllers/admin/blacklist.js b/src/controllers/admin/blacklist.js
index 73e4d6c333..7ce4edda49 100644
--- a/src/controllers/admin/blacklist.js
+++ b/src/controllers/admin/blacklist.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var meta = require('../../meta');
@@ -11,7 +11,7 @@ blacklistController.get = function (req, res, next) {
}
res.render('admin/manage/ip-blacklist', {
rules: rules,
- title: '[[pages:ip-blacklist]]'
+ title: '[[pages:ip-blacklist]]',
});
});
};
diff --git a/src/controllers/admin/cache.js b/src/controllers/admin/cache.js
index 21ef6ff086..dce16818f8 100644
--- a/src/controllers/admin/cache.js
+++ b/src/controllers/admin/cache.js
@@ -2,7 +2,7 @@
var cacheController = {};
-cacheController.get = function (req, res, next) {
+cacheController.get = function (req, res) {
var postCache = require('../../posts/cache');
var groupCache = require('../../groups').cache;
@@ -19,17 +19,17 @@ cacheController.get = function (req, res, next) {
max: postCache.max,
itemCount: postCache.itemCount,
percentFull: percentFull,
- avgPostSize: avgPostSize
+ avgPostSize: avgPostSize,
},
groupCache: {
length: groupCache.length,
max: groupCache.max,
itemCount: groupCache.itemCount,
percentFull: ((groupCache.length / groupCache.max) * 100).toFixed(2),
- dump: req.query.debug ? JSON.stringify(groupCache.dump(), null, 4) : false
- }
+ dump: req.query.debug ? JSON.stringify(groupCache.dump(), null, 4) : false,
+ },
});
};
-module.exports = cacheController;
\ No newline at end of file
+module.exports = cacheController;
diff --git a/src/controllers/admin/categories.js b/src/controllers/admin/categories.js
index 8a59bb0b4e..4a60fc14e2 100644
--- a/src/controllers/admin/categories.js
+++ b/src/controllers/admin/categories.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -14,7 +14,7 @@ var categoriesController = {};
categoriesController.get = function (req, res, next) {
async.parallel({
category: async.apply(categories.getCategories, [req.params.category_id], req.user.uid),
- privileges: async.apply(privileges.categories.list, req.params.category_id)
+ privileges: async.apply(privileges.categories.list, req.params.category_id),
}, function (err, data) {
if (err) {
return next(err);
@@ -32,13 +32,13 @@ categoriesController.get = function (req, res, next) {
data.category.name = translator.escape(String(data.category.name));
res.render('admin/manage/category', {
category: data.category,
- privileges: data.privileges
+ privileges: data.privileges,
});
});
});
};
-categoriesController.getAll = function (req, res, next) {
+categoriesController.getAll = function (req, res) {
// Categories list will be rendered on client side with recursion, etc.
res.render('admin/manage/categories', {});
};
@@ -46,7 +46,7 @@ categoriesController.getAll = function (req, res, next) {
categoriesController.getAnalytics = function (req, res, next) {
async.parallel({
name: async.apply(categories.getCategoryField, req.params.category_id, 'name'),
- analytics: async.apply(analytics.getCategoryAnalytics, req.params.category_id)
+ analytics: async.apply(analytics.getCategoryAnalytics, req.params.category_id),
}, function (err, data) {
if (err) {
return next(err);
diff --git a/src/controllers/admin/dashboard.js b/src/controllers/admin/dashboard.js
index 2ffbea0e98..70149e580e 100644
--- a/src/controllers/admin/dashboard.js
+++ b/src/controllers/admin/dashboard.js
@@ -20,26 +20,26 @@ dashboardController.get = function (req, res, next) {
{
done: !meta.reloadRequired,
doneText: '[[admin/general/dashboard:restart-not-required]]',
- notDoneText:'[[admin/general/dashboard:restart-required]]'
+ notDoneText: '[[admin/general/dashboard:restart-required]]',
},
{
done: plugins.hasListeners('filter:search.query'),
doneText: '[[admin/general/dashboard:search-plugin-installed]]',
- notDoneText:'[[admin/general/dashboard:search-plugin-not-installed]]',
+ notDoneText: '[[admin/general/dashboard:search-plugin-not-installed]]',
tooltip: '[[admin/general/dashboard:search-plugin-tooltip]]',
- link:'/admin/extend/plugins'
- }
+ link: '/admin/extend/plugins',
+ },
];
if (global.env !== 'production') {
notices.push({
done: false,
- notDoneText: '[[admin/general/dashboard:running-in-development]]'
+ notDoneText: '[[admin/general/dashboard:running-in-development]]',
});
}
plugins.fireHook('filter:admin.notices', notices, next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -47,7 +47,7 @@ dashboardController.get = function (req, res, next) {
res.render('admin/general/dashboard', {
version: nconf.get('version'),
notices: results.notices,
- stats: results.stats
+ stats: results.stats,
});
});
};
@@ -65,7 +65,7 @@ function getStats(callback) {
},
function (next) {
getStatsForSet('topics:tid', 'topicCount', next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -83,7 +83,7 @@ function getStatsForSet(set, field, callback) {
var terms = {
day: 86400000,
week: 604800000,
- month: 2592000000
+ month: 2592000000,
};
var now = Date.now();
@@ -99,7 +99,7 @@ function getStatsForSet(set, field, callback) {
},
alltime: function (next) {
getGlobalField(field, next);
- }
+ },
}, callback);
}
diff --git a/src/controllers/admin/database.js b/src/controllers/admin/database.js
index 5a28b95ec4..9ce8a3c00f 100644
--- a/src/controllers/admin/database.js
+++ b/src/controllers/admin/database.js
@@ -6,7 +6,6 @@ var nconf = require('nconf');
var databaseController = {};
-
databaseController.get = function (req, res, next) {
async.parallel({
redis: function (next) {
@@ -24,7 +23,7 @@ databaseController.get = function (req, res, next) {
} else {
next();
}
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -33,4 +32,4 @@ databaseController.get = function (req, res, next) {
});
};
-module.exports = databaseController;
\ No newline at end of file
+module.exports = databaseController;
diff --git a/src/controllers/admin/errors.js b/src/controllers/admin/errors.js
index 4cacd425c9..5a00e95537 100644
--- a/src/controllers/admin/errors.js
+++ b/src/controllers/admin/errors.js
@@ -11,7 +11,7 @@ var errorsController = {};
errorsController.get = function (req, res, next) {
async.parallel({
'not-found': async.apply(meta.errors.get, true),
- analytics: async.apply(analytics.getErrorAnalytics)
+ analytics: async.apply(analytics.getErrorAnalytics),
}, function (err, data) {
if (err) {
return next(err);
@@ -24,7 +24,7 @@ errorsController.get = function (req, res, next) {
errorsController.export = function (req, res, next) {
async.waterfall([
async.apply(meta.errors.get, false),
- async.apply(json2csv)
+ async.apply(json2csv),
], function (err, csv) {
if (err) {
return next(err);
@@ -35,4 +35,4 @@ errorsController.export = function (req, res, next) {
};
-module.exports = errorsController;
\ No newline at end of file
+module.exports = errorsController;
diff --git a/src/controllers/admin/events.js b/src/controllers/admin/events.js
index 8a4d63bad1..97838d2266 100644
--- a/src/controllers/admin/events.js
+++ b/src/controllers/admin/events.js
@@ -10,7 +10,6 @@ var eventsController = {};
eventsController.get = function (req, res, next) {
-
var page = parseInt(req.query.page, 10) || 1;
var itemsPerPage = 20;
var start = (page - 1) * itemsPerPage;
@@ -22,7 +21,7 @@ eventsController.get = function (req, res, next) {
},
events: function (next) {
events.getEvents(start, stop, next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -33,10 +32,10 @@ eventsController.get = function (req, res, next) {
res.render('admin/advanced/events', {
events: results.events,
pagination: pagination.create(page, pageCount),
- next: 20
+ next: 20,
});
});
};
-module.exports = eventsController;
\ No newline at end of file
+module.exports = eventsController;
diff --git a/src/controllers/admin/flags.js b/src/controllers/admin/flags.js
index 03c9329fca..2191394b57 100644
--- a/src/controllers/admin/flags.js
+++ b/src/controllers/admin/flags.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var validator = require('validator');
@@ -29,7 +29,7 @@ flagsController.get = function (req, res, next) {
analytics: function (next) {
analytics.getDailyStatsForSet('analytics:flags', Date.now(), 30, next);
},
- assignees: async.apply(user.getAdminsandGlobalModsandModerators)
+ assignees: async.apply(user.getAdminsandGlobalModsandModerators),
}, function (err, results) {
if (err) {
return next(err);
@@ -39,7 +39,7 @@ flagsController.get = function (req, res, next) {
results.assignees = results.assignees.map(function (userObj) {
return {
uid: userObj.uid,
- username: userObj.username
+ username: userObj.username,
};
});
@@ -94,7 +94,7 @@ function getFlagData(req, res, callback) {
}
posts.getFlags(sets, cid, req.uid, start, stop, next);
- }
+ },
], callback);
}
diff --git a/src/controllers/admin/groups.js b/src/controllers/admin/groups.js
index db940c8324..5e7dd1e78f 100644
--- a/src/controllers/admin/groups.js
+++ b/src/controllers/admin/groups.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -6,12 +6,9 @@ var db = require('../../database');
var groups = require('../../groups');
var meta = require('../../meta');
var pagination = require('../../pagination');
-var helpers = require('../helpers');
-
var groupsController = {};
-
groupsController.list = function (req, res, next) {
var page = parseInt(req.query.page, 10) || 1;
var groupsPerPage = 20;
@@ -28,14 +25,14 @@ groupsController.list = function (req, res, next) {
pageCount = Math.ceil(groupNames.length / groupsPerPage);
var start = (page - 1) * groupsPerPage;
- var stop = start + groupsPerPage - 1;
+ var stop = start + groupsPerPage - 1;
groupNames = groupNames.slice(start, stop + 1);
groups.getGroupsData(groupNames, next);
},
function (groupData, next) {
- next(null, {groups: groupData, pagination: pagination.create(page, pageCount)});
- }
+ next(null, { groups: groupData, pagination: pagination.create(page, pageCount) });
+ },
], function (err, data) {
if (err) {
return next(err);
@@ -44,7 +41,7 @@ groupsController.list = function (req, res, next) {
res.render('admin/manage/groups', {
groups: data.groups,
pagination: data.pagination,
- yourid: req.uid
+ yourid: req.uid,
});
});
};
@@ -59,14 +56,14 @@ groupsController.get = function (req, res, callback) {
if (!exists) {
return callback();
}
- groups.get(groupName, {uid: req.uid, truncateUserList: true, userListCount: 20}, next);
- }
+ groups.get(groupName, { uid: req.uid, truncateUserList: true, userListCount: 20 }, next);
+ },
], function (err, group) {
if (err) {
return callback(err);
}
group.isOwner = true;
- res.render('admin/manage/group', {group: group, allowPrivateGroups: parseInt(meta.config.allowPrivateGroups, 10) === 1});
+ res.render('admin/manage/group', { group: group, allowPrivateGroups: parseInt(meta.config.allowPrivateGroups, 10) === 1 });
});
};
diff --git a/src/controllers/admin/homepage.js b/src/controllers/admin/homepage.js
index 9fdf3a2371..1450283847 100644
--- a/src/controllers/admin/homepage.js
+++ b/src/controllers/admin/homepage.js
@@ -25,37 +25,37 @@ homePageController.get = function (req, res, next) {
categoryData = categoryData.map(function (category) {
return {
route: 'category/' + category.slug,
- name: 'Category: ' + category.name
+ name: 'Category: ' + category.name,
};
});
next(null, categoryData);
- }
+ },
], function (err, categoryData) {
if (err || !categoryData) {
categoryData = [];
}
- plugins.fireHook('filter:homepage.get', {routes: [
+ plugins.fireHook('filter:homepage.get', { routes: [
{
route: 'categories',
- name: 'Categories'
+ name: 'Categories',
},
{
route: 'recent',
- name: 'Recent'
+ name: 'Recent',
},
{
route: 'popular',
- name: 'Popular'
- }
- ].concat(categoryData)}, function (err, data) {
+ name: 'Popular',
+ },
+ ].concat(categoryData) }, function (err, data) {
if (err) {
return next(err);
}
data.routes.push({
route: '',
- name: 'Custom'
+ name: 'Custom',
});
res.render('admin/general/homepage', data);
@@ -63,4 +63,4 @@ homePageController.get = function (req, res, next) {
});
};
-module.exports = homePageController;
\ No newline at end of file
+module.exports = homePageController;
diff --git a/src/controllers/admin/info.js b/src/controllers/admin/info.js
index 8fa54ae4f0..88fef98b4b 100644
--- a/src/controllers/admin/info.js
+++ b/src/controllers/admin/info.js
@@ -13,7 +13,7 @@ var infoController = {};
var info = {};
-infoController.get = function (req, res, next) {
+infoController.get = function (req, res) {
info = {};
pubsub.publish('sync:node:info:start');
setTimeout(function () {
@@ -22,9 +22,15 @@ infoController.get = function (req, res, next) {
data.push(info[key]);
});
data.sort(function (a, b) {
- return (a.os.hostname < b.os.hostname) ? -1 : (a.os.hostname > b.os.hostname) ? 1 : 0;
+ if (a.os.hostname < b.os.hostname) {
+ return -1;
+ }
+ if (a.os.hostname > b.os.hostname) {
+ return 1;
+ }
+ return 0;
});
- res.render('admin/development/info', {info: data, infoJSON: JSON.stringify(data, null, 4), host: os.hostname(), port: nconf.get('port')});
+ res.render('admin/development/info', { info: data, infoJSON: JSON.stringify(data, null, 4), host: os.hostname(), port: nconf.get('port') });
}, 500);
};
@@ -33,7 +39,7 @@ pubsub.on('sync:node:info:start', function () {
if (err) {
return winston.error(err);
}
- pubsub.publish('sync:node:info:end', {data: data, id: os.hostname() + ':' + nconf.get('port')});
+ pubsub.publish('sync:node:info:end', { data: data, id: os.hostname() + ':' + nconf.get('port') });
});
});
@@ -49,7 +55,7 @@ function getNodeInfo(callback) {
title: process.title,
version: process.version,
memoryUsage: process.memoryUsage(),
- uptime: process.uptime()
+ uptime: process.uptime(),
},
os: {
hostname: os.hostname(),
@@ -57,8 +63,8 @@ function getNodeInfo(callback) {
platform: os.platform(),
arch: os.arch(),
release: os.release(),
- load: os.loadavg().map(function (load) { return load.toFixed(2); }).join(', ')
- }
+ load: os.loadavg().map(function (load) { return load.toFixed(2); }).join(', '),
+ },
};
async.parallel({
@@ -67,7 +73,7 @@ function getNodeInfo(callback) {
},
gitInfo: function (next) {
getGitInfo(next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -79,7 +85,7 @@ function getNodeInfo(callback) {
}
function getGitInfo(callback) {
- function get(cmd, callback) {
+ function get(cmd, callback) {
exec(cmd, function (err, stdout) {
if (err) {
winston.error(err);
@@ -93,8 +99,8 @@ function getGitInfo(callback) {
},
branch: function (next) {
get('git rev-parse --abbrev-ref HEAD', next);
- }
+ },
}, callback);
}
-module.exports = infoController;
\ No newline at end of file
+module.exports = infoController;
diff --git a/src/controllers/admin/languages.js b/src/controllers/admin/languages.js
index 2b458d1508..0ac4e98e99 100644
--- a/src/controllers/admin/languages.js
+++ b/src/controllers/admin/languages.js
@@ -17,9 +17,9 @@ languagesController.get = function (req, res, next) {
});
res.render('admin/general/languages', {
- languages: languages
+ languages: languages,
});
});
};
-module.exports = languagesController;
\ No newline at end of file
+module.exports = languagesController;
diff --git a/src/controllers/admin/logger.js b/src/controllers/admin/logger.js
index 7ae327a858..0e8006bbeb 100644
--- a/src/controllers/admin/logger.js
+++ b/src/controllers/admin/logger.js
@@ -6,4 +6,4 @@ loggerController.get = function (req, res) {
res.render('admin/development/logger', {});
};
-module.exports = loggerController;
\ No newline at end of file
+module.exports = loggerController;
diff --git a/src/controllers/admin/logs.js b/src/controllers/admin/logs.js
index 6723d3795f..c2c5166dd7 100644
--- a/src/controllers/admin/logs.js
+++ b/src/controllers/admin/logs.js
@@ -13,10 +13,10 @@ logsController.get = function (req, res, next) {
}
res.render('admin/advanced/logs', {
- data: validator.escape(logs)
+ data: validator.escape(logs),
});
});
};
-module.exports = logsController;
\ No newline at end of file
+module.exports = logsController;
diff --git a/src/controllers/admin/navigation.js b/src/controllers/admin/navigation.js
index 423f21721c..9c96444be3 100644
--- a/src/controllers/admin/navigation.js
+++ b/src/controllers/admin/navigation.js
@@ -20,4 +20,4 @@ navigationController.get = function (req, res, next) {
});
};
-module.exports = navigationController;
\ No newline at end of file
+module.exports = navigationController;
diff --git a/src/controllers/admin/plugins.js b/src/controllers/admin/plugins.js
index f1a72720ac..4e8e1a415e 100644
--- a/src/controllers/admin/plugins.js
+++ b/src/controllers/admin/plugins.js
@@ -24,22 +24,22 @@ pluginsController.get = function (req, res, next) {
next(null, plugins);
});
- }
+ },
}, function (err, payload) {
if (err) {
return next(err);
}
var compatiblePkgNames = payload.compatible.map(function (pkgData) {
- return pkgData.name;
- });
+ return pkgData.name;
+ });
- res.render('admin/extend/plugins' , {
+ res.render('admin/extend/plugins', {
installed: payload.compatible.filter(function (plugin) {
return plugin.installed;
}),
upgradeCount: payload.compatible.reduce(function (count, current) {
if (current.installed && current.outdated) {
- ++count;
+ count += 1;
}
return count;
}, 0),
@@ -48,9 +48,9 @@ pluginsController.get = function (req, res, next) {
}),
incompatible: payload.all.filter(function (plugin) {
return compatiblePkgNames.indexOf(plugin.name) === -1;
- })
+ }),
});
});
};
-module.exports = pluginsController;
\ No newline at end of file
+module.exports = pluginsController;
diff --git a/src/controllers/admin/rewards.js b/src/controllers/admin/rewards.js
index 8ff05c75b3..56c5ed3cd0 100644
--- a/src/controllers/admin/rewards.js
+++ b/src/controllers/admin/rewards.js
@@ -13,5 +13,4 @@ rewardsController.get = function (req, res, next) {
};
-
-module.exports = rewardsController;
\ No newline at end of file
+module.exports = rewardsController;
diff --git a/src/controllers/admin/settings.js b/src/controllers/admin/settings.js
index 0d1f509631..55e5a1dfbf 100644
--- a/src/controllers/admin/settings.js
+++ b/src/controllers/admin/settings.js
@@ -11,12 +11,12 @@ settingsController.get = function (req, res, next) {
var term = req.params.term ? req.params.term : 'general';
switch (req.params.term) {
- case 'email':
- renderEmail(req, res, next);
- break;
+ case 'email':
+ renderEmail(req, res, next);
+ break;
- default:
- res.render('admin/settings/' + term);
+ default:
+ res.render('admin/settings/' + term);
}
};
@@ -47,11 +47,11 @@ function renderEmail(req, res, next) {
path: path,
fullpath: email,
text: text,
- original: original.toString()
+ original: original.toString(),
});
});
}, next);
- }
+ },
], function (err, emails) {
if (err) {
return next(err);
@@ -61,7 +61,7 @@ function renderEmail(req, res, next) {
emails: emails,
sendable: emails.filter(function (email) {
return email.path.indexOf('_plaintext') === -1 && email.path.indexOf('partials') === -1;
- })
+ }),
});
});
}
diff --git a/src/controllers/admin/social.js b/src/controllers/admin/social.js
index 11c7982701..da12f3341e 100644
--- a/src/controllers/admin/social.js
+++ b/src/controllers/admin/social.js
@@ -12,9 +12,9 @@ socialController.get = function (req, res, next) {
}
res.render('admin/general/social', {
- posts: posts
+ posts: posts,
});
});
};
-module.exports = socialController;
\ No newline at end of file
+module.exports = socialController;
diff --git a/src/controllers/admin/sounds.js b/src/controllers/admin/sounds.js
index b042048313..164bf4a427 100644
--- a/src/controllers/admin/sounds.js
+++ b/src/controllers/admin/sounds.js
@@ -1,23 +1,23 @@
'use strict';
var plugins = require('../../plugins');
-var db = require('../../database');
+var meta = require('../../meta');
var soundsController = {};
soundsController.get = function (req, res, next) {
- db.getObject('settings:sounds', function (err, settings) {
+ var types = [
+ 'notification',
+ 'chat-incoming',
+ 'chat-outgoing',
+ ];
+ meta.configs.getFields(types, function (err, settings) {
if (err) {
return next(err);
}
-
+
settings = settings || {};
- var types = [
- 'notification',
- 'chat-incoming',
- 'chat-outgoing',
- ];
var output = {};
types.forEach(function (type) {
@@ -44,4 +44,4 @@ soundsController.get = function (req, res, next) {
});
};
-module.exports = soundsController;
\ No newline at end of file
+module.exports = soundsController;
diff --git a/src/controllers/admin/tags.js b/src/controllers/admin/tags.js
index a645e2ef11..f586e5f70c 100644
--- a/src/controllers/admin/tags.js
+++ b/src/controllers/admin/tags.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var topics = require('../../topics');
@@ -10,7 +10,7 @@ tagsController.get = function (req, res, next) {
return next(err);
}
- res.render('admin/manage/tags', {tags: tags});
+ res.render('admin/manage/tags', { tags: tags });
});
};
diff --git a/src/controllers/admin/themes.js b/src/controllers/admin/themes.js
index 4f6f3e1f3b..598cd7cf94 100644
--- a/src/controllers/admin/themes.js
+++ b/src/controllers/admin/themes.js
@@ -12,8 +12,8 @@ themesController.get = function (req, res, next) {
return next();
}
- var themeConfig = require(path.join(themeDir, 'theme.json')),
- screenshotPath = path.join(themeDir, themeConfig.screenshot);
+ var themeConfig = require(path.join(themeDir, 'theme.json'));
+ var screenshotPath = path.join(themeDir, themeConfig.screenshot);
if (themeConfig.screenshot && file.existsSync(screenshotPath)) {
res.sendFile(screenshotPath);
} else {
@@ -22,4 +22,4 @@ themesController.get = function (req, res, next) {
});
};
-module.exports = themesController;
\ No newline at end of file
+module.exports = themesController;
diff --git a/src/controllers/admin/uploads.js b/src/controllers/admin/uploads.js
index 0b7104f1de..02bd065c0b 100644
--- a/src/controllers/admin/uploads.js
+++ b/src/controllers/admin/uploads.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var fs = require('fs');
var path = require('path');
@@ -31,7 +31,7 @@ uploadsController.uploadCategoryPicture = function (req, res, next) {
}
if (validateUpload(req, res, next, uploadedFile, allowedImageTypes)) {
- var filename = 'category-' + params.cid + path.extname(uploadedFile.name);
+ var filename = 'category-' + params.cid + path.extname(uploadedFile.name);
uploadImage(filename, 'category', uploadedFile, req, res, next);
}
};
@@ -51,15 +51,15 @@ uploadsController.uploadFavicon = function (req, res, next) {
return next(err);
}
- res.json([{name: uploadedFile.name, url: image.url}]);
+ res.json([{ name: uploadedFile.name, url: image.url }]);
});
}
};
uploadsController.uploadTouchIcon = function (req, res, next) {
- var uploadedFile = req.files.files[0],
- allowedTypes = ['image/png'],
- sizes = [36, 48, 72, 96, 144, 192];
+ var uploadedFile = req.files.files[0];
+ var allowedTypes = ['image/png'];
+ var sizes = [36, 48, 72, 96, 144, 192];
if (validateUpload(req, res, next, uploadedFile, allowedTypes)) {
file.saveFileToLocal('touchicon-orig.png', 'system', uploadedFile.path, function (err, imageObj) {
@@ -75,8 +75,8 @@ uploadsController.uploadTouchIcon = function (req, res, next) {
path: path.join(nconf.get('upload_path'), 'system', 'touchicon-' + size + '.png'),
extension: 'png',
width: size,
- height: size
- })
+ height: size,
+ }),
], next);
}, function (err) {
fs.unlink(uploadedFile.path, function (err) {
@@ -89,7 +89,7 @@ uploadsController.uploadTouchIcon = function (req, res, next) {
return next(err);
}
- res.json([{name: uploadedFile.name, url: imageObj.url}]);
+ res.json([{ name: uploadedFile.name, url: imageObj.url }]);
});
});
}
@@ -142,7 +142,7 @@ function validateUpload(req, res, next, uploadedFile, allowedTypes) {
}
});
- res.json({error: '[[error:invalid-image-type, ' + allowedTypes.join(', ') + ']]'});
+ res.json({ error: '[[error:invalid-image-type, ' + allowedTypes.join(', ') + ']]' });
return false;
}
@@ -160,11 +160,11 @@ function uploadImage(filename, folder, uploadedFile, req, res, next) {
return next(err);
}
- res.json([{name: uploadedFile.name, url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url}]);
+ res.json([{ name: uploadedFile.name, url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url }]);
}
if (plugins.hasListeners('filter:uploadImage')) {
- plugins.fireHook('filter:uploadImage', {image: uploadedFile, uid: req.user.uid}, done);
+ plugins.fireHook('filter:uploadImage', { image: uploadedFile, uid: req.user.uid }, done);
} else {
file.saveFileToLocal(filename, folder, uploadedFile.path, done);
}
diff --git a/src/controllers/admin/users.js b/src/controllers/admin/users.js
index 0e67c7d64c..54d9ab93de 100644
--- a/src/controllers/admin/users.js
+++ b/src/controllers/admin/users.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var validator = require('validator');
@@ -15,10 +15,10 @@ var usersController = {};
var userFields = ['uid', 'username', 'userslug', 'email', 'postcount', 'joindate', 'banned',
'reputation', 'picture', 'flags', 'lastonline', 'email:confirmed'];
-usersController.search = function (req, res, next) {
+usersController.search = function (req, res) {
res.render('admin/manage/users', {
search_display: '',
- users: []
+ users: [],
});
};
@@ -71,7 +71,7 @@ usersController.registrationQueue = function (req, res, next) {
user.getRegistrationQueue(start, stop, next);
},
customHeaders: function (next) {
- plugins.fireHook('filter:admin.registrationQueue.customHeaders', {headers: []}, next);
+ plugins.fireHook('filter:admin.registrationQueue.customHeaders', { headers: [] }, next);
},
invites: function (next) {
async.waterfall([
@@ -97,14 +97,14 @@ usersController.registrationQueue = function (req, res, next) {
invites.invitations = invites.invitations.map(function (email, i) {
return {
email: email,
- username: usernames[index][i] === '[[global:guest]]' ? '' : usernames[index][i]
+ username: usernames[index][i] === '[[global:guest]]' ? '' : usernames[index][i],
};
});
});
next(null, invitations);
- }
+ },
], next);
- }
+ },
}, function (err, data) {
if (err) {
return next(err);
@@ -142,9 +142,9 @@ function getUsers(set, section, min, max, req, res, next) {
},
function (uids, next) {
user.getUsersWithFields(uids, userFields, req.uid, next);
- }
+ },
], next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -157,7 +157,7 @@ function getUsers(set, section, min, max, req, res, next) {
var data = {
users: results.users,
page: page,
- pageCount: Math.max(1, Math.ceil(results.count / resultsPerPage))
+ pageCount: Math.max(1, Math.ceil(results.count / resultsPerPage)),
};
data[section] = true;
render(req, res, data);
@@ -181,7 +181,7 @@ usersController.getCSV = function (req, res, next) {
events.log({
type: 'getUsersCSV',
uid: req.user.uid,
- ip: req.ip
+ ip: req.ip,
});
user.getUsersCSV(function (err, data) {
diff --git a/src/controllers/admin/widgets.js b/src/controllers/admin/widgets.js
index c2d0d1e667..889fa1dcc6 100644
--- a/src/controllers/admin/widgets.js
+++ b/src/controllers/admin/widgets.js
@@ -13,4 +13,4 @@ widgetsController.get = function (req, res, next) {
};
-module.exports = widgetsController;
\ No newline at end of file
+module.exports = widgetsController;
diff --git a/src/controllers/api.js b/src/controllers/api.js
index 1bbf3962c8..f7158481e7 100644
--- a/src/controllers/api.js
+++ b/src/controllers/api.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var validator = require('validator');
@@ -13,9 +13,8 @@ var privileges = require('../privileges');
var plugins = require('../plugins');
var widgets = require('../widgets');
var translator = require('../../public/src/modules/translator');
-var accountHelpers = require('../controllers/accounts/helpers');
-var apiController = {};
+var apiController = module.exports;
apiController.getConfig = function (req, res, next) {
var config = {};
@@ -62,7 +61,12 @@ apiController.getConfig = function (req, res, next) {
config.categoryTopicSort = meta.config.categoryTopicSort || 'newest_to_oldest';
config.csrf_token = req.csrfToken();
config.searchEnabled = plugins.hasListeners('filter:search.query');
- config.bootswatchSkin = 'default';
+ config.bootswatchSkin = meta.config.bootswatchSkin || 'noskin';
+ config.defaultBootswatchSkin = meta.config.bootswatchSkin || 'noskin';
+
+ if (config.useOutgoingLinksPage) {
+ config.outgoingLinksWhitelist = meta.config['outgoingLinks:whitelist'];
+ }
var timeagoCutoff = meta.config.timeagoCutoff === undefined ? 30 : meta.config.timeagoCutoff;
config.timeagoCutoff = timeagoCutoff !== '' ? Math.max(0, parseInt(timeagoCutoff, 10)) : timeagoCutoff;
@@ -71,7 +75,7 @@ apiController.getConfig = function (req, res, next) {
enabled: parseInt(meta.config.cookieConsentEnabled, 10) === 1,
message: translator.escape(meta.config.cookieConsentMessage || '[[global:cookies.message]]').replace(/\\/g, '\\\\'),
dismiss: translator.escape(meta.config.cookieConsentDismiss || '[[global:cookies.accept]]').replace(/\\/g, '\\\\'),
- link: translator.escape(meta.config.cookieConsentLink || '[[global:cookies.learn_more]]').replace(/\\/g, '\\\\')
+ link: translator.escape(meta.config.cookieConsentLink || '[[global:cookies.learn_more]]').replace(/\\/g, '\\\\'),
};
async.waterfall([
@@ -91,9 +95,9 @@ apiController.getConfig = function (req, res, next) {
config.categoryTopicSort = settings.categoryTopicSort || config.categoryTopicSort;
config.topicSearchEnabled = settings.topicSearchEnabled || false;
config.delayImageLoading = settings.delayImageLoading !== undefined ? settings.delayImageLoading : true;
- config.bootswatchSkin = settings.bootswatchSkin || config.bootswatchSkin;
+ config.bootswatchSkin = (settings.bootswatchSkin && settings.bootswatchSkin !== 'default') ? settings.bootswatchSkin : config.bootswatchSkin;
plugins.fireHook('filter:config.get', config, next);
- }
+ },
], function (err, config) {
if (err) {
return next(err);
@@ -119,16 +123,16 @@ apiController.renderWidgets = function (req, res, next) {
url: req.query.url,
locations: req.query.locations,
isMobile: req.query.isMobile === 'true',
- cid: req.query.cid
+ cid: req.query.cid,
},
req,
res,
function (err, widgets) {
- if (err) {
- return next(err);
- }
- res.status(200).json(widgets);
- });
+ if (err) {
+ return next(err);
+ }
+ res.status(200).json(widgets);
+ });
};
apiController.getPostData = function (pid, uid, callback) {
@@ -138,7 +142,7 @@ apiController.getPostData = function (pid, uid, callback) {
},
post: function (next) {
posts.getPostData(pid, next);
- }
+ },
}, function (err, results) {
if (err || !results.post) {
return callback(err);
@@ -167,7 +171,7 @@ apiController.getTopicData = function (tid, uid, callback) {
},
topic: function (next) {
topics.getTopicData(tid, next);
- }
+ },
}, function (err, results) {
if (err || !results.topic) {
return callback(err);
@@ -187,7 +191,7 @@ apiController.getCategoryData = function (cid, uid, callback) {
},
category: function (next) {
categories.getCategoryData(cid, next);
- }
+ },
}, function (err, results) {
if (err || !results.category) {
return callback(err);
@@ -205,7 +209,7 @@ apiController.getObject = function (req, res, next) {
var methods = {
post: apiController.getPostData,
topic: apiController.getTopicData,
- category: apiController.getCategoryData
+ category: apiController.getCategoryData,
};
var method = methods[req.params.type];
if (!method) {
@@ -220,110 +224,11 @@ apiController.getObject = function (req, res, next) {
});
};
-apiController.getCurrentUser = function (req, res, next) {
- if (!req.uid) {
- return res.status(401).json('not-authorized');
- }
- async.waterfall([
- function (next) {
- user.getUserField(req.uid, 'userslug', next);
- },
- function (userslug, next) {
- accountHelpers.getUserDataByUserSlug(userslug, req.uid, next);
- }
- ], function (err, userData) {
- if (err) {
- return next(err);
- }
- res.json(userData);
- });
-};
-
-apiController.getUserByUID = function (req, res, next) {
- byType('uid', req, res, next);
-};
-
-apiController.getUserByUsername = function (req, res, next) {
- byType('username', req, res, next);
-};
-
-apiController.getUserByEmail = function (req, res, next) {
- byType('email', req, res, next);
-};
-
-function byType(type, req, res, next) {
- apiController.getUserDataByField(req.uid, type, req.params[type], function (err, data) {
- if (err || !data) {
- return next(err);
- }
- res.json(data);
- });
-}
-
-apiController.getUserDataByField = function (callerUid, field, fieldValue, callback) {
- async.waterfall([
- function (next) {
- if (field === 'uid') {
- next(null, fieldValue);
- } else if (field === 'username') {
- user.getUidByUsername(fieldValue, next);
- } else if (field === 'email') {
- user.getUidByEmail(fieldValue, next);
- } else {
- next();
- }
- },
- function (uid, next) {
- if (!uid) {
- return next();
- }
- apiController.getUserDataByUID(callerUid, uid, next);
- }
- ], callback);
-};
-
-apiController.getUserDataByUID = function (callerUid, uid, callback) {
- if (!parseInt(callerUid, 10) && parseInt(meta.config.privateUserInfo, 10) === 1) {
- return callback(new Error('[[error:no-privileges]]'));
- }
-
- if (!parseInt(uid, 10)) {
- return callback(new Error('[[error:no-user]]'));
- }
-
- async.parallel({
- userData: async.apply(user.getUserData, uid),
- settings: async.apply(user.getSettings, uid)
- }, function (err, results) {
- if (err || !results.userData) {
- return callback(err || new Error('[[error:no-user]]'));
- }
-
- results.userData.email = results.settings.showemail ? results.userData.email : undefined;
- results.userData.fullname = results.settings.showfullname ? results.userData.fullname : undefined;
-
- callback(null, results.userData);
- });
-};
-
apiController.getModerators = function (req, res, next) {
categories.getModerators(req.params.cid, function (err, moderators) {
if (err) {
return next(err);
}
- res.json({moderators: moderators});
+ res.json({ moderators: moderators });
});
};
-
-
-apiController.getRecentPosts = function (req, res, next) {
- posts.getRecentPosts(req.uid, 0, 19, req.params.term, function (err, data) {
- if (err) {
- return next(err);
- }
-
- res.json(data);
- });
-};
-
-module.exports = apiController;
diff --git a/src/controllers/authentication.js b/src/controllers/authentication.js
index 90a1715cbb..6a2051d2c9 100644
--- a/src/controllers/authentication.js
+++ b/src/controllers/authentication.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var winston = require('winston');
@@ -6,7 +6,6 @@ var passport = require('passport');
var nconf = require('nconf');
var validator = require('validator');
var _ = require('underscore');
-var url = require('url');
var db = require('../database');
var meta = require('../meta');
@@ -19,7 +18,7 @@ var sockets = require('../socket.io');
var authenticationController = {};
-authenticationController.register = function (req, res, next) {
+authenticationController.register = function (req, res) {
var registrationType = meta.config.registrationType || 'normal';
if (registrationType === 'disabled') {
@@ -74,7 +73,7 @@ authenticationController.register = function (req, res, next) {
},
function (queue, next) {
res.locals.processLogin = true; // set it to false in plugin if you wish to just register only
- plugins.fireHook('filter:register.check', {req: req, res: res, userData: userData, queue: queue}, next);
+ plugins.fireHook('filter:register.check', { req: req, res: res, userData: userData, queue: queue }, next);
},
function (data, next) {
if (data.queue) {
@@ -82,7 +81,7 @@ authenticationController.register = function (req, res, next) {
} else {
registerAndLoginUser(req, res, userData, next);
}
- }
+ },
], function (err, data) {
if (err) {
return res.status(400).send(err.message);
@@ -102,7 +101,7 @@ function registerAndLoginUser(req, res, userData, callback) {
function (next) {
plugins.fireHook('filter:register.interstitial', {
userData: userData,
- interstitials: []
+ interstitials: [],
}, function (err, data) {
if (err) {
return next(err);
@@ -113,11 +112,10 @@ function registerAndLoginUser(req, res, userData, callback) {
if (!deferRegistration) {
return next();
- } else {
- userData.register = true;
- req.session.registration = userData;
- return res.json({ referrer: nconf.get('relative_path') + '/register/complete' });
}
+ userData.register = true;
+ req.session.registration = userData;
+ return res.json({ referrer: nconf.get('relative_path') + '/register/complete' });
});
},
function (next) {
@@ -133,8 +131,8 @@ function registerAndLoginUser(req, res, userData, callback) {
},
function (next) {
user.deleteInvitationKey(userData.email);
- plugins.fireHook('filter:register.complete', {uid: uid, referrer: req.body.referrer || nconf.get('relative_path') + '/'}, next);
- }
+ plugins.fireHook('filter:register.complete', { uid: uid, referrer: req.body.referrer || nconf.get('relative_path') + '/' }, next);
+ },
], callback);
}
@@ -145,8 +143,8 @@ function addToApprovalQueue(req, userData, callback) {
user.addToApprovalQueue(userData, next);
},
function (next) {
- next(null, {message: '[[register:registration-added-to-queue]]'});
- }
+ next(null, { message: '[[register:registration-added-to-queue]]' });
+ },
], callback);
}
@@ -154,7 +152,7 @@ authenticationController.registerComplete = function (req, res, next) {
// For the interstitials that respond, execute the callback with the form body
plugins.fireHook('filter:register.interstitial', {
userData: req.session.registration,
- interstitials: []
+ interstitials: [],
}, function (err, data) {
if (err) {
return next(err);
@@ -214,7 +212,7 @@ authenticationController.login = function (req, res, next) {
if (err) {
return next(err);
}
- req.body.username = username ? username : req.body.username;
+ req.body.username = username || req.body.username;
continueLogin(req, res, next);
});
} else if (loginWith.indexOf('username') !== -1 && !validator.isEmail(req.body.username)) {
@@ -284,7 +282,7 @@ authenticationController.doLogin = function (req, uid, callback) {
return callback();
}
- req.login({uid: uid}, function (err) {
+ req.login({ uid: uid }, function (err) {
if (err) {
return callback(err);
}
@@ -310,7 +308,7 @@ authenticationController.onSuccessfulLogin = function (req, uid, callback) {
datetime: Date.now(),
platform: req.useragent.platform,
browser: req.useragent.browser,
- version: req.useragent.version
+ version: req.useragent.version,
});
// Associate login session with user
@@ -323,7 +321,7 @@ authenticationController.onSuccessfulLogin = function (req, uid, callback) {
},
function (next) {
user.updateLastOnlineTime(uid, next);
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -343,7 +341,8 @@ authenticationController.localLogin = function (req, username, password, next) {
}
var userslug = utils.slugify(username);
- var uid, userData = {};
+ var uid;
+ var userData = {};
async.waterfall([
function (next) {
@@ -369,7 +368,7 @@ authenticationController.localLogin = function (req, username, password, next) {
},
banned: function (next) {
user.isBanned(uid, next);
- }
+ },
}, next);
},
function (result, next) {
@@ -408,7 +407,7 @@ authenticationController.localLogin = function (req, username, password, next) {
}
user.auth.clearLoginAttempts(uid);
next(null, userData, '[[success:authentication-successful]]');
- }
+ },
], next);
};
@@ -426,7 +425,7 @@ authenticationController.logout = function (req, res, next) {
user.setUserField(uid, 'lastonline', Date.now() - 300000);
- plugins.fireHook('static:user.loggedOut', {req: req, res: res, uid: uid}, function () {
+ plugins.fireHook('static:user.loggedOut', { req: req, res: res, uid: uid }, function () {
res.status(200).send('');
// Force session check for all connected socket.io clients with the same session id
diff --git a/src/controllers/categories.js b/src/controllers/categories.js
index 9a18e7f1dd..e02f107b4a 100644
--- a/src/controllers/categories.js
+++ b/src/controllers/categories.js
@@ -1,8 +1,7 @@
-"use strict";
+'use strict';
var async = require('async');
var nconf = require('nconf');
-var validator = require('validator');
var categories = require('../categories');
var meta = require('../meta');
@@ -12,17 +11,14 @@ var categoriesController = {};
categoriesController.list = function (req, res, next) {
res.locals.metaTags = [{
- name: "title",
- content: validator.escape(String(meta.config.title || 'NodeBB'))
- }, {
- name: "description",
- content: validator.escape(String(meta.config.description || ''))
+ name: 'title',
+ content: String(meta.config.title || 'NodeBB'),
}, {
property: 'og:title',
- content: '[[pages:categories]]'
+ content: '[[pages:categories]]',
}, {
property: 'og:type',
- content: 'website'
+ content: 'website',
}];
var ogImage = meta.config['og:image'] || meta.config['brand:logo'] || '';
@@ -32,7 +28,7 @@ categoriesController.list = function (req, res, next) {
}
res.locals.metaTags.push({
property: 'og:image',
- content: ogImage
+ content: ogImage,
});
}
@@ -48,7 +44,7 @@ categoriesController.list = function (req, res, next) {
categories.flattenCategories(allCategories, categoryData);
categories.getRecentTopicReplies(allCategories, req.uid, next);
- }
+ },
], function (err) {
if (err) {
return next(err);
@@ -56,11 +52,11 @@ categoriesController.list = function (req, res, next) {
var data = {
title: '[[pages:categories]]',
- categories: categoryData
+ categories: categoryData,
};
if (req.path.startsWith('/api/categories') || req.path.startsWith('/categories')) {
- data.breadcrumbs = helpers.buildBreadcrumbs([{text: data.title}]);
+ data.breadcrumbs = helpers.buildBreadcrumbs([{ text: data.title }]);
}
data.categories.forEach(function (category) {
@@ -68,7 +64,7 @@ categoriesController.list = function (req, res, next) {
category.teaser = {
url: nconf.get('relative_path') + '/topic/' + category.posts[0].topic.slug + '/' + category.posts[0].index,
timestampISO: category.posts[0].timestampISO,
- pid: category.posts[0].pid
+ pid: category.posts[0].pid,
};
}
});
diff --git a/src/controllers/category.js b/src/controllers/category.js
index 3570f279ee..ce5f7b5e07 100644
--- a/src/controllers/category.js
+++ b/src/controllers/category.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -37,7 +37,7 @@ categoryController.get = function (req, res, callback) {
},
userSettings: function (next) {
user.getSettings(req.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -87,7 +87,7 @@ categoryController.get = function (req, res, callback) {
set = 'cid:' + cid + ':tids:posts';
}
- var start = (currentPage - 1) * settings.topicsPerPage + topicIndex;
+ var start = ((currentPage - 1) * settings.topicsPerPage) + topicIndex;
var stop = start + settings.topicsPerPage - 1;
var payload = {
@@ -97,7 +97,7 @@ categoryController.get = function (req, res, callback) {
start: start,
stop: stop,
uid: req.uid,
- settings: settings
+ settings: settings,
};
async.waterfall([
@@ -120,11 +120,10 @@ categoryController.get = function (req, res, callback) {
}
}
categories.getCategoryById(payload, next);
- }
+ },
], next);
},
function (categoryData, next) {
-
categories.modifyTopicsByPrivilege(categoryData.topics, userPrivileges);
if (categoryData.link) {
@@ -135,8 +134,8 @@ categoryController.get = function (req, res, callback) {
var breadcrumbs = [
{
text: categoryData.name,
- url: nconf.get('relative_path') + '/category/' + categoryData.slug
- }
+ url: nconf.get('relative_path') + '/category/' + categoryData.slug,
+ },
];
helpers.buildCategoryBreadcrumbs(categoryData.parentCid, function (err, crumbs) {
if (err) {
@@ -155,7 +154,7 @@ categoryController.get = function (req, res, callback) {
categories.getRecentTopicReplies(allCategories, req.uid, function (err) {
next(err, categoryData);
});
- }
+ },
], function (err, categoryData) {
if (err) {
return callback(err);
@@ -167,26 +166,26 @@ categoryController.get = function (req, res, callback) {
res.locals.metaTags = [
{
name: 'title',
- content: categoryData.name
+ content: categoryData.name,
},
{
property: 'og:title',
- content: categoryData.name
+ content: categoryData.name,
},
{
name: 'description',
- content: categoryData.description
+ content: categoryData.description,
},
{
- property: "og:type",
- content: 'website'
- }
+ property: 'og:type',
+ content: 'website',
+ },
];
if (categoryData.backgroundImage) {
res.locals.metaTags.push({
name: 'og:image',
- content: categoryData.backgroundImage
+ content: categoryData.backgroundImage,
});
}
@@ -194,12 +193,12 @@ categoryController.get = function (req, res, callback) {
{
rel: 'alternate',
type: 'application/rss+xml',
- href: nconf.get('url') + '/category/' + cid + '.rss'
+ href: nconf.get('url') + '/category/' + cid + '.rss',
},
{
rel: 'up',
- href: nconf.get('url')
- }
+ href: nconf.get('url'),
+ },
];
if (parseInt(req.uid, 10)) {
diff --git a/src/controllers/errors.js b/src/controllers/errors.js
new file mode 100644
index 0000000000..6ab0dc6471
--- /dev/null
+++ b/src/controllers/errors.js
@@ -0,0 +1,63 @@
+'use strict';
+
+var nconf = require('nconf');
+var winston = require('winston');
+var validator = require('validator');
+
+exports.handleURIErrors = function (err, req, res, next) {
+ // Handle cases where malformed URIs are passed in
+ if (err instanceof URIError) {
+ var tidMatch = req.path.match(/^\/topic\/(\d+)\//);
+ var cidMatch = req.path.match(/^\/category\/(\d+)\//);
+
+ if (tidMatch) {
+ res.redirect(nconf.get('relative_path') + tidMatch[0]);
+ } else if (cidMatch) {
+ res.redirect(nconf.get('relative_path') + cidMatch[0]);
+ } else {
+ winston.warn('[controller] Bad request: ' + req.path);
+ if (res.locals.isAPI) {
+ res.status(400).json({
+ error: '[[global:400.title]]',
+ });
+ } else {
+ var middleware = require('../middleware');
+ middleware.buildHeader(req, res, function () {
+ res.render('400', { error: validator.escape(String(err.message)) });
+ });
+ }
+ }
+ } else {
+ next(err);
+ }
+};
+
+// this needs to have four arguments or express treats it as `(req, res, next)`
+// don't remove `next`!
+exports.handleErrors = function (err, req, res, next) { // eslint-disable-line no-unused-vars
+ switch (err.code) {
+ case 'EBADCSRFTOKEN':
+ winston.error(req.path + '\n', err.message);
+ return res.sendStatus(403);
+ case 'blacklisted-ip':
+ return res.status(403).type('text/plain').send(err.message);
+ }
+
+ if (parseInt(err.status, 10) === 302 && err.path) {
+ return res.locals.isAPI ? res.status(302).json(err.path) : res.redirect(err.path);
+ }
+
+ winston.error(req.path + '\n', err.stack);
+
+ res.status(err.status || 500);
+
+ var path = String(req.path || '');
+ if (res.locals.isAPI) {
+ res.json({ path: validator.escape(path), error: err.message });
+ } else {
+ var middleware = require('../middleware');
+ middleware.buildHeader(req, res, function () {
+ res.render('500', { path: validator.escape(path), error: validator.escape(String(err.message)) });
+ });
+ }
+};
diff --git a/src/controllers/globalmods.js b/src/controllers/globalmods.js
index 7e4fd1ffec..793c33653e 100644
--- a/src/controllers/globalmods.js
+++ b/src/controllers/globalmods.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var user = require('../user');
var adminBlacklistController = require('./admin/blacklist');
diff --git a/src/controllers/groups.js b/src/controllers/groups.js
index 25a6d928db..94f5469ef4 100644
--- a/src/controllers/groups.js
+++ b/src/controllers/groups.js
@@ -1,7 +1,6 @@
-"use strict";
+'use strict';
var async = require('async');
-var nconf = require('nconf');
var validator = require('validator');
var meta = require('../meta');
@@ -19,7 +18,7 @@ groupsController.list = function (req, res, next) {
return next(err);
}
data.title = '[[pages:groups]]';
- data.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[pages:groups]]'}]);
+ data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[pages:groups]]' }]);
res.render('groups/list', data);
});
};
@@ -40,9 +39,9 @@ groupsController.getGroupsFromSet = function (uid, sort, start, stop, callback)
next(null, {
groups: groupsData,
allowGroupCreation: parseInt(meta.config.allowGroupCreation, 10) === 1,
- nextStart: stop + 1
+ nextStart: stop + 1,
});
- }
+ },
], callback);
};
@@ -59,7 +58,7 @@ groupsController.details = function (req, res, callback) {
}
async.parallel({
exists: async.apply(groups.exists, groupName),
- hidden: async.apply(groups.isHidden, groupName)
+ hidden: async.apply(groups.isHidden, groupName),
}, next);
},
function (results, next) {
@@ -71,7 +70,7 @@ groupsController.details = function (req, res, callback) {
}
async.parallel({
isMember: async.apply(groups.isMember, req.uid, groupName),
- isInvited: async.apply(groups.isInvited, req.uid, groupName)
+ isInvited: async.apply(groups.isInvited, req.uid, groupName),
}, function (err, checks) {
if (err || checks.isMember || checks.isInvited) {
return next(err);
@@ -85,20 +84,20 @@ groupsController.details = function (req, res, callback) {
groups.get(groupName, {
uid: req.uid,
truncateUserList: true,
- userListCount: 20
+ userListCount: 20,
}, next);
},
posts: function (next) {
groups.getLatestMemberPosts(groupName, 10, req.uid, next);
},
- isAdmin:function (next) {
+ isAdmin: function (next) {
user.isAdministrator(req.uid, next);
},
isGlobalMod: function (next) {
user.isGlobalModerator(req.uid, next);
- }
+ },
}, next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -109,7 +108,7 @@ groupsController.details = function (req, res, callback) {
}
results.group.isOwner = results.group.isOwner || results.isAdmin || (results.isGlobalMod && !results.group.system);
results.title = '[[pages:group, ' + results.group.displayName + ']]';
- results.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[pages:groups]]', url: '/groups' }, {text: results.group.displayName}]);
+ results.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[pages:groups]]', url: '/groups' }, { text: results.group.displayName }]);
results.allowPrivateGroups = parseInt(meta.config.allowPrivateGroups, 10) === 1;
res.render('groups/details', results);
@@ -130,7 +129,7 @@ groupsController.members = function (req, res, callback) {
async.parallel({
isAdminOrGlobalMod: async.apply(user.isAdminOrGlobalMod, req.uid),
isMember: async.apply(groups.isMember, req.uid, groupName),
- isHidden: async.apply(groups.isHidden, groupName)
+ isHidden: async.apply(groups.isHidden, groupName),
}, next);
},
function (results, next) {
@@ -146,16 +145,16 @@ groupsController.members = function (req, res, callback) {
}
var breadcrumbs = helpers.buildBreadcrumbs([
- {text: '[[pages:groups]]', url: '/groups' },
- {text: validator.escape(String(groupName)), url: '/groups/' + req.params.slug},
- {text: '[[groups:details.members]]'}
+ { text: '[[pages:groups]]', url: '/groups' },
+ { text: validator.escape(String(groupName)), url: '/groups/' + req.params.slug },
+ { text: '[[groups:details.members]]' },
]);
res.render('groups/members', {
users: users,
nextStart: 50,
loadmore_display: users.length > 50 ? 'block' : 'hide',
- breadcrumbs: breadcrumbs
+ breadcrumbs: breadcrumbs,
});
});
};
@@ -174,14 +173,14 @@ groupsController.uploadCover = function (req, res, next) {
groups.updateCover(req.uid, {
file: req.files.files[0].path,
- groupName: params.groupName
+ groupName: params.groupName,
}, next);
- }
+ },
], function (err, image) {
if (err) {
return next(err);
}
- res.json([{url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url}]);
+ res.json([{ url: image.url }]);
});
};
diff --git a/src/controllers/helpers.js b/src/controllers/helpers.js
index 488ac6507c..5571bfbf62 100644
--- a/src/controllers/helpers.js
+++ b/src/controllers/helpers.js
@@ -17,8 +17,8 @@ helpers.notAllowed = function (req, res, error) {
plugins.fireHook('filter:helpers.notAllowed', {
req: req,
res: res,
- error: error
- }, function (err, data) {
+ error: error,
+ }, function (err) {
if (err) {
return winston.error(err);
}
@@ -28,24 +28,22 @@ helpers.notAllowed = function (req, res, error) {
path: req.path.replace(/^\/api/, ''),
loggedIn: !!req.uid,
error: error,
- title: '[[global:403.title]]'
+ title: '[[global:403.title]]',
});
} else {
res.status(403).render('403', {
path: req.path,
loggedIn: !!req.uid,
error: error,
- title: '[[global:403.title]]'
+ title: '[[global:403.title]]',
});
}
+ } else if (res.locals.isAPI) {
+ req.session.returnTo = nconf.get('relative_path') + req.url.replace(/^\/api/, '');
+ res.status(401).json('not-authorized');
} else {
- if (res.locals.isAPI) {
- req.session.returnTo = nconf.get('relative_path') + req.url.replace(/^\/api/, '');
- res.status(401).json('not-authorized');
- } else {
- req.session.returnTo = nconf.get('relative_path') + req.url;
- res.redirect(nconf.get('relative_path') + '/login');
- }
+ req.session.returnTo = nconf.get('relative_path') + req.url;
+ res.redirect(nconf.get('relative_path') + '/login');
}
});
};
@@ -72,7 +70,7 @@ helpers.buildCategoryBreadcrumbs = function (cid, callback) {
if (!parseInt(data.disabled, 10)) {
breadcrumbs.unshift({
text: validator.escape(String(data.name)),
- url: nconf.get('relative_path') + '/category/' + data.slug
+ url: nconf.get('relative_path') + '/category/' + data.slug,
});
}
@@ -87,13 +85,13 @@ helpers.buildCategoryBreadcrumbs = function (cid, callback) {
if (!meta.config.homePageRoute && meta.config.homePageCustom) {
breadcrumbs.unshift({
text: '[[global:header.categories]]',
- url: nconf.get('relative_path') + '/categories'
+ url: nconf.get('relative_path') + '/categories',
});
}
breadcrumbs.unshift({
text: '[[global:home]]',
- url: nconf.get('relative_path') + '/'
+ url: nconf.get('relative_path') + '/',
});
callback(null, breadcrumbs);
@@ -104,8 +102,8 @@ helpers.buildBreadcrumbs = function (crumbs) {
var breadcrumbs = [
{
text: '[[global:home]]',
- url: nconf.get('relative_path') + '/'
- }
+ url: nconf.get('relative_path') + '/',
+ },
];
crumbs.forEach(function (crumb) {
@@ -164,8 +162,8 @@ helpers.getWatchedCategories = function (uid, selectedCid, callback) {
recursive(category, categoriesData, '');
});
- next(null, {categories: categoriesData, selectedCategory: selectedCategory});
- }
+ next(null, { categories: categoriesData, selectedCategory: selectedCategory });
+ },
], callback);
};
diff --git a/src/controllers/index.js b/src/controllers/index.js
index 800559db4b..93b8e9a383 100644
--- a/src/controllers/index.js
+++ b/src/controllers/index.js
@@ -1,36 +1,38 @@
-"use strict";
+'use strict';
var async = require('async');
var nconf = require('nconf');
var validator = require('validator');
-var winston = require('winston');
var meta = require('../meta');
var user = require('../user');
var plugins = require('../plugins');
var helpers = require('./helpers');
-var Controllers = {
- topics: require('./topics'),
- posts: require('./posts'),
- categories: require('./categories'),
- category: require('./category'),
- unread: require('./unread'),
- recent: require('./recent'),
- popular: require('./popular'),
- tags: require('./tags'),
- search: require('./search'),
- users: require('./users'),
- groups: require('./groups'),
- accounts: require('./accounts'),
- authentication: require('./authentication'),
- api: require('./api'),
- admin: require('./admin'),
- globalMods: require('./globalmods'),
- mods: require('./mods'),
- sitemap: require('./sitemap')
-};
+var Controllers = module.exports;
+Controllers.topics = require('./topics');
+Controllers.posts = require('./posts');
+Controllers.categories = require('./categories');
+Controllers.category = require('./category');
+Controllers.unread = require('./unread');
+Controllers.recent = require('./recent');
+Controllers.popular = require('./popular');
+Controllers.tags = require('./tags');
+Controllers.search = require('./search');
+Controllers.user = require('./user');
+Controllers.users = require('./users');
+Controllers.groups = require('./groups');
+Controllers.accounts = require('./accounts');
+Controllers.authentication = require('./authentication');
+Controllers.api = require('./api');
+Controllers.admin = require('./admin');
+Controllers.globalMods = require('./globalmods');
+Controllers.mods = require('./mods');
+Controllers.sitemap = require('./sitemap');
+Controllers.osd = require('./osd');
+Controllers['404'] = require('./404');
+Controllers.errors = require('./errors');
Controllers.home = function (req, res, next) {
var route = meta.config.homePageRoute || (meta.config.homePageCustom || '').replace(/^\/+/, '') || 'categories';
@@ -46,7 +48,7 @@ Controllers.home = function (req, res, next) {
var hook = 'action:homepage.get:' + route;
if (plugins.hasListeners(hook)) {
- return plugins.fireHook(hook, {req: req, res: res, next: next});
+ return plugins.fireHook(hook, { req: req, res: res, next: next });
}
if (route === 'categories' || route === '/') {
@@ -61,7 +63,7 @@ Controllers.home = function (req, res, next) {
var match = /^category\/(\d+)\/(.*)$/.exec(route);
if (match) {
- req.params.topic_index = "1";
+ req.params.topic_index = '1';
req.params.category_id = match[1];
req.params.slug = match[2];
Controllers.category.get(req, res, next);
@@ -83,8 +85,8 @@ Controllers.reset = function (req, res, next) {
displayExpiryNotice: req.session.passwordExpired,
code: req.params.code,
minimumPasswordLength: parseInt(meta.config.minimumPasswordLength, 10),
- breadcrumbs: helpers.buildBreadcrumbs([{text: '[[reset_password:reset_password]]', url: '/reset'}, {text: '[[reset_password:update_password]]'}]),
- title: '[[pages:reset]]'
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[reset_password:reset_password]]', url: '/reset' }, { text: '[[reset_password:update_password]]' }]),
+ title: '[[pages:reset]]',
});
delete req.session.passwordExpired;
@@ -92,8 +94,8 @@ Controllers.reset = function (req, res, next) {
} else {
res.render('reset', {
code: null,
- breadcrumbs: helpers.buildBreadcrumbs([{text: '[[reset_password:reset_password]]'}]),
- title: '[[pages:reset]]'
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[reset_password:reset_password]]' }]),
+ title: '[[pages:reset]]',
});
}
};
@@ -122,18 +124,17 @@ Controllers.login = function (req, res, next) {
data.allowLocalLogin = parseInt(meta.config.allowLocalLogin, 10) === 1 || parseInt(req.query.local, 10) === 1;
data.allowRegistration = registrationType === 'normal' || registrationType === 'admin-approval' || registrationType === 'admin-approval-ip';
data.allowLoginWith = '[[login:' + allowLoginWith + ']]';
- data.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[global:login]]'}]);
+ data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[global:login]]' }]);
data.error = req.flash('error')[0] || errorText;
data.title = '[[pages:login]]';
if (!data.allowLocalLogin && !data.allowRegistration && data.alternate_logins && data.authentication.length === 1) {
if (res.locals.isAPI) {
return helpers.redirect(res, {
- external: data.authentication[0].url
+ external: nconf.get('relative_path') + data.authentication[0].url,
});
- } else {
- return res.redirect(nconf.get('relative_path') + data.authentication[0].url);
}
+ return res.redirect(nconf.get('relative_path') + data.authentication[0].url);
}
if (req.uid) {
user.getUserFields(req.uid, ['username', 'email'], function (err, user) {
@@ -147,7 +148,6 @@ Controllers.login = function (req, res, next) {
} else {
res.render('login', data);
}
-
};
Controllers.register = function (req, res, next) {
@@ -171,8 +171,8 @@ Controllers.register = function (req, res, next) {
}
},
function (next) {
- plugins.fireHook('filter:parse.post', {postData: {content: meta.config.termsOfUse || ''}}, next);
- }
+ plugins.fireHook('filter:parse.post', { postData: { content: meta.config.termsOfUse || '' } }, next);
+ },
], function (err, termsOfUse) {
if (err) {
return next(err);
@@ -180,7 +180,7 @@ Controllers.register = function (req, res, next) {
var loginStrategies = require('../routes/authentication').getLoginStrategies();
var data = {
'register_window:spansize': loginStrategies.length ? 'col-md-6' : 'col-md-12',
- 'alternate_logins': !!loginStrategies.length
+ alternate_logins: !!loginStrategies.length,
};
data.authentication = loginStrategies;
@@ -189,7 +189,7 @@ Controllers.register = function (req, res, next) {
data.maximumUsernameLength = parseInt(meta.config.maximumUsernameLength, 10);
data.minimumPasswordLength = parseInt(meta.config.minimumPasswordLength, 10);
data.termsOfUse = termsOfUse.postData.content;
- data.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[register:register]]'}]);
+ data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[register:register]]' }]);
data.regFormEntry = [];
data.error = req.flash('error')[0] || errorText;
data.title = '[[pages:register]]';
@@ -203,37 +203,35 @@ Controllers.registerInterstitial = function (req, res, next) {
return res.redirect(nconf.get('relative_path') + '/register');
}
- plugins.fireHook('filter:register.interstitial', {
- userData: req.session.registration,
- interstitials: []
- }, function (err, data) {
- if (err) {
- return next(err);
- }
-
- if (!data.interstitials.length) {
- // No interstitials, redirect to home
- delete req.session.registration;
- return res.redirect('/');
- }
-
- var renders = data.interstitials.map(function (interstitial) {
- return async.apply(req.app.render.bind(req.app), interstitial.template, interstitial.data || {});
- });
- var errors = req.flash('error');
-
- async.parallel(renders, function (err, sections) {
- if (err) {
- return next(err);
+ async.waterfall([
+ function (next) {
+ plugins.fireHook('filter:register.interstitial', {
+ userData: req.session.registration,
+ interstitials: [],
+ }, next);
+ },
+ function (data, next) {
+ if (!data.interstitials.length) {
+ // No interstitials, redirect to home
+ delete req.session.registration;
+ return res.redirect('/');
}
+ var renders = data.interstitials.map(function (interstitial) {
+ return async.apply(req.app.render.bind(req.app), interstitial.template, interstitial.data || {});
+ });
+
+ async.parallel(renders, next);
+ },
+ function (sections) {
+ var errors = req.flash('error');
res.render('registerComplete', {
title: '[[pages:registration-complete]]',
errors: errors,
- sections: sections
+ sections: sections,
});
- });
- });
+ },
+ ], next);
};
Controllers.compose = function (req, res, next) {
@@ -241,7 +239,7 @@ Controllers.compose = function (req, res, next) {
req: req,
res: res,
next: next,
- templateData: {}
+ templateData: {},
}, function (err, data) {
if (err) {
return next(err);
@@ -249,7 +247,7 @@ Controllers.compose = function (req, res, next) {
if (data.templateData.disabled) {
res.render('', {
- title: '[[modules:composer.compose]]'
+ title: '[[modules:composer.compose]]',
});
} else {
data.templateData.title = '[[modules:composer.compose]]';
@@ -270,12 +268,12 @@ Controllers.confirmEmail = function (req, res) {
Controllers.robots = function (req, res) {
res.set('Content-Type', 'text/plain');
- if (meta.config["robots.txt"]) {
- res.send(meta.config["robots.txt"]);
+ if (meta.config['robots.txt']) {
+ res.send(meta.config['robots.txt']);
} else {
- res.send("User-agent: *\n" +
- "Disallow: " + nconf.get('relative_path') + "/admin/\n" +
- "Sitemap: " + nconf.get('url') + "/sitemap.xml");
+ res.send('User-agent: *\n' +
+ 'Disallow: ' + nconf.get('relative_path') + '/admin/\n' +
+ 'Sitemap: ' + nconf.get('url') + '/sitemap.xml');
}
};
@@ -285,7 +283,7 @@ Controllers.manifest = function (req, res) {
start_url: nconf.get('relative_path') + '/',
display: 'standalone',
orientation: 'portrait',
- icons: []
+ icons: [],
};
if (meta.config['brand:touchIcon']) {
@@ -293,159 +291,59 @@ Controllers.manifest = function (req, res) {
src: nconf.get('relative_path') + '/assets/uploads/system/touchicon-36.png',
sizes: '36x36',
type: 'image/png',
- density: 0.75
+ density: 0.75,
}, {
src: nconf.get('relative_path') + '/assets/uploads/system/touchicon-48.png',
sizes: '48x48',
type: 'image/png',
- density: 1.0
+ density: 1.0,
}, {
src: nconf.get('relative_path') + '/assets/uploads/system/touchicon-72.png',
sizes: '72x72',
type: 'image/png',
- density: 1.5
+ density: 1.5,
}, {
src: nconf.get('relative_path') + '/assets/uploads/system/touchicon-96.png',
sizes: '96x96',
type: 'image/png',
- density: 2.0
+ density: 2.0,
}, {
src: nconf.get('relative_path') + '/assets/uploads/system/touchicon-144.png',
sizes: '144x144',
type: 'image/png',
- density: 3.0
+ density: 3.0,
}, {
src: nconf.get('relative_path') + '/assets/uploads/system/touchicon-192.png',
sizes: '192x192',
type: 'image/png',
- density: 4.0
+ density: 4.0,
});
}
res.status(200).json(manifest);
};
-Controllers.outgoing = function (req, res) {
+Controllers.outgoing = function (req, res, next) {
var url = req.query.url || '';
- var data = {
+
+ if (!url) {
+ return next();
+ }
+
+ res.render('outgoing', {
outgoing: validator.escape(String(url)),
title: meta.config.title,
- breadcrumbs: helpers.buildBreadcrumbs([{text: '[[notifications:outgoing_link]]'}])
- };
-
- if (url) {
- res.render('outgoing', data);
- } else {
- res.status(404).redirect(nconf.get('relative_path') + '/404');
- }
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[notifications:outgoing_link]]' }]),
+ });
};
Controllers.termsOfUse = function (req, res, next) {
if (!meta.config.termsOfUse) {
return next();
}
- res.render('tos', {termsOfUse: meta.config.termsOfUse});
+ res.render('tos', { termsOfUse: meta.config.termsOfUse });
};
Controllers.ping = function (req, res) {
res.status(200).send(req.path === '/sping' ? 'healthy' : '200');
};
-
-Controllers.handle404 = function (req, res) {
- var relativePath = nconf.get('relative_path');
- var isClientScript = new RegExp('^' + relativePath + '\\/assets\\/src\\/.+\\.js');
-
- if (plugins.hasListeners('action:meta.override404')) {
- return plugins.fireHook('action:meta.override404', {
- req: req,
- res: res,
- error: {}
- });
- }
-
- if (isClientScript.test(req.url)) {
- res.type('text/javascript').status(200).send('');
- } else if (req.path.startsWith(relativePath + '/assets/uploads') || (req.get('accept') && req.get('accept').indexOf('text/html') === -1) || req.path === '/favicon.ico') {
- meta.errors.log404(req.path || '');
- res.sendStatus(404);
- } else if (req.accepts('html')) {
- if (process.env.NODE_ENV === 'development') {
- winston.warn('Route requested but not found: ' + req.url);
- }
-
- meta.errors.log404(req.path.replace(/^\/api/, '') || '');
- res.status(404);
-
- var path = String(req.path || '');
-
- if (res.locals.isAPI) {
- return res.json({path: validator.escape(path.replace(/^\/api/, '')), title: '[[global:404.title]]'});
- }
- var middleware = require('../middleware');
- middleware.buildHeader(req, res, function () {
- res.render('404', {path: validator.escape(path), title: '[[global:404.title]]'});
- });
- } else {
- res.status(404).type('txt').send('Not found');
- }
-};
-
-Controllers.handleURIErrors = function (err, req, res, next) {
- // Handle cases where malformed URIs are passed in
- if (err instanceof URIError) {
- var tidMatch = req.path.match(/^\/topic\/(\d+)\//);
- var cidMatch = req.path.match(/^\/category\/(\d+)\//);
-
- if (tidMatch) {
- res.redirect(nconf.get('relative_path') + tidMatch[0]);
- } else if (cidMatch) {
- res.redirect(nconf.get('relative_path') + cidMatch[0]);
- } else {
- winston.warn('[controller] Bad request: ' + req.path);
- if (res.locals.isAPI) {
- res.status(400).json({
- error: '[[global:400.title]]'
- });
- } else {
- var middleware = require('../middleware');
- middleware.buildHeader(req, res, function () {
- res.render('400', { error: validator.escape(String(err.message)) });
- });
- }
- }
-
- return;
- } else {
- next(err);
- }
-};
-
-Controllers.handleErrors = function (err, req, res, next) {
- switch (err.code) {
- case 'EBADCSRFTOKEN':
- winston.error(req.path + '\n', err.message);
- return res.sendStatus(403);
- case 'blacklisted-ip':
- return res.status(403).type('text/plain').send(err.message);
- }
-
- if (parseInt(err.status, 10) === 302 && err.path) {
- return res.locals.isAPI ? res.status(302).json(err.path) : res.redirect(err.path);
- }
-
- winston.error(req.path + '\n', err.stack);
-
- res.status(err.status || 500);
-
- var path = String(req.path || '');
- if (res.locals.isAPI) {
- res.json({path: validator.escape(path), error: err.message});
- } else {
- var middleware = require('../middleware');
- middleware.buildHeader(req, res, function () {
- res.render('500', { path: validator.escape(path), error: validator.escape(String(err.message)) });
- });
- }
-};
-
-module.exports = Controllers;
diff --git a/src/controllers/mods.js b/src/controllers/mods.js
index 0079412f87..6a1835f980 100644
--- a/src/controllers/mods.js
+++ b/src/controllers/mods.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -10,7 +10,7 @@ var modsController = {};
modsController.flagged = function (req, res, next) {
async.parallel({
isAdminOrGlobalMod: async.apply(user.isAdminOrGlobalMod, req.uid),
- moderatedCids: async.apply(user.getModeratedCids, req.uid)
+ moderatedCids: async.apply(user.getModeratedCids, req.uid),
}, function (err, results) {
if (err || !(results.isAdminOrGlobalMod || !!results.moderatedCids.length)) {
return next(err);
diff --git a/src/controllers/osd.js b/src/controllers/osd.js
new file mode 100644
index 0000000000..c83f7f142c
--- /dev/null
+++ b/src/controllers/osd.js
@@ -0,0 +1,32 @@
+'use strict';
+
+var xml = require('xml');
+var nconf = require('nconf');
+
+var plugins = require('../plugins');
+var meta = require('../meta');
+
+module.exports.handle = function (req, res, next) {
+ if (plugins.hasListeners('filter:search.query')) {
+ res.type('application/xml').send(generateXML());
+ } else {
+ next();
+ }
+};
+
+function generateXML() {
+ return xml([{
+ OpenSearchDescription: [
+ { _attr: { xmlns: 'http://a9.com/-/spec/opensearch/1.1/' } },
+ { ShortName: String(meta.config.title || meta.config.browserTitle || 'NodeBB') },
+ { Description: String(meta.config.description || '') },
+ { Url: {
+ _attr: {
+ type: 'text/html',
+ method: 'get',
+ template: nconf.get('url') + '/search?term={searchTerms}&in=titlesposts',
+ },
+ } },
+ ],
+ }], { declaration: true, indent: '\t' });
+}
diff --git a/src/controllers/popular.js b/src/controllers/popular.js
index f38edd594c..21c07224c1 100644
--- a/src/controllers/popular.js
+++ b/src/controllers/popular.js
@@ -14,11 +14,10 @@ var lastUpdateTime = 0;
var terms = {
daily: 'day',
weekly: 'week',
- monthly: 'month'
+ monthly: 'month',
};
popularController.get = function (req, res, next) {
-
var term = terms[req.params.term];
if (!term && req.params.term) {
@@ -30,7 +29,7 @@ popularController.get = function (req, res, next) {
day: '[[recent:day]]',
week: '[[recent:week]]',
month: '[[recent:month]]',
- alltime: '[[global:header.popular]]'
+ alltime: '[[global:header.popular]]',
};
if (!req.uid) {
@@ -49,14 +48,14 @@ popularController.get = function (req, res, next) {
'feeds:disableRSS': parseInt(meta.config['feeds:disableRSS'], 10) === 1,
rssFeedUrl: nconf.get('relative_path') + '/popular/' + (req.params.term || 'daily') + '.rss',
title: '[[pages:popular-' + term + ']]',
- term: term
+ term: term,
};
if (req.path.startsWith('/api/popular') || req.path.startsWith('/popular')) {
- var breadcrumbs = [{text: termToBreadcrumb[term]}];
+ var breadcrumbs = [{ text: termToBreadcrumb[term] }];
if (req.params.term) {
- breadcrumbs.unshift({text: '[[global:header.popular]]', url: '/popular'});
+ breadcrumbs.unshift({ text: '[[global:header.popular]]', url: '/popular' });
}
data.breadcrumbs = helpers.buildBreadcrumbs(breadcrumbs);
@@ -71,4 +70,4 @@ popularController.get = function (req, res, next) {
});
};
-module.exports = popularController;
\ No newline at end of file
+module.exports = popularController;
diff --git a/src/controllers/posts.js b/src/controllers/posts.js
index dae990e171..8afb3f5729 100644
--- a/src/controllers/posts.js
+++ b/src/controllers/posts.js
@@ -1,24 +1,38 @@
-"use strict";
+'use strict';
+
+var async = require('async');
var posts = require('../posts');
var helpers = require('./helpers');
-var postsController = {};
+var postsController = module.exports;
-postsController.redirectToPost = function (req, res, callback) {
+postsController.redirectToPost = function (req, res, next) {
var pid = parseInt(req.params.pid, 10);
if (!pid) {
- return callback();
+ return next();
}
- posts.generatePostPath(pid, req.uid, function (err, path) {
- if (err || !path) {
- return callback(err);
- }
-
- helpers.redirect(res, path);
- });
+ async.waterfall([
+ function (next) {
+ posts.generatePostPath(pid, req.uid, next);
+ },
+ function (path, next) {
+ if (!path) {
+ return next();
+ }
+ helpers.redirect(res, path);
+ },
+ ], next);
};
-
-module.exports = postsController;
+postsController.getRecentPosts = function (req, res, next) {
+ async.waterfall([
+ function (next) {
+ posts.getRecentPosts(req.uid, 0, 19, req.params.term, next);
+ },
+ function (data) {
+ res.json(data);
+ },
+ ], next);
+};
diff --git a/src/controllers/recent.js b/src/controllers/recent.js
index 2da6e7d09c..c5d1d2128a 100644
--- a/src/controllers/recent.js
+++ b/src/controllers/recent.js
@@ -13,7 +13,7 @@ var pagination = require('../pagination');
var recentController = {};
-var validFilter = {'': true, 'new': true, 'watched': true};
+var validFilter = { '': true, new: true, watched: true };
recentController.get = function (req, res, next) {
var page = parseInt(req.query.page, 10) || 1;
@@ -35,7 +35,7 @@ recentController.get = function (req, res, next) {
},
watchedCategories: function (next) {
helpers.getWatchedCategories(req.uid, cid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -46,7 +46,7 @@ recentController.get = function (req, res, next) {
stop = start + settings.topicsPerPage - 1;
topics.getRecentTopics(cid, req.uid, start, stop, filter, next);
- }
+ },
], function (err, data) {
if (err) {
return next(err);
@@ -63,17 +63,17 @@ recentController.get = function (req, res, next) {
name: '[[unread:all-topics]]',
url: 'recent',
selected: filter === '',
- filter: ''
+ filter: '',
}, {
name: '[[unread:new-topics]]',
url: 'recent/new',
selected: filter === 'new',
- filter: 'new'
+ filter: 'new',
}, {
name: '[[unread:watched-topics]]',
url: 'recent/watched',
selected: filter === 'watched',
- filter: 'watched'
+ filter: 'watched',
}];
data.selectedFilter = data.filters.find(function (filter) {
@@ -84,7 +84,7 @@ recentController.get = function (req, res, next) {
data.pagination = pagination.create(page, pageCount, req.query);
if (req.path.startsWith('/api/recent') || req.path.startsWith('/recent')) {
- data.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[recent:title]]'}]);
+ data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[recent:title]]' }]);
}
data.querystring = cid ? ('?cid=' + validator.escape(String(cid))) : '';
@@ -92,4 +92,4 @@ recentController.get = function (req, res, next) {
});
};
-module.exports = recentController;
\ No newline at end of file
+module.exports = recentController;
diff --git a/src/controllers/search.js b/src/controllers/search.js
index 2261e4f3b7..29a883489f 100644
--- a/src/controllers/search.js
+++ b/src/controllers/search.js
@@ -42,20 +42,20 @@ searchController.search = function (req, res, next) {
sortDirection: req.query.sortDirection,
page: page,
uid: req.uid,
- qs: req.query
+ qs: req.query,
};
async.parallel({
categories: async.apply(categories.buildForSelect, req.uid),
- search: async.apply(search.search, data)
+ search: async.apply(search.search, data),
}, function (err, results) {
if (err) {
return next(err);
}
var categoriesData = [
- {value: 'all', text: '[[unread:all_categories]]'},
- {value: 'watched', text: '[[category:watched-categories]]'}
+ { value: 'all', text: '[[unread:all_categories]]' },
+ { value: 'watched', text: '[[category:watched-categories]]' },
].concat(results.categories);
var searchData = results.search;
@@ -65,7 +65,7 @@ searchController.search = function (req, res, next) {
searchData.showAsPosts = !req.query.showAs || req.query.showAs === 'posts';
searchData.showAsTopics = req.query.showAs === 'topics';
searchData.title = '[[global:header.search]]';
- searchData.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[global:search]]'}]);
+ searchData.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[global:search]]' }]);
searchData.expandSearch = !req.query.term;
res.render('search', searchData);
diff --git a/src/controllers/sitemap.js b/src/controllers/sitemap.js
index 42b0ae1076..846c6facb2 100644
--- a/src/controllers/sitemap.js
+++ b/src/controllers/sitemap.js
@@ -1,68 +1,57 @@
'use strict';
+var async = require('async');
+
var sitemap = require('../sitemap');
var meta = require('../meta');
-var sitemapController = {};
-sitemapController.render = function (req, res, next) {
- sitemap.render(function (err, tplData) {
- if (err) {
- return next(err);
- }
+var sitemapController = module.exports;
- req.app.render('sitemap', tplData, function (err, xml) {
- if (err) {
- return next(err);
- }
+sitemapController.render = function (req, res, next) {
+ async.waterfall([
+ function (next) {
+ sitemap.render(next);
+ },
+ function (tplData, next) {
+ req.app.render('sitemap', tplData, next);
+ },
+ function (xml) {
res.header('Content-Type', 'application/xml');
res.send(xml);
- });
- });
+ },
+ ], next);
};
sitemapController.getPages = function (req, res, next) {
- if (parseInt(meta.config['feeds:disableSitemap'], 10) === 1) {
- return next();
- }
-
- sitemap.getPages(function (err, xml) {
- if (err) {
- return next(err);
- }
- res.header('Content-Type', 'application/xml');
- res.send(xml);
- });
+ sendSitemap(sitemap.getPages, res, next);
};
sitemapController.getCategories = function (req, res, next) {
- if (parseInt(meta.config['feeds:disableSitemap'], 10) === 1) {
- return next();
- }
-
- sitemap.getCategories(function (err, xml) {
- if (err) {
- return next(err);
- }
- res.header('Content-Type', 'application/xml');
- res.send(xml);
- });
+ sendSitemap(sitemap.getCategories, res, next);
};
sitemapController.getTopicPage = function (req, res, next) {
- if (parseInt(meta.config['feeds:disableSitemap'], 10) === 1) {
- return next();
- }
-
- sitemap.getTopicPage(parseInt(req.params[0], 10), function (err, xml) {
- if (err) {
- return next(err);
- } else if (!xml) {
- return next();
- }
-
- res.header('Content-Type', 'application/xml');
- res.send(xml);
- });
+ sendSitemap(function (callback) {
+ sitemap.getTopicPage(parseInt(req.params[0], 10), callback);
+ }, res, next);
};
-module.exports = sitemapController;
\ No newline at end of file
+function sendSitemap(method, res, callback) {
+ if (parseInt(meta.config['feeds:disableSitemap'], 10) === 1) {
+ return callback();
+ }
+ async.waterfall([
+ function (next) {
+ method(next);
+ },
+ function (xml) {
+ if (!xml) {
+ return callback();
+ }
+
+ res.header('Content-Type', 'application/xml');
+ res.send(xml);
+ },
+ ], callback);
+}
+
diff --git a/src/controllers/tags.js b/src/controllers/tags.js
index a433694220..cffff0e44c 100644
--- a/src/controllers/tags.js
+++ b/src/controllers/tags.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -8,7 +8,7 @@ var validator = require('validator');
var user = require('../user');
var topics = require('../topics');
var pagination = require('../pagination');
-var helpers = require('./helpers');
+var helpers = require('./helpers');
var tagsController = {};
@@ -19,8 +19,8 @@ tagsController.getTag = function (req, res, next) {
var templateData = {
topics: [],
tag: tag,
- breadcrumbs: helpers.buildBreadcrumbs([{text: '[[tags:tags]]', url: '/tags'}, {text: tag}]),
- title: '[[pages:tag, ' + tag + ']]'
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[tags:tags]]', url: '/tags' }, { text: tag }]),
+ title: '[[pages:tag, ' + tag + ']]',
};
var settings;
var topicCount = 0;
@@ -39,7 +39,7 @@ tagsController.getTag = function (req, res, next) {
},
tids: function (next) {
topics.getTagTids(req.params.tag, start, stop, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -48,7 +48,7 @@ tagsController.getTag = function (req, res, next) {
}
topicCount = results.topicCount;
topics.getTopics(results.tids, req.uid, next);
- }
+ },
], function (err, topics) {
if (err) {
return next(err);
@@ -57,16 +57,16 @@ tagsController.getTag = function (req, res, next) {
res.locals.metaTags = [
{
name: 'title',
- content: tag
+ content: tag,
},
{
property: 'og:title',
- content: tag
+ content: tag,
},
{
property: 'og:url',
- content: nconf.get('url') + '/tags/' + tag
- }
+ content: nconf.get('url') + '/tags/' + tag,
+ },
];
templateData.topics = topics;
@@ -86,8 +86,8 @@ tagsController.getTags = function (req, res, next) {
var data = {
tags: tags,
nextStart: 100,
- breadcrumbs: helpers.buildBreadcrumbs([{text: '[[tags:tags]]'}]),
- title: '[[pages:tags]]'
+ breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[tags:tags]]' }]),
+ title: '[[pages:tags]]',
};
res.render('tags', data);
});
diff --git a/src/controllers/topics.js b/src/controllers/topics.js
index 0677c0a8c3..1d813868ae 100644
--- a/src/controllers/topics.js
+++ b/src/controllers/topics.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -39,7 +39,7 @@ topicsController.get = function (req, res, callback) {
},
topic: function (next) {
topics.getTopicData(tid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -113,7 +113,7 @@ topicsController.get = function (req, res, callback) {
currentPage = Math.max(1, Math.ceil(index / settings.postsPerPage));
}
- var start = (currentPage - 1) * settings.postsPerPage + postIndex;
+ var start = ((currentPage - 1) * settings.postsPerPage) + postIndex;
var stop = start + settings.postsPerPage - 1;
topics.getTopicWithPosts(results.topic, set, req.uid, start, stop, reverse, next);
@@ -125,18 +125,17 @@ topicsController.get = function (req, res, callback) {
topics.modifyPostsByPrivilege(topicData, userPrivileges);
- plugins.fireHook('filter:controllers.topic.get', {topicData: topicData, uid: req.uid}, next);
+ plugins.fireHook('filter:controllers.topic.get', { topicData: topicData, uid: req.uid }, next);
},
function (data, next) {
-
var breadcrumbs = [
{
text: data.topicData.category.name,
- url: nconf.get('relative_path') + '/category/' + data.topicData.category.slug
+ url: nconf.get('relative_path') + '/category/' + data.topicData.category.slug,
},
{
- text: data.topicData.title
- }
+ text: data.topicData.title,
+ },
];
helpers.buildCategoryBreadcrumbs(data.topicData.category.parentCid, function (err, crumbs) {
@@ -149,7 +148,7 @@ topicsController.get = function (req, res, callback) {
},
function (topicData, next) {
function findPost(index) {
- for(var i = 0; i < topicData.posts.length; ++i) {
+ for (var i = 0; i < topicData.posts.length; i += 1) {
if (parseInt(topicData.posts[i].index, 10) === parseInt(index, 10)) {
return topicData.posts[i];
}
@@ -187,71 +186,71 @@ topicsController.get = function (req, res, callback) {
res.locals.metaTags = [
{
- name: "title",
- content: topicData.titleRaw
+ name: 'title',
+ content: topicData.titleRaw,
},
{
- name: "description",
- content: description
+ name: 'description',
+ content: description,
},
{
property: 'og:title',
- content: topicData.titleRaw
+ content: topicData.titleRaw,
},
{
property: 'og:description',
- content: description
+ content: description,
},
{
- property: "og:type",
- content: 'article'
+ property: 'og:type',
+ content: 'article',
},
{
- property: "og:url",
+ property: 'og:url',
content: nconf.get('url') + '/topic/' + topicData.slug + (req.params.post_index ? ('/' + req.params.post_index) : ''),
- noEscape: true
+ noEscape: true,
},
{
property: 'og:image',
content: ogImageUrl,
- noEscape: true
+ noEscape: true,
},
{
- property: "og:image:url",
+ property: 'og:image:url',
content: ogImageUrl,
- noEscape: true
+ noEscape: true,
},
{
- property: "article:published_time",
- content: utils.toISOString(topicData.timestamp)
+ property: 'article:published_time',
+ content: utils.toISOString(topicData.timestamp),
},
{
property: 'article:modified_time',
- content: utils.toISOString(topicData.lastposttime)
+ content: utils.toISOString(topicData.lastposttime),
},
{
property: 'article:section',
- content: topicData.category ? topicData.category.name : ''
- }
+ content: topicData.category ? topicData.category.name : '',
+ },
];
res.locals.linkTags = [
{
rel: 'alternate',
type: 'application/rss+xml',
- href: nconf.get('url') + '/topic/' + tid + '.rss'
- }
+ href: nconf.get('url') + '/topic/' + tid + '.rss',
+ },
];
if (topicData.category) {
res.locals.linkTags.push({
rel: 'up',
- href: nconf.get('url') + '/category/' + topicData.category.slug
+ href: nconf.get('url') + '/category/' + topicData.category.slug,
});
}
next(null, topicData);
- }
+ },
], function (err, data) {
if (err) {
return callback(err);
@@ -316,8 +315,8 @@ topicsController.teaser = function (req, res, next) {
if (!pid) {
return res.status(404).json('not-found');
}
- posts.getPostSummaryByPids([pid], req.uid, {stripTags: false}, next);
- }
+ posts.getPostSummaryByPids([pid], req.uid, { stripTags: false }, next);
+ },
], function (err, posts) {
if (err) {
return next(err);
@@ -341,7 +340,7 @@ topicsController.pagination = function (req, res, callback) {
async.parallel({
privileges: async.apply(privileges.topics.get, tid, req.uid),
settings: async.apply(user.getSettings, req.uid),
- topic: async.apply(topics.getTopicData, tid)
+ topic: async.apply(topics.getTopicData, tid),
}, function (err, results) {
if (err || !results.topic) {
return callback(err);
diff --git a/src/controllers/unread.js b/src/controllers/unread.js
index 83de85a67e..c5d0d4d950 100644
--- a/src/controllers/unread.js
+++ b/src/controllers/unread.js
@@ -12,7 +12,7 @@ var helpers = require('./helpers');
var unreadController = {};
-var validFilter = {'': true, 'new': true, 'watched': true};
+var validFilter = { '': true, new: true, watched: true };
unreadController.get = function (req, res, next) {
var page = parseInt(req.query.page, 10) || 1;
@@ -32,7 +32,7 @@ unreadController.get = function (req, res, next) {
},
settings: function (next) {
user.getSettings(req.uid, next);
- }
+ },
}, next);
},
function (_results, next) {
@@ -41,7 +41,7 @@ unreadController.get = function (req, res, next) {
var start = Math.max(0, (page - 1) * settings.topicsPerPage);
var stop = start + settings.topicsPerPage - 1;
topics.getUnreadTopics(cid, req.uid, start, stop, filter, next);
- }
+ },
], function (err, data) {
if (err) {
return next(err);
@@ -59,7 +59,7 @@ unreadController.get = function (req, res, next) {
data.selectedCategory = results.watchedCategories.selectedCategory;
if (req.path.startsWith('/api/unread') || req.path.startsWith('/unread')) {
- data.breadcrumbs = helpers.buildBreadcrumbs([{text: '[[unread:title]]'}]);
+ data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]);
}
data.title = '[[pages:unread]]';
@@ -67,17 +67,17 @@ unreadController.get = function (req, res, next) {
name: '[[unread:all-topics]]',
url: 'unread',
selected: filter === '',
- filter: ''
+ filter: '',
}, {
name: '[[unread:new-topics]]',
url: 'unread/new',
selected: filter === 'new',
- filter: 'new'
+ filter: 'new',
}, {
name: '[[unread:watched-topics]]',
url: 'unread/watched',
selected: filter === 'watched',
- filter: 'watched'
+ filter: 'watched',
}];
data.selectedFilter = data.filters.find(function (filter) {
diff --git a/src/controllers/uploads.js b/src/controllers/uploads.js
index 22e533a33d..82556ee12c 100644
--- a/src/controllers/uploads.js
+++ b/src/controllers/uploads.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var fs = require('fs');
var path = require('path');
@@ -30,7 +30,7 @@ uploadsController.upload = function (req, res, filesIterator) {
deleteTempFiles(files);
if (err) {
- return res.status(500).json({path: req.path, error: err.message});
+ return res.status(500).json({ path: req.path, error: err.message });
}
res.status(200).send(images);
@@ -60,13 +60,13 @@ function uploadAsImage(req, uploadedFile, callback) {
if (plugins.hasListeners('filter:uploadImage')) {
return plugins.fireHook('filter:uploadImage', {
image: uploadedFile,
- uid: req.uid
+ uid: req.uid,
}, callback);
}
file.isFileTypeAllowed(uploadedFile.path, next);
},
function (next) {
- uploadFile(req.uid, uploadedFile, next);
+ uploadsController.uploadFile(req.uid, uploadedFile, next);
},
function (fileObj, next) {
if (parseInt(meta.config.maximumImageWidth, 10) === 0) {
@@ -74,7 +74,7 @@ function uploadAsImage(req, uploadedFile, callback) {
}
resizeImage(fileObj, next);
- }
+ },
], callback);
}
@@ -90,8 +90,8 @@ function uploadAsFile(req, uploadedFile, callback) {
if (parseInt(meta.config.allowFileUploads, 10) !== 1) {
return next(new Error('[[error:uploads-are-disabled]]'));
}
- uploadFile(req.uid, uploadedFile, next);
- }
+ uploadsController.uploadFile(req.uid, uploadedFile, next);
+ },
], callback);
}
@@ -113,20 +113,19 @@ function resizeImage(fileObj, callback) {
path: fileObj.path,
target: path.join(dirname, basename + '-resized' + extname),
extension: extname,
- width: parseInt(meta.config.maximumImageWidth, 10) || 760
+ width: parseInt(meta.config.maximumImageWidth, 10) || 760,
}, next);
},
function (next) {
-
// Return the resized version to the composer/postData
var dirname = path.dirname(fileObj.url);
var extname = path.extname(fileObj.url);
var basename = path.basename(fileObj.url, extname);
- fileObj.url = path.join(dirname, basename + '-resized' + extname);
+ fileObj.url = dirname + '/' + basename + '-resized' + extname;
next(null, fileObj);
- }
+ },
], callback);
}
@@ -151,19 +150,19 @@ uploadsController.uploadThumb = function (req, res, next) {
path: uploadedFile.path,
extension: path.extname(uploadedFile.name),
width: size,
- height: size
+ height: size,
}, next);
},
function (next) {
if (plugins.hasListeners('filter:uploadImage')) {
return plugins.fireHook('filter:uploadImage', {
image: uploadedFile,
- uid: req.uid
+ uid: req.uid,
}, next);
}
- uploadFile(req.uid, uploadedFile, next);
- }
+ uploadsController.uploadFile(req.uid, uploadedFile, next);
+ },
], next);
}, next);
};
@@ -172,14 +171,14 @@ uploadsController.uploadGroupCover = function (uid, uploadedFile, callback) {
if (plugins.hasListeners('filter:uploadImage')) {
return plugins.fireHook('filter:uploadImage', {
image: uploadedFile,
- uid: uid
+ uid: uid,
}, callback);
}
if (plugins.hasListeners('filter:uploadFile')) {
return plugins.fireHook('filter:uploadFile', {
file: uploadedFile,
- uid: uid
+ uid: uid,
}, callback);
}
@@ -189,15 +188,15 @@ uploadsController.uploadGroupCover = function (uid, uploadedFile, callback) {
},
function (next) {
saveFileToLocal(uploadedFile, next);
- }
+ },
], callback);
};
-function uploadFile(uid, uploadedFile, callback) {
+uploadsController.uploadFile = function (uid, uploadedFile, callback) {
if (plugins.hasListeners('filter:uploadFile')) {
return plugins.fireHook('filter:uploadFile', {
file: uploadedFile,
- uid: uid
+ uid: uid,
}, callback);
}
@@ -218,7 +217,7 @@ function uploadFile(uid, uploadedFile, callback) {
}
saveFileToLocal(uploadedFile, callback);
-}
+};
function saveFileToLocal(uploadedFile, callback) {
var extension = file.typeToExtension(uploadedFile.type);
@@ -237,9 +236,9 @@ function saveFileToLocal(uploadedFile, callback) {
next(null, {
url: nconf.get('relative_path') + upload.url,
path: upload.path,
- name: uploadedFile.name
+ name: uploadedFile.name,
});
- }
+ },
], callback);
}
diff --git a/src/controllers/user.js b/src/controllers/user.js
new file mode 100644
index 0000000000..0f93f549b3
--- /dev/null
+++ b/src/controllers/user.js
@@ -0,0 +1,99 @@
+'use strict';
+
+var async = require('async');
+
+var user = require('../user');
+var meta = require('../meta');
+var accountHelpers = require('./accounts/helpers');
+
+var userController = module.exports;
+
+userController.getCurrentUser = function (req, res, next) {
+ if (!req.uid) {
+ return res.status(401).json('not-authorized');
+ }
+ async.waterfall([
+ function (next) {
+ user.getUserField(req.uid, 'userslug', next);
+ },
+ function (userslug, next) {
+ accountHelpers.getUserDataByUserSlug(userslug, req.uid, next);
+ },
+ function (userData) {
+ res.json(userData);
+ },
+ ], next);
+};
+
+
+userController.getUserByUID = function (req, res, next) {
+ byType('uid', req, res, next);
+};
+
+userController.getUserByUsername = function (req, res, next) {
+ byType('username', req, res, next);
+};
+
+userController.getUserByEmail = function (req, res, next) {
+ byType('email', req, res, next);
+};
+
+function byType(type, req, res, next) {
+ async.waterfall([
+ function (next) {
+ userController.getUserDataByField(req.uid, type, req.params[type], next);
+ },
+ function (data, next) {
+ if (!data) {
+ return next();
+ }
+ res.json(data);
+ },
+ ], next);
+}
+
+userController.getUserDataByField = function (callerUid, field, fieldValue, callback) {
+ async.waterfall([
+ function (next) {
+ if (field === 'uid') {
+ next(null, fieldValue);
+ } else if (field === 'username') {
+ user.getUidByUsername(fieldValue, next);
+ } else if (field === 'email') {
+ user.getUidByEmail(fieldValue, next);
+ } else {
+ next(null, null);
+ }
+ },
+ function (uid, next) {
+ if (!uid) {
+ return next(null, null);
+ }
+ userController.getUserDataByUID(callerUid, uid, next);
+ },
+ ], callback);
+};
+
+userController.getUserDataByUID = function (callerUid, uid, callback) {
+ if (!parseInt(callerUid, 10) && parseInt(meta.config.privateUserInfo, 10) === 1) {
+ return callback(new Error('[[error:no-privileges]]'));
+ }
+
+ if (!parseInt(uid, 10)) {
+ return callback(new Error('[[error:no-user]]'));
+ }
+
+ async.parallel({
+ userData: async.apply(user.getUserData, uid),
+ settings: async.apply(user.getSettings, uid),
+ }, function (err, results) {
+ if (err || !results.userData) {
+ return callback(err || new Error('[[error:no-user]]'));
+ }
+
+ results.userData.email = results.settings.showemail ? results.userData.email : undefined;
+ results.userData.fullname = results.settings.showfullname ? results.userData.fullname : undefined;
+
+ callback(null, results.userData);
+ });
+};
diff --git a/src/controllers/users.js b/src/controllers/users.js
index baf18a5b64..45cb5f1e21 100644
--- a/src/controllers/users.js
+++ b/src/controllers/users.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var user = require('../user');
@@ -8,9 +8,7 @@ var pagination = require('../pagination');
var db = require('../database');
var helpers = require('./helpers');
-
-var usersController = {};
-
+var usersController = module.exports;
usersController.index = function (req, res, next) {
var section = req.query.section || 'joindate';
@@ -20,7 +18,7 @@ usersController.index = function (req, res, next) {
'sort-posts': usersController.getUsersSortedByPosts,
'sort-reputation': usersController.getUsersSortedByReputation,
banned: usersController.getBannedUsers,
- flagged: usersController.getFlaggedUsers
+ flagged: usersController.getFlaggedUsers,
};
if (req.query.term) {
@@ -33,62 +31,65 @@ usersController.index = function (req, res, next) {
};
usersController.search = function (req, res, next) {
- async.parallel({
- search: function (next) {
- user.search({
- query: req.query.term,
- searchBy: req.query.searchBy || 'username',
- page: req.query.page || 1,
- sortBy: req.query.sortBy,
- onlineOnly: req.query.onlineOnly === 'true',
- bannedOnly: req.query.bannedOnly === 'true',
- flaggedOnly: req.query.flaggedOnly === 'true'
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ search: function (next) {
+ user.search({
+ query: req.query.term,
+ searchBy: req.query.searchBy || 'username',
+ page: req.query.page || 1,
+ sortBy: req.query.sortBy,
+ onlineOnly: req.query.onlineOnly === 'true',
+ bannedOnly: req.query.bannedOnly === 'true',
+ flaggedOnly: req.query.flaggedOnly === 'true',
+ }, next);
+ },
+ isAdminOrGlobalMod: function (next) {
+ user.isAdminOrGlobalMod(req.uid, next);
+ },
}, next);
},
- isAdminOrGlobalMod: function (next) {
- user.isAdminOrGlobalMod(req.uid, next);
- }
- }, function (err, results) {
- if (err) {
- return next(err);
- }
+ function (results, next) {
+ var section = req.query.section || 'joindate';
- var section = req.query.section || 'joindate';
-
- results.search.isAdminOrGlobalMod = results.isAdminOrGlobalMod;
- results.search.pagination = pagination.create(req.query.page, results.search.pageCount, req.query);
- results.search['section_' + section] = true;
- render(req, res, results.search, next);
- });
+ results.search.isAdminOrGlobalMod = results.isAdminOrGlobalMod;
+ results.search.pagination = pagination.create(req.query.page, results.search.pageCount, req.query);
+ results.search['section_' + section] = true;
+ render(req, res, results.search, next);
+ },
+ ], next);
};
usersController.getOnlineUsers = function (req, res, next) {
- async.parallel({
- users: function (next) {
- usersController.getUsers('users:online', req.uid, req.query, next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ users: function (next) {
+ usersController.getUsers('users:online', req.uid, req.query, next);
+ },
+ guests: function (next) {
+ require('../socket.io/admin/rooms').getTotalGuestCount(next);
+ },
+ }, next);
},
- guests: function (next) {
- require('../socket.io/admin/rooms').getTotalGuestCount(next);
- }
- }, function (err, results) {
- if (err) {
- return next(err);
- }
- var userData = results.users;
- var hiddenCount = 0;
- if (!userData.isAdminOrGlobalMod) {
- userData.users = userData.users.filter(function (user) {
- if (user && user.status === 'offline') {
- hiddenCount ++;
- }
- return user && user.status !== 'offline';
- });
- }
+ function (results, next) {
+ var userData = results.users;
+ var hiddenCount = 0;
+ if (!userData.isAdminOrGlobalMod) {
+ userData.users = userData.users.filter(function (user) {
+ if (user && user.status === 'offline') {
+ hiddenCount += 1;
+ }
+ return user && user.status !== 'offline';
+ });
+ }
- userData.anonymousUserCount = results.guests + hiddenCount;
+ userData.anonymousUserCount = results.guests + hiddenCount;
- render(req, res, userData, next);
- });
+ render(req, res, userData, next);
+ },
+ ], next);
};
usersController.getUsersSortedByPosts = function (req, res, next) {
@@ -107,61 +108,56 @@ usersController.getUsersSortedByJoinDate = function (req, res, next) {
};
usersController.getBannedUsers = function (req, res, next) {
- usersController.getUsers('users:banned', req.uid, req.query, function (err, userData) {
- if (err) {
- return next(err);
- }
-
- if (!userData.isAdminOrGlobalMod) {
- return next();
- }
-
- render(req, res, userData, next);
- });
+ renderIfAdminOrGlobalMod('users:banned', req, res, next);
};
usersController.getFlaggedUsers = function (req, res, next) {
- usersController.getUsers('users:flags', req.uid, req.query, function (err, userData) {
- if (err) {
- return next(err);
- }
-
- if (!userData.isAdminOrGlobalMod) {
- return next();
- }
-
- render(req, res, userData, next);
- });
+ renderIfAdminOrGlobalMod('users:flags', req, res, next);
};
-usersController.renderUsersPage = function (set, req, res, next) {
- usersController.getUsers(set, req.uid, req.query, function (err, userData) {
- if (err) {
- return next(err);
- }
+function renderIfAdminOrGlobalMod(set, req, res, next) {
+ async.waterfall([
+ function (next) {
+ user.isAdminOrGlobalMod(req.uid, next);
+ },
+ function (isAdminOrGlobalMod, next) {
+ if (!isAdminOrGlobalMod) {
+ return helpers.notAllowed(req, res);
+ }
+ usersController.renderUsersPage(set, req, res, next);
+ },
+ ], next);
+}
- render(req, res, userData, next);
- });
+usersController.renderUsersPage = function (set, req, res, next) {
+ async.waterfall([
+ function (next) {
+ usersController.getUsers(set, req.uid, req.query, next);
+ },
+ function (userData, next) {
+ render(req, res, userData, next);
+ },
+ ], next);
};
usersController.getUsers = function (set, uid, query, callback) {
var setToData = {
- 'users:postcount': {title: '[[pages:users/sort-posts]]', crumb: '[[users:top_posters]]'},
- 'users:reputation': {title: '[[pages:users/sort-reputation]]', crumb: '[[users:most_reputation]]'},
- 'users:joindate': {title: '[[pages:users/latest]]', crumb: '[[global:users]]'},
- 'users:online': {title: '[[pages:users/online]]', crumb: '[[global:online]]'},
- 'users:banned': {title: '[[pages:users/banned]]', crumb: '[[user:banned]]'},
- 'users:flags': {title: '[[pages:users/most-flags]]', crumb: '[[users:most_flags]]'},
+ 'users:postcount': { title: '[[pages:users/sort-posts]]', crumb: '[[users:top_posters]]' },
+ 'users:reputation': { title: '[[pages:users/sort-reputation]]', crumb: '[[users:most_reputation]]' },
+ 'users:joindate': { title: '[[pages:users/latest]]', crumb: '[[global:users]]' },
+ 'users:online': { title: '[[pages:users/online]]', crumb: '[[global:online]]' },
+ 'users:banned': { title: '[[pages:users/banned]]', crumb: '[[user:banned]]' },
+ 'users:flags': { title: '[[pages:users/most-flags]]', crumb: '[[users:most_flags]]' },
};
if (!setToData[set]) {
- setToData[set] = {title: '', crumb: ''};
+ setToData[set] = { title: '', crumb: '' };
}
- var breadcrumbs = [{text: setToData[set].crumb}];
+ var breadcrumbs = [{ text: setToData[set].crumb }];
if (set !== 'users:joindate') {
- breadcrumbs.unshift({text: '[[global:users]]', url: '/users'});
+ breadcrumbs.unshift({ text: '[[global:users]]', url: '/users' });
}
var page = parseInt(query.page, 10) || 1;
@@ -169,59 +165,62 @@ usersController.getUsers = function (set, uid, query, callback) {
var start = Math.max(0, page - 1) * resultsPerPage;
var stop = start + resultsPerPage - 1;
- async.parallel({
- isAdminOrGlobalMod: function (next) {
- user.isAdminOrGlobalMod(uid, next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ isAdminOrGlobalMod: function (next) {
+ user.isAdminOrGlobalMod(uid, next);
+ },
+ usersData: function (next) {
+ usersController.getUsersAndCount(set, uid, start, stop, next);
+ },
+ }, next);
},
- usersData: function (next) {
- usersController.getUsersAndCount(set, uid, start, stop, next);
- }
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
-
- var pageCount = Math.ceil(results.usersData.count / resultsPerPage);
- var userData = {
- users: results.usersData.users,
- pagination: pagination.create(page, pageCount, query),
- userCount: results.usersData.count,
- title: setToData[set].title || '[[pages:users/latest]]',
- breadcrumbs: helpers.buildBreadcrumbs(breadcrumbs),
- isAdminOrGlobalMod: results.isAdminOrGlobalMod
- };
- userData['section_' + (query.section || 'joindate')] = true;
- callback(null, userData);
- });
+ function (results, next) {
+ var pageCount = Math.ceil(results.usersData.count / resultsPerPage);
+ var userData = {
+ users: results.usersData.users,
+ pagination: pagination.create(page, pageCount, query),
+ userCount: results.usersData.count,
+ title: setToData[set].title || '[[pages:users/latest]]',
+ breadcrumbs: helpers.buildBreadcrumbs(breadcrumbs),
+ isAdminOrGlobalMod: results.isAdminOrGlobalMod,
+ };
+ userData['section_' + (query.section || 'joindate')] = true;
+ next(null, userData);
+ },
+ ], callback);
};
usersController.getUsersAndCount = function (set, uid, start, stop, callback) {
- async.parallel({
- users: function (next) {
- user.getUsersFromSet(set, uid, start, stop, next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ users: function (next) {
+ user.getUsersFromSet(set, uid, start, stop, next);
+ },
+ count: function (next) {
+ if (set === 'users:online') {
+ var now = Date.now();
+ db.sortedSetCount('users:online', now - 300000, '+inf', next);
+ } else if (set === 'users:banned') {
+ db.sortedSetCard('users:banned', next);
+ } else if (set === 'users:flags') {
+ db.sortedSetCard('users:flags', next);
+ } else {
+ db.getObjectField('global', 'userCount', next);
+ }
+ },
+ }, next);
},
- count: function (next) {
- if (set === 'users:online') {
- var now = Date.now();
- db.sortedSetCount('users:online', now - 300000, '+inf', next);
- } else if (set === 'users:banned') {
- db.sortedSetCard('users:banned', next);
- } else if (set === 'users:flags') {
- db.sortedSetCard('users:flags', next);
- } else {
- db.getObjectField('global', 'userCount', next);
- }
- }
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
- results.users = results.users.filter(function (user) {
- return user && parseInt(user.uid, 10);
- });
+ function (results, next) {
+ results.users = results.users.filter(function (user) {
+ return user && parseInt(user.uid, 10);
+ });
- callback(null, results);
- });
+ next(null, results);
+ },
+ ], callback);
};
function render(req, res, data, next) {
@@ -232,16 +231,15 @@ function render(req, res, data, next) {
data.adminInviteOnly = registrationType === 'admin-invite-only';
data['reputation:disabled'] = parseInt(meta.config['reputation:disabled'], 10) === 1;
- user.getInvitesNumber(req.uid, function (err, numInvites) {
- if (err) {
- return next(err);
- }
+ async.waterfall([
+ function (next) {
+ user.getInvitesNumber(req.uid, next);
+ },
+ function (numInvites) {
+ res.append('X-Total-Count', data.userCount);
+ data.invites = numInvites;
- res.append('X-Total-Count', data.userCount);
- data.invites = numInvites;
-
- res.render('users', data);
- });
+ res.render('users', data);
+ },
+ ], next);
}
-
-module.exports = usersController;
diff --git a/src/coverPhoto.js b/src/coverPhoto.js
index 6307110253..024ae48f20 100644
--- a/src/coverPhoto.js
+++ b/src/coverPhoto.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var coverPhoto = {};
var meta = require('./meta');
@@ -14,13 +14,13 @@ coverPhoto.getDefaultProfileCover = function (uid) {
};
function getCover(type, id) {
- if (meta.config[type + ':defaultCovers']) {
+ if (meta.config[type + ':defaultCovers']) {
var covers = meta.config[type + ':defaultCovers'].trim().split(/[\s,]+/g);
-
+
if (typeof id === 'string') {
id = (id.charCodeAt(0) + id.charCodeAt(1)) % covers.length;
} else {
- id = id % covers.length;
+ id %= covers.length;
}
return covers[id];
diff --git a/src/database.js b/src/database.js
index 65a5453d09..c62255306b 100644
--- a/src/database.js
+++ b/src/database.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var nconf = require('nconf');
var databaseName = nconf.get('database');
@@ -11,4 +11,4 @@ if (!databaseName) {
var primaryDB = require('./database/' + databaseName);
-module.exports = primaryDB;
\ No newline at end of file
+module.exports = primaryDB;
diff --git a/src/database/mongo.js b/src/database/mongo.js
index 3a3331e900..8e6494ffd7 100644
--- a/src/database/mongo.js
+++ b/src/database/mongo.js
@@ -2,7 +2,6 @@
'use strict';
(function (module) {
-
var winston = require('winston');
var async = require('async');
var nconf = require('nconf');
@@ -17,30 +16,30 @@
{
name: 'mongo:host',
description: 'Host IP or address of your MongoDB instance',
- 'default': nconf.get('mongo:host') || '127.0.0.1'
+ default: nconf.get('mongo:host') || '127.0.0.1',
},
{
name: 'mongo:port',
description: 'Host port of your MongoDB instance',
- 'default': nconf.get('mongo:port') || 27017
+ default: nconf.get('mongo:port') || 27017,
},
{
name: 'mongo:username',
description: 'MongoDB username',
- 'default': nconf.get('mongo:username') || ''
+ default: nconf.get('mongo:username') || '',
},
{
name: 'mongo:password',
description: 'Password of your MongoDB database',
hidden: true,
default: nconf.get('mongo:password') || '',
- before: function (value) { value = value || nconf.get('mongo:password') || ''; return value; }
+ before: function (value) { value = value || nconf.get('mongo:password') || ''; return value; },
},
{
- name: "mongo:database",
- description: "MongoDB database name",
- 'default': nconf.get('mongo:database') || 'nodebb'
- }
+ name: 'mongo:database',
+ description: 'MongoDB database name',
+ default: nconf.get('mongo:database') || 'nodebb',
+ },
];
module.helpers = module.helpers || {};
@@ -48,13 +47,8 @@
module.init = function (callback) {
callback = callback || function () { };
- var mongoClient;
- try {
- mongoClient = require('mongodb').MongoClient;
- } catch (err) {
- winston.error('Unable to initialize MongoDB! Is MongoDB installed? Error :' + err.message);
- return callback(err);
- }
+
+ var mongoClient = require('mongodb').MongoClient;
var usernamePassword = '';
if (nconf.get('mongo:username') && nconf.get('mongo:password')) {
@@ -76,7 +70,7 @@
var ports = nconf.get('mongo:port').toString().split(',');
var servers = [];
- for (var i = 0; i < hosts.length; i++) {
+ for (var i = 0; i < hosts.length; i += 1) {
servers.push(hosts[i] + ':' + ports[i]);
}
@@ -84,15 +78,18 @@
var connOptions = {
server: {
- poolSize: parseInt(nconf.get('mongo:poolSize'), 10) || 10
- }
+ poolSize: parseInt(nconf.get('mongo:poolSize'), 10) || 10,
+ socketOptions: { autoReconnect: true, keepAlive: nconf.get('mongo:keepAlive') || 0 },
+ reconnectTries: 3600,
+ reconnectInterval: 1000,
+ },
};
- connOptions = _.deepExtend((nconf.get('mongo:options') || {}), connOptions);
+ connOptions = _.deepExtend(connOptions, nconf.get('mongo:options') || {});
mongoClient.connect(connString, connOptions, function (err, _db) {
if (err) {
- winston.error("NodeBB could not connect to your Mongo database. Mongo returned the following error: " + err.message);
+ winston.error('NodeBB could not connect to your Mongo database. Mongo returned the following error: ' + err.message);
return callback(err);
}
@@ -108,10 +105,7 @@
if (nconf.get('mongo:password') && nconf.get('mongo:username')) {
db.authenticate(nconf.get('mongo:username'), nconf.get('mongo:password'), function (err) {
- if (err) {
- return callback(err);
- }
- callback();
+ callback(err);
});
} else {
winston.warn('You have no mongo password setup!');
@@ -135,13 +129,13 @@
module.sessionStore = new sessionStore({
client: rdb.client,
- ttl: ttl
+ ttl: ttl,
});
} else if (nconf.get('mongo')) {
sessionStore = require('connect-mongo')(session);
module.sessionStore = new sessionStore({
db: db,
- ttl: ttl
+ ttl: ttl,
});
}
@@ -162,7 +156,7 @@
async.series([
async.apply(createIndex, 'objects', { _key: 1, score: -1 }, { background: true }),
async.apply(createIndex, 'objects', { _key: 1, value: -1 }, { background: true, unique: true, sparse: true }),
- async.apply(createIndex, 'objects', { expireAt: 1 }, { expireAfterSeconds: 0, background: true })
+ async.apply(createIndex, 'objects', { expireAt: 1 }, { expireAfterSeconds: 0, background: true }),
], function (err) {
if (err) {
winston.error('Error creating index ' + err.message);
@@ -189,10 +183,10 @@
}
async.parallel({
serverStatus: function (next) {
- db.command({ 'serverStatus': 1 }, next);
+ db.command({ serverStatus: 1 }, next);
},
stats: function (next) {
- db.command({ 'dbStats': 1 }, next);
+ db.command({ dbStats: 1 }, next);
},
listCollections: function (next) {
db.listCollections().toArray(function (err, items) {
@@ -203,7 +197,7 @@
db.collection(collection.name).stats(next);
}, next);
});
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -219,7 +213,7 @@
avgObjSize: collectionInfo.avgObjSize,
storageSize: collectionInfo.storageSize,
totalIndexSize: collectionInfo.totalIndexSize,
- indexSizes: collectionInfo.indexSizes
+ indexSizes: collectionInfo.indexSizes,
};
});
@@ -246,5 +240,4 @@
module.close = function () {
db.close();
};
-
-} (exports));
+}(exports));
diff --git a/src/database/mongo/hash.js b/src/database/mongo/hash.js
index 4951b44529..57c72cdc91 100644
--- a/src/database/mongo/hash.js
+++ b/src/database/mongo/hash.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
module.exports = function (db, module) {
var helpers = module.helpers.mongo;
@@ -9,7 +9,7 @@ module.exports = function (db, module) {
return callback();
}
- db.collection('objects').update({_key: key}, {$set: data}, {upsert: true, w: 1}, function (err) {
+ db.collection('objects').update({ _key: key }, { $set: data }, { upsert: true, w: 1 }, function (err) {
callback(err);
});
};
@@ -29,14 +29,14 @@ module.exports = function (db, module) {
if (!key) {
return callback();
}
- db.collection('objects').findOne({_key: key}, {_id: 0, _key: 0}, callback);
+ db.collection('objects').findOne({ _key: key }, { _id: 0, _key: 0 }, callback);
};
module.getObjects = function (keys, callback) {
if (!Array.isArray(keys) || !keys.length) {
return callback(null, []);
}
- db.collection('objects').find({_key: {$in: keys}}, {_id: 0}).toArray(function (err, data) {
+ db.collection('objects').find({ _key: { $in: keys } }, { _id: 0 }).toArray(function (err, data) {
if (err) {
return callback(err);
}
@@ -44,7 +44,7 @@ module.exports = function (db, module) {
var map = helpers.toMap(data);
var returnData = [];
- for (var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
returnData.push(map[keys[i]]);
}
@@ -58,10 +58,10 @@ module.exports = function (db, module) {
}
field = helpers.fieldToString(field);
var _fields = {
- _id: 0
+ _id: 0,
};
_fields[field] = 1;
- db.collection('objects').findOne({_key: key}, {fields: _fields}, function (err, item) {
+ db.collection('objects').findOne({ _key: key }, { fields: _fields }, function (err, item) {
if (err || !item) {
return callback(err, null);
}
@@ -75,20 +75,21 @@ module.exports = function (db, module) {
return callback();
}
var _fields = {
- _id: 0
+ _id: 0,
};
+ var i;
- for(var i = 0; i < fields.length; ++i) {
+ for (i = 0; i < fields.length; i += 1) {
fields[i] = helpers.fieldToString(fields[i]);
_fields[fields[i]] = 1;
}
- db.collection('objects').findOne({_key: key}, {fields: _fields}, function (err, item) {
+ db.collection('objects').findOne({ _key: key }, { fields: _fields }, function (err, item) {
if (err) {
return callback(err);
}
item = item || {};
var result = {};
- for(i = 0; i < fields.length; ++i) {
+ for (i = 0; i < fields.length; i += 1) {
result[fields[i]] = item[fields[i]] !== undefined ? item[fields[i]] : null;
}
callback(null, result);
@@ -101,15 +102,15 @@ module.exports = function (db, module) {
}
var _fields = {
_id: 0,
- _key: 1
+ _key: 1,
};
- for(var i = 0; i < fields.length; ++i) {
+ for (var i = 0; i < fields.length; i += 1) {
fields[i] = helpers.fieldToString(fields[i]);
_fields[fields[i]] = 1;
}
- db.collection('objects').find({_key: {$in: keys}}, {fields: _fields}).toArray(function (err, items) {
+ db.collection('objects').find({ _key: { $in: keys } }, { fields: _fields }).toArray(function (err, items) {
if (err) {
return callback(err);
}
@@ -122,10 +123,10 @@ module.exports = function (db, module) {
var returnData = [];
var item;
- for (var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
item = map[keys[i]] || {};
- for (var k = 0; k < fields.length; ++k) {
+ for (var k = 0; k < fields.length; k += 1) {
if (item[fields[k]] === undefined) {
item[fields[k]] = null;
}
@@ -145,12 +146,12 @@ module.exports = function (db, module) {
module.getObjectValues = function (key, callback) {
module.getObject(key, function (err, data) {
- if(err) {
+ if (err) {
return callback(err);
}
var values = [];
- for(var key in data) {
+ for (var key in data) {
if (data && data.hasOwnProperty(key)) {
values.push(data[key]);
}
@@ -166,7 +167,7 @@ module.exports = function (db, module) {
var data = {};
field = helpers.fieldToString(field);
data[field] = '';
- db.collection('objects').findOne({_key: key}, {fields: data}, function (err, item) {
+ db.collection('objects').findOne({ _key: key }, { fields: data }, function (err, item) {
callback(err, !!item && item[field] !== undefined && item[field] !== null);
});
};
@@ -182,7 +183,7 @@ module.exports = function (db, module) {
data[field] = '';
});
- db.collection('objects').findOne({_key: key}, {fields: data}, function (err, item) {
+ db.collection('objects').findOne({ _key: key }, { fields: data }, function (err, item) {
if (err) {
return callback(err);
}
@@ -216,7 +217,7 @@ module.exports = function (db, module) {
data[field] = '';
});
- db.collection('objects').update({_key: key}, {$unset : data}, function (err) {
+ db.collection('objects').update({ _key: key }, { $unset: data }, function (err) {
callback(err);
});
};
@@ -240,8 +241,8 @@ module.exports = function (db, module) {
field = helpers.fieldToString(field);
data[field] = value;
- db.collection('objects').findAndModify({_key: key}, {}, {$inc: data}, {new: true, upsert: true}, function (err, result) {
+ db.collection('objects').findAndModify({ _key: key }, {}, { $inc: data }, { new: true, upsert: true }, function (err, result) {
callback(err, result && result.value ? result.value[field] : null);
});
};
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/helpers.js b/src/database/mongo/helpers.js
index 0985e62617..47f8434c77 100644
--- a/src/database/mongo/helpers.js
+++ b/src/database/mongo/helpers.js
@@ -1,10 +1,10 @@
-"use strict";
+'use strict';
var helpers = {};
helpers.toMap = function (data) {
var map = {};
- for (var i = 0; i < data.length; ++i) {
+ for (var i = 0; i < data.length; i += 1) {
map[data[i]._key] = data[i];
data[i]._key = undefined;
}
@@ -12,11 +12,11 @@ helpers.toMap = function (data) {
};
helpers.fieldToString = function (field) {
- if(field === null || field === undefined) {
+ if (field === null || field === undefined) {
return field;
}
- if(typeof field !== 'string') {
+ if (typeof field !== 'string') {
field = field.toString();
}
// if there is a '.' in the field name it inserts subdocument in mongo, replace '.'s with \uff0E
@@ -25,7 +25,7 @@ helpers.fieldToString = function (field) {
};
helpers.valueToString = function (value) {
- if(value === null || value === undefined) {
+ if (value === null || value === undefined) {
return value;
}
@@ -34,4 +34,4 @@ helpers.valueToString = function (value) {
helpers.noop = function () {};
-module.exports = helpers;
\ No newline at end of file
+module.exports = helpers;
diff --git a/src/database/mongo/list.js b/src/database/mongo/list.js
index c4b4ffbb6c..0c5e2955e5 100644
--- a/src/database/mongo/list.js
+++ b/src/database/mongo/list.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
module.exports = function (db, module) {
var helpers = module.helpers.mongo;
@@ -18,7 +18,7 @@ module.exports = function (db, module) {
}
if (exists) {
- db.collection('objects').update({_key:key}, {$push: {array: {$each: [value], $position: 0}}}, {upsert:true, w:1 }, function (err, res) {
+ db.collection('objects').update({ _key: key }, { $push: { array: { $each: [value], $position: 0 } } }, { upsert: true, w: 1 }, function (err) {
callback(err);
});
} else {
@@ -33,7 +33,7 @@ module.exports = function (db, module) {
return callback();
}
value = helpers.valueToString(value);
- db.collection('objects').update({ _key: key }, { $push: { array: value } }, {upsert:true, w:1}, function (err, res) {
+ db.collection('objects').update({ _key: key }, { $push: { array: value } }, { upsert: true, w: 1 }, function (err) {
callback(err);
});
};
@@ -48,20 +48,20 @@ module.exports = function (db, module) {
return callback(err);
}
- db.collection('objects').update({_key: key }, { $pop: { array: 1 } }, function (err, result) {
+ db.collection('objects').update({ _key: key }, { $pop: { array: 1 } }, function (err) {
callback(err, (value && value.length) ? value[0] : null);
});
});
};
module.listRemoveAll = function (key, value, callback) {
- callback = callback || helpers.noop;
+ callback = callback || helpers.noop;
if (!key) {
return callback();
}
value = helpers.valueToString(value);
- db.collection('objects').update({_key: key }, { $pull: { array: value } }, function (err, res) {
+ db.collection('objects').update({ _key: key }, { $pull: { array: value } }, function (err) {
callback(err);
});
};
@@ -76,7 +76,7 @@ module.exports = function (db, module) {
return callback(err);
}
- db.collection('objects').update({_key: key}, {$set: {array: value}}, function (err, res) {
+ db.collection('objects').update({ _key: key }, { $set: { array: value } }, function (err) {
callback(err);
});
});
@@ -87,8 +87,8 @@ module.exports = function (db, module) {
return callback();
}
- db.collection('objects').findOne({_key:key}, { array: 1}, function (err, data) {
- if(err || !(data && data.array)) {
+ db.collection('objects').findOne({ _key: key }, { array: 1 }, function (err, data) {
+ if (err || !(data && data.array)) {
return callback(err, []);
}
@@ -100,4 +100,4 @@ module.exports = function (db, module) {
callback(null, data.array);
});
};
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/main.js b/src/database/mongo/main.js
index 0aebaf75b2..4ca3bb2cd3 100644
--- a/src/database/mongo/main.js
+++ b/src/database/mongo/main.js
@@ -1,6 +1,4 @@
-"use strict";
-
-var winston = require('winston');
+'use strict';
module.exports = function (db, module) {
var helpers = module.helpers.mongo;
@@ -23,7 +21,7 @@ module.exports = function (db, module) {
if (!key) {
return callback();
}
- db.collection('objects').findOne({_key: key}, function (err, item) {
+ db.collection('objects').findOne({ _key: key }, function (err, item) {
callback(err, item !== undefined && item !== null);
});
};
@@ -33,7 +31,7 @@ module.exports = function (db, module) {
if (!key) {
return callback();
}
- db.collection('objects').remove({_key: key}, function (err, res) {
+ db.collection('objects').remove({ _key: key }, function (err) {
callback(err);
});
};
@@ -43,7 +41,7 @@ module.exports = function (db, module) {
if (!Array.isArray(keys) || !keys.length) {
return callback();
}
- db.collection('objects').remove({_key: {$in: keys}}, function (err, res) {
+ db.collection('objects').remove({ _key: { $in: keys } }, function (err) {
callback(err);
});
};
@@ -60,7 +58,7 @@ module.exports = function (db, module) {
if (!key) {
return callback();
}
- var data = {value: value};
+ var data = { value: value };
module.setObject(key, data, callback);
};
@@ -69,14 +67,14 @@ module.exports = function (db, module) {
if (!key) {
return callback();
}
- db.collection('objects').findAndModify({_key: key}, {}, {$inc: {value: 1}}, {new: true, upsert: true}, function (err, result) {
+ db.collection('objects').findAndModify({ _key: key }, {}, { $inc: { value: 1 } }, { new: true, upsert: true }, function (err, result) {
callback(err, result && result.value ? result.value.value : null);
});
};
module.rename = function (oldKey, newKey, callback) {
callback = callback || helpers.noop;
- db.collection('objects').update({_key: oldKey}, {$set:{_key: newKey}}, {multi: true}, function (err, res) {
+ db.collection('objects').update({ _key: oldKey }, { $set: { _key: newKey } }, { multi: true }, function (err) {
callback(err);
});
};
@@ -96,4 +94,4 @@ module.exports = function (db, module) {
module.pexpireAt = function (key, timestamp, callback) {
module.setObjectField(key, 'expireAt', new Date(timestamp), callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/sets.js b/src/database/mongo/sets.js
index 0a035a3398..18ce2a932a 100644
--- a/src/database/mongo/sets.js
+++ b/src/database/mongo/sets.js
@@ -1,11 +1,11 @@
-"use strict";
+'use strict';
module.exports = function (db, module) {
var helpers = module.helpers.mongo;
module.setAdd = function (key, value, callback) {
callback = callback || helpers.noop;
- if(!Array.isArray(value)) {
+ if (!Array.isArray(value)) {
value = [value];
}
@@ -14,17 +14,17 @@ module.exports = function (db, module) {
});
db.collection('objects').update({
- _key: key
+ _key: key,
}, {
$addToSet: {
members: {
- $each: value
- }
- }
+ $each: value,
+ },
+ },
}, {
upsert: true,
- w: 1
- }, function (err, res) {
+ w: 1,
+ }, function (err) {
callback(err);
});
};
@@ -36,7 +36,7 @@ module.exports = function (db, module) {
return callback();
}
- if(!Array.isArray(value)) {
+ if (!Array.isArray(value)) {
value = [value];
}
@@ -46,22 +46,22 @@ module.exports = function (db, module) {
var bulk = db.collection('objects').initializeUnorderedBulkOp();
- for(var i = 0; i < keys.length; ++i) {
- bulk.find({_key: keys[i]}).upsert().updateOne({ $addToSet: {
+ for (var i = 0; i < keys.length; i += 1) {
+ bulk.find({ _key: keys[i] }).upsert().updateOne({ $addToSet: {
members: {
- $each: value
- }
- }});
+ $each: value,
+ },
+ } });
}
- bulk.execute(function (err, res) {
+ bulk.execute(function (err) {
callback(err);
});
};
module.setRemove = function (key, value, callback) {
callback = callback || helpers.noop;
- if(!Array.isArray(value)) {
+ if (!Array.isArray(value)) {
value = [value];
}
@@ -69,7 +69,7 @@ module.exports = function (db, module) {
array[index] = helpers.valueToString(element);
});
- db.collection('objects').update({_key: key}, {$pullAll: {members: value}}, function (err, res) {
+ db.collection('objects').update({ _key: key }, { $pullAll: { members: value } }, function (err) {
callback(err);
});
};
@@ -83,13 +83,13 @@ module.exports = function (db, module) {
var bulk = db.collection('objects').initializeUnorderedBulkOp();
- for(var i = 0; i < keys.length; ++i) {
- bulk.find({_key: keys[i]}).updateOne({$pull: {
- members: value
- }});
+ for (var i = 0; i < keys.length; i += 1) {
+ bulk.find({ _key: keys[i] }).updateOne({ $pull: {
+ members: value,
+ } });
}
- bulk.execute(function (err, res) {
+ bulk.execute(function (err) {
callback(err);
});
};
@@ -100,7 +100,7 @@ module.exports = function (db, module) {
}
value = helpers.valueToString(value);
- db.collection('objects').findOne({_key: key, members: value}, {_id: 0, members: 0},function (err, item) {
+ db.collection('objects').findOne({ _key: key, members: value }, { _id: 0, members: 0 }, function (err, item) {
callback(err, item !== null && item !== undefined);
});
};
@@ -110,11 +110,11 @@ module.exports = function (db, module) {
return callback(null, []);
}
- for (var i = 0; i < values.length; ++i) {
+ for (var i = 0; i < values.length; i += 1) {
values[i] = helpers.valueToString(values[i]);
}
- db.collection('objects').findOne({_key: key}, {_id: 0, _key: 0}, function (err, items) {
+ db.collection('objects').findOne({ _key: key }, { _id: 0, _key: 0 }, function (err, items) {
if (err) {
return callback(err);
}
@@ -133,7 +133,7 @@ module.exports = function (db, module) {
}
value = helpers.valueToString(value);
- db.collection('objects').find({_key: {$in : sets}, members: value}, {_id:0, members: 0}).toArray(function (err, result) {
+ db.collection('objects').find({ _key: { $in: sets }, members: value }, { _id: 0, members: 0 }).toArray(function (err, result) {
if (err) {
return callback(err);
}
@@ -154,7 +154,7 @@ module.exports = function (db, module) {
if (!key) {
return callback(null, []);
}
- db.collection('objects').findOne({_key: key}, {members: 1}, {_id: 0, _key: 0}, function (err, data) {
+ db.collection('objects').findOne({ _key: key }, { members: 1 }, { _id: 0, _key: 0 }, function (err, data) {
callback(err, data ? data.members : []);
});
};
@@ -163,7 +163,7 @@ module.exports = function (db, module) {
if (!Array.isArray(keys) || !keys.length) {
return callback(null, []);
}
- db.collection('objects').find({_key: {$in: keys}}, {_id: 0, _key: 1, members: 1}).toArray(function (err, data) {
+ db.collection('objects').find({ _key: { $in: keys } }, { _id: 0, _key: 1, members: 1 }).toArray(function (err, data) {
if (err) {
return callback(err);
}
@@ -174,7 +174,7 @@ module.exports = function (db, module) {
});
var returnData = new Array(keys.length);
- for(var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
returnData[i] = sets[keys[i]] || [];
}
callback(null, returnData);
@@ -185,7 +185,7 @@ module.exports = function (db, module) {
if (!key) {
return callback(null, 0);
}
- db.collection('objects').findOne({_key: key}, {_id: 0}, function (err, data) {
+ db.collection('objects').findOne({ _key: key }, { _id: 0 }, function (err, data) {
callback(err, data ? data.members.length : 0);
});
};
@@ -205,8 +205,8 @@ module.exports = function (db, module) {
module.setRemoveRandom = function (key, callback) {
callback = callback || function () {};
- db.collection('objects').findOne({_key:key}, function (err, data) {
- if(err || !data) {
+ db.collection('objects').findOne({ _key: key }, function (err, data) {
+ if (err || !data) {
return callback(err);
}
@@ -217,4 +217,4 @@ module.exports = function (db, module) {
});
});
};
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/sorted.js b/src/database/mongo/sorted.js
index b9d511d94d..defaed80fc 100644
--- a/src/database/mongo/sorted.js
+++ b/src/database/mongo/sorted.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var utils = require('../../../public/src/utils');
@@ -32,13 +32,13 @@ module.exports = function (db, module) {
return callback();
}
- var fields = {_id: 0, value: 1};
+ var fields = { _id: 0, value: 1 };
if (withScores) {
fields.score = 1;
}
if (Array.isArray(key)) {
- key = {$in: key};
+ key = { $in: key };
}
var limit = stop - start + 1;
@@ -46,10 +46,10 @@ module.exports = function (db, module) {
limit = 0;
}
- db.collection('objects').find({_key: key}, {fields: fields})
+ db.collection('objects').find({ _key: key }, { fields: fields })
.limit(limit)
.skip(start)
- .sort({score: sort})
+ .sort({ score: sort })
.toArray(function (err, data) {
if (err || !data) {
return callback(err);
@@ -89,25 +89,25 @@ module.exports = function (db, module) {
count = 0;
}
- var query = {_key: key};
+ var query = { _key: key };
if (min !== '-inf') {
- query.score = {$gte: min};
+ query.score = { $gte: min };
}
if (max !== '+inf') {
query.score = query.score || {};
query.score.$lte = max;
}
- var fields = {_id: 0, value: 1};
+ var fields = { _id: 0, value: 1 };
if (withScores) {
fields.score = 1;
}
- db.collection('objects').find(query, {fields: fields})
+ db.collection('objects').find(query, { fields: fields })
.limit(count)
.skip(start)
- .sort({score: sort})
+ .sort({ score: sort })
.toArray(function (err, data) {
if (err) {
return callback(err);
@@ -128,9 +128,9 @@ module.exports = function (db, module) {
return callback();
}
- var query = {_key: key};
+ var query = { _key: key };
if (min !== '-inf') {
- query.score = {$gte: min};
+ query.score = { $gte: min };
}
if (max !== '+inf') {
query.score = query.score || {};
@@ -138,7 +138,7 @@ module.exports = function (db, module) {
}
db.collection('objects').count(query, function (err, count) {
- callback(err, count ? count : 0);
+ callback(err, count || 0);
});
};
@@ -146,9 +146,9 @@ module.exports = function (db, module) {
if (!key) {
return callback(null, 0);
}
- db.collection('objects').count({_key: key}, function (err, count) {
+ db.collection('objects').count({ _key: key }, function (err, count) {
count = parseInt(count, 10);
- callback(err, count ? count : 0);
+ callback(err, count || 0);
});
};
@@ -157,9 +157,9 @@ module.exports = function (db, module) {
return callback();
}
var pipeline = [
- { $match : { _key : { $in: keys } } } ,
- { $group: { _id: {_key: '$_key'}, count: { $sum: 1 } } },
- { $project: { _id: 1, count: '$count' } }
+ { $match: { _key: { $in: keys } } },
+ { $group: { _id: { _key: '$_key' }, count: { $sum: 1 } } },
+ { $project: { _id: 1, count: '$count' } },
];
db.collection('objects').aggregate(pipeline, function (err, results) {
if (err) {
@@ -198,7 +198,7 @@ module.exports = function (db, module) {
}
value = helpers.valueToString(value);
method(key, 0, -1, function (err, result) {
- if(err) {
+ if (err) {
return callback(err);
}
@@ -212,8 +212,8 @@ module.exports = function (db, module) {
return callback(null, []);
}
var data = new Array(values.length);
- for (var i = 0; i < values.length; ++i) {
- data[i] = {key: keys[i], value: values[i]};
+ for (var i = 0; i < values.length; i += 1) {
+ data[i] = { key: keys[i], value: values[i] };
}
async.map(data, function (item, next) {
@@ -244,7 +244,7 @@ module.exports = function (db, module) {
return callback();
}
value = helpers.valueToString(value);
- db.collection('objects').findOne({_key: key, value: value}, {fields:{_id: 0, score: 1}}, function (err, result) {
+ db.collection('objects').findOne({ _key: key, value: value }, { fields: { _id: 0, score: 1 } }, function (err, result) {
callback(err, result ? result.score : null);
});
};
@@ -254,16 +254,16 @@ module.exports = function (db, module) {
return callback();
}
value = helpers.valueToString(value);
- db.collection('objects').find({_key:{$in:keys}, value: value}, {_id:0, _key:1, score: 1}).toArray(function (err, result) {
+ db.collection('objects').find({ _key: { $in: keys }, value: value }, { _id: 0, _key: 1, score: 1 }).toArray(function (err, result) {
if (err) {
return callback(err);
}
- var map = helpers.toMap(result),
- returnData = [],
- item;
+ var map = helpers.toMap(result);
+ var returnData = [];
+ var item;
- for(var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
item = map[keys[i]];
returnData.push(item ? item.score : null);
}
@@ -277,7 +277,7 @@ module.exports = function (db, module) {
return callback();
}
values = values.map(helpers.valueToString);
- db.collection('objects').find({_key: key, value: {$in: values}}, {_id: 0, value: 1, score: 1}).toArray(function (err, result) {
+ db.collection('objects').find({ _key: key, value: { $in: values } }, { _id: 0, value: 1, score: 1 }).toArray(function (err, result) {
if (err) {
return callback(err);
}
@@ -290,7 +290,7 @@ module.exports = function (db, module) {
var returnData = new Array(values.length);
var score;
- for(var i = 0; i < values.length; ++i) {
+ for (var i = 0; i < values.length; i += 1) {
score = map[values[i]];
returnData[i] = utils.isNumber(score) ? score : null;
}
@@ -304,7 +304,7 @@ module.exports = function (db, module) {
return callback();
}
value = helpers.valueToString(value);
- db.collection('objects').findOne({_key: key, value: value}, {_id: 0, value: 1}, function (err, result) {
+ db.collection('objects').findOne({ _key: key, value: value }, { _id: 0, value: 1 }, function (err, result) {
callback(err, !!result);
});
};
@@ -314,7 +314,7 @@ module.exports = function (db, module) {
return callback();
}
values = values.map(helpers.valueToString);
- db.collection('objects').find({_key: key, value: {$in: values}}, {fields: {_id: 0, value: 1}}).toArray(function (err, results) {
+ db.collection('objects').find({ _key: key, value: { $in: values } }, { fields: { _id: 0, value: 1 } }).toArray(function (err, results) {
if (err) {
return callback(err);
}
@@ -335,7 +335,7 @@ module.exports = function (db, module) {
return callback();
}
value = helpers.valueToString(value);
- db.collection('objects').find({_key: {$in: keys}, value: value}, {fields: {_id: 0, _key: 1, value: 1}}).toArray(function (err, results) {
+ db.collection('objects').find({ _key: { $in: keys }, value: value }, { fields: { _id: 0, _key: 1, value: 1 } }).toArray(function (err, results) {
if (err) {
return callback(err);
}
@@ -355,20 +355,20 @@ module.exports = function (db, module) {
if (!Array.isArray(keys) || !keys.length) {
return callback(null, []);
}
- db.collection('objects').find({_key: {$in: keys}}, {_id: 0, _key: 1, value: 1}).toArray(function (err, data) {
+ db.collection('objects').find({ _key: { $in: keys } }, { _id: 0, _key: 1, value: 1 }).toArray(function (err, data) {
if (err) {
return callback(err);
}
var sets = {};
data.forEach(function (set) {
- sets[set._key] = sets[set._key] || [];
- sets[set._key].push(set.value);
+ sets[set._key] = sets[set._key] || [];
+ sets[set._key].push(set.value);
});
var returnData = new Array(keys.length);
- for(var i = 0; i < keys.length; ++i) {
- returnData[i] = sets[keys[i]] || [];
+ for (var i = 0; i < keys.length; i += 1) {
+ returnData[i] = sets[keys[i]] || [];
}
callback(null, returnData);
});
@@ -383,7 +383,7 @@ module.exports = function (db, module) {
value = helpers.valueToString(value);
data.score = parseFloat(increment);
- db.collection('objects').findAndModify({_key: key, value: value}, {}, {$inc: data}, {new: true, upsert: true}, function (err, result) {
+ db.collection('objects').findAndModify({ _key: key, value: value }, {}, { $inc: data }, { new: true, upsert: true }, function (err, result) {
// if there is duplicate key error retry the upsert
// https://github.com/NodeBB/NodeBB/issues/4467
// https://jira.mongodb.org/browse/SERVER-14322
@@ -416,11 +416,11 @@ module.exports = function (db, module) {
count = 0;
}
- var query = {_key: key};
+ var query = { _key: key };
buildLexQuery(query, min, max);
- db.collection('objects').find(query, {_id: 0, value: 1})
- .sort({value: sort})
+ db.collection('objects').find(query, { _id: 0, value: 1 })
+ .sort({ value: sort })
.skip(start)
.limit(count === -1 ? 0 : count)
.toArray(function (err, data) {
@@ -431,13 +431,13 @@ module.exports = function (db, module) {
return item && item.value;
});
callback(err, data);
- });
+ });
}
module.sortedSetRemoveRangeByLex = function (key, min, max, callback) {
callback = callback || helpers.noop;
- var query = {_key: key};
+ var query = { _key: key };
buildLexQuery(query, min, max);
db.collection('objects').remove(query, function (err) {
@@ -448,11 +448,11 @@ module.exports = function (db, module) {
function buildLexQuery(query, min, max) {
if (min !== '-') {
if (min.match(/^\(/)) {
- query.value = {$gt: min.slice(1)};
+ query.value = { $gt: min.slice(1) };
} else if (min.match(/^\[/)) {
- query.value = {$gte: min.slice(1)};
+ query.value = { $gte: min.slice(1) };
} else {
- query.value = {$gte: min};
+ query.value = { $gte: min };
}
}
if (max !== '+') {
@@ -470,9 +470,9 @@ module.exports = function (db, module) {
module.processSortedSet = function (setKey, process, batch, callback) {
var done = false;
var ids = [];
- var cursor = db.collection('objects').find({_key: setKey})
- .sort({score: 1})
- .project({_id: 0, value: 1})
+ var cursor = db.collection('objects').find({ _key: setKey })
+ .sort({ score: 1 })
+ .project({ _id: 0, value: 1 })
.batchSize(batch);
async.whilst(
@@ -503,5 +503,4 @@ module.exports = function (db, module) {
callback
);
};
-
};
diff --git a/src/database/mongo/sorted/add.js b/src/database/mongo/sorted/add.js
index e03452b3df..b90501feee 100644
--- a/src/database/mongo/sorted/add.js
+++ b/src/database/mongo/sorted/add.js
@@ -1,7 +1,6 @@
'use strict';
module.exports = function (db, module) {
-
var helpers = module.helpers.mongo;
module.sortedSetAdd = function (key, score, value, callback) {
@@ -15,7 +14,7 @@ module.exports = function (db, module) {
value = helpers.valueToString(value);
- db.collection('objects').update({_key: key, value: value}, {$set: {score: parseFloat(score)}}, {upsert:true, w: 1}, function (err) {
+ db.collection('objects').update({ _key: key, value: value }, { $set: { score: parseFloat(score) } }, { upsert: true, w: 1 }, function (err) {
if (err && err.message.startsWith('E11000 duplicate key error')) {
return process.nextTick(module.sortedSetAdd, key, score, value, callback);
}
@@ -35,8 +34,8 @@ module.exports = function (db, module) {
var bulk = db.collection('objects').initializeUnorderedBulkOp();
- for(var i = 0; i < scores.length; ++i) {
- bulk.find({_key: key, value: values[i]}).upsert().updateOne({$set: {score: parseFloat(scores[i])}});
+ for (var i = 0; i < scores.length; i += 1) {
+ bulk.find({ _key: key, value: values[i] }).upsert().updateOne({ $set: { score: parseFloat(scores[i]) } });
}
bulk.execute(function (err) {
@@ -53,13 +52,12 @@ module.exports = function (db, module) {
var bulk = db.collection('objects').initializeUnorderedBulkOp();
- for(var i = 0; i < keys.length; ++i) {
- bulk.find({_key: keys[i], value: value}).upsert().updateOne({$set: {score: parseFloat(score)}});
+ for (var i = 0; i < keys.length; i += 1) {
+ bulk.find({ _key: keys[i], value: value }).upsert().updateOne({ $set: { score: parseFloat(score) } });
}
bulk.execute(function (err) {
callback(err);
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/sorted/intersect.js b/src/database/mongo/sorted/intersect.js
index ed8ade3fb3..82f24214ea 100644
--- a/src/database/mongo/sorted/intersect.js
+++ b/src/database/mongo/sorted/intersect.js
@@ -1,17 +1,16 @@
'use strict';
module.exports = function (db, module) {
-
module.sortedSetIntersectCard = function (keys, callback) {
if (!Array.isArray(keys) || !keys.length) {
return callback(null, 0);
}
var pipeline = [
- { $match: { _key: {$in: keys}} },
- { $group: { _id: {value: '$value'}, count: {$sum: 1}} },
- { $match: { count: keys.length} },
- { $group: { _id: null, count: { $sum: 1 } } }
+ { $match: { _key: { $in: keys } } },
+ { $group: { _id: { value: '$value' }, count: { $sum: 1 } } },
+ { $match: { count: keys.length } },
+ { $group: { _id: null, count: { $sum: 1 } } },
];
db.collection('objects').aggregate(pipeline, function (err, data) {
@@ -48,7 +47,7 @@ module.exports = function (db, module) {
limit = 0;
}
- var pipeline = [{ $match: { _key: {$in: sets}} }];
+ var pipeline = [{ $match: { _key: { $in: sets } } }];
weights.forEach(function (weight, index) {
if (weight !== 1) {
@@ -56,16 +55,24 @@ module.exports = function (db, module) {
$project: {
value: 1,
score: {
- $cond: { if: { $eq: [ "$_key", sets[index] ] }, then: { $multiply: [ '$score', weight ] }, else: '$score' }
- }
- }
+ $cond: {
+ if: {
+ $eq: ['$_key', sets[index]],
+ },
+ then: {
+ $multiply: ['$score', weight],
+ },
+ else: '$score',
+ },
+ },
+ },
});
}
});
- pipeline.push({ $group: { _id: {value: '$value'}, totalScore: aggregate, count: {$sum: 1}} });
- pipeline.push({ $match: { count: sets.length} });
- pipeline.push({ $sort: { totalScore: params.sort} });
+ pipeline.push({ $group: { _id: { value: '$value' }, totalScore: aggregate, count: { $sum: 1 } } });
+ pipeline.push({ $match: { count: sets.length } });
+ pipeline.push({ $sort: { totalScore: params.sort } });
if (start) {
pipeline.push({ $skip: start });
@@ -75,7 +82,7 @@ module.exports = function (db, module) {
pipeline.push({ $limit: limit });
}
- var project = { _id: 0, value: '$_id.value'};
+ var project = { _id: 0, value: '$_id.value' };
if (params.withScores) {
project.score = '$totalScore';
}
@@ -95,5 +102,4 @@ module.exports = function (db, module) {
callback(null, data);
});
}
-
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/sorted/remove.js b/src/database/mongo/sorted/remove.js
index 71320619c4..e8dea857eb 100644
--- a/src/database/mongo/sorted/remove.js
+++ b/src/database/mongo/sorted/remove.js
@@ -1,7 +1,6 @@
'use strict';
module.exports = function (db, module) {
-
var helpers = module.helpers.mongo;
module.sortedSetRemove = function (key, value, callback) {
@@ -15,10 +14,10 @@ module.exports = function (db, module) {
if (Array.isArray(value)) {
value = value.map(helpers.valueToString);
- db.collection('objects').remove({_key: key, value: {$in: value}}, done);
+ db.collection('objects').remove({ _key: key, value: { $in: value } }, done);
} else {
value = helpers.valueToString(value);
- db.collection('objects').remove({_key: key, value: value}, done);
+ db.collection('objects').remove({ _key: key, value: value }, done);
}
};
@@ -29,7 +28,7 @@ module.exports = function (db, module) {
}
value = helpers.valueToString(value);
- db.collection('objects').remove({_key: {$in: keys}, value: value}, function (err) {
+ db.collection('objects').remove({ _key: { $in: keys }, value: value }, function (err) {
callback(err);
});
};
@@ -39,10 +38,10 @@ module.exports = function (db, module) {
if (!Array.isArray(keys) || !keys.length) {
return callback();
}
- var query = {_key: {$in: keys}};
+ var query = { _key: { $in: keys } };
if (min !== '-inf') {
- query.score = {$gte: min};
+ query.score = { $gte: min };
}
if (max !== '+inf') {
query.score = query.score || {};
@@ -53,5 +52,4 @@ module.exports = function (db, module) {
callback(err);
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/database/mongo/sorted/union.js b/src/database/mongo/sorted/union.js
index 49669bd830..a06df788aa 100644
--- a/src/database/mongo/sorted/union.js
+++ b/src/database/mongo/sorted/union.js
@@ -1,16 +1,15 @@
'use strict';
module.exports = function (db, module) {
-
module.sortedSetUnionCard = function (keys, callback) {
if (!Array.isArray(keys) || !keys.length) {
return callback(null, 0);
}
var pipeline = [
- { $match: { _key: {$in: keys} } },
- { $group: { _id: {value: '$value' } } },
- { $group: { _id: null, count: { $sum: 1 } } }
+ { $match: { _key: { $in: keys } } },
+ { $group: { _id: { value: '$value' } } },
+ { $group: { _id: null, count: { $sum: 1 } } },
];
var project = { _id: 0, count: '$count' };
@@ -48,9 +47,9 @@ module.exports = function (db, module) {
}
var pipeline = [
- { $match: { _key: {$in: params.sets}} },
- { $group: { _id: {value: '$value'}, totalScore: aggregate} },
- { $sort: { totalScore: params.sort} }
+ { $match: { _key: { $in: params.sets } } },
+ { $group: { _id: { value: '$value' }, totalScore: aggregate } },
+ { $sort: { totalScore: params.sort } },
];
if (params.start) {
@@ -81,5 +80,4 @@ module.exports = function (db, module) {
callback(null, data);
});
}
-
-};
\ No newline at end of file
+};
diff --git a/src/database/redis.js b/src/database/redis.js
index 8519b57bae..27394f7463 100644
--- a/src/database/redis.js
+++ b/src/database/redis.js
@@ -1,38 +1,36 @@
'use strict';
(function (module) {
-
var winston = require('winston');
var nconf = require('nconf');
var semver = require('semver');
var session = require('express-session');
var redis;
- var connectRedis;
var redisClient;
module.questions = [
{
name: 'redis:host',
description: 'Host IP or address of your Redis instance',
- 'default': nconf.get('redis:host') || '127.0.0.1'
+ default: nconf.get('redis:host') || '127.0.0.1',
},
{
name: 'redis:port',
description: 'Host port of your Redis instance',
- 'default': nconf.get('redis:port') || 6379
+ default: nconf.get('redis:port') || 6379,
},
{
name: 'redis:password',
description: 'Password of your Redis database',
hidden: true,
default: nconf.get('redis:password') || '',
- before: function (value) { value = value || nconf.get('redis:password') || ''; return value; }
+ before: function (value) { value = value || nconf.get('redis:password') || ''; return value; },
},
{
- name: "redis:database",
- description: "Which database to use (0..n)",
- 'default': nconf.get('redis:database') || 0
- }
+ name: 'redis:database',
+ description: 'Which database to use (0..n)',
+ default: nconf.get('redis:database') || 0,
+ },
];
module.init = function (callback) {
@@ -68,7 +66,7 @@
module.sessionStore = new sessionStore({
client: module.client,
- ttl: ttl
+ ttl: ttl,
});
if (typeof callback === 'function') {
@@ -110,7 +108,7 @@
if (dbIdx) {
cxn.select(dbIdx, function (error) {
if (error) {
- winston.error("NodeBB could not connect to your Redis database. Redis returned the following error: " + error.message);
+ winston.error('NodeBB could not connect to your Redis database. Redis returned the following error: ' + error.message);
process.exit();
}
});
@@ -150,7 +148,7 @@
return callback(err);
}
- var lines = data.toString().split("\r\n").sort();
+ var lines = data.toString().split('\r\n').sort();
var redisData = {};
lines.forEach(function (line) {
var parts = line.split(':');
@@ -168,5 +166,5 @@
module.helpers = module.helpers || {};
module.helpers.redis = require('./redis/helpers');
-} (exports));
+}(exports));
diff --git a/src/database/redis/hash.js b/src/database/redis/hash.js
index f679f7637d..61d83a93f6 100644
--- a/src/database/redis/hash.js
+++ b/src/database/redis/hash.js
@@ -1,7 +1,6 @@
-"use strict";
+'use strict';
module.exports = function (redisClient, module) {
-
var helpers = module.helpers.redis;
module.setObject = function (key, data, callback) {
@@ -52,14 +51,14 @@ module.exports = function (redisClient, module) {
}
var multi = redisClient.multi();
- for(var x = 0; x < keys.length; ++x) {
+ for (var x = 0; x < keys.length; x += 1) {
multi.hmget.apply(multi, [keys[x]].concat(fields));
}
function makeObject(array) {
var obj = {};
- for (var i = 0, ii = fields.length; i < ii; ++i) {
+ for (var i = 0, ii = fields.length; i < ii; i += 1) {
obj[fields[i]] = array[i];
}
return obj;
@@ -97,13 +96,16 @@ module.exports = function (redisClient, module) {
module.deleteObjectField = function (key, field, callback) {
callback = callback || function () {};
- redisClient.hdel(key, field, function (err, res) {
+ if (field === null) {
+ return setImmediate(callback);
+ }
+ redisClient.hdel(key, field, function (err) {
callback(err);
});
};
module.deleteObjectFields = function (key, fields, callback) {
- helpers.multiKeyValues(redisClient, 'hdel', key, fields, function (err, results) {
+ helpers.multiKeyValues(redisClient, 'hdel', key, fields, function (err) {
callback(err);
});
};
@@ -119,4 +121,4 @@ module.exports = function (redisClient, module) {
module.incrObjectFieldBy = function (key, field, value, callback) {
redisClient.hincrby(key, field, value, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/database/redis/helpers.js b/src/database/redis/helpers.js
index a4ca7e116f..7100437177 100644
--- a/src/database/redis/helpers.js
+++ b/src/database/redis/helpers.js
@@ -1,11 +1,11 @@
-"use strict";
+'use strict';
var helpers = {};
helpers.multiKeys = function (redisClient, command, keys, callback) {
callback = callback || function () {};
var multi = redisClient.multi();
- for (var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi[command](keys[i]);
}
multi.exec(callback);
@@ -14,7 +14,7 @@ helpers.multiKeys = function (redisClient, command, keys, callback) {
helpers.multiKeysValue = function (redisClient, command, keys, value, callback) {
callback = callback || function () {};
var multi = redisClient.multi();
- for (var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi[command](keys[i], value);
}
multi.exec(callback);
@@ -23,17 +23,17 @@ helpers.multiKeysValue = function (redisClient, command, keys, value, callback)
helpers.multiKeyValues = function (redisClient, command, key, values, callback) {
callback = callback || function () {};
var multi = redisClient.multi();
- for (var i = 0; i < values.length; ++i) {
+ for (var i = 0; i < values.length; i += 1) {
multi[command](key, values[i]);
}
multi.exec(callback);
};
helpers.resultsToBool = function (results) {
- for (var i = 0; i < results.length; ++i) {
+ for (var i = 0; i < results.length; i += 1) {
results[i] = results[i] === 1;
}
return results;
};
-module.exports = helpers;
\ No newline at end of file
+module.exports = helpers;
diff --git a/src/database/redis/list.js b/src/database/redis/list.js
index c44c23b475..fb445573ff 100644
--- a/src/database/redis/list.js
+++ b/src/database/redis/list.js
@@ -1,16 +1,16 @@
-"use strict";
+'use strict';
module.exports = function (redisClient, module) {
module.listPrepend = function (key, value, callback) {
callback = callback || function () {};
- redisClient.lpush(key, value, function (err, res) {
+ redisClient.lpush(key, value, function (err) {
callback(err);
});
};
module.listAppend = function (key, value, callback) {
callback = callback || function () {};
- redisClient.rpush(key, value, function (err, res) {
+ redisClient.rpush(key, value, function (err) {
callback(err);
});
};
@@ -22,14 +22,14 @@ module.exports = function (redisClient, module) {
module.listRemoveAll = function (key, value, callback) {
callback = callback || function () {};
- redisClient.lrem(key, 0, value, function (err, res) {
+ redisClient.lrem(key, 0, value, function (err) {
callback(err);
});
};
module.listTrim = function (key, start, stop, callback) {
callback = callback || function () {};
- redisClient.ltrim(key, start, stop, function (err, res) {
+ redisClient.ltrim(key, start, stop, function (err) {
callback(err);
});
};
@@ -38,4 +38,4 @@ module.exports = function (redisClient, module) {
callback = callback || function () {};
redisClient.lrange(key, start, stop, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/database/redis/main.js b/src/database/redis/main.js
index 10f26cfd3e..baca6b0ffe 100644
--- a/src/database/redis/main.js
+++ b/src/database/redis/main.js
@@ -1,7 +1,6 @@
-"use strict";
+'use strict';
module.exports = function (redisClient, module) {
-
module.flushdb = function (callback) {
redisClient.send_command('flushdb', [], function (err) {
if (typeof callback === 'function') {
@@ -22,7 +21,7 @@ module.exports = function (redisClient, module) {
module.delete = function (key, callback) {
callback = callback || function () {};
- redisClient.del(key, function (err, res) {
+ redisClient.del(key, function (err) {
callback(err);
});
};
@@ -30,10 +29,10 @@ module.exports = function (redisClient, module) {
module.deleteAll = function (keys, callback) {
callback = callback || function () {};
var multi = redisClient.multi();
- for(var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi.del(keys[i]);
}
- multi.exec(function (err, res) {
+ multi.exec(function (err) {
callback(err);
});
};
@@ -56,7 +55,7 @@ module.exports = function (redisClient, module) {
module.rename = function (oldKey, newKey, callback) {
callback = callback || function () {};
- redisClient.rename(oldKey, newKey, function (err, res) {
+ redisClient.rename(oldKey, newKey, function (err) {
callback(err && err.message !== 'ERR no such key' ? err : null);
});
};
diff --git a/src/database/redis/sets.js b/src/database/redis/sets.js
index 5b2b803868..a5716438e4 100644
--- a/src/database/redis/sets.js
+++ b/src/database/redis/sets.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
module.exports = function (redisClient, module) {
var helpers = module.helpers.redis;
@@ -11,28 +11,28 @@ module.exports = function (redisClient, module) {
if (!value.length) {
return callback();
}
- redisClient.sadd(key, value, function (err, res) {
+ redisClient.sadd(key, value, function (err) {
callback(err);
});
};
module.setsAdd = function (keys, value, callback) {
callback = callback || function () {};
- helpers.multiKeysValue(redisClient, 'sadd', keys, value, function (err, res) {
+ helpers.multiKeysValue(redisClient, 'sadd', keys, value, function (err) {
callback(err);
});
};
module.setRemove = function (key, value, callback) {
callback = callback || function () {};
- redisClient.srem(key, value, function (err, res) {
+ redisClient.srem(key, value, function (err) {
callback(err);
});
};
module.setsRemove = function (keys, value, callback) {
callback = callback || function () {};
- helpers.multiKeysValue(redisClient, 'srem', keys, value, function (err, res) {
+ helpers.multiKeysValue(redisClient, 'srem', keys, value, function (err) {
callback(err);
});
};
@@ -77,4 +77,4 @@ module.exports = function (redisClient, module) {
};
return module;
-};
\ No newline at end of file
+};
diff --git a/src/database/redis/sorted.js b/src/database/redis/sorted.js
index 1e8c629fa9..a2c18296db 100644
--- a/src/database/redis/sorted.js
+++ b/src/database/redis/sorted.js
@@ -1,7 +1,6 @@
-"use strict";
+'use strict';
module.exports = function (redisClient, module) {
-
var utils = require('../../../public/src/utils');
var helpers = module.helpers.redis;
@@ -29,7 +28,7 @@ module.exports = function (redisClient, module) {
function sortedSetRange(method, key, start, stop, withScores, callback) {
if (Array.isArray(key)) {
- return module.sortedSetUnion({method: method, sets: key, start: start, stop: stop, withScores: withScores}, callback);
+ return module.sortedSetUnion({ method: method, sets: key, start: start, stop: stop, withScores: withScores }, callback);
}
var params = [key, start, stop];
@@ -45,8 +44,8 @@ module.exports = function (redisClient, module) {
return callback(null, data);
}
var objects = [];
- for(var i = 0; i < data.length; i += 2) {
- objects.push({value: data[i], score: parseFloat(data[i + 1])});
+ for (var i = 0; i < data.length; i += 2) {
+ objects.push({ value: data[i], score: parseFloat(data[i + 1]) });
}
callback(null, objects);
});
@@ -74,8 +73,8 @@ module.exports = function (redisClient, module) {
return callback(err);
}
var objects = [];
- for(var i = 0; i < data.length; i += 2) {
- objects.push({value: data[i], score: parseFloat(data[i + 1])});
+ for (var i = 0; i < data.length; i += 2) {
+ objects.push({ value: data[i], score: parseFloat(data[i + 1]) });
}
callback(null, objects);
});
@@ -94,7 +93,7 @@ module.exports = function (redisClient, module) {
return callback(null, []);
}
var multi = redisClient.multi();
- for(var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi.zcard(keys[i]);
}
multi.exec(callback);
@@ -106,7 +105,7 @@ module.exports = function (redisClient, module) {
module.sortedSetsRanks = function (keys, values, callback) {
var multi = redisClient.multi();
- for(var i = 0; i < values.length; ++i) {
+ for (var i = 0; i < values.length; i += 1) {
multi.zrank(keys[i], values[i]);
}
multi.exec(callback);
@@ -114,7 +113,7 @@ module.exports = function (redisClient, module) {
module.sortedSetRanks = function (key, values, callback) {
var multi = redisClient.multi();
- for(var i = 0; i < values.length; ++i) {
+ for (var i = 0; i < values.length; i += 1) {
multi.zrank(key, values[i]);
}
multi.exec(callback);
@@ -164,7 +163,7 @@ module.exports = function (redisClient, module) {
module.getSortedSetsMembers = function (keys, callback) {
var multi = redisClient.multi();
- for (var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi.zrange(keys[i], 0, -1);
}
multi.exec(callback);
@@ -198,7 +197,8 @@ module.exports = function (redisClient, module) {
function sortedSetLex(method, reverse, key, min, max, start, count, callback) {
callback = callback || start;
- var minmin, maxmax;
+ var minmin;
+ var maxmax;
if (reverse) {
minmin = '+';
maxmax = '-';
@@ -207,10 +207,10 @@ module.exports = function (redisClient, module) {
maxmax = '+';
}
- if (min !== minmin && !min.match(/^[\[\(]/)) {
+ if (min !== minmin && !min.match(/^[[(]/)) {
min = '[' + min;
}
- if (max !== maxmax && !max.match(/^[\[\(]/)) {
+ if (max !== maxmax && !max.match(/^[[(]/)) {
max = '[' + max;
}
diff --git a/src/database/redis/sorted/add.js b/src/database/redis/sorted/add.js
index b2eb710221..e60d079eac 100644
--- a/src/database/redis/sorted/add.js
+++ b/src/database/redis/sorted/add.js
@@ -1,7 +1,6 @@
'use strict';
module.exports = function (redisClient, module) {
-
module.sortedSetAdd = function (key, score, value, callback) {
callback = callback || function () {};
if (Array.isArray(score) && Array.isArray(value)) {
@@ -23,7 +22,7 @@ module.exports = function (redisClient, module) {
var args = [key];
- for(var i = 0; i < scores.length; ++i) {
+ for (var i = 0; i < scores.length; i += 1) {
args.push(scores[i], values[i]);
}
@@ -36,7 +35,7 @@ module.exports = function (redisClient, module) {
callback = callback || function () {};
var multi = redisClient.multi();
- for(var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi.zadd(keys[i], score, value);
}
@@ -44,6 +43,4 @@ module.exports = function (redisClient, module) {
callback(err);
});
};
-
-
-};
\ No newline at end of file
+};
diff --git a/src/database/redis/sorted/intersect.js b/src/database/redis/sorted/intersect.js
index a4e3c131b4..86240a7a34 100644
--- a/src/database/redis/sorted/intersect.js
+++ b/src/database/redis/sorted/intersect.js
@@ -2,7 +2,6 @@
'use strict';
module.exports = function (redisClient, module) {
-
module.sortedSetIntersectCard = function (keys, callback) {
if (!Array.isArray(keys) || !keys.length) {
return callback(null, 0);
@@ -70,10 +69,10 @@ module.exports = function (redisClient, module) {
}
results = results[1] || [];
var objects = [];
- for(var i = 0; i < results.length; i += 2) {
- objects.push({value: results[i], score: parseFloat(results[i + 1])});
+ for (var i = 0; i < results.length; i += 2) {
+ objects.push({ value: results[i], score: parseFloat(results[i + 1]) });
}
callback(null, objects);
});
}
-};
\ No newline at end of file
+};
diff --git a/src/database/redis/sorted/remove.js b/src/database/redis/sorted/remove.js
index aa1d42a3ce..eacb6ca861 100644
--- a/src/database/redis/sorted/remove.js
+++ b/src/database/redis/sorted/remove.js
@@ -2,7 +2,6 @@
'use strict';
module.exports = function (redisClient, module) {
-
var helpers = module.helpers.redis;
module.sortedSetRemove = function (key, value, callback) {
@@ -28,11 +27,11 @@ module.exports = function (redisClient, module) {
module.sortedSetsRemoveRangeByScore = function (keys, min, max, callback) {
callback = callback || function () {};
var multi = redisClient.multi();
- for(var i = 0; i < keys.length; ++i) {
+ for (var i = 0; i < keys.length; i += 1) {
multi.zremrangebyscore(keys[i], min, max);
}
multi.exec(function (err) {
callback(err);
});
};
-};
\ No newline at end of file
+};
diff --git a/src/database/redis/sorted/union.js b/src/database/redis/sorted/union.js
index 677b086259..ea17ee2d4e 100644
--- a/src/database/redis/sorted/union.js
+++ b/src/database/redis/sorted/union.js
@@ -2,7 +2,6 @@
'use strict';
module.exports = function (redisClient, module) {
-
module.sortedSetUnionCard = function (keys, callback) {
var tempSetName = 'temp_' + Date.now();
@@ -30,7 +29,6 @@ module.exports = function (redisClient, module) {
};
module.sortedSetUnion = function (params, callback) {
-
var tempSetName = 'temp_' + Date.now();
var rangeParams = [tempSetName, params.start, params.stop];
@@ -51,10 +49,10 @@ module.exports = function (redisClient, module) {
}
results = results[1] || [];
var objects = [];
- for(var i = 0; i < results.length; i += 2) {
- objects.push({value: results[i], score: parseFloat(results[i + 1])});
+ for (var i = 0; i < results.length; i += 2) {
+ objects.push({ value: results[i], score: parseFloat(results[i + 1]) });
}
callback(null, objects);
});
};
-};
\ No newline at end of file
+};
diff --git a/src/emailer.js b/src/emailer.js
index 4ccd35ed99..95ffbdceba 100644
--- a/src/emailer.js
+++ b/src/emailer.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var winston = require('winston');
@@ -17,7 +17,7 @@ var translator = require('../public/src/modules/translator');
var transports = {
sendmail: nodemailer.createTransport(sendmailTransport()),
- gmail: undefined
+ gmail: undefined,
};
var app;
@@ -29,15 +29,16 @@ var fallbackTransport;
// Enable Gmail transport if enabled in ACP
if (parseInt(meta.config['email:GmailTransport:enabled'], 10) === 1) {
- fallbackTransport = transports.gmail = nodemailer.createTransport(smtpTransport({
+ transports.gmail = nodemailer.createTransport(smtpTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: meta.config['email:GmailTransport:user'],
- pass: meta.config['email:GmailTransport:pass']
- }
+ pass: meta.config['email:GmailTransport:pass'],
+ },
}));
+ fallbackTransport = transports.gmail;
} else {
fallbackTransport = transports.sendmail;
}
@@ -56,7 +57,7 @@ var fallbackTransport;
function (next) {
async.parallel({
email: async.apply(User.getUserField, uid, 'email'),
- settings: async.apply(User.getSettings, uid)
+ settings: async.apply(User.getSettings, uid),
}, next);
},
function (results, next) {
@@ -66,7 +67,7 @@ var fallbackTransport;
}
params.uid = uid;
Emailer.sendToEmail(template, results.email, results.settings.userLang, params, next);
- }
+ },
], callback);
};
@@ -85,7 +86,7 @@ var fallbackTransport;
translator.translate(params.subject, lang, function (translated) {
next(null, translated);
});
- }
+ },
}, next);
},
function (results, next) {
@@ -97,12 +98,12 @@ var fallbackTransport;
subject: results.subject,
html: results.html,
plaintext: htmlToText.fromString(results.html, {
- ignoreImage: true
+ ignoreImage: true,
}),
template: template,
uid: params.uid,
pid: params.pid,
- fromUid: params.fromUid
+ fromUid: params.fromUid,
};
Plugins.fireHook('filter:email.modify', data, next);
},
@@ -112,7 +113,7 @@ var fallbackTransport;
} else {
Emailer.sendViaFallback(data, next);
}
- }
+ },
], function (err) {
if (err && err.code === 'ENOENT') {
callback(new Error('[[error:sendmail-not-found]]'));
@@ -163,6 +164,5 @@ var fallbackTransport;
return parsed.hostname;
}
-
}(module.exports));
diff --git a/src/emitter.js b/src/emitter.js
index ca262257b7..140c35f639 100644
--- a/src/emitter.js
+++ b/src/emitter.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var eventEmitter = new (require('events')).EventEmitter();
@@ -32,4 +32,4 @@ eventEmitter.any = function (events, callback) {
});
};
-module.exports = eventEmitter;
\ No newline at end of file
+module.exports = eventEmitter;
diff --git a/src/events.js b/src/events.js
index 3f061566b9..ab2864bc23 100644
--- a/src/events.js
+++ b/src/events.js
@@ -4,7 +4,7 @@
var async = require('async');
var validator = require('validator');
-var db = require('./database');
+var db = require('./database');
var batch = require('./batch');
var user = require('./user');
var utils = require('../public/src/utils');
@@ -27,10 +27,10 @@ var utils = require('../public/src/utils');
},
function (next) {
db.setObject('event:' + eid, data, next);
- }
+ },
], next);
- }
- ], function (err, result) {
+ },
+ ], function (err) {
callback(err);
});
};
@@ -61,12 +61,16 @@ var utils = require('../public/src/utils');
}
});
var e = utils.merge(event);
- e.eid = e.uid = e.type = e.ip = e.user = undefined;
+ e.eid = undefined;
+ e.uid = undefined;
+ e.type = undefined;
+ e.ip = undefined;
+ e.user = undefined;
event.jsonString = JSON.stringify(e, null, 4);
event.timestampISO = new Date(parseInt(event.timestamp, 10)).toUTCString();
});
next(null, eventsData);
- }
+ },
], callback);
};
@@ -87,7 +91,7 @@ var utils = require('../public/src/utils');
},
userData: function (next) {
user.getUsersFields(uids, ['username', 'userslug', 'picture'], next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -121,7 +125,7 @@ var utils = require('../public/src/utils');
},
function (next) {
db.sortedSetRemove('events:time', eids, next);
- }
+ },
], callback);
};
@@ -130,8 +134,6 @@ var utils = require('../public/src/utils');
batch.processSortedSet('events:time', function (eids, next) {
events.deleteEvents(eids, next);
- }, {alwaysStartAt: 0}, callback);
+ }, { alwaysStartAt: 0 }, callback);
};
-
-
}(module.exports));
diff --git a/src/file.js b/src/file.js
index afdcef82bf..78d428c41e 100644
--- a/src/file.js
+++ b/src/file.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var fs = require('fs');
var nconf = require('nconf');
@@ -35,7 +35,7 @@ file.saveFileToLocal = function (filename, folder, tempPath, callback) {
is.on('end', function () {
callback(null, {
url: '/assets/uploads/' + folder + '/' + filename,
- path: uploadPath
+ path: uploadPath,
});
});
@@ -49,7 +49,7 @@ file.base64ToLocal = function (imageData, uploadPath, callback) {
uploadPath = path.join(nconf.get('upload_path'), uploadPath);
fs.writeFile(uploadPath, buffer, {
- encoding: 'base64'
+ encoding: 'base64',
}, function (err) {
callback(err, uploadPath);
});
@@ -101,8 +101,7 @@ file.existsSync = function (path) {
var exists = false;
try {
exists = fs.statSync(path);
- }
- catch (err) {
+ } catch (err) {
exists = false;
}
@@ -112,8 +111,7 @@ file.existsSync = function (path) {
file.link = function link(filePath, destPath, cb) {
if (process.platform === 'win32') {
fs.link(filePath, destPath, cb);
- }
- else {
+ } else {
fs.symlink(filePath, destPath, 'file', cb);
}
};
diff --git a/src/groups.js b/src/groups.js
index 51c1d97dc8..fd8c4a958f 100644
--- a/src/groups.js
+++ b/src/groups.js
@@ -6,217 +6,197 @@ var validator = require('validator');
var user = require('./user');
var db = require('./database');
var plugins = require('./plugins');
-var posts = require('./posts');
-var privileges = require('./privileges');
var utils = require('../public/src/utils');
-(function (Groups) {
+var Groups = module.exports;
- require('./groups/create')(Groups);
- require('./groups/delete')(Groups);
- require('./groups/update')(Groups);
- require('./groups/membership')(Groups);
- require('./groups/ownership')(Groups);
- require('./groups/search')(Groups);
- require('./groups/cover')(Groups);
+require('./groups/data')(Groups);
+require('./groups/create')(Groups);
+require('./groups/delete')(Groups);
+require('./groups/update')(Groups);
+require('./groups/membership')(Groups);
+require('./groups/ownership')(Groups);
+require('./groups/search')(Groups);
+require('./groups/cover')(Groups);
+require('./groups/posts')(Groups);
+require('./groups/user')(Groups);
- var ephemeralGroups = ['guests'],
- internals = {
- getEphemeralGroup: function (groupName) {
- return {
- name: groupName,
- slug: utils.slugify(groupName),
- description: '',
- deleted: '0',
- hidden: '0',
- system: '1'
- };
- },
- removeEphemeralGroups: function (groups) {
- var x = groups.length;
- while(x--) {
- if (ephemeralGroups.indexOf(groups[x]) !== -1) {
- groups.splice(x, 1);
- }
- }
+Groups.ephemeralGroups = ['guests'];
- return groups;
- }
- };
-
- Groups.internals = internals;
-
- var isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w:]+$/;
- Groups.isPrivilegeGroup = function (groupName) {
- return isPrivilegeGroupRegex.test(groupName);
+Groups.getEphemeralGroup = function (groupName) {
+ return {
+ name: groupName,
+ slug: utils.slugify(groupName),
+ description: '',
+ deleted: '0',
+ hidden: '0',
+ system: '1',
};
+};
- Groups.getEphemeralGroups = function () {
- return ephemeralGroups;
- };
-
- Groups.getGroupsFromSet = function (set, uid, start, stop, callback) {
- async.waterfall([
- function (next) {
- if (set === 'groups:visible:name') {
- db.getSortedSetRangeByLex(set, '-', '+', start, stop - start + 1, next);
- } else {
- db.getSortedSetRevRange(set, start, stop, next);
- }
- },
- function (groupNames, next) {
- if (set === 'groups:visible:name') {
- groupNames = groupNames.map(function (name) {
- return name.split(':')[1];
- });
- }
-
- Groups.getGroupsAndMembers(groupNames, next);
- }
- ], callback);
- };
-
- Groups.getGroups = function (set, start, stop, callback) {
- db.getSortedSetRevRange(set, start, stop, callback);
- };
-
- Groups.getGroupsAndMembers = function (groupNames, callback) {
- async.parallel({
- groups: function (next) {
- Groups.getGroupsData(groupNames, next);
- },
- members: function (next) {
- Groups.getMemberUsers(groupNames, 0, 3, next);
- }
- }, function (err, data) {
- if (err) {
- return callback(err);
- }
-
- data.groups.forEach(function (group, index) {
- if (!group) {
- return;
- }
-
- group.members = data.members[index] || [];
- group.truncated = group.memberCount > data.members.length;
- });
-
- callback(null, data.groups);
- });
- };
-
- Groups.get = function (groupName, options, callback) {
- if (!groupName) {
- return callback(new Error('[[error:invalid-group]]'));
+Groups.removeEphemeralGroups = function (groups) {
+ for (var x = groups.length; x >= 0; x -= 1) {
+ if (Groups.ephemeralGroups.indexOf(groups[x]) !== -1) {
+ groups.splice(x, 1);
}
+ }
- var stop = -1;
+ return groups;
+};
- async.parallel({
- base: function (next) {
- db.getObject('group:' + groupName, next);
- },
- members: function (next) {
- if (options.truncateUserList) {
- stop = (parseInt(options.userListCount, 10) || 4) - 1;
+var isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w:]+$/;
+Groups.isPrivilegeGroup = function (groupName) {
+ return isPrivilegeGroupRegex.test(groupName);
+};
+
+Groups.getGroupsFromSet = function (set, uid, start, stop, callback) {
+ async.waterfall([
+ function (next) {
+ if (set === 'groups:visible:name') {
+ db.getSortedSetRangeByLex(set, '-', '+', start, stop - start + 1, next);
+ } else {
+ db.getSortedSetRevRange(set, start, stop, next);
+ }
+ },
+ function (groupNames, next) {
+ if (set === 'groups:visible:name') {
+ groupNames = groupNames.map(function (name) {
+ return name.split(':')[1];
+ });
+ }
+
+ Groups.getGroupsAndMembers(groupNames, next);
+ },
+ ], callback);
+};
+
+Groups.getGroups = function (set, start, stop, callback) {
+ db.getSortedSetRevRange(set, start, stop, callback);
+};
+
+Groups.getGroupsAndMembers = function (groupNames, callback) {
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ groups: function (next) {
+ Groups.getGroupsData(groupNames, next);
+ },
+ members: function (next) {
+ Groups.getMemberUsers(groupNames, 0, 3, next);
+ },
+ }, next);
+ },
+ function (data, next) {
+ data.groups.forEach(function (group, index) {
+ if (group) {
+ group.members = data.members[index] || [];
+ group.truncated = group.memberCount > data.members.length;
}
+ });
+ next(null, data.groups);
+ },
+ ], callback);
+};
- Groups.getOwnersAndMembers(groupName, options.uid, 0, stop, next);
- },
- pending: function (next) {
- async.waterfall([
- function (next) {
- db.getSetMembers('group:' + groupName + ':pending', next);
- },
- function (uids, next) {
- user.getUsersData(uids, next);
+Groups.get = function (groupName, options, callback) {
+ if (!groupName) {
+ return callback(new Error('[[error:invalid-group]]'));
+ }
+
+ var stop = -1;
+
+ var results;
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ base: function (next) {
+ db.getObject('group:' + groupName, next);
+ },
+ members: function (next) {
+ if (options.truncateUserList) {
+ stop = (parseInt(options.userListCount, 10) || 4) - 1;
}
- ], next);
- },
- invited: function (next) {
- async.waterfall([
- function (next) {
- db.getSetMembers('group:' + groupName + ':invited', next);
- },
- function (uids, next) {
- user.getUsersData(uids, next);
- }
- ], next);
- },
- isMember: async.apply(Groups.isMember, options.uid, groupName),
- isPending: async.apply(Groups.isPending, options.uid, groupName),
- isInvited: async.apply(Groups.isInvited, options.uid, groupName),
- isOwner: async.apply(Groups.ownership.isOwner, options.uid, groupName)
- }, function (err, results) {
- if (err) {
- return callback(err);
- } else if (!results.base) {
+
+ Groups.getOwnersAndMembers(groupName, options.uid, 0, stop, next);
+ },
+ pending: function (next) {
+ Groups.getUsersFromSet('group:' + groupName + ':pending', next);
+ },
+ invited: function (next) {
+ Groups.getUsersFromSet('group:' + groupName + ':invited', next);
+ },
+ isMember: async.apply(Groups.isMember, options.uid, groupName),
+ isPending: async.apply(Groups.isPending, options.uid, groupName),
+ isInvited: async.apply(Groups.isInvited, options.uid, groupName),
+ isOwner: async.apply(Groups.ownership.isOwner, options.uid, groupName),
+ }, next);
+ },
+ function (_results, next) {
+ results = _results;
+ if (!results.base) {
return callback(new Error('[[error:no-group]]'));
}
+ plugins.fireHook('filter:parse.raw', results.base.description, next);
+ },
+ function (descriptionParsed, next) {
+ var groupData = results.base;
+ Groups.escapeGroupData(groupData);
- results.base['cover:url'] = results.base['cover:url'] || require('./coverPhoto').getDefaultGroupCover(groupName);
- results.base['cover:position'] = validator.escape(String(results.base['cover:position'] || '50% 50%'));
- results.base.labelColor = validator.escape(String(results.base.labelColor || '#000000'));
- results.base.icon = validator.escape(String(results.base.icon || ''));
+ groupData.descriptionParsed = descriptionParsed;
+ groupData.userTitleEnabled = groupData.userTitleEnabled ? !!parseInt(groupData.userTitleEnabled, 10) : true;
+ groupData.createtimeISO = utils.toISOString(groupData.createtime);
+ groupData.members = results.members;
+ groupData.membersNextStart = stop + 1;
+ groupData.pending = results.pending.filter(Boolean);
+ groupData.invited = results.invited.filter(Boolean);
+ groupData.deleted = !!parseInt(groupData.deleted, 10);
+ groupData.hidden = !!parseInt(groupData.hidden, 10);
+ groupData.system = !!parseInt(groupData.system, 10);
+ groupData.memberCount = parseInt(groupData.memberCount, 10);
+ groupData.private = (groupData.private === null || groupData.private === undefined) ? true : !!parseInt(groupData.private, 10);
+ groupData.disableJoinRequests = parseInt(groupData.disableJoinRequests, 10) === 1;
+ groupData.isMember = results.isMember;
+ groupData.isPending = results.isPending;
+ groupData.isInvited = results.isInvited;
+ groupData.isOwner = results.isOwner;
+ groupData['cover:url'] = groupData['cover:url'] || require('./coverPhoto').getDefaultGroupCover(groupName);
+ groupData['cover:position'] = validator.escape(String(groupData['cover:position'] || '50% 50%'));
+ groupData.labelColor = validator.escape(String(groupData.labelColor || '#000000'));
+ groupData.icon = validator.escape(String(groupData.icon || ''));
- plugins.fireHook('filter:parse.raw', results.base.description, function (err, descriptionParsed) {
- if (err) {
- return callback(err);
- }
+ plugins.fireHook('filter:group.get', { group: groupData }, next);
+ },
+ function (results, next) {
+ next(null, results.group);
+ },
+ ], callback);
+};
- Groups.escapeGroupData(results.base);
-
- results.base.descriptionParsed = descriptionParsed;
- results.base.userTitleEnabled = results.base.userTitleEnabled ? !!parseInt(results.base.userTitleEnabled, 10) : true;
- results.base.createtimeISO = utils.toISOString(results.base.createtime);
- results.base.members = results.members;
- results.base.membersNextStart = stop + 1;
- results.base.pending = results.pending.filter(Boolean);
- results.base.invited = results.invited.filter(Boolean);
- results.base.deleted = !!parseInt(results.base.deleted, 10);
- results.base.hidden = !!parseInt(results.base.hidden, 10);
- results.base.system = !!parseInt(results.base.system, 10);
- results.base.memberCount = parseInt(results.base.memberCount, 10);
- results.base.private = (results.base.private === null || results.base.private === undefined) ? true : !!parseInt(results.base.private, 10);
- results.base.disableJoinRequests = parseInt(results.base.disableJoinRequests, 10) === 1;
- results.base.isMember = results.isMember;
- results.base.isPending = results.isPending;
- results.base.isInvited = results.isInvited;
- results.base.isOwner = results.isOwner;
-
- plugins.fireHook('filter:group.get', {group: results.base}, function (err, data) {
- callback(err, data ? data.group : null);
- });
- });
- });
- };
-
- Groups.getOwners = function (groupName, callback) {
- db.getSetMembers('group:' + groupName + ':owners', callback);
- };
-
- Groups.getOwnersAndMembers = function (groupName, uid, start, stop, callback) {
- async.parallel({
- owners: function (next) {
- async.waterfall([
- function (next) {
- db.getSetMembers('group:' + groupName + ':owners', next);
- },
- function (uids, next) {
- user.getUsers(uids, uid, next);
- }
- ], next);
- },
- members: function (next) {
- user.getUsersFromSet('group:' + groupName + ':members', uid, start, stop, next);
- }
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
+Groups.getOwners = function (groupName, callback) {
+ db.getSetMembers('group:' + groupName + ':owners', callback);
+};
+Groups.getOwnersAndMembers = function (groupName, uid, start, stop, callback) {
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ owners: function (next) {
+ async.waterfall([
+ function (next) {
+ db.getSetMembers('group:' + groupName + ':owners', next);
+ },
+ function (uids, next) {
+ user.getUsers(uids, uid, next);
+ },
+ ], next);
+ },
+ members: function (next) {
+ user.getUsersFromSet('group:' + groupName + ':members', uid, start, stop, next);
+ },
+ }, next);
+ },
+ function (results, next) {
var ownerUids = [];
results.owners.forEach(function (user) {
if (user) {
@@ -230,230 +210,94 @@ var utils = require('../public/src/utils');
});
results.members = results.owners.concat(results.members);
- callback(null, results.members);
- });
- };
+ next(null, results.members);
+ },
+ ], callback);
+};
- Groups.escapeGroupData = function (group) {
- if (group) {
- group.nameEncoded = encodeURIComponent(group.name);
- group.displayName = validator.escape(String(group.name));
- group.description = validator.escape(String(group.description || ''));
- group.userTitle = validator.escape(String(group.userTitle || '')) || group.displayName;
- }
- };
+Groups.escapeGroupData = function (group) {
+ if (group) {
+ group.nameEncoded = encodeURIComponent(group.name);
+ group.displayName = validator.escape(String(group.name));
+ group.description = validator.escape(String(group.description || ''));
+ group.userTitle = validator.escape(String(group.userTitle || '')) || group.displayName;
+ }
+};
- Groups.getByGroupslug = function (slug, options, callback) {
- db.getObjectField('groupslug:groupname', slug, function (err, groupName) {
- if (err) {
- return callback(err);
- } else if (!groupName) {
- return callback(new Error('[[error:no-group]]'));
+Groups.getByGroupslug = function (slug, options, callback) {
+ async.waterfall([
+ function (next) {
+ db.getObjectField('groupslug:groupname', slug, next);
+ },
+ function (groupName, next) {
+ if (!groupName) {
+ return next(new Error('[[error:no-group]]'));
}
+ Groups.get(groupName, options, next);
+ },
+ ], callback);
+};
- Groups.get(groupName, options, callback);
+Groups.getGroupNameByGroupSlug = function (slug, callback) {
+ db.getObjectField('groupslug:groupname', slug, callback);
+};
+
+Groups.isPrivate = function (groupName, callback) {
+ isFieldOn(groupName, 'private', callback);
+};
+
+Groups.isHidden = function (groupName, callback) {
+ isFieldOn(groupName, 'hidden', callback);
+};
+
+function isFieldOn(groupName, field, callback) {
+ async.waterfall([
+ function (next) {
+ db.getObjectField('group:' + groupName, field, next);
+ },
+ function (value, next) {
+ next(null, parseInt(value, 10) === 1);
+ },
+ ], callback);
+}
+
+Groups.exists = function (name, callback) {
+ if (Array.isArray(name)) {
+ var slugs = name.map(function (groupName) {
+ return utils.slugify(groupName);
});
- };
-
- Groups.getGroupNameByGroupSlug = function (slug, callback) {
- db.getObjectField('groupslug:groupname', slug, callback);
- };
-
- Groups.getGroupFields = function (groupName, fields, callback) {
- Groups.getMultipleGroupFields([groupName], fields, function (err, groups) {
- callback(err, groups ? groups[0] : null);
- });
- };
-
- Groups.getMultipleGroupFields = function (groups, fields, callback) {
- db.getObjectsFields(groups.map(function (group) {
- return 'group:' + group;
- }), fields, callback);
- };
-
- Groups.setGroupField = function (groupName, field, value, callback) {
- db.setObjectField('group:' + groupName, field, value, function (err) {
- if (err) {
- return callback(err);
- }
- plugins.fireHook('action:group.set', {field: field, value: value, type: 'set'});
- callback();
- });
- };
-
- Groups.isPrivate = function (groupName, callback) {
- db.getObjectField('group:' + groupName, 'private', function (err, isPrivate) {
- if (err) {
- return callback(err);
- }
-
- callback(null, (parseInt(isPrivate, 10) === 0) ? false : true);
- });
- };
-
- Groups.isHidden = function (groupName, callback) {
- db.getObjectField('group:' + groupName, 'hidden', function (err, isHidden) {
- if (err) {
- return callback(err);
- }
-
- callback(null, parseInt(isHidden, 10) === 1);
- });
- };
-
- Groups.exists = function (name, callback) {
- if (Array.isArray(name)) {
- var slugs = name.map(function (groupName) {
- return utils.slugify(groupName);
- });
- async.parallel([
- function (next) {
- next(null, slugs.map(function (slug) {
- return ephemeralGroups.indexOf(slug) !== -1;
- }));
- },
- async.apply(db.isSortedSetMembers, 'groups:createtime', name)
- ], function (err, results) {
- if (err) {
- return callback(err);
- }
- callback(null, name.map(function (n, index) {
- return results[0][index] || results[1][index];
+ async.parallel([
+ function (next) {
+ next(null, slugs.map(function (slug) {
+ return Groups.ephemeralGroups.indexOf(slug) !== -1;
}));
- });
- } else {
- var slug = utils.slugify(name);
- async.parallel([
- function (next) {
- next(null, ephemeralGroups.indexOf(slug) !== -1);
- },
- async.apply(db.isSortedSetMember, 'groups:createtime', name)
- ], function (err, results) {
- callback(err, !err ? (results[0] || results[1]) : null);
- });
- }
- };
-
- Groups.existsBySlug = function (slug, callback) {
- if (Array.isArray(slug)) {
- db.isObjectFields('groupslug:groupname', slug, callback);
- } else {
- db.isObjectField('groupslug:groupname', slug, callback);
- }
- };
-
- Groups.getLatestMemberPosts = function (groupName, max, uid, callback) {
- async.waterfall([
- function (next) {
- Groups.getMembers(groupName, 0, -1, next);
},
- function (uids, next) {
- if (!Array.isArray(uids) || !uids.length) {
- return callback(null, []);
- }
- var keys = uids.map(function (uid) {
- return 'uid:' + uid + ':posts';
- });
- db.getSortedSetRevRange(keys, 0, max - 1, next);
- },
- function (pids, next) {
- privileges.posts.filter('read', pids, uid, next);
- },
- function (pids, next) {
- posts.getPostSummaryByPids(pids, uid, {stripTags: false}, next);
- }
- ], callback);
- };
-
- Groups.getGroupData = function (groupName, callback) {
- Groups.getGroupsData([groupName], function (err, groupsData) {
- callback(err, Array.isArray(groupsData) && groupsData[0] ? groupsData[0] : null);
- });
- };
-
- Groups.getGroupsData = function (groupNames, callback) {
- if (!Array.isArray(groupNames) || !groupNames.length) {
- return callback(null, []);
- }
-
- var keys = groupNames.map(function (groupName) {
- return 'group:' + groupName;
- });
-
- var ephemeralIdx = groupNames.reduce(function (memo, cur, idx) {
- if (ephemeralGroups.indexOf(cur) !== -1) {
- memo.push(idx);
- }
- return memo;
- }, []);
-
- db.getObjects(keys, function (err, groupData) {
+ async.apply(db.isSortedSetMembers, 'groups:createtime', name),
+ ], function (err, results) {
if (err) {
return callback(err);
}
-
- if (ephemeralIdx.length) {
- ephemeralIdx.forEach(function (idx) {
- groupData[idx] = internals.getEphemeralGroup(groupNames[idx]);
- });
- }
-
- groupData.forEach(function (group) {
- if (group) {
- Groups.escapeGroupData(group);
- group.userTitleEnabled = group.userTitleEnabled ? parseInt(group.userTitleEnabled, 10) === 1 : true;
- group.labelColor = validator.escape(String(group.labelColor || '#000000'));
- group.icon = validator.escape(String(group.icon || ''));
- group.createtimeISO = utils.toISOString(group.createtime);
- group.hidden = parseInt(group.hidden, 10) === 1;
- group.system = parseInt(group.system, 10) === 1;
- group.private = (group.private === null || group.private === undefined) ? true : !!parseInt(group.private, 10);
- group.disableJoinRequests = parseInt(group.disableJoinRequests) === 1;
-
- group['cover:url'] = group['cover:url'] || require('./coverPhoto').getDefaultGroupCover(group.name);
- group['cover:thumb:url'] = group['cover:thumb:url'] || group['cover:url'];
- group['cover:position'] = validator.escape(String(group['cover:position'] || '50% 50%'));
- }
- });
-
- plugins.fireHook('filter:groups.get', {groups: groupData}, function (err, data) {
- callback(err, data ? data.groups : null);
- });
+ callback(null, name.map(function (n, index) {
+ return results[0][index] || results[1][index];
+ }));
});
- };
-
- Groups.getUserGroups = function (uids, callback) {
- Groups.getUserGroupsFromSet('groups:visible:createtime', uids, callback);
- };
-
- Groups.getUserGroupsFromSet = function (set, uids, callback) {
- async.waterfall([
+ } else {
+ var slug = utils.slugify(name);
+ async.parallel([
function (next) {
- db.getSortedSetRevRange(set, 0, -1, next);
+ next(null, Groups.ephemeralGroups.indexOf(slug) !== -1);
},
- function (groupNames, next) {
- var groupSets = groupNames.map(function (name) {
- return 'group:' + name + ':members';
- });
+ async.apply(db.isSortedSetMember, 'groups:createtime', name),
+ ], function (err, results) {
+ callback(err, !err ? (results[0] || results[1]) : null);
+ });
+ }
+};
- async.map(uids, function (uid, next) {
- db.isMemberOfSortedSets(groupSets, uid, function (err, isMembers) {
- if (err) {
- return next(err);
- }
-
- var memberOf = [];
- isMembers.forEach(function (isMember, index) {
- if (isMember) {
- memberOf.push(groupNames[index]);
- }
- });
-
- Groups.getGroupsData(memberOf, next);
- });
- }, next);
- }
- ], callback);
- };
-
-}(module.exports));
+Groups.existsBySlug = function (slug, callback) {
+ if (Array.isArray(slug)) {
+ db.isObjectFields('groupslug:groupname', slug, callback);
+ } else {
+ db.isObjectField('groupslug:groupname', slug, callback);
+ }
+};
diff --git a/src/groups/cover.js b/src/groups/cover.js
index 8f18c60ad7..a7d7550fa0 100644
--- a/src/groups/cover.js
+++ b/src/groups/cover.js
@@ -1,10 +1,7 @@
'use strict';
var async = require('async');
-var nconf = require('nconf');
-var path = require('path');
var fs = require('fs');
-var crypto = require('crypto');
var Jimp = require('jimp');
var mime = require('mime');
var winston = require('winston');
@@ -14,7 +11,6 @@ var image = require('../image');
var uploadsController = require('../controllers/uploads');
module.exports = function (Groups) {
-
Groups.updateCoverPosition = function (groupName, position, callback) {
if (!groupName) {
return callback(new Error('[[error:invalid-data]]'));
@@ -23,7 +19,6 @@ module.exports = function (Groups) {
};
Groups.updateCover = function (uid, data, callback) {
-
// Position only? That's fine
if (!data.imageData && !data.file && data.position) {
return Groups.updateCoverPosition(data.groupName, data.position, callback);
@@ -45,7 +40,7 @@ module.exports = function (Groups) {
uploadsController.uploadGroupCover(uid, {
name: 'groupCover',
path: tempPath,
- type: type
+ type: type,
}, next);
},
function (uploadData, next) {
@@ -59,7 +54,7 @@ module.exports = function (Groups) {
uploadsController.uploadGroupCover(uid, {
name: 'groupCoverThumb',
path: tempPath,
- type: type
+ type: type,
}, next);
},
function (uploadData, next) {
@@ -71,13 +66,13 @@ module.exports = function (Groups) {
} else {
next(null);
}
- }
+ },
], function (err) {
fs.unlink(tempPath, function (unlinkErr) {
if (unlinkErr) {
winston.error(unlinkErr);
}
- callback(err, {url: url});
+ callback(err, { url: url });
});
});
};
@@ -92,7 +87,7 @@ module.exports = function (Groups) {
},
function (image, next) {
image.write(path, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -101,5 +96,4 @@ module.exports = function (Groups) {
Groups.removeCover = function (data, callback) {
db.deleteObjectFields('group:' + data.groupName, ['cover:url', 'cover:thumb:url', 'cover:position'], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/groups/create.js b/src/groups/create.js
index a59567afe6..4b680b8992 100644
--- a/src/groups/create.js
+++ b/src/groups/create.js
@@ -7,7 +7,6 @@ var utils = require('../../public/src/utils');
var db = require('../database');
module.exports = function (Groups) {
-
Groups.create = function (data, callback) {
var system = isSystemGroup(data);
var groupData;
@@ -42,14 +41,14 @@ module.exports = function (Groups) {
hidden: parseInt(data.hidden, 10) === 1 ? 1 : 0,
system: system ? 1 : 0,
private: isPrivate,
- disableJoinRequests: disableJoinRequests
+ disableJoinRequests: disableJoinRequests,
};
- plugins.fireHook('filter:group.create', {group: groupData, data: data}, next);
+ plugins.fireHook('filter:group.create', { group: groupData, data: data }, next);
},
function (results, next) {
var tasks = [
async.apply(db.sortedSetAdd, 'groups:createtime', groupData.createtime, groupData.name),
- async.apply(db.setObject, 'group:' + groupData.name, groupData)
+ async.apply(db.setObject, 'group:' + groupData.name, groupData),
];
if (data.hasOwnProperty('ownerUid')) {
@@ -72,9 +71,8 @@ module.exports = function (Groups) {
function (results, next) {
plugins.fireHook('action:group.create', groupData);
next(null, groupData);
- }
+ },
], callback);
-
};
function isSystemGroup(data) {
diff --git a/src/groups/data.js b/src/groups/data.js
new file mode 100644
index 0000000000..24e7f99a02
--- /dev/null
+++ b/src/groups/data.js
@@ -0,0 +1,93 @@
+'use strict';
+
+var async = require('async');
+var validator = require('validator');
+
+var db = require('../database');
+var plugins = require('../plugins');
+var utils = require('../../public/src/utils');
+
+module.exports = function (Groups) {
+ Groups.getGroupsData = function (groupNames, callback) {
+ if (!Array.isArray(groupNames) || !groupNames.length) {
+ return callback(null, []);
+ }
+
+ var keys = groupNames.map(function (groupName) {
+ return 'group:' + groupName;
+ });
+
+ var ephemeralIdx = groupNames.reduce(function (memo, cur, idx) {
+ if (Groups.ephemeralGroups.indexOf(cur) !== -1) {
+ memo.push(idx);
+ }
+ return memo;
+ }, []);
+
+ async.waterfall([
+ function (next) {
+ db.getObjects(keys, next);
+ },
+ function (groupData, next) {
+ if (ephemeralIdx.length) {
+ ephemeralIdx.forEach(function (idx) {
+ groupData[idx] = Groups.getEphemeralGroup(groupNames[idx]);
+ });
+ }
+
+ groupData.forEach(function (group) {
+ if (group) {
+ Groups.escapeGroupData(group);
+ group.userTitleEnabled = group.userTitleEnabled ? parseInt(group.userTitleEnabled, 10) === 1 : true;
+ group.labelColor = validator.escape(String(group.labelColor || '#000000'));
+ group.icon = validator.escape(String(group.icon || ''));
+ group.createtimeISO = utils.toISOString(group.createtime);
+ group.hidden = parseInt(group.hidden, 10) === 1;
+ group.system = parseInt(group.system, 10) === 1;
+ group.private = (group.private === null || group.private === undefined) ? true : !!parseInt(group.private, 10);
+ group.disableJoinRequests = parseInt(group.disableJoinRequests, 10) === 1;
+
+ group['cover:url'] = group['cover:url'] || require('../coverPhoto').getDefaultGroupCover(group.name);
+ group['cover:thumb:url'] = group['cover:thumb:url'] || group['cover:url'];
+ group['cover:position'] = validator.escape(String(group['cover:position'] || '50% 50%'));
+ }
+ });
+
+ plugins.fireHook('filter:groups.get', { groups: groupData }, next);
+ },
+ function (results, next) {
+ next(null, results.groups);
+ },
+ ], callback);
+ };
+
+ Groups.getGroupData = function (groupName, callback) {
+ Groups.getGroupsData([groupName], function (err, groupsData) {
+ callback(err, Array.isArray(groupsData) && groupsData[0] ? groupsData[0] : null);
+ });
+ };
+
+ Groups.getGroupFields = function (groupName, fields, callback) {
+ Groups.getMultipleGroupFields([groupName], fields, function (err, groups) {
+ callback(err, groups ? groups[0] : null);
+ });
+ };
+
+ Groups.getMultipleGroupFields = function (groups, fields, callback) {
+ db.getObjectsFields(groups.map(function (group) {
+ return 'group:' + group;
+ }), fields, callback);
+ };
+
+ Groups.setGroupField = function (groupName, field, value, callback) {
+ async.waterfall([
+ function (next) {
+ db.setObjectField('group:' + groupName, field, value, next);
+ },
+ function (next) {
+ plugins.fireHook('action:group.set', { field: field, value: value, type: 'set' });
+ next();
+ },
+ ], callback);
+ };
+};
diff --git a/src/groups/delete.js b/src/groups/delete.js
index 0838dd2407..6aed7173a2 100644
--- a/src/groups/delete.js
+++ b/src/groups/delete.js
@@ -6,7 +6,6 @@ var utils = require('../../public/src/utils');
var db = require('./../database');
module.exports = function (Groups) {
-
Groups.destroy = function (groupName, callback) {
Groups.getGroupsData([groupName], function (err, groupsData) {
if (err) {
@@ -39,7 +38,7 @@ module.exports = function (Groups) {
db.sortedSetRemove('group:' + group + ':members', groupName, next);
}, next);
});
- }
+ },
], function (err) {
if (err) {
return callback(err);
diff --git a/src/groups/membership.js b/src/groups/membership.js
index 68a9724c9c..6bcafd2343 100644
--- a/src/groups/membership.js
+++ b/src/groups/membership.js
@@ -15,11 +15,10 @@ var LRU = require('lru-cache');
var cache = LRU({
max: 40000,
- maxAge: 1000 * 60 * 60
+ maxAge: 1000 * 60 * 60,
});
module.exports = function (Groups) {
-
Groups.cache = cache;
Groups.join = function (groupName, uid, callback) {
@@ -46,7 +45,7 @@ module.exports = function (Groups) {
Groups.create({
name: groupName,
description: '',
- hidden: 1
+ hidden: 1,
}, function (err) {
if (err && err.message !== '[[error:group-already-exists]]') {
winston.error('[groups.join] Could not create new hidden group: ' + err.message);
@@ -62,13 +61,13 @@ module.exports = function (Groups) {
},
isHidden: function (next) {
Groups.isHidden(groupName, next);
- }
+ },
}, next);
},
function (results, next) {
var tasks = [
async.apply(db.sortedSetAdd, 'group:' + groupName + ':members', Date.now(), uid),
- async.apply(db.incrObjectField, 'group:' + groupName, 'memberCount')
+ async.apply(db.incrObjectField, 'group:' + groupName, 'memberCount'),
];
if (results.isAdmin) {
tasks.push(async.apply(db.setAdd, 'group:' + groupName + ':owners', uid));
@@ -85,10 +84,10 @@ module.exports = function (Groups) {
function (next) {
plugins.fireHook('action:group.join', {
groupName: groupName,
- uid: uid
+ uid: uid,
});
next();
- }
+ },
], callback);
};
@@ -120,12 +119,12 @@ module.exports = function (Groups) {
bodyLong: '[[groups:request.notification_text, ' + username + ', ' + groupName + ']]',
nid: 'group:' + groupName + ':uid:' + uid + ':request',
path: '/groups/' + utils.slugify(groupName),
- from: uid
+ from: uid,
}, next);
},
owners: function (next) {
Groups.getOwners(groupName, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -133,7 +132,7 @@ module.exports = function (Groups) {
return next();
}
notifications.push(results.notification, results.owners, next);
- }
+ },
], callback);
};
@@ -141,14 +140,14 @@ module.exports = function (Groups) {
async.waterfall([
async.apply(db.setRemove, 'group:' + groupName + ':pending', uid),
async.apply(db.setRemove, 'group:' + groupName + ':invited', uid),
- async.apply(Groups.join, groupName, uid)
+ async.apply(Groups.join, groupName, uid),
], callback);
};
Groups.rejectMembership = function (groupName, uid, callback) {
async.parallel([
async.apply(db.setRemove, 'group:' + groupName + ':pending', uid),
- async.apply(db.setRemove, 'group:' + groupName + ':invited', uid)
+ async.apply(db.setRemove, 'group:' + groupName + ':invited', uid),
], callback);
};
@@ -159,11 +158,11 @@ module.exports = function (Groups) {
bodyShort: '[[groups:invited.notification_title, ' + groupName + ']]',
bodyLong: '',
nid: 'group:' + groupName + ':uid:' + uid + ':invite',
- path: '/groups/' + utils.slugify(groupName)
+ path: '/groups/' + utils.slugify(groupName),
}),
function (notification, next) {
notifications.push(notification, [uid], next);
- }
+ },
], callback);
};
@@ -180,7 +179,7 @@ module.exports = function (Groups) {
exists: async.apply(Groups.exists, groupName),
isMember: async.apply(Groups.isMember, uid, groupName),
isPending: async.apply(Groups.isPending, uid, groupName),
- isInvited: async.apply(Groups.isInvited, uid, groupName)
+ isInvited: async.apply(Groups.isInvited, uid, groupName),
}, next);
},
function (checks, next) {
@@ -199,10 +198,10 @@ module.exports = function (Groups) {
function (next) {
plugins.fireHook(hookName, {
groupName: groupName,
- uid: uid
+ uid: uid,
});
next();
- }
+ },
], callback);
}
@@ -227,7 +226,7 @@ module.exports = function (Groups) {
async.parallel([
async.apply(db.sortedSetRemove, 'group:' + groupName + ':members', uid),
async.apply(db.setRemove, 'group:' + groupName + ':owners', uid),
- async.apply(db.decrObjectField, 'group:' + groupName, 'memberCount')
+ async.apply(db.decrObjectField, 'group:' + groupName, 'memberCount'),
], next);
},
function (results, next) {
@@ -240,21 +239,19 @@ module.exports = function (Groups) {
}
if (Groups.isPrivilegeGroup(groupName) && parseInt(groupData.memberCount, 10) === 0) {
Groups.destroy(groupName, next);
+ } else if (parseInt(groupData.hidden, 10) !== 1) {
+ db.sortedSetAdd('groups:visible:memberCount', groupData.memberCount, groupName, next);
} else {
- if (parseInt(groupData.hidden, 10) !== 1) {
- db.sortedSetAdd('groups:visible:memberCount', groupData.memberCount, groupName, next);
- } else {
- next();
- }
+ next();
}
},
function (next) {
plugins.fireHook('action:group.leave', {
groupName: groupName,
- uid: uid
+ uid: uid,
});
next();
- }
+ },
], callback);
};
@@ -277,10 +274,10 @@ module.exports = function (Groups) {
},
function (next) {
Groups.rejectMembership(groupName, uid, next);
- }
+ },
], next);
}, next);
- }
+ },
], callback);
};
@@ -316,7 +313,7 @@ module.exports = function (Groups) {
});
function clearCache(uid, groupName) {
- pubsub.publish('group:cache:del', {uid: uid, groupName: groupName});
+ pubsub.publish('group:cache:del', { uid: uid, groupName: groupName });
cache.del(uid + ':' + groupName);
}
@@ -341,7 +338,7 @@ module.exports = function (Groups) {
function (isMember, next) {
cache.set(cacheKey, isMember);
next(null, isMember);
- }
+ },
], callback);
};
@@ -353,7 +350,7 @@ module.exports = function (Groups) {
}
if (!groupName || !uids.length) {
- return callback(null, uids.map(function () {return false;}));
+ return callback(null, uids.map(function () { return false; }));
}
var nonCachedUids = uids.filter(function (uid) {
@@ -374,7 +371,7 @@ module.exports = function (Groups) {
});
getFromCache(next);
- }
+ },
], callback);
};
@@ -386,7 +383,7 @@ module.exports = function (Groups) {
}
if (!uid || parseInt(uid, 10) <= 0 || !groups.length) {
- return callback(null, groups.map(function () {return false;}));
+ return callback(null, groups.map(function () { return false; }));
}
var nonCachedGroups = groups.filter(function (groupName) {
@@ -411,37 +408,38 @@ module.exports = function (Groups) {
});
getFromCache(next);
- }
+ },
], callback);
};
Groups.getMemberCount = function (groupName, callback) {
- db.getObjectField('group:' + groupName, 'memberCount', function (err, count) {
- if (err) {
- return callback(err);
- }
- callback(null, parseInt(count, 10));
- });
+ async.waterfall([
+ function (next) {
+ db.getObjectField('group:' + groupName, 'memberCount', next);
+ },
+ function (count, next) {
+ next(null, parseInt(count, 10));
+ },
+ ], callback);
};
Groups.isMemberOfGroupList = function (uid, groupListKey, callback) {
- db.getSortedSetRange('group:' + groupListKey + ':members', 0, -1, function (err, groupNames) {
- if (err) {
- return callback(err);
- }
- groupNames = Groups.internals.removeEphemeralGroups(groupNames);
- if (groupNames.length === 0) {
- return callback(null, false);
- }
-
- Groups.isMemberOfGroups(uid, groupNames, function (err, isMembers) {
- if (err) {
- return callback(err);
+ async.waterfall([
+ function (next) {
+ db.getSortedSetRange('group:' + groupListKey + ':members', 0, -1, next);
+ },
+ function (groupNames, next) {
+ groupNames = Groups.removeEphemeralGroups(groupNames);
+ if (groupNames.length === 0) {
+ return callback(null, false);
}
- callback(null, isMembers.indexOf(true) !== -1);
- });
- });
+ Groups.isMemberOfGroups(uid, groupNames, next);
+ },
+ function (isMembers, next) {
+ next(null, isMembers.indexOf(true) !== -1);
+ },
+ ], callback);
};
Groups.isMemberOfGroupsList = function (uid, groupListKeys, callback) {
@@ -449,19 +447,20 @@ module.exports = function (Groups) {
return 'group:' + groupName + ':members';
});
- db.getSortedSetsMembers(sets, function (err, members) {
- if (err) {
- return callback(err);
- }
-
- var uniqueGroups = _.unique(_.flatten(members));
- uniqueGroups = Groups.internals.removeEphemeralGroups(uniqueGroups);
-
- Groups.isMemberOfGroups(uid, uniqueGroups, function (err, isMembers) {
- if (err) {
- return callback(err);
- }
+ var uniqueGroups;
+ var members;
+ async.waterfall([
+ function (next) {
+ db.getSortedSetsMembers(sets, next);
+ },
+ function (_members, next) {
+ members = _members;
+ uniqueGroups = _.unique(_.flatten(members));
+ uniqueGroups = Groups.removeEphemeralGroups(uniqueGroups);
+ Groups.isMemberOfGroups(uid, uniqueGroups, next);
+ },
+ function (isMembers, next) {
var map = {};
uniqueGroups.forEach(function (groupName, index) {
@@ -469,7 +468,7 @@ module.exports = function (Groups) {
});
var result = members.map(function (groupNames) {
- for (var i = 0; i < groupNames.length; ++i) {
+ for (var i = 0; i < groupNames.length; i += 1) {
if (map[groupNames[i]]) {
return true;
}
@@ -477,62 +476,63 @@ module.exports = function (Groups) {
return false;
});
- callback(null, result);
- });
- });
+ next(null, result);
+ },
+ ], callback);
};
Groups.isMembersOfGroupList = function (uids, groupListKey, callback) {
- db.getSortedSetRange('group:' + groupListKey + ':members', 0, -1, function (err, groupNames) {
- if (err) {
- return callback(err);
- }
+ var groupNames;
+ var results = [];
+ uids.forEach(function () {
+ results.push(false);
+ });
- var results = [];
- uids.forEach(function () {
- results.push(false);
- });
+ async.waterfall([
+ function (next) {
+ db.getSortedSetRange('group:' + groupListKey + ':members', 0, -1, next);
+ },
+ function (_groupNames, next) {
+ groupNames = Groups.removeEphemeralGroups(_groupNames);
- groupNames = Groups.internals.removeEphemeralGroups(groupNames);
- if (groupNames.length === 0) {
- return callback(null, results);
- }
+ if (groupNames.length === 0) {
+ return callback(null, results);
+ }
- async.each(groupNames, function (groupName, next) {
- Groups.isMembers(uids, groupName, function (err, isMembers) {
- if (err) {
- return next(err);
- }
+ async.map(groupNames, function (groupName, next) {
+ Groups.isMembers(uids, groupName, next);
+ }, next);
+ },
+ function (isGroupMembers, next) {
+ isGroupMembers.forEach(function (isMembers) {
results.forEach(function (isMember, index) {
if (!isMember && isMembers[index]) {
results[index] = true;
}
});
- next();
});
- }, function (err) {
- callback(err, results);
- });
- });
+ next(null, results);
+ },
+ ], callback);
};
Groups.isInvited = function (uid, groupName, callback) {
if (!uid) {
- return callback(null, false);
+ return setImmediate(callback, null, false);
}
db.isSetMember('group:' + groupName + ':invited', uid, callback);
};
Groups.isPending = function (uid, groupName, callback) {
if (!uid) {
- return callback(null, false);
+ return setImmediate(callback, null, false);
}
db.isSetMember('group:' + groupName + ':pending', uid, callback);
};
Groups.getPending = function (groupName, callback) {
if (!groupName) {
- return callback(null, []);
+ return setImmediate(callback, null, []);
}
db.getSetMembers('group:' + groupName + ':pending', callback);
};
@@ -549,7 +549,7 @@ module.exports = function (Groups) {
return next(new Error('[[error:group-needs-owner]]'));
}
Groups.leave(groupName, uid, next);
- }
+ },
], callback);
} else {
Groups.leave(groupName, uid, callback);
diff --git a/src/groups/ownership.js b/src/groups/ownership.js
index f397abe5e7..0b386bbe35 100644
--- a/src/groups/ownership.js
+++ b/src/groups/ownership.js
@@ -1,11 +1,10 @@
'use strict';
-var async = require('async'),
- db = require('../database'),
- plugins = require('../plugins');
+var async = require('async');
+var db = require('../database');
+var plugins = require('../plugins');
module.exports = function (Groups) {
-
Groups.ownership = {};
Groups.ownership.isOwner = function (uid, groupName, callback) {
@@ -30,9 +29,9 @@ module.exports = function (Groups) {
db.setAdd('group:' + groupName + ':owners', toUid, next);
},
function (next) {
- plugins.fireHook('action:group.grantOwnership', {uid: toUid, groupName: groupName});
+ plugins.fireHook('action:group.grantOwnership', { uid: toUid, groupName: groupName });
next();
- }
+ },
], callback);
};
@@ -51,9 +50,9 @@ module.exports = function (Groups) {
db.setRemove('group:' + groupName + ':owners', toUid, next);
},
function (next) {
- plugins.fireHook('action:group.rescindOwnership', {uid: toUid, groupName: groupName});
+ plugins.fireHook('action:group.rescindOwnership', { uid: toUid, groupName: groupName });
next();
- }
+ },
], callback);
};
};
diff --git a/src/groups/posts.js b/src/groups/posts.js
new file mode 100644
index 0000000000..6f4d65520d
--- /dev/null
+++ b/src/groups/posts.js
@@ -0,0 +1,32 @@
+'use strict';
+
+var async = require('async');
+
+var db = require('../database');
+var privileges = require('../privileges');
+var posts = require('../posts');
+
+module.exports = function (Groups) {
+ Groups.getLatestMemberPosts = function (groupName, max, uid, callback) {
+ async.waterfall([
+ function (next) {
+ Groups.getMembers(groupName, 0, -1, next);
+ },
+ function (uids, next) {
+ if (!Array.isArray(uids) || !uids.length) {
+ return callback(null, []);
+ }
+ var keys = uids.map(function (uid) {
+ return 'uid:' + uid + ':posts';
+ });
+ db.getSortedSetRevRange(keys, 0, max - 1, next);
+ },
+ function (pids, next) {
+ privileges.posts.filter('read', pids, uid, next);
+ },
+ function (pids, next) {
+ posts.getPostSummaryByPids(pids, uid, { stripTags: false }, next);
+ },
+ ], callback);
+ };
+};
diff --git a/src/groups/search.js b/src/groups/search.js
index 3b6bfab9cd..62df79696c 100644
--- a/src/groups/search.js
+++ b/src/groups/search.js
@@ -7,7 +7,6 @@ var db = require('./../database');
module.exports = function (Groups) {
-
Groups.search = function (query, options, callback) {
if (!query) {
return callback(null, []);
@@ -17,7 +16,7 @@ module.exports = function (Groups) {
async.apply(db.getObjectValues, 'groupslug:groupname'),
function (groupNames, next) {
// Ephemeral groups and the registered-users groups are searchable
- groupNames = Groups.getEphemeralGroups().concat(groupNames).concat('registered-users');
+ groupNames = Groups.ephemeralGroups.concat(groupNames).concat('registered-users');
groupNames = groupNames.filter(function (name) {
return name.toLowerCase().indexOf(query) !== -1 && name !== 'administrators' && !Groups.isPrivilegeGroup(name);
});
@@ -33,38 +32,37 @@ module.exports = function (Groups) {
}
Groups.sort(options.sort, groupsData, next);
- }
+ },
], callback);
};
Groups.sort = function (strategy, groups, next) {
- switch(strategy) {
- case 'count':
- groups = groups.sort(function (a, b) {
- return a.slug > b.slug;
- }).sort(function (a, b) {
- return b.memberCount - a.memberCount;
- });
- break;
+ switch (strategy) {
+ case 'count':
+ groups = groups.sort(function (a, b) {
+ return a.slug > b.slug;
+ }).sort(function (a, b) {
+ return b.memberCount - a.memberCount;
+ });
+ break;
- case 'date':
- groups = groups.sort(function (a, b) {
- return b.createtime - a.createtime;
- });
- break;
+ case 'date':
+ groups = groups.sort(function (a, b) {
+ return b.createtime - a.createtime;
+ });
+ break;
- case 'alpha': // intentional fall-through
- default:
- groups = groups.sort(function (a, b) {
- return a.slug > b.slug ? 1 : -1;
- });
+ case 'alpha': // intentional fall-through
+ default:
+ groups = groups.sort(function (a, b) {
+ return a.slug > b.slug ? 1 : -1;
+ });
}
next(null, groups);
};
Groups.searchMembers = function (data, callback) {
-
function findUids(query, searchBy, callback) {
query = query.toLowerCase();
@@ -77,14 +75,14 @@ module.exports = function (Groups) {
},
function (users, next) {
var uids = [];
- for(var i = 0; i < users.length; ++i) {
+ for (var i = 0; i < users.length; i += 1) {
var field = users[i][searchBy];
if (field.toLowerCase().startsWith(query)) {
uids.push(users[i].uid);
}
}
next(null, uids);
- }
+ },
], callback);
}
@@ -93,7 +91,7 @@ module.exports = function (Groups) {
if (err) {
return callback(err);
}
- callback(null, {users: users});
+ callback(null, { users: users });
});
return;
}
@@ -112,24 +110,22 @@ module.exports = function (Groups) {
Groups.ownership.isOwners(uids, data.groupName, next);
},
function (isOwners, next) {
-
results.users.forEach(function (user, index) {
if (user) {
user.isOwner = isOwners[index];
}
});
- results.users.sort(function (a,b) {
+ results.users.sort(function (a, b) {
if (a.isOwner && !b.isOwner) {
return -1;
} else if (!a.isOwner && b.isOwner) {
return 1;
- } else {
- return 0;
}
+ return 0;
});
next(null, results);
- }
+ },
], callback);
};
};
diff --git a/src/groups/update.js b/src/groups/update.js
index 4dfe760a96..9bf53886e5 100644
--- a/src/groups/update.js
+++ b/src/groups/update.js
@@ -9,7 +9,6 @@ var db = require('../database');
module.exports = function (Groups) {
-
Groups.update = function (groupName, values, callback) {
callback = callback || function () {};
@@ -23,7 +22,7 @@ module.exports = function (Groups) {
}
plugins.fireHook('filter:group.update', {
groupName: groupName,
- values: values
+ values: values,
}, next);
},
function (result, next) {
@@ -32,7 +31,7 @@ module.exports = function (Groups) {
var payload = {
description: values.description || '',
icon: values.icon || '',
- labelColor: values.labelColor || '#000000'
+ labelColor: values.labelColor || '#000000',
};
if (values.hasOwnProperty('userTitle')) {
@@ -71,16 +70,16 @@ module.exports = function (Groups) {
}
},
async.apply(db.setObject, 'group:' + groupName, payload),
- async.apply(renameGroup, groupName, values.name)
+ async.apply(renameGroup, groupName, values.name),
], next);
},
function (result, next) {
plugins.fireHook('action:group.update', {
name: groupName,
- values: values
+ values: values,
});
next();
- }
+ },
], callback);
};
@@ -92,16 +91,18 @@ module.exports = function (Groups) {
async.apply(db.sortedSetRemove, 'groups:visible:name', groupName.toLowerCase() + ':' + groupName),
], callback);
} else {
- db.getObjectFields('group:' + groupName, ['createtime', 'memberCount'], function (err, groupData) {
- if (err) {
- return callback(err);
- }
- async.parallel([
- async.apply(db.sortedSetAdd, 'groups:visible:createtime', groupData.createtime, groupName),
- async.apply(db.sortedSetAdd, 'groups:visible:memberCount', groupData.memberCount, groupName),
- async.apply(db.sortedSetAdd, 'groups:visible:name', 0, groupName.toLowerCase() + ':' + groupName),
- ], callback);
- });
+ async.waterfall([
+ function (next) {
+ db.getObjectFields('group:' + groupName, ['createtime', 'memberCount'], next);
+ },
+ function (groupData, next) {
+ async.parallel([
+ async.apply(db.sortedSetAdd, 'groups:visible:createtime', groupData.createtime, groupName),
+ async.apply(db.sortedSetAdd, 'groups:visible:memberCount', groupData.memberCount, groupName),
+ async.apply(db.sortedSetAdd, 'groups:visible:name', 0, groupName.toLowerCase() + ':' + groupName),
+ ], next);
+ },
+ ], callback);
}
}
@@ -118,7 +119,7 @@ module.exports = function (Groups) {
callback = callback || function () {};
async.parallel([
async.apply(db.setObjectField, 'group:' + groupName, 'hidden', hidden ? 1 : 0),
- async.apply(updateVisibility, groupName, hidden)
+ async.apply(updateVisibility, groupName, hidden),
], function (err) {
callback(err);
});
@@ -131,7 +132,7 @@ module.exports = function (Groups) {
},
function (currentValue, next) {
var currentlyPrivate = parseInt(currentValue.private, 10) === 1;
- if (!currentlyPrivate || currentlyPrivate === isPrivate) {
+ if (!currentlyPrivate || currentlyPrivate === isPrivate) {
return callback();
}
db.getSetMembers('group:' + groupName + ':pending', next);
@@ -146,9 +147,9 @@ module.exports = function (Groups) {
winston.verbose('[groups.update] Group is now public, automatically adding ' + uids.length + ' new members, who were pending prior.');
async.series([
async.apply(db.sortedSetAdd, 'group:' + groupName + ':members', scores, uids),
- async.apply(db.delete, 'group:' + groupName + ':pending')
+ async.apply(db.delete, 'group:' + groupName + ':pending'),
], next);
- }
+ },
], function (err) {
callback(err);
});
@@ -156,40 +157,48 @@ module.exports = function (Groups) {
function checkNameChange(currentName, newName, callback) {
if (currentName === newName) {
- return callback();
+ return setImmediate(callback);
}
var currentSlug = utils.slugify(currentName);
var newSlug = utils.slugify(newName);
if (currentSlug === newSlug) {
- return callback();
+ return setImmediate(callback);
}
- Groups.existsBySlug(newSlug, function (err, exists) {
- if (err || exists) {
- return callback(err || new Error('[[error:group-already-exists]]'));
- }
- callback();
- });
+ async.waterfall([
+ function (next) {
+ Groups.existsBySlug(newSlug, next);
+ },
+ function (exists, next) {
+ next(exists ? new Error('[[error:group-already-exists]]') : null);
+ },
+ ], callback);
}
function renameGroup(oldName, newName, callback) {
if (oldName === newName || !newName || newName.length === 0) {
- return callback();
+ return setImmediate(callback);
}
-
- db.getObject('group:' + oldName, function (err, group) {
- if (err || !group) {
- return callback(err);
- }
-
- if (parseInt(group.system, 10) === 1) {
- return callback();
- }
-
- Groups.exists(newName, function (err, exists) {
- if (err || exists) {
- return callback(err || new Error('[[error:group-already-exists]]'));
+ var group;
+ async.waterfall([
+ function (next) {
+ db.getObject('group:' + oldName, next);
+ },
+ function (_group, next) {
+ group = _group;
+ if (!group) {
+ return callback();
}
+ if (parseInt(group.system, 10) === 1) {
+ return callback(new Error('[[error:not-allowed-to-rename-system-group]]'));
+ }
+
+ Groups.exists(newName, next);
+ },
+ function (exists, next) {
+ if (exists) {
+ return callback(new Error('[[error:group-already-exists]]'));
+ }
async.series([
async.apply(db.setObjectField, 'group:' + oldName, 'name', newName),
async.apply(db.setObjectField, 'group:' + oldName, 'slug', utils.slugify(newName)),
@@ -218,34 +227,38 @@ module.exports = function (Groups) {
function (next) {
plugins.fireHook('action:group.rename', {
old: oldName,
- new: newName
+ new: newName,
});
next();
- }
- ], callback);
- });
+ },
+ ], next);
+ },
+ ], function (err) {
+ callback(err);
});
}
function renameGroupMember(group, oldName, newName, callback) {
- db.isSortedSetMember(group, oldName, function (err, isMember) {
- if (err || !isMember) {
- return callback(err);
- }
- var score;
- async.waterfall([
- function (next) {
- db.sortedSetScore(group, oldName, next);
- },
- function (_score, next) {
- score = _score;
- db.sortedSetRemove(group, oldName, next);
- },
- function (next) {
- db.sortedSetAdd(group, score, newName, next);
+ var score;
+ async.waterfall([
+ function (next) {
+ db.isSortedSetMember(group, oldName, next);
+ },
+ function (isMember, next) {
+ if (!isMember) {
+ return callback();
}
- ], callback);
- });
+
+ db.sortedSetScore(group, oldName, next);
+ },
+ function (_score, next) {
+ score = _score;
+ db.sortedSetRemove(group, oldName, next);
+ },
+ function (next) {
+ db.sortedSetAdd(group, score, newName, next);
+ },
+ ], callback);
}
};
diff --git a/src/groups/user.js b/src/groups/user.js
new file mode 100644
index 0000000000..9a68478ade
--- /dev/null
+++ b/src/groups/user.js
@@ -0,0 +1,50 @@
+'use strict';
+
+var async = require('async');
+
+var db = require('../database');
+var user = require('../user');
+
+module.exports = function (Groups) {
+ Groups.getUsersFromSet = function (set, callback) {
+ async.waterfall([
+ function (next) {
+ db.getSetMembers(set, next);
+ },
+ function (uids, next) {
+ user.getUsersData(uids, next);
+ },
+ ], callback);
+ };
+
+ Groups.getUserGroups = function (uids, callback) {
+ Groups.getUserGroupsFromSet('groups:visible:createtime', uids, callback);
+ };
+
+ Groups.getUserGroupsFromSet = function (set, uids, callback) {
+ async.waterfall([
+ function (next) {
+ db.getSortedSetRevRange(set, 0, -1, next);
+ },
+ function (groupNames, next) {
+ async.map(uids, function (uid, next) {
+ async.waterfall([
+ function (next) {
+ Groups.isMemberOfGroups(uid, groupNames, next);
+ },
+ function (isMembers, next) {
+ var memberOf = [];
+ isMembers.forEach(function (isMember, index) {
+ if (isMember) {
+ memberOf.push(groupNames[index]);
+ }
+ });
+
+ Groups.getGroupsData(memberOf, next);
+ },
+ ], next);
+ }, next);
+ },
+ ], callback);
+ };
+};
diff --git a/src/hotswap.js b/src/hotswap.js
index ece8f205d7..76cb2f774b 100644
--- a/src/hotswap.js
+++ b/src/hotswap.js
@@ -1,8 +1,8 @@
-"use strict";
+'use strict';
-var HotSwap = {},
- winston = require('winston'),
- stack;
+var HotSwap = {};
+var winston = require('winston');
+var stack;
HotSwap.prepare = function (app) {
stack = app._router.stack;
@@ -10,7 +10,7 @@ HotSwap.prepare = function (app) {
HotSwap.find = function (id) {
if (stack) {
- for(var x = 0,numEntries = stack.length; x < numEntries; x++) {
+ for (var x = 0, numEntries = stack.length; x < numEntries; x += 1) {
if (stack[x].handle.hotswapId === id) {
return x;
}
@@ -31,4 +31,4 @@ HotSwap.replace = function (id, router) {
}
};
-module.exports = HotSwap;
\ No newline at end of file
+module.exports = HotSwap;
diff --git a/src/image.js b/src/image.js
index 7b428f2331..1609993731 100644
--- a/src/image.js
+++ b/src/image.js
@@ -19,7 +19,7 @@ image.resizeImage = function (data, callback) {
target: data.target,
extension: data.extension,
width: data.width,
- height: data.height
+ height: data.height,
}, function (err) {
callback(err);
});
@@ -29,13 +29,13 @@ image.resizeImage = function (data, callback) {
return callback(err);
}
- var w = image.bitmap.width,
- h = image.bitmap.height,
- origRatio = w / h,
- desiredRatio = data.width && data.height ? data.width / data.height : origRatio,
- x = 0,
- y = 0,
- crop;
+ var w = image.bitmap.width;
+ var h = image.bitmap.height;
+ var origRatio = w / h;
+ var desiredRatio = data.width && data.height ? data.width / data.height : origRatio;
+ var x = 0;
+ var y = 0;
+ var crop;
if (origRatio !== desiredRatio) {
if (desiredRatio > origRatio) {
@@ -47,7 +47,7 @@ image.resizeImage = function (data, callback) {
crop = async.apply(image.crop.bind(image), x, y, h * desiredRatio, h);
} else {
x = 0; // width is the smaller dimension here
- y = Math.floor(h / 2 - (w * desiredRatio / 2));
+ y = Math.floor((h / 2) - (w * desiredRatio / 2));
crop = async.apply(image.crop.bind(image), x, y, w, w * desiredRatio);
}
} else {
@@ -71,7 +71,7 @@ image.resizeImage = function (data, callback) {
},
function (image, next) {
image.write(data.target || data.path, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -83,7 +83,7 @@ image.normalise = function (path, extension, callback) {
if (plugins.hasListeners('filter:image.normalise')) {
plugins.fireHook('filter:image.normalise', {
path: path,
- extension: extension
+ extension: extension,
}, function (err) {
callback(err, path + '.png');
});
@@ -138,8 +138,8 @@ image.writeImageDataToTempFile = function (imageData, callback) {
var buffer = new Buffer(imageData.slice(imageData.indexOf('base64') + 7), 'base64');
fs.writeFile(filepath, buffer, {
- encoding: 'base64'
+ encoding: 'base64',
}, function (err) {
callback(err, filepath);
});
-};
\ No newline at end of file
+};
diff --git a/src/install.js b/src/install.js
index c5ae1e214b..a06a138f26 100644
--- a/src/install.js
+++ b/src/install.js
@@ -15,7 +15,7 @@ questions.main = [
{
name: 'url',
description: 'URL used to access this NodeBB',
- 'default':
+ default:
nconf.get('url') ||
(nconf.get('base_url') ? (nconf.get('base_url') + (nconf.get('use_port') ? ':' + nconf.get('port') : '')) : null) || // backwards compatibility (remove for v0.7.0)
'http://localhost:4567',
@@ -25,20 +25,20 @@ questions.main = [
{
name: 'secret',
description: 'Please enter a NodeBB secret',
- 'default': nconf.get('secret') || utils.generateUUID()
+ default: nconf.get('secret') || utils.generateUUID(),
},
{
name: 'database',
description: 'Which database to use',
- 'default': nconf.get('database') || 'mongo'
- }
+ default: nconf.get('database') || 'mongo',
+ },
];
questions.optional = [
{
name: 'port',
- default: nconf.get('port') || 4567
- }
+ default: nconf.get('port') || 4567,
+ },
];
function checkSetupFlag(next) {
@@ -75,7 +75,7 @@ function checkSetupFlag(next) {
}
} else if (nconf.get('database')) {
install.values = {
- database: nconf.get('database')
+ database: nconf.get('database'),
};
next();
} else {
@@ -133,7 +133,7 @@ function setupConfig(next) {
var allQuestions = questions.main.concat(questions.optional).concat(redisQuestions).concat(mongoQuestions);
allQuestions.forEach(function (question) {
- config[question.name] = install.values[question.name] || question['default'] || undefined;
+ config[question.name] = install.values[question.name] || question.default || undefined;
});
setImmediate(next, null, config);
} else {
@@ -145,7 +145,7 @@ function setupConfig(next) {
},
function (config, next) {
completeConfigSetup(config, next);
- }
+ },
], next);
}
@@ -153,7 +153,7 @@ function completeConfigSetup(config, next) {
// Add CI object
if (install.ciVals) {
config.test_database = {};
- for(var prop in install.ciVals) {
+ for (var prop in install.ciVals) {
if (install.ciVals.hasOwnProperty(prop)) {
config.test_database[prop] = install.ciVals[prop];
}
@@ -169,7 +169,7 @@ function completeConfigSetup(config, next) {
},
function (next) {
require('./database').createIndices(next);
- }
+ },
], next);
}
@@ -199,7 +199,7 @@ function enableDefaultTheme(next) {
process.stdout.write('Enabling default theme: ' + defaultTheme + '\n');
meta.themes.set({
type: 'local',
- id: defaultTheme
+ id: defaultTheme,
}, next);
});
}
@@ -228,84 +228,84 @@ function createAdmin(callback) {
winston.warn('No administrators have been detected, running initial user setup\n');
var questions = [{
- name: 'username',
- description: 'Administrator username',
- required: true,
- type: 'string'
- }, {
- name: 'email',
- description: 'Administrator email address',
- pattern: /.+@.+/,
- required: true
- }],
- passwordQuestions = [{
- name: 'password',
- description: 'Password',
- required: true,
- hidden: true,
- type: 'string'
- }, {
- name: 'password:confirm',
- description: 'Confirm Password',
- required: true,
- hidden: true,
- type: 'string'
- }],
- success = function (err, results) {
+ name: 'username',
+ description: 'Administrator username',
+ required: true,
+ type: 'string',
+ }, {
+ name: 'email',
+ description: 'Administrator email address',
+ pattern: /.+@.+/,
+ required: true,
+ }];
+ var passwordQuestions = [{
+ name: 'password',
+ description: 'Password',
+ required: true,
+ hidden: true,
+ type: 'string',
+ }, {
+ name: 'password:confirm',
+ description: 'Confirm Password',
+ required: true,
+ hidden: true,
+ type: 'string',
+ }];
+ function success(err, results) {
+ if (err) {
+ return callback(err);
+ }
+ if (!results) {
+ return callback(new Error('aborted'));
+ }
+
+ if (results['password:confirm'] !== results.password) {
+ winston.warn('Passwords did not match, please try again');
+ return retryPassword(results);
+ }
+
+ if (results.password.length < meta.config.minimumPasswordLength) {
+ winston.warn('Password too short, please try again');
+ return retryPassword(results);
+ }
+
+ var adminUid;
+ async.waterfall([
+ function (next) {
+ User.create({ username: results.username, password: results.password, email: results.email }, next);
+ },
+ function (uid, next) {
+ adminUid = uid;
+ Groups.join('administrators', uid, next);
+ },
+ function (next) {
+ Groups.show('administrators', next);
+ },
+ function (next) {
+ Groups.ownership.grant(adminUid, 'administrators', next);
+ },
+ ], function (err) {
if (err) {
return callback(err);
}
+ callback(null, password ? results : undefined);
+ });
+ }
+ function retryPassword(originalResults) {
+ // Ask only the password questions
+ prompt.get(passwordQuestions, function (err, results) {
if (!results) {
return callback(new Error('aborted'));
}
- if (results['password:confirm'] !== results.password) {
- winston.warn("Passwords did not match, please try again");
- return retryPassword(results);
- }
-
- if (results.password.length < meta.config.minimumPasswordLength) {
- winston.warn("Password too short, please try again");
- return retryPassword(results);
- }
-
- var adminUid;
- async.waterfall([
- function (next) {
- User.create({username: results.username, password: results.password, email: results.email}, next);
- },
- function (uid, next) {
- adminUid = uid;
- Groups.join('administrators', uid, next);
- },
- function (next) {
- Groups.show('administrators', next);
- },
- function (next) {
- Groups.ownership.grant(adminUid, 'administrators', next);
- }
- ], function (err) {
- if (err) {
- return callback(err);
- }
- callback(null, password ? results : undefined);
- });
- },
- retryPassword = function (originalResults) {
- // Ask only the password questions
- prompt.get(passwordQuestions, function (err, results) {
- if (!results) {
- return callback(new Error('aborted'));
- }
+ // Update the original data with newly collected password
+ originalResults.password = results.password;
+ originalResults['password:confirm'] = results['password:confirm'];
- // Update the original data with newly collected password
- originalResults.password = results.password;
- originalResults['password:confirm'] = results['password:confirm'];
-
- // Send back to success to handle
- success(err, originalResults);
- });
- };
+ // Send back to success to handle
+ success(err, originalResults);
+ });
+ }
// Add the password questions
questions = questions.concat(passwordQuestions);
@@ -323,7 +323,7 @@ function createAdmin(callback) {
username: install.values['admin:username'] || nconf.get('admin:username') || 'admin',
email: install.values['admin:email'] || nconf.get('admin:email') || '',
password: install.values['admin:password'] || nconf.get('admin:password') || password,
- 'password:confirm': install.values['admin:password:confirm'] || nconf.get('admin:password') || password
+ 'password:confirm': install.values['admin:password:confirm'] || nconf.get('admin:password') || password,
};
success(null, results);
@@ -347,12 +347,12 @@ function createGlobalModeratorsGroup(next) {
description: 'Forum wide moderators',
hidden: 0,
private: 1,
- disableJoinRequests: 1
+ disableJoinRequests: 1,
}, next);
},
function (groupData, next) {
groups.show('Global Moderators', next);
- }
+ },
], next);
}
@@ -397,8 +397,8 @@ function createMenuItems(next) {
}
function createWelcomePost(next) {
- var db = require('./database'),
- Topics = require('./topics');
+ var db = require('./database');
+ var Topics = require('./topics');
async.parallel([
function (next) {
@@ -406,14 +406,14 @@ function createWelcomePost(next) {
},
function (next) {
db.getObjectField('global', 'topicCount', next);
- }
+ },
], function (err, results) {
if (err) {
return next(err);
}
- var content = results[0],
- numTopics = results[1];
+ var content = results[0];
+ var numTopics = results[1];
if (!parseInt(numTopics, 10)) {
process.stdout.write('Creating welcome post!\n');
@@ -421,7 +421,7 @@ function createWelcomePost(next) {
uid: 1,
cid: 2,
title: 'Welcome to your NodeBB!',
- content: content.toString()
+ content: content.toString(),
}, next);
} else {
next();
@@ -430,20 +430,19 @@ function createWelcomePost(next) {
}
function enableDefaultPlugins(next) {
-
process.stdout.write('Enabling default plugins\n');
var defaultEnabled = [
- 'nodebb-plugin-composer-default',
- 'nodebb-plugin-markdown',
- 'nodebb-plugin-mentions',
- 'nodebb-widget-essentials',
- 'nodebb-rewards-essentials',
- 'nodebb-plugin-soundpack-default',
- 'nodebb-plugin-emoji-extended',
- 'nodebb-plugin-emoji-one'
- ],
- customDefaults = nconf.get('defaultPlugins');
+ 'nodebb-plugin-composer-default',
+ 'nodebb-plugin-markdown',
+ 'nodebb-plugin-mentions',
+ 'nodebb-widget-essentials',
+ 'nodebb-rewards-essentials',
+ 'nodebb-plugin-soundpack-default',
+ 'nodebb-plugin-emoji-extended',
+ 'nodebb-plugin-emoji-one',
+ ];
+ var customDefaults = nconf.get('defaultPlugins');
winston.info('[install/defaultPlugins] customDefaults', customDefaults);
@@ -478,7 +477,7 @@ function setCopyrightWidget(next) {
},
footer: function (next) {
db.getObjectField('widgets:global', 'footer', next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -493,7 +492,6 @@ function setCopyrightWidget(next) {
}
install.setup = function (callback) {
-
async.series([
checkSetupFlag,
checkCIFlag,
@@ -513,10 +511,13 @@ install.setup = function (callback) {
if (err) {
return next(err);
}
- if (!uptodate) { upgrade.upgrade(next); }
- else { next(); }
+ if (!uptodate) {
+ upgrade.upgrade(next);
+ } else {
+ next();
+ }
});
- }
+ },
], function (err, results) {
if (err) {
winston.warn('NodeBB Setup Aborted.\n ' + err.stack);
@@ -549,7 +550,7 @@ install.save = function (server_conf, callback) {
process.stdout.write('Configuration Saved OK\n');
nconf.file({
- file: path.join(__dirname, '..', 'config.json')
+ file: path.join(__dirname, '..', 'config.json'),
});
callback();
diff --git a/src/logger.js b/src/logger.js
index 4d6b8f717c..73180d7add 100644
--- a/src/logger.js
+++ b/src/logger.js
@@ -4,35 +4,33 @@
* Logger module: ability to dynamically turn on/off logging for http requests & socket.io events
*/
-var fs = require('fs'),
- path = require('path'),
- winston = require('winston'),
- util = require('util'),
+var fs = require('fs');
+var path = require('path');
+var winston = require('winston');
+var util = require('util');
- file = require('./file'),
- meta = require('./meta'),
- morgan = require('morgan');
+var file = require('./file');
+var meta = require('./meta');
+var morgan = require('morgan');
var opts = {
/*
* state used by Logger
*/
- express : {
- app : {},
- set : 0,
- ofn : null,
+ express: {
+ app: {},
+ set: 0,
+ ofn: null,
+ },
+ streams: {
+ log: { f: process.stdout },
},
- streams : {
- log : { f : process.stdout },
- }
};
/* -- Logger -- */
(function (Logger) {
-
-
Logger.init = function (app) {
opts.express.app = app;
/* Open log file stream & initialize express logging if meta.config.logger* variables are set */
@@ -59,15 +57,14 @@ var opts = {
* If logging is currently enabled, create a stream.
* Otherwise, close the current stream
*/
- if(meta.config.loggerStatus > 0 || meta.config.loggerIOStatus) {
+ if (meta.config.loggerStatus > 0 || meta.config.loggerIOStatus) {
var stream = Logger.open(value);
- if(stream) {
+ if (stream) {
opts.streams.log.f = stream;
} else {
opts.streams.log.f = process.stdout;
}
- }
- else {
+ } else {
Logger.close(opts.streams.log);
}
};
@@ -75,22 +72,21 @@ var opts = {
Logger.open = function (value) {
/* Open the streams to log to: either a path or stdout */
var stream;
- if(value) {
- if(file.existsSync(value)) {
+ if (value) {
+ if (file.existsSync(value)) {
var stats = fs.statSync(value);
- if(stats) {
- if(stats.isDirectory()) {
- stream = fs.createWriteStream(path.join(value, 'nodebb.log'), {flags: 'a'});
+ if (stats) {
+ if (stats.isDirectory()) {
+ stream = fs.createWriteStream(path.join(value, 'nodebb.log'), { flags: 'a' });
} else {
- stream = fs.createWriteStream(value, {flags: 'a'});
+ stream = fs.createWriteStream(value, { flags: 'a' });
}
}
} else {
- stream = fs.createWriteStream(value, {flags: 'a'});
-
+ stream = fs.createWriteStream(value, { flags: 'a' });
}
- if(stream) {
+ if (stream) {
stream.on('error', function (err) {
winston.error(err.message);
});
@@ -102,7 +98,7 @@ var opts = {
};
Logger.close = function (stream) {
- if(stream.f !== process.stdout && stream.f) {
+ if (stream.f !== process.stdout && stream.f) {
stream.end();
}
stream.f = null;
@@ -112,33 +108,32 @@ var opts = {
/*
* This monitor's when a user clicks "save" in the Logger section of the admin panel
*/
- Logger.setup_one(data.key,data.value);
+ Logger.setup_one(data.key, data.value);
Logger.io_close(socket);
Logger.io(socket);
};
Logger.express_open = function () {
- if(opts.express.set !== 1) {
+ if (opts.express.set !== 1) {
opts.express.set = 1;
opts.express.app.use(Logger.expressLogger);
}
/*
* Always initialize "ofn" (original function) with the original logger function
*/
- opts.express.ofn = morgan('combined', {stream : opts.streams.log.f});
+ opts.express.ofn = morgan('combined', { stream: opts.streams.log.f });
};
- Logger.expressLogger = function (req,res,next) {
+ Logger.expressLogger = function (req, res, next) {
/*
* The new express.logger
*
* This hijack allows us to turn logger on/off dynamically within express
*/
- if(meta.config.loggerStatus > 0) {
- return opts.express.ofn(req,res,next);
- } else {
- return next();
+ if (meta.config.loggerStatus > 0) {
+ return opts.express.ofn(req, res, next);
}
+ return next();
};
Logger.prepare_io_string = function (_type, _uid, _args) {
@@ -149,9 +144,9 @@ var opts = {
*/
try {
return 'io: ' + _uid + ' ' + _type + ' ' + util.inspect(Array.prototype.slice.call(_args)) + '\n';
- } catch(err) {
- winston.info("Logger.prepare_io_string: Failed", err);
- return "error";
+ } catch (err) {
+ winston.info('Logger.prepare_io_string: Failed', err);
+ return 'error';
}
};
@@ -166,11 +161,11 @@ var opts = {
for (var sid in clients) {
if (clients.hasOwnProperty(sid)) {
var client = clients[sid];
- if(client.oEmit && client.oEmit !== client.emit) {
+ if (client.oEmit && client.oEmit !== client.emit) {
client.emit = client.oEmit;
}
- if(client.$oEmit && client.$oEmit !== client.$emit) {
+ if (client.$oEmit && client.$oEmit !== client.$emit) {
client.$emit = client.$oEmit;
}
}
@@ -187,7 +182,7 @@ var opts = {
}
var clients = socket.io.sockets.sockets;
- for(var sid in clients) {
+ for (var sid in clients) {
if (clients.hasOwnProperty(sid)) {
Logger.io_one(clients[sid], clients[sid].uid);
}
@@ -200,13 +195,13 @@ var opts = {
*/
function override(method, name, errorMsg) {
return function () {
- if(opts.streams.log.f) {
+ if (opts.streams.log.f) {
opts.streams.log.f.write(Logger.prepare_io_string(name, uid, arguments));
}
try {
method.apply(socket, arguments);
- } catch(err) {
+ } catch (err) {
winston.info(errorMsg, err);
}
};
@@ -223,5 +218,4 @@ var opts = {
socket.$emit = override($emit, 'on', 'Logger.io_one: $emit.apply: Failed');
}
};
-
}(exports));
diff --git a/src/messaging.js b/src/messaging.js
index a37503e3e3..e141adff4f 100644
--- a/src/messaging.js
+++ b/src/messaging.js
@@ -57,7 +57,7 @@ Messaging.getMessages = function (params, callback) {
messageData.index = indices[messageData.messageId.toString()];
});
next(null, messageData);
- }
+ },
], callback);
};
@@ -65,7 +65,7 @@ function canGet(hook, callerUid, uid, callback) {
plugins.fireHook(hook, {
callerUid: callerUid,
uid: uid,
- canGet: parseInt(callerUid, 10) === parseInt(uid, 10)
+ canGet: parseInt(callerUid, 10) === parseInt(uid, 10),
}, function (err, data) {
callback(err, data ? data.canGet : false);
});
@@ -84,7 +84,7 @@ Messaging.parse = function (message, fromuid, uid, roomId, isNew, callback) {
uid: uid,
roomId: roomId,
isNew: isNew,
- parsedMessage: parsed
+ parsedMessage: parsed,
};
plugins.fireHook('filter:messaging.parse', messageData, function (err, messageData) {
@@ -106,7 +106,7 @@ Messaging.isNewSet = function (uid, roomId, timestamp, callback) {
} else {
next(null, true);
}
- }
+ },
], callback);
};
@@ -139,7 +139,7 @@ Messaging.getRecentChats = function (callerUid, uid, start, stop, callback) {
uids = uids.filter(function (value) {
return value && parseInt(value, 10) !== parseInt(uid, 10);
});
- user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture', 'status', 'lastonline'] , next);
+ user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture', 'status', 'lastonline'], next);
});
}, next);
},
@@ -147,7 +147,7 @@ Messaging.getRecentChats = function (callerUid, uid, start, stop, callback) {
async.map(roomIds, function (roomId, next) {
Messaging.getTeaser(uid, roomId, next);
}, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -170,8 +170,8 @@ Messaging.getRecentChats = function (callerUid, uid, start, stop, callback) {
room.usernames = Messaging.generateUsernames(room.users, uid);
});
- next(null, {rooms: results.roomData, nextStart: stop + 1});
- }
+ next(null, { rooms: results.roomData, nextStart: stop + 1 });
+ },
], callback);
};
@@ -206,19 +206,19 @@ Messaging.getTeaser = function (uid, roomId, callback) {
}
teaser.timestampISO = utils.toISOString(teaser.timestamp);
- user.getUserFields(teaser.fromuid, ['uid', 'username', 'userslug', 'picture', 'status', 'lastonline'] , next);
+ user.getUserFields(teaser.fromuid, ['uid', 'username', 'userslug', 'picture', 'status', 'lastonline'], next);
},
function (user, next) {
teaser.user = user;
plugins.fireHook('filter:messaging.getTeaser', { teaser: teaser }, function (err, data) {
next(err, data.teaser);
});
- }
+ },
], callback);
};
Messaging.canMessageUser = function (uid, toUid, callback) {
- if (parseInt(meta.config.disableChat) === 1 || !uid || uid === toUid) {
+ if (parseInt(meta.config.disableChat, 10) === 1 || !uid || uid === toUid) {
return callback(new Error('[[error:chat-disabled]]'));
}
@@ -248,7 +248,7 @@ Messaging.canMessageUser = function (uid, toUid, callback) {
async.parallel({
settings: async.apply(user.getSettings, toUid),
isAdmin: async.apply(user.isAdministrator, uid),
- isFollowing: async.apply(user.isFollowing, toUid, uid)
+ isFollowing: async.apply(user.isFollowing, toUid, uid),
}, next);
},
function (results, next) {
@@ -256,13 +256,13 @@ Messaging.canMessageUser = function (uid, toUid, callback) {
return next();
}
- next(new Error('[[error:chat-restricted]]'));
- }
+ next(new Error('[[error:chat-restricted]]'));
+ },
], callback);
};
Messaging.canMessageRoom = function (uid, roomId, callback) {
- if (parseInt(meta.config.disableChat) === 1 || !uid) {
+ if (parseInt(meta.config.disableChat, 10) === 1 || !uid) {
return callback(new Error('[[error:chat-disabled]]'));
}
@@ -294,7 +294,7 @@ Messaging.canMessageRoom = function (uid, roomId, callback) {
}
next();
- }
+ },
], callback);
};
@@ -306,7 +306,7 @@ Messaging.hasPrivateChat = function (uid, withUid, callback) {
function (next) {
async.parallel({
myRooms: async.apply(db.getSortedSetRevRange, 'uid:' + uid + ':chat:rooms', 0, -1),
- theirRooms: async.apply(db.getSortedSetRevRange, 'uid:' + withUid + ':chat:rooms', 0, -1)
+ theirRooms: async.apply(db.getSortedSetRevRange, 'uid:' + withUid + ':chat:rooms', 0, -1),
}, next);
},
function (results, next) {
@@ -331,13 +331,13 @@ Messaging.hasPrivateChat = function (uid, withUid, callback) {
roomId = roomIds[index];
next(null, roomId);
} else {
- ++ index;
+ index += 1;
next();
}
});
}, function (err) {
next(err, roomId);
});
- }
+ },
], callback);
};
diff --git a/src/messaging/create.js b/src/messaging/create.js
index face15f589..2c6ac84ffb 100644
--- a/src/messaging/create.js
+++ b/src/messaging/create.js
@@ -8,7 +8,6 @@ var db = require('../database');
module.exports = function (Messaging) {
-
Messaging.sendMessage = function (uid, roomId, content, timestamp, callback) {
async.waterfall([
function (next) {
@@ -23,7 +22,7 @@ module.exports = function (Messaging) {
}
Messaging.addMessage(uid, roomId, content, timestamp, next);
- }
+ },
], callback);
};
@@ -56,7 +55,7 @@ module.exports = function (Messaging) {
content: content,
timestamp: timestamp,
fromuid: fromuid,
- roomId: roomId
+ roomId: roomId,
};
plugins.fireHook('filter:messaging.save', message, next);
@@ -76,13 +75,13 @@ module.exports = function (Messaging) {
async.apply(Messaging.addRoomToUsers, roomId, uids, timestamp),
async.apply(Messaging.addMessageToUsers, roomId, uids, mid, timestamp),
async.apply(Messaging.markUnread, uids, roomId),
- async.apply(Messaging.addUsersToRoom, fromuid, [fromuid], roomId)
+ async.apply(Messaging.addUsersToRoom, fromuid, [fromuid], roomId),
], next);
},
function (results, next) {
async.parallel({
markRead: async.apply(Messaging.markRead, fromuid, roomId),
- messages: async.apply(Messaging.getMessagesData, [mid], fromuid, roomId, true)
+ messages: async.apply(Messaging.getMessagesData, [mid], fromuid, roomId, true),
}, next);
},
function (results, next) {
@@ -94,7 +93,7 @@ module.exports = function (Messaging) {
results.messages[0].mid = mid;
results.messages[0].roomId = roomId;
next(null, results.messages[0]);
- }
+ },
], callback);
};
@@ -117,4 +116,4 @@ module.exports = function (Messaging) {
});
db.sortedSetsAdd(keys, timestamp, mid, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/messaging/data.js b/src/messaging/data.js
index d1a00bd8f4..e3cb67fbd8 100644
--- a/src/messaging/data.js
+++ b/src/messaging/data.js
@@ -8,7 +8,6 @@ var user = require('../user');
var utils = require('../../public/src/utils');
module.exports = function (Messaging) {
-
Messaging.getMessageField = function (mid, field, callback) {
Messaging.getMessageFields(mid, [field], function (err, fields) {
callback(err, fields ? fields[field] : null);
@@ -28,7 +27,6 @@ module.exports = function (Messaging) {
};
Messaging.getMessagesData = function (mids, uid, roomId, isNew, callback) {
-
var messages;
async.waterfall([
@@ -110,7 +108,7 @@ module.exports = function (Messaging) {
},
function (mid, next) {
Messaging.getMessageFields(mid, ['fromuid', 'timestamp'], next);
- }
+ },
], function (err, fields) {
if (err) {
return next(err);
@@ -129,8 +127,7 @@ module.exports = function (Messaging) {
} else {
next(null, []);
}
- }
+ },
], callback);
};
-
};
diff --git a/src/messaging/delete.js b/src/messaging/delete.js
index e9f48232d1..6fdf5177ef 100644
--- a/src/messaging/delete.js
+++ b/src/messaging/delete.js
@@ -4,7 +4,6 @@ var async = require('async');
var db = require('../database');
module.exports = function (Messaging) {
-
Messaging.deleteMessage = function (mid, roomId, callback) {
async.waterfall([
function (next) {
@@ -21,7 +20,7 @@ module.exports = function (Messaging) {
},
function (next) {
db.delete('message:' + mid, next);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/messaging/edit.js b/src/messaging/edit.js
index b472aea261..f9c664d67f 100644
--- a/src/messaging/edit.js
+++ b/src/messaging/edit.js
@@ -9,7 +9,6 @@ var sockets = require('../socket.io');
module.exports = function (Messaging) {
-
Messaging.editMessage = function (uid, mid, roomId, content, callback) {
var uids;
async.waterfall([
@@ -23,7 +22,7 @@ module.exports = function (Messaging) {
Messaging.setMessageFields(mid, {
content: content,
- edited: Date.now()
+ edited: Date.now(),
}, next);
},
function (next) {
@@ -36,11 +35,11 @@ module.exports = function (Messaging) {
function (messages, next) {
uids.forEach(function (uid) {
sockets.in('uid_' + uid).emit('event:chats.edit', {
- messages: messages
+ messages: messages,
});
});
next();
- }
+ },
], callback);
};
@@ -75,8 +74,7 @@ module.exports = function (Messaging) {
},
function (isAdmin, next) {
next(null, isAdmin);
- }
+ },
], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/messaging/notifications.js b/src/messaging/notifications.js
index 2eeb562b5c..eb7a1a1a74 100644
--- a/src/messaging/notifications.js
+++ b/src/messaging/notifications.js
@@ -11,7 +11,6 @@ var meta = require('../meta');
var sockets = require('../socket.io');
module.exports = function (Messaging) {
-
Messaging.notifyQueue = {}; // Only used to notify a user of a new chat message, see Messaging.notifyUser
Messaging.notificationSendDelay = 1000 * 60;
@@ -25,11 +24,11 @@ module.exports = function (Messaging) {
var data = {
roomId: roomId,
fromUid: fromUid,
- message: messageObj
+ message: messageObj,
};
uids.forEach(function (uid) {
- data.self = parseInt(uid, 10) === parseInt(fromUid) ? 1 : 0;
+ data.self = parseInt(uid, 10) === parseInt(fromUid, 10) ? 1 : 0;
Messaging.pushUnreadCount(uid);
sockets.in('uid_' + uid).emit('event:chats.receive', data);
});
@@ -40,16 +39,17 @@ module.exports = function (Messaging) {
queueObj.message.content += '\n' + messageObj.content;
clearTimeout(queueObj.timeout);
} else {
- queueObj = Messaging.notifyQueue[fromUid + ':' + roomId] = {
- message: messageObj
+ queueObj = {
+ message: messageObj,
};
+ Messaging.notifyQueue[fromUid + ':' + roomId] = queueObj;
}
queueObj.timeout = setTimeout(function () {
sendNotifications(fromUid, uids, roomId, queueObj.message);
}, Messaging.notificationSendDelay);
next();
- }
+ },
]);
};
@@ -72,9 +72,9 @@ module.exports = function (Messaging) {
bodyLong: messageObj.content,
nid: 'chat_' + fromuid + '_' + roomId,
from: fromuid,
- path: '/chats/' + messageObj.roomId
+ path: '/chats/' + messageObj.roomId,
}, next);
- }
+ },
], function (err, notification) {
if (!err) {
delete Messaging.notifyQueue[fromuid + ':' + roomId];
@@ -99,9 +99,10 @@ module.exports = function (Messaging) {
},
userSettings: function (next) {
user.getMultipleUserSettings(uids, next);
- }
+ },
}, next);
},
+
function (results, next) {
results.userData = results.userData.filter(function (userData, index) {
return userData && results.userSettings[index] && results.userSettings[index].sendChatNotifications;
@@ -115,14 +116,14 @@ module.exports = function (Messaging) {
url: nconf.get('url'),
roomId: messageObj.roomId,
username: userData.username,
- userslug: userData.userslug
+ userslug: userData.userslug,
}, next);
}, next);
- }
+ },
], function (err) {
if (err) {
return winston.error(err);
}
});
}
-};
\ No newline at end of file
+};
diff --git a/src/messaging/rooms.js b/src/messaging/rooms.js
index bea909946a..ead62fee4d 100644
--- a/src/messaging/rooms.js
+++ b/src/messaging/rooms.js
@@ -8,7 +8,6 @@ var user = require('../user');
var plugins = require('../plugins');
module.exports = function (Messaging) {
-
Messaging.getRoomData = function (roomId, callback) {
db.getObject('chat:room:' + roomId, function (err, data) {
if (err || !data) {
@@ -55,7 +54,7 @@ module.exports = function (Messaging) {
roomId = _roomId;
var room = {
owner: uid,
- roomId: roomId
+ roomId: roomId,
};
db.setObject('chat:room:' + roomId, room, next);
},
@@ -70,7 +69,7 @@ module.exports = function (Messaging) {
},
function (next) {
next(null, roomId);
- }
+ },
], callback);
};
@@ -80,11 +79,11 @@ module.exports = function (Messaging) {
db.isSortedSetMember('chat:room:' + roomId + ':uids', uid, next);
},
function (inRoom, next) {
- plugins.fireHook('filter:messaging.isUserInRoom', {uid: uid, roomId: roomId, inRoom: inRoom}, next);
+ plugins.fireHook('filter:messaging.isUserInRoom', { uid: uid, roomId: roomId, inRoom: inRoom }, next);
},
function (data, next) {
next(null, data.inRoom);
- }
+ },
], callback);
};
@@ -124,7 +123,7 @@ module.exports = function (Messaging) {
function (next) {
async.parallel({
userCount: async.apply(db.sortedSetCard, 'chat:room:' + roomId + ':uids'),
- roomData: async.apply(db.getObject, 'chat:room:' + roomId)
+ roomData: async.apply(db.getObject, 'chat:room:' + roomId),
}, next);
},
function (results, next) {
@@ -132,7 +131,7 @@ module.exports = function (Messaging) {
return db.setObjectField('chat:room:' + roomId, 'groupChat', 1, next);
}
next();
- }
+ },
], callback);
};
@@ -141,7 +140,7 @@ module.exports = function (Messaging) {
function (next) {
async.parallel({
isOwner: async.apply(Messaging.isRoomOwner, uid, roomId),
- userCount: async.apply(Messaging.getUserCountInRoom, roomId)
+ userCount: async.apply(Messaging.getUserCountInRoom, roomId),
}, next);
},
function (results, next) {
@@ -152,7 +151,7 @@ module.exports = function (Messaging) {
return next(new Error('[[error:cant-remove-last-user]]'));
}
Messaging.leaveRoom(uids, roomId, next);
- }
+ },
], callback);
};
@@ -169,7 +168,7 @@ module.exports = function (Messaging) {
return 'uid:' + uid + ':chat:rooms:unread';
}));
db.sortedSetsRemove(keys, roomId, next);
- }
+ },
], callback);
};
@@ -184,7 +183,7 @@ module.exports = function (Messaging) {
},
function (uids, next) {
user.getUsersFields(uids, ['uid', 'username', 'picture', 'status'], next);
- }
+ },
], callback);
};
@@ -205,7 +204,7 @@ module.exports = function (Messaging) {
return next(new Error('[[error:no-privileges]]'));
}
db.setObjectField('chat:room:' + roomId, 'roomName', newName, next);
- }
+ },
], callback);
};
@@ -215,12 +214,11 @@ module.exports = function (Messaging) {
db.isSortedSetMember('chat:room:' + roomId + ':uids', uid, next);
},
function (inRoom, next) {
- plugins.fireHook('filter:messaging.canReply', {uid: uid, roomId: roomId, inRoom: inRoom, canReply: inRoom}, next);
+ plugins.fireHook('filter:messaging.canReply', { uid: uid, roomId: roomId, inRoom: inRoom, canReply: inRoom }, next);
},
function (data, next) {
next(null, data.canReply);
- }
+ },
], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/messaging/unread.js b/src/messaging/unread.js
index 91c9a364ac..660eece5ce 100644
--- a/src/messaging/unread.js
+++ b/src/messaging/unread.js
@@ -6,7 +6,6 @@ var db = require('../database');
var sockets = require('../socket.io');
module.exports = function (Messaging) {
-
Messaging.getUnreadCount = function (uid, callback) {
if (!parseInt(uid, 10)) {
return callback(null, 0);
@@ -16,7 +15,7 @@ module.exports = function (Messaging) {
Messaging.pushUnreadCount = function (uid) {
if (!parseInt(uid, 10)) {
- return callback(null, 0);
+ return;
}
Messaging.getUnreadCount(uid, function (err, unreadCount) {
if (err) {
@@ -48,8 +47,7 @@ module.exports = function (Messaging) {
});
db.sortedSetsAdd(keys, Date.now(), roomId, next);
- }
+ },
], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/meta.js b/src/meta.js
index 2333e54d89..6cbccd70a1 100644
--- a/src/meta.js
+++ b/src/meta.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var winston = require('winston');
@@ -32,7 +32,7 @@ var utils = require('../public/src/utils');
slug = utils.slugify(slug);
async.parallel([
async.apply(user.existsBySlug, slug),
- async.apply(groups.existsBySlug, slug)
+ async.apply(groups.existsBySlug, slug),
], function (err, results) {
callback(err, results ? results.some(function (result) { return result; }) : false);
});
@@ -47,7 +47,7 @@ var utils = require('../public/src/utils');
};
Meta.restart = function () {
- pubsub.publish('meta:restart', {hostname: os.hostname()});
+ pubsub.publish('meta:restart', { hostname: os.hostname() });
restart();
};
@@ -62,7 +62,7 @@ var utils = require('../public/src/utils');
function restart() {
if (process.send) {
process.send({
- action: 'restart'
+ action: 'restart',
});
} else {
winston.error('[meta.restart] Could not restart, are you sure NodeBB was started with `./nodebb start`?');
diff --git a/src/meta/blacklist.js b/src/meta/blacklist.js
index a078b89815..31ce06af8c 100644
--- a/src/meta/blacklist.js
+++ b/src/meta/blacklist.js
@@ -8,14 +8,14 @@ var db = require('../database');
var pubsub = require('../pubsub');
var Blacklist = {
- _rules: []
+ _rules: [],
};
Blacklist.load = function (callback) {
callback = callback || function () {};
async.waterfall([
- async.apply(Blacklist.get),
- async.apply(Blacklist.validate)
+ Blacklist.get,
+ Blacklist.validate,
], function (err, rules) {
if (err) {
return callback(err);
@@ -29,7 +29,7 @@ Blacklist.load = function (callback) {
Blacklist._rules = {
ipv4: rules.ipv4,
ipv6: rules.ipv6,
- cidr: rules.cidr
+ cidr: rules.cidr,
};
callback();
@@ -46,7 +46,7 @@ Blacklist.save = function (rules, callback) {
function (next) {
Blacklist.load(next);
pubsub.publish('blacklist:reload');
- }
+ },
], callback);
};
@@ -107,18 +107,18 @@ Blacklist.validate = function (rules, callback) {
if (ip.isV4Format(rule)) {
ipv4.push(rule);
return true;
- } else if (ip.isV6Format(rule)) {
+ }
+ if (ip.isV6Format(rule)) {
ipv6.push(rule);
return true;
- } else if (isCidrSubnet.test(rule)) {
+ }
+ if (isCidrSubnet.test(rule)) {
cidr.push(rule);
return true;
- } else {
- invalid.push(rule);
- return false;
}
- return true;
+ invalid.push(rule);
+ return false;
});
callback(null, {
@@ -127,8 +127,8 @@ Blacklist.validate = function (rules, callback) {
ipv6: ipv6,
cidr: cidr,
valid: rules,
- invalid: invalid
+ invalid: invalid,
});
};
-module.exports = Blacklist;
\ No newline at end of file
+module.exports = Blacklist;
diff --git a/src/meta/build.js b/src/meta/build.js
index 29cfbc45be..9ba5ec89bf 100644
--- a/src/meta/build.js
+++ b/src/meta/build.js
@@ -31,7 +31,7 @@ exports.build = function build(targets, callback) {
async.series([
async.apply(db.init),
async.apply(meta.themes.setupPaths),
- async.apply(plugins.prepareForBuild)
+ async.apply(plugins.prepareForBuild),
], function (err) {
if (err) {
winston.error('[build] Encountered error preparing for build: ' + err.message);
@@ -52,7 +52,7 @@ exports.buildTargets = function (targets, callback) {
var step = function (startTime, target, next, err) {
if (err) {
- winston.error('Build failed: ' + err.message);
+ winston.error('Build failed: ' + err.stack);
process.exit(1);
}
winston.info('[build] ' + target + ' => Completed in ' + ((Date.now() - startTime) / 1000) + 's');
@@ -74,7 +74,7 @@ exports.buildTargets = function (targets, callback) {
meta.js.buildModules,
meta.js.linkStatics,
async.apply(meta.js.minify, 'nodebb.min.js'),
- async.apply(meta.js.minify, 'acp.min.js')
+ async.apply(meta.js.minify, 'acp.min.js'),
], step.bind(this, startTime, 'js', next));
} else {
setImmediate(next);
@@ -83,47 +83,47 @@ exports.buildTargets = function (targets, callback) {
function (next) {
async.eachSeries(targets, function (target, next) {
var startTime;
- switch(target) {
- case 'js':
- setImmediate(next);
- break;
- case 'clientCSS':
- winston.info('[build] Building client-side CSS');
- startTime = Date.now();
- meta.css.minify('client', step.bind(this, startTime, target, next));
- break;
+ switch (target) {
+ case 'js':
+ setImmediate(next);
+ break;
+ case 'clientCSS':
+ winston.info('[build] Building client-side CSS');
+ startTime = Date.now();
+ meta.css.minify('client', step.bind(this, startTime, target, next));
+ break;
- case 'acpCSS':
- winston.info('[build] Building admin control panel CSS');
- startTime = Date.now();
- meta.css.minify('admin', step.bind(this, startTime, target, next));
- break;
+ case 'acpCSS':
+ winston.info('[build] Building admin control panel CSS');
+ startTime = Date.now();
+ meta.css.minify('admin', step.bind(this, startTime, target, next));
+ break;
- case 'tpl':
- winston.info('[build] Building templates');
- startTime = Date.now();
- meta.templates.compile(step.bind(this, startTime, target, next));
- break;
+ case 'tpl':
+ winston.info('[build] Building templates');
+ startTime = Date.now();
+ meta.templates.compile(step.bind(this, startTime, target, next));
+ break;
- case 'lang':
- winston.info('[build] Building language files');
- startTime = Date.now();
- meta.languages.build(step.bind(this, startTime, target, next));
- break;
+ case 'lang':
+ winston.info('[build] Building language files');
+ startTime = Date.now();
+ meta.languages.build(step.bind(this, startTime, target, next));
+ break;
- case 'sound':
- winston.info('[build] Linking sound files');
- startTime = Date.now();
- meta.sounds.build(step.bind(this, startTime, target, next));
- break;
+ case 'sound':
+ winston.info('[build] Linking sound files');
+ startTime = Date.now();
+ meta.sounds.build(step.bind(this, startTime, target, next));
+ break;
- default:
- winston.warn('[build] Unknown build target: \'' + target + '\'');
- setImmediate(next);
- break;
+ default:
+ winston.warn('[build] Unknown build target: \'' + target + '\'');
+ setImmediate(next);
+ break;
}
}, next);
- }
+ },
], function (err) {
if (err) {
winston.error('[build] Encountered error during build step: ' + err.message);
@@ -147,4 +147,4 @@ exports.buildTargets = function (targets, callback) {
}
});
});
-};
\ No newline at end of file
+};
diff --git a/src/meta/configs.js b/src/meta/configs.js
index 907e0ef477..82d8640e4c 100644
--- a/src/meta/configs.js
+++ b/src/meta/configs.js
@@ -9,7 +9,6 @@ var pubsub = require('../pubsub');
var cacheBuster = require('./cacheBuster');
module.exports = function (Meta) {
-
Meta.config = {};
Meta.configs = {};
@@ -25,13 +24,13 @@ module.exports = function (Meta) {
if (err) {
return next(err);
}
-
+
config['cache-buster'] = 'v=' + (buster || Date.now());
Meta.config = config;
next();
});
- }
+ },
], callback);
};
@@ -75,7 +74,7 @@ module.exports = function (Meta) {
function (next) {
updateConfig(data);
setImmediate(next);
- }
+ },
], callback);
};
@@ -91,13 +90,13 @@ module.exports = function (Meta) {
async.waterfall([
function (next) {
less.render(data.customCSS, {
- compress: true
+ compress: true,
}, next);
},
function (lessObject, next) {
data.renderedCustomCSS = lessObject.css;
setImmediate(next);
- }
+ },
], callback);
}
@@ -133,12 +132,11 @@ module.exports = function (Meta) {
} else {
setImmediate(next);
}
- }
+ },
], callback);
};
Meta.configs.remove = function (field, callback) {
db.deleteObjectField('config', field, callback);
};
-
};
diff --git a/src/meta/css.js b/src/meta/css.js
index df613ee39f..33bd0877e0 100644
--- a/src/meta/css.js
+++ b/src/meta/css.js
@@ -16,7 +16,6 @@ var file = require('../file');
var utils = require('../../public/src/utils');
module.exports = function (Meta) {
-
Meta.css = {};
var buildImports = {
@@ -65,7 +64,7 @@ module.exports = function (Meta) {
var paths = [
baseThemePath,
path.join(__dirname, '../../node_modules'),
- path.join(__dirname, '../../public/vendor/fontawesome/less')
+ path.join(__dirname, '../../public/vendor/fontawesome/less'),
];
var source = '';
@@ -83,7 +82,7 @@ module.exports = function (Meta) {
function (src, next) {
source += src;
next();
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -95,8 +94,8 @@ module.exports = function (Meta) {
};
function getStyleSource(files, prefix, extension, callback) {
- var pluginDirectories = [],
- source = '';
+ var pluginDirectories = [];
+ var source = '';
files.forEach(function (styleFile) {
if (styleFile.endsWith(extension)) {
@@ -141,7 +140,7 @@ module.exports = function (Meta) {
function minify(source, paths, target, callback) {
callback = callback || function () {};
less.render(source, {
- paths: paths
+ paths: paths,
}, function (err, lessOutput) {
if (err) {
winston.error('[meta/css] Could not minify LESS/CSS: ' + err.message);
@@ -151,7 +150,7 @@ module.exports = function (Meta) {
postcss(global.env === 'development' ? [autoprefixer] : [
autoprefixer,
clean({
- processImportFrom: ['local']
+ processImportFrom: ['local'],
}),
]).process(lessOutput.css).then(function (result) {
result.warnings().forEach(function (warn) {
diff --git a/src/meta/dependencies.js b/src/meta/dependencies.js
index 3f892c37ab..939f14b674 100644
--- a/src/meta/dependencies.js
+++ b/src/meta/dependencies.js
@@ -5,7 +5,7 @@ var fs = require('fs');
var async = require('async');
var semver = require('semver');
var winston = require('winston');
-var colors = require('colors');
+require('colors');
var pkg = require('../../package.json');
@@ -21,7 +21,7 @@ module.exports = function (Meta) {
async.every(modules, function (module, next) {
fs.readFile(path.join(__dirname, '../../node_modules/', module, 'package.json'), {
- encoding: 'utf-8'
+ encoding: 'utf-8',
}, function (err, pkgData) {
// If a bundled plugin/theme is not present, skip the dep check (#3384)
if (err && err.code === 'ENOENT' && (module === 'nodebb-rewards-essentials' || module.startsWith('nodebb-plugin') || module.startsWith('nodebb-theme'))) {
@@ -31,7 +31,7 @@ module.exports = function (Meta) {
try {
pkgData = JSON.parse(pkgData);
- } catch(e) {
+ } catch (e) {
process.stdout.write('[' + 'missing'.red + '] ' + module.bold + ' is a required dependency but could not be found\n');
depsMissing = true;
return next(true);
@@ -47,7 +47,7 @@ module.exports = function (Meta) {
next(true);
}
});
- }, function (ok) {
+ }, function () {
if (depsMissing) {
callback(new Error('dependencies-missing'));
} else if (depsOutdated) {
diff --git a/src/meta/errors.js b/src/meta/errors.js
index 58e381e270..fb169764ba 100644
--- a/src/meta/errors.js
+++ b/src/meta/errors.js
@@ -1,12 +1,12 @@
'use strict';
+var async = require('async');
var validator = require('validator');
var db = require('../database');
var analytics = require('../analytics');
module.exports = function (Meta) {
-
Meta.errors = {};
Meta.errors.log404 = function (route, callback) {
@@ -17,18 +17,19 @@ module.exports = function (Meta) {
};
Meta.errors.get = function (escape, callback) {
- db.getSortedSetRevRangeWithScores('errors:404', 0, -1, function (err, data) {
- if (err) {
- return callback(err);
- }
+ async.waterfall([
+ function (next) {
+ db.getSortedSetRevRangeWithScores('errors:404', 0, -1, next);
+ },
+ function (data, next) {
+ data = data.map(function (nfObject) {
+ nfObject.value = escape ? validator.escape(String(nfObject.value || '')) : nfObject.value;
+ return nfObject;
+ });
- data = data.map(function (nfObject) {
- nfObject.value = escape ? validator.escape(String(nfObject.value || '')) : nfObject.value;
- return nfObject;
- });
-
- callback(null, data);
- });
+ next(null, data);
+ },
+ ], callback);
};
Meta.errors.clear = function (callback) {
diff --git a/src/meta/js.js b/src/meta/js.js
index 90f757361a..72e41c578f 100644
--- a/src/meta/js.js
+++ b/src/meta/js.js
@@ -16,7 +16,6 @@ var utils = require('../../public/src/utils');
var minifierPath = path.join(__dirname, 'minifier.js');
module.exports = function (Meta) {
-
Meta.js = {
target: {},
scripts: {
@@ -43,7 +42,7 @@ module.exports = function (Meta) {
'public/src/ajaxify.js',
'public/src/overrides.js',
'public/src/widgets.js',
- "./node_modules/promise-polyfill/promise.js"
+ './node_modules/promise-polyfill/promise.js',
],
// files listed below are only available client-side, or are bundled in to reduce # of network requests on cold load
@@ -60,6 +59,7 @@ module.exports = function (Meta) {
'public/src/client/topic/fork.js',
'public/src/client/topic/move.js',
'public/src/client/topic/posts.js',
+ 'public/src/client/topic/images.js',
'public/src/client/topic/postTools.js',
'public/src/client/topic/threadTools.js',
'public/src/client/categories.js',
@@ -79,18 +79,18 @@ module.exports = function (Meta) {
'public/src/modules/taskbar.js',
'public/src/modules/helpers.js',
'public/src/modules/sounds.js',
- 'public/src/modules/string.js'
+ 'public/src/modules/string.js',
],
// modules listed below are built (/src/modules) so they can be defined anonymously
modules: {
- "Chart.js": './node_modules/chart.js/dist/Chart.min.js',
- "mousetrap.js": './node_modules/mousetrap/mousetrap.min.js',
- "jqueryui.js": 'public/vendor/jquery/js/jquery-ui.js',
- "buzz.js": 'public/vendor/buzz/buzz.js',
- "cropper.js": './node_modules/cropperjs/dist/cropper.min.js'
- }
- }
+ 'Chart.js': './node_modules/chart.js/dist/Chart.min.js',
+ 'mousetrap.js': './node_modules/mousetrap/mousetrap.min.js',
+ 'jqueryui.js': 'public/vendor/jquery/js/jquery-ui.js',
+ 'buzz.js': 'public/vendor/buzz/buzz.js',
+ 'cropper.js': './node_modules/cropperjs/dist/cropper.min.js',
+ },
+ },
};
function minifyModules(modules, callback) {
@@ -108,6 +108,12 @@ module.exports = function (Meta) {
if (err) {
return cb(err);
}
+
+ if (filePath.endsWith('.min.js')) {
+ minified = { code: buffer.toString() };
+ return cb();
+ }
+
try {
minified = uglifyjs.minify(buffer.toString(), {
fromString: true,
@@ -119,7 +125,7 @@ module.exports = function (Meta) {
cb();
});
- }
+ },
], function (err) {
if (err) {
return next(err);
@@ -128,7 +134,7 @@ module.exports = function (Meta) {
fs.writeFile(destPath, minified.code, next);
});
}, callback);
- };
+ }
function linkModules(callback) {
var modules = Meta.js.scripts.modules;
@@ -145,7 +151,7 @@ module.exports = function (Meta) {
file.link(filePath, destPath, next);
});
}, callback);
- };
+ }
var moduleDirs = ['modules', 'admin', 'client'];
@@ -167,12 +173,16 @@ module.exports = function (Meta) {
return next(err);
}
- modules = modules.concat(files.map(function (filePath) {
+ var mods = files.filter(function (filePath) {
+ return path.extname(filePath) === '.js';
+ }).map(function (filePath) {
return {
filePath: filePath,
destPath: path.join(__dirname, '../../build/public/src', path.relative(path.dirname(dir), filePath)),
};
- }));
+ });
+
+ modules = modules.concat(mods);
next();
});
@@ -204,7 +214,7 @@ module.exports = function (Meta) {
},
function (modules, next) {
minifyModules(modules, next);
- }
+ },
], callback);
};
@@ -232,7 +242,8 @@ module.exports = function (Meta) {
winston.verbose('[meta/js] Minifying ' + target);
var forkProcessParams = setupDebugging();
- var minifier = Meta.js.minifierProc = fork(minifierPath, [], forkProcessParams);
+ var minifier = fork(minifierPath, [], forkProcessParams);
+ Meta.js.minifierProc = minifier;
Meta.js.target[target] = {};
@@ -243,12 +254,12 @@ module.exports = function (Meta) {
minifier.send({
action: 'js',
minify: global.env !== 'development',
- scripts: Meta.js.target[target].scripts
+ scripts: Meta.js.target[target].scripts,
});
});
minifier.on('message', function (message) {
- switch(message.type) {
+ switch (message.type) {
case 'end':
Meta.js.target[target].cache = message.minified;
Meta.js.target[target].map = message.sourceMap;
@@ -324,17 +335,17 @@ module.exports = function (Meta) {
* Check if the parent process is running with the debug option --debug (or --debug-brk)
*/
var forkProcessParams = {};
- if(global.v8debug || parseInt(process.execArgv.indexOf('--debug'), 10) !== -1) {
+ if (global.v8debug || parseInt(process.execArgv.indexOf('--debug'), 10) !== -1) {
/**
* use the line below if you want to debug minifier.js script too (or even --debug-brk option, but
* you'll have to setup your debugger and connect to the forked process)
*/
- //forkProcessParams = {execArgv: ['--debug=' + (global.process.debugPort + 1), '--nolazy']};
+ // forkProcessParams = {execArgv: ['--debug=' + (global.process.debugPort + 1), '--nolazy']};
/**
* otherwise, just clean up --debug/--debug-brk options which are set up by default from the parent one
*/
- forkProcessParams = {execArgv: []};
+ forkProcessParams = { execArgv: [] };
}
return forkProcessParams;
diff --git a/src/meta/languages.js b/src/meta/languages.js
index b7c79db5ba..67bd9fabd5 100644
--- a/src/meta/languages.js
+++ b/src/meta/languages.js
@@ -38,12 +38,13 @@ function getTranslationTree(callback) {
// generate list of languages and namespaces
function (plugins, next) {
- var languages = [], namespaces = [];
+ var languages = [];
+ var namespaces = [];
// pull languages and namespaces from paths
function extrude(languageDir, paths) {
paths.forEach(function (p) {
- var rel = p.split(languageDir)[1].split(/[\/\\]/).slice(1);
+ var rel = p.split(languageDir)[1].split(/[/\\]/).slice(1);
var language = rel.shift().replace('_', '-').replace('@', '-x-');
var namespace = rel.join('/').replace(/\.json$/, '');
diff --git a/src/meta/logs.js b/src/meta/logs.js
index 32f6d7a141..e85c0a5e11 100644
--- a/src/meta/logs.js
+++ b/src/meta/logs.js
@@ -7,12 +7,12 @@ var winston = require('winston');
module.exports = function (Meta) {
Meta.logs = {
- path: path.join(nconf.get('base_dir'), 'logs', 'output.log')
+ path: path.join(nconf.get('base_dir'), 'logs', 'output.log'),
};
Meta.logs.get = function (callback) {
fs.readFile(Meta.logs.path, {
- encoding: 'utf-8'
+ encoding: 'utf-8',
}, function (err, logs) {
if (err) {
winston.error('[meta/logs] Could not retrieve logs: ' + err.message);
@@ -25,5 +25,4 @@ module.exports = function (Meta) {
Meta.logs.clear = function (callback) {
fs.truncate(Meta.logs.path, 0, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/meta/minifier.js b/src/meta/minifier.js
index 5c47bc3e4e..6152112c59 100644
--- a/src/meta/minifier.js
+++ b/src/meta/minifier.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var uglifyjs = require('uglify-js');
var async = require('async');
@@ -6,12 +6,11 @@ var fs = require('fs');
var file = require('../file');
var Minifier = {
- js: {}
+ js: {},
};
/* Javascript */
Minifier.js.minify = function (scripts, minify, callback) {
-
scripts = scripts.filter(function (file) {
return file && file.endsWith('.js');
});
@@ -33,13 +32,13 @@ Minifier.js.minify = function (scripts, minify, callback) {
};
process.on('message', function (payload) {
- switch(payload.action) {
+ switch (payload.action) {
case 'js':
- Minifier.js.minify(payload.scripts, payload.minify, function (minified/*, sourceMap*/) {
+ Minifier.js.minify(payload.scripts, payload.minify, function (minified/* , sourceMap*/) {
process.send({
type: 'end',
// sourceMap: sourceMap,
- minified: minified
+ minified: minified,
});
});
break;
@@ -51,15 +50,15 @@ function minifyScripts(scripts, callback) {
// Follow along here: https://github.com/mishoo/UglifyJS2/issues/700
try {
var minified = uglifyjs.minify(scripts, {
- // outSourceMap: "nodebb.min.js.map",
- compress: false
- });
+ // outSourceMap: "nodebb.min.js.map",
+ compress: false,
+ });
- callback(minified.code/*, minified.map*/);
- } catch(err) {
+ callback(minified.code/* , minified.map*/);
+ } catch (err) {
process.send({
type: 'error',
- message: err.message
+ message: err.message,
});
}
}
@@ -69,7 +68,7 @@ function concatenateScripts(scripts, callback) {
if (err) {
process.send({
type: 'error',
- message: err.message
+ message: err.message,
});
return;
}
@@ -78,4 +77,4 @@ function concatenateScripts(scripts, callback) {
callback(scripts);
});
-}
\ No newline at end of file
+}
diff --git a/src/meta/settings.js b/src/meta/settings.js
index 785d22961f..a1d13b248d 100644
--- a/src/meta/settings.js
+++ b/src/meta/settings.js
@@ -6,7 +6,6 @@ var db = require('../database');
var plugins = require('../plugins');
module.exports = function (Meta) {
-
Meta.settings = {};
Meta.settings.get = function (hash, callback) {
@@ -27,12 +26,12 @@ module.exports = function (Meta) {
function (next) {
plugins.fireHook('action:settings.set', {
plugin: hash,
- settings: values
+ settings: values,
});
Meta.reloadRequired = true;
next();
- }
+ },
], callback);
};
@@ -59,7 +58,7 @@ module.exports = function (Meta) {
} else {
next();
}
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/meta/sounds.js b/src/meta/sounds.js
index 00bcbc2410..3de45b388c 100644
--- a/src/meta/sounds.js
+++ b/src/meta/sounds.js
@@ -9,7 +9,6 @@ var async = require('async');
var file = require('../file');
var plugins = require('../plugins');
var user = require('../user');
-var db = require('../database');
var soundsPath = path.join(__dirname, '../../build/public/sounds');
var uploadsPath = path.join(__dirname, '../../public/uploads/sounds');
@@ -99,11 +98,11 @@ module.exports = function (Meta) {
Meta.sounds.getUserSoundMap = function getUserSoundMap(uid, callback) {
async.parallel({
defaultMapping: function (next) {
- db.getObject('settings:sounds', next);
+ Meta.configs.getFields(keys, next);
},
userSettings: function (next) {
user.getSettings(uid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -120,9 +119,9 @@ module.exports = function (Meta) {
keys.forEach(function (key) {
if (userSettings[key] || userSettings[key] === '') {
- soundMapping[key] = userSettings[key] || null;
+ soundMapping[key] = userSettings[key] || '';
} else {
- soundMapping[key] = defaultMapping[key] || null;
+ soundMapping[key] = defaultMapping[key] || '';
}
});
diff --git a/src/meta/tags.js b/src/meta/tags.js
index 0cd680a70a..5b1097d427 100644
--- a/src/meta/tags.js
+++ b/src/meta/tags.js
@@ -14,30 +14,30 @@ module.exports = function (Meta) {
tags: function (next) {
var defaultTags = [{
name: 'viewport',
- content: 'width=device-width, initial-scale=1.0'
+ content: 'width=device-width, initial-scale=1.0',
}, {
name: 'content-type',
content: 'text/html; charset=UTF-8',
- noEscape: true
+ noEscape: true,
}, {
name: 'apple-mobile-web-app-capable',
- content: 'yes'
+ content: 'yes',
}, {
name: 'mobile-web-app-capable',
- content: 'yes'
+ content: 'yes',
}, {
property: 'og:site_name',
- content: Meta.config.title || 'NodeBB'
+ content: Meta.config.title || 'NodeBB',
}, {
name: 'msapplication-badge',
content: 'frequency=30; polling-uri=' + nconf.get('url') + '/sitemap.xml',
- noEscape: true
+ noEscape: true,
}];
if (Meta.config.keywords) {
defaultTags.push({
name: 'keywords',
- content: Meta.config.keywords
+ content: Meta.config.keywords,
});
}
@@ -45,7 +45,7 @@ module.exports = function (Meta) {
defaultTags.push({
name: 'msapplication-square150x150logo',
content: Meta.config['brand:logo'],
- noEscape: true
+ noEscape: true,
});
}
@@ -53,47 +53,55 @@ module.exports = function (Meta) {
},
links: function (next) {
var defaultLinks = [{
- rel: "icon",
- type: "image/x-icon",
- href: nconf.get('relative_path') + '/favicon.ico' + (Meta.config['cache-buster'] ? '?' + Meta.config['cache-buster'] : '')
+ rel: 'icon',
+ type: 'image/x-icon',
+ href: nconf.get('relative_path') + '/favicon.ico' + (Meta.config['cache-buster'] ? '?' + Meta.config['cache-buster'] : ''),
}, {
- rel: "manifest",
- href: nconf.get('relative_path') + '/manifest.json'
+ rel: 'manifest',
+ href: nconf.get('relative_path') + '/manifest.json',
}];
+ if (plugins.hasListeners('filter:search.query')) {
+ defaultLinks.push({
+ rel: 'search',
+ type: 'application/opensearchdescription+xml',
+ href: nconf.get('relative_path') + '/osd.xml',
+ });
+ }
+
// Touch icons for mobile-devices
if (Meta.config['brand:touchIcon']) {
defaultLinks.push({
rel: 'apple-touch-icon',
- href: nconf.get('relative_path') + '/apple-touch-icon'
+ href: nconf.get('relative_path') + '/apple-touch-icon',
}, {
rel: 'icon',
sizes: '36x36',
- href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-36.png'
+ href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-36.png',
}, {
rel: 'icon',
sizes: '48x48',
- href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-48.png'
+ href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-48.png',
}, {
rel: 'icon',
sizes: '72x72',
- href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-72.png'
+ href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-72.png',
}, {
rel: 'icon',
sizes: '96x96',
- href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-96.png'
+ href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-96.png',
}, {
rel: 'icon',
sizes: '144x144',
- href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-144.png'
+ href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-144.png',
}, {
rel: 'icon',
sizes: '192x192',
- href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-192.png'
+ href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-192.png',
});
}
plugins.fireHook('filter:meta.getLinkTags', defaultLinks, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -118,7 +126,7 @@ module.exports = function (Meta) {
callback(null, {
meta: meta,
- link: link
+ link: link,
});
});
};
@@ -131,10 +139,10 @@ module.exports = function (Meta) {
}
});
- if (!hasDescription) {
+ if (!hasDescription && Meta.config.description) {
meta.push({
name: 'description',
- content: validator.escape(String(Meta.config.description || ''))
+ content: validator.escape(String(Meta.config.description)),
});
}
}
diff --git a/src/meta/templates.js b/src/meta/templates.js
index fd5c1f71e1..4c2a8b1fb9 100644
--- a/src/meta/templates.js
+++ b/src/meta/templates.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
@@ -21,8 +21,9 @@ Templates.compile = function (callback) {
function getBaseTemplates(theme) {
- var baseTemplatesPaths = [],
- baseThemePath, baseThemeConfig;
+ var baseTemplatesPaths = [];
+ var baseThemePath;
+ var baseThemeConfig;
while (theme) {
baseThemePath = path.join(nconf.get('themes_path'), theme);
@@ -51,7 +52,7 @@ function preparePaths(baseTemplatesPaths, callback) {
},
function (next) {
plugins.getTemplates(next);
- }
+ },
], function (err, pluginTemplates) {
if (err) {
return callback(err);
@@ -69,18 +70,18 @@ function preparePaths(baseTemplatesPaths, callback) {
paths = paths.map(function (tpl) {
return {
base: baseTemplatePath,
- path: tpl.replace(baseTemplatePath, '')
+ path: tpl.replace(baseTemplatePath, ''),
};
});
next(err, paths);
});
}, next);
- }
+ },
}, function (err, data) {
- var baseThemes = data.baseThemes,
- coreTpls = data.coreTpls,
- paths = {};
+ var baseThemes = data.baseThemes;
+ var coreTpls = data.coreTpls;
+ var paths = {};
coreTpls.forEach(function (el, i) {
paths[coreTpls[i].replace(coreTemplatesPath, '')] = coreTpls[i];
@@ -104,9 +105,9 @@ function preparePaths(baseTemplatesPaths, callback) {
}
function compile(callback) {
- var themeConfig = require(nconf.get('theme_config')),
- baseTemplatesPaths = themeConfig.baseTheme ? getBaseTemplates(themeConfig.baseTheme) : [nconf.get('base_templates_path')],
- viewsPath = nconf.get('views_dir');
+ var themeConfig = require(nconf.get('theme_config'));
+ var baseTemplatesPaths = themeConfig.baseTheme ? getBaseTemplates(themeConfig.baseTheme) : [nconf.get('base_templates_path')];
+ var viewsPath = nconf.get('views_dir');
preparePaths(baseTemplatesPaths, function (err, paths) {
@@ -115,19 +116,20 @@ function compile(callback) {
}
async.each(Object.keys(paths), function (relativePath, next) {
- var file = fs.readFileSync(paths[relativePath]).toString(),
- matches = null,
- regex = /[ \t]*[ \t]*/;
+ var file = fs.readFileSync(paths[relativePath]).toString();
+ var regex = /[ \t]*[ \t]*/;
+ var matches = file.match(regex);
- while((matches = file.match(regex)) !== null) {
- var partial = "/" + matches[1];
+ while (matches !== null) {
+ var partial = '/' + matches[1];
if (paths[partial] && relativePath !== partial) {
file = file.replace(regex, fs.readFileSync(paths[partial]).toString());
} else {
winston.warn('[meta/templates] Partial not loaded: ' + matches[1]);
- file = file.replace(regex, "");
+ file = file.replace(regex, '');
}
+ matches = file.match(regex);
}
mkdirp.sync(path.join(viewsPath, relativePath.split('/').slice(0, -1).join('/')));
@@ -145,4 +147,4 @@ function compile(callback) {
});
}
-module.exports = Templates;
\ No newline at end of file
+module.exports = Templates;
diff --git a/src/meta/themes.js b/src/meta/themes.js
index e19dcdbf4c..8853c9a086 100644
--- a/src/meta/themes.js
+++ b/src/meta/themes.js
@@ -56,7 +56,6 @@ module.exports = function (Meta) {
next(null, null);
}
});
-
}, function (err, themes) {
if (err) {
return callback(err);
@@ -75,17 +74,17 @@ module.exports = function (Meta) {
'theme:id': data.id,
'theme:staticDir': '',
'theme:templates': '',
- 'theme:src': ''
+ 'theme:src': '',
};
- switch(data.type) {
+ switch (data.type) {
case 'local':
async.waterfall([
async.apply(Meta.configs.get, 'theme:id'),
function (current, next) {
async.series([
async.apply(db.sortedSetRemove, 'plugins:active', current),
- async.apply(db.sortedSetAdd, 'plugins:active', 0, data.id)
+ async.apply(db.sortedSetAdd, 'plugins:active', 0, data.id),
], function (err) {
next(err);
});
@@ -105,18 +104,21 @@ module.exports = function (Meta) {
themeData['theme:templates'] = config.templates ? config.templates : '';
themeData['theme:src'] = '';
- db.setObject('config', themeData, next);
+ Meta.configs.setMultiple(themeData, next);
// Re-set the themes path (for when NodeBB is reloaded)
Meta.themes.setPath(config);
- }
+ },
], callback);
Meta.reloadRequired = true;
break;
case 'bootswatch':
- Meta.configs.set('theme:src', data.src, callback);
+ Meta.configs.setMultiple({
+ 'theme:src': data.src,
+ bootswatchSkin: data.id.toLowerCase(),
+ }, callback);
break;
}
};
@@ -126,7 +128,7 @@ module.exports = function (Meta) {
themesData: Meta.themes.get,
currentThemeId: function (next) {
db.getObjectField('config', 'theme:id', next);
- }
+ },
}, function (err, data) {
if (err) {
return callback(err);
@@ -135,8 +137,8 @@ module.exports = function (Meta) {
var themeId = data.currentThemeId || 'nodebb-theme-persona';
var themeObj = data.themesData.filter(function (themeObj) {
- return themeObj.id === themeId;
- })[0];
+ return themeObj.id === themeId;
+ })[0];
if (process.env.NODE_ENV === 'development') {
winston.info('[themes] Using theme ' + themeId);
@@ -153,8 +155,8 @@ module.exports = function (Meta) {
Meta.themes.setPath = function (themeObj) {
// Theme's templates path
- var themePath = nconf.get('base_templates_path'),
- fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
+ var themePath = nconf.get('base_templates_path');
+ var fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
if (themeObj.templates) {
themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates);
@@ -165,4 +167,4 @@ module.exports = function (Meta) {
nconf.set('theme_templates_path', themePath);
nconf.set('theme_config', path.join(nconf.get('themes_path'), themeObj.id, 'theme.json'));
};
-};
\ No newline at end of file
+};
diff --git a/src/middleware/admin.js b/src/middleware/admin.js
index 9d4b43bf25..3e36b74db9 100644
--- a/src/middleware/admin.js
+++ b/src/middleware/admin.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var winston = require('winston');
@@ -8,7 +8,7 @@ var plugins = require('../plugins');
var controllers = {
api: require('../controllers/api'),
- helpers: require('../controllers/helpers')
+ helpers: require('../controllers/helpers'),
};
module.exports = function (middleware) {
@@ -44,8 +44,8 @@ module.exports = function (middleware) {
middleware.admin.renderHeader = function (req, res, data, next) {
var custom_header = {
- 'plugins': [],
- 'authentication': []
+ plugins: [],
+ authentication: [],
};
user.getUserFields(req.uid, ['username', 'userslug', 'email', 'picture', 'email:confirmed'], function (err, userData) {
@@ -64,7 +64,7 @@ module.exports = function (middleware) {
}
var arr = [];
scripts.forEach(function (script) {
- arr.push({src: script});
+ arr.push({ src: script });
});
next(null, arr);
@@ -78,7 +78,7 @@ module.exports = function (middleware) {
},
configs: function (next) {
meta.configs.list(next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -102,12 +102,12 @@ module.exports = function (middleware) {
authentication: results.custom_header.authentication,
scripts: results.scripts,
'cache-buster': meta.config['cache-buster'] || '',
- env: process.env.NODE_ENV ? true : false,
+ env: !!process.env.NODE_ENV,
title: (acpPath || 'Dashboard') + ' | NodeBB Admin Control Panel',
- bodyClass: data.bodyClass
+ bodyClass: data.bodyClass,
};
- templateValues.template = {name: res.locals.template};
+ templateValues.template = { name: res.locals.template };
templateValues.template[res.locals.template] = true;
req.app.render('admin/header', templateValues, next);
diff --git a/src/middleware/header.js b/src/middleware/header.js
index 0c33e621e5..70c0755def 100644
--- a/src/middleware/header.js
+++ b/src/middleware/header.js
@@ -11,11 +11,10 @@ var navigation = require('../navigation');
var controllers = {
api: require('../controllers/api'),
- helpers: require('../controllers/helpers')
+ helpers: require('../controllers/helpers'),
};
module.exports = function (middleware) {
-
middleware.buildHeader = function (req, res, next) {
res.locals.renderHeader = true;
res.locals.isAPI = false;
@@ -29,21 +28,20 @@ module.exports = function (middleware) {
controllers.api.getConfig(req, res, next);
},
plugins: function (next) {
- plugins.fireHook('filter:middleware.buildHeader', {req: req, locals: res.locals}, next);
- }
+ plugins.fireHook('filter:middleware.buildHeader', { req: req, locals: res.locals }, next);
+ },
}, next);
},
function (results, next) {
res.locals.config = results.config;
next();
- }
+ },
], next);
};
middleware.renderHeader = function (req, res, data, callback) {
var registrationType = meta.config.registrationType || 'normal';
var templateValues = {
- bootswatchCSS: meta.config['theme:src'],
title: meta.config.title || '',
description: meta.config.description || '',
'cache-buster': meta.config['cache-buster'] || '',
@@ -55,10 +53,11 @@ module.exports = function (middleware) {
searchEnabled: plugins.hasListeners('filter:search.query'),
config: res.locals.config,
relative_path: nconf.get('relative_path'),
- bodyClass: data.bodyClass
+ bodyClass: data.bodyClass,
};
templateValues.configJSON = JSON.stringify(res.locals.config);
+
async.waterfall([
function (next) {
async.parallel({
@@ -83,7 +82,7 @@ module.exports = function (middleware) {
picture: meta.config.defaultAvatar,
status: 'offline',
reputation: 0,
- 'email:confirmed': false
+ 'email:confirmed': 0,
};
if (req.uid) {
user.getUserFields(req.uid, Object.keys(userData), next);
@@ -100,7 +99,7 @@ module.exports = function (middleware) {
navigation: async.apply(navigation.get),
tags: async.apply(meta.tags.parse, res.locals.metaTags, res.locals.linkTags),
banned: async.apply(user.isBanned, req.uid),
- banReason: async.apply(user.getBannedReason, req.uid)
+ banReason: async.apply(user.getBannedReason, req.uid),
}, next);
},
function (results, next) {
@@ -117,9 +116,7 @@ module.exports = function (middleware) {
results.user['email:confirmed'] = parseInt(results.user['email:confirmed'], 10) === 1;
results.user.isEmailConfirmSent = !!results.isEmailConfirmSent;
- if (res.locals.config && parseInt(meta.config.disableCustomUserSkins, 10) !== 1 && res.locals.config.bootswatchSkin !== 'default') {
- templateValues.bootswatchCSS = '//maxcdn.bootstrapcdn.com/bootswatch/latest/' + res.locals.config.bootswatchSkin + '/bootstrap.min.css';
- }
+ setBootswatchCSS(templateValues, res.locals.config);
templateValues.browserTitle = controllers.helpers.buildTitle(data.title);
templateValues.navigation = results.navigation;
@@ -139,11 +136,11 @@ module.exports = function (middleware) {
templateValues.privateUserInfo = parseInt(meta.config.privateUserInfo, 10) === 1;
templateValues.privateTagListing = parseInt(meta.config.privateTagListing, 10) === 1;
- templateValues.template = {name: res.locals.template};
+ templateValues.template = { name: res.locals.template };
templateValues.template[res.locals.template] = true;
templateValues.scripts = results.scripts.map(function (script) {
- return {src: script};
+ return { src: script };
});
if (req.route && req.route.path === '/') {
@@ -151,14 +148,14 @@ module.exports = function (middleware) {
}
plugins.fireHook('filter:middleware.renderHeader', {
- req: req,
+ req: req,
res: res,
- templateValues: templateValues
- }, next);
+ templateValues: templateValues,
+ }, next);
},
function (data, next) {
req.app.render('header', data.templateValues, next);
- }
+ },
], callback);
};
@@ -168,12 +165,12 @@ module.exports = function (middleware) {
plugins.fireHook('filter:middleware.renderFooter', {
req: req,
res: res,
- templateValues: data,
+ templateValues: data,
}, next);
},
function (data, next) {
req.app.render('footer', data.templateValues, next);
- }
+ },
], callback);
};
@@ -192,7 +189,20 @@ module.exports = function (middleware) {
return title;
}
+ function setBootswatchCSS(obj, config) {
+ if (config && config.bootswatchSkin !== 'noskin') {
+ var skinToUse = '';
+
+ if (parseInt(meta.config.disableCustomUserSkins, 10) !== 1) {
+ skinToUse = config.bootswatchSkin;
+ } else if (meta.config.bootswatchSkin) {
+ skinToUse = meta.config.bootswatchSkin;
+ }
+
+ if (skinToUse) {
+ obj.bootswatchCSS = '//maxcdn.bootstrapcdn.com/bootswatch/latest/' + skinToUse + '/bootstrap.min.css';
+ }
+ }
+ }
};
-
-
diff --git a/src/middleware/headers.js b/src/middleware/headers.js
index 66f0603b0d..ae63b19124 100644
--- a/src/middleware/headers.js
+++ b/src/middleware/headers.js
@@ -3,14 +3,13 @@
var meta = require('../meta');
module.exports = function (middleware) {
-
middleware.addHeaders = function (req, res, next) {
var headers = {
'X-Powered-By': encodeURI(meta.config['powered-by'] || 'NodeBB'),
'X-Frame-Options': meta.config['allow-from-uri'] ? 'ALLOW-FROM ' + encodeURI(meta.config['allow-from-uri']) : 'SAMEORIGIN',
'Access-Control-Allow-Origin': encodeURI(meta.config['access-control-allow-origin'] || 'null'),
'Access-Control-Allow-Methods': encodeURI(meta.config['access-control-allow-methods'] || ''),
- 'Access-Control-Allow-Headers': encodeURI(meta.config['access-control-allow-headers'] || '')
+ 'Access-Control-Allow-Headers': encodeURI(meta.config['access-control-allow-headers'] || ''),
};
for (var key in headers) {
@@ -24,17 +23,14 @@ module.exports = function (middleware) {
middleware.addExpiresHeaders = function (req, res, next) {
if (req.app.enabled('cache')) {
- res.setHeader("Cache-Control", "public, max-age=5184000");
- res.setHeader("Expires", new Date(Date.now() + 5184000000).toUTCString());
+ res.setHeader('Cache-Control', 'public, max-age=5184000');
+ res.setHeader('Expires', new Date(Date.now() + 5184000000).toUTCString());
} else {
- res.setHeader("Cache-Control", "public, max-age=0");
- res.setHeader("Expires", new Date().toUTCString());
+ res.setHeader('Cache-Control', 'public, max-age=0');
+ res.setHeader('Expires', new Date().toUTCString());
}
next();
};
-
};
-
-
diff --git a/src/middleware/index.js b/src/middleware/index.js
index 82a7fd12cb..faf2ad832d 100644
--- a/src/middleware/index.js
+++ b/src/middleware/index.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var fs = require('fs');
@@ -10,7 +10,6 @@ var ensureLoggedIn = require('connect-ensure-login');
var toobusy = require('toobusy-js');
var plugins = require('../plugins');
-var languages = require('../languages');
var meta = require('../meta');
var user = require('../user');
var groups = require('../groups');
@@ -19,7 +18,7 @@ var analytics = require('../analytics');
var controllers = {
api: require('./../controllers/api'),
- helpers: require('../controllers/helpers')
+ helpers: require('../controllers/helpers'),
};
var middleware = {};
@@ -42,7 +41,7 @@ middleware.authenticate = function (req, res, next) {
return plugins.fireHook('action:middleware.authenticate', {
req: req,
res: res,
- next: next
+ next: next,
});
}
@@ -54,33 +53,34 @@ middleware.ensureSelfOrGlobalPrivilege = function (req, res, next) {
The "self" part of this middleware hinges on you having used
middleware.exposeUid prior to invoking this middleware.
*/
- if (req.user) {
- if (req.user.uid === res.locals.uid) {
- return next();
- }
-
- user.isAdminOrGlobalMod(req.uid, function (err, ok) {
- if (err) {
- return next(err);
- } else if (ok) {
- return next();
- } else {
- controllers.helpers.notAllowed(req, res);
+ async.waterfall([
+ function (next) {
+ if (!req.uid) {
+ return setImmediate(next, null, false);
}
- });
- } else {
- controllers.helpers.notAllowed(req, res);
- }
+
+ if (req.uid === parseInt(res.locals.uid, 10)) {
+ return setImmediate(next, null, true);
+ }
+ user.isAdminOrGlobalMod(req.uid, next);
+ },
+ function (isAdminOrGlobalMod, next) {
+ if (!isAdminOrGlobalMod) {
+ return controllers.helpers.notAllowed(req, res);
+ }
+ next();
+ },
+ ], next);
};
middleware.pageView = function (req, res, next) {
analytics.pageView({
ip: req.ip,
path: req.path,
- uid: req.uid
+ uid: req.uid,
});
- plugins.fireHook('action:middleware.pageView', {req: req});
+ plugins.fireHook('action:middleware.pageView', { req: req });
if (req.user) {
user.updateLastOnlineTime(req.user.uid);
@@ -121,13 +121,10 @@ middleware.prepareAPI = function (req, res, next) {
middleware.routeTouchIcon = function (req, res) {
if (meta.config['brand:touchIcon'] && validator.isURL(meta.config['brand:touchIcon'])) {
return res.redirect(meta.config['brand:touchIcon']);
- } else {
- var touchIconPath = meta.config['brand:touchIcon'] || 'logo.png';
- touchIconPath = path.join(nconf.get('base_dir'), 'public', touchIconPath.replace(/assets\/uploads/, 'uploads'));
- return res.sendFile(touchIconPath, {
- maxAge: req.app.enabled('cache') ? 5184000000 : 0
- });
}
+ return res.sendFile(path.join(__dirname, '../../public', meta.config['brand:touchIcon'] || '/logo.png'), {
+ maxAge: req.app.enabled('cache') ? 5184000000 : 0,
+ });
};
middleware.privateTagListing = function (req, res, next) {
@@ -185,24 +182,24 @@ middleware.applyBlacklist = function (req, res, next) {
});
};
-middleware.processTimeagoLocales = function (req, res, next) {
- var fallback = req.path.indexOf('-short') === -1 ? 'jquery.timeago.en.js' : 'jquery.timeago.en-short.js',
- localPath = path.join(__dirname, '../../public/vendor/jquery/timeago/locales', req.path),
- exists;
+middleware.processTimeagoLocales = function (req, res) {
+ var fallback = req.path.indexOf('-short') === -1 ? 'jquery.timeago.en.js' : 'jquery.timeago.en-short.js';
+ var localPath = path.join(__dirname, '../../public/vendor/jquery/timeago/locales', req.path);
+ var exists;
try {
exists = fs.accessSync(localPath, fs.F_OK | fs.R_OK);
- } catch(e) {
+ } catch (e) {
exists = false;
}
if (exists) {
res.status(200).sendFile(localPath, {
- maxAge: req.app.enabled('cache') ? 5184000000 : 0
+ maxAge: req.app.enabled('cache') ? 5184000000 : 0,
});
} else {
res.status(200).sendFile(path.join(__dirname, '../../public/vendor/jquery/timeago/locales', fallback), {
- maxAge: req.app.enabled('cache') ? 5184000000 : 0
+ maxAge: req.app.enabled('cache') ? 5184000000 : 0,
});
}
};
diff --git a/src/middleware/maintenance.js b/src/middleware/maintenance.js
index 3193e820fa..4f4cb03982 100644
--- a/src/middleware/maintenance.js
+++ b/src/middleware/maintenance.js
@@ -5,7 +5,6 @@ var meta = require('../meta');
var user = require('../user');
module.exports = function (middleware) {
-
middleware.maintenanceMode = function (req, res, next) {
if (parseInt(meta.config.maintenanceMode, 10) !== 1) {
return next();
@@ -24,7 +23,7 @@ module.exports = function (middleware) {
res.status(503);
var data = {
site_title: meta.config.title || 'NodeBB',
- message: meta.config.maintenanceModeMessage
+ message: meta.config.maintenanceModeMessage,
};
if (res.locals.isAPI) {
@@ -36,5 +35,4 @@ module.exports = function (middleware) {
});
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/middleware/ratelimit.js b/src/middleware/ratelimit.js
index f02bf74c3e..504cb0acd7 100644
--- a/src/middleware/ratelimit.js
+++ b/src/middleware/ratelimit.js
@@ -1,6 +1,5 @@
-
-
'use strict';
+
var winston = require('winston');
var ratelimit = module.exports;
@@ -13,7 +12,7 @@ ratelimit.isFlooding = function (socket) {
socket.elapsedTime = socket.elapsedTime || 0;
socket.lastCallTime = socket.lastCallTime || Date.now();
- ++socket.callsPerSecond;
+ socket.callsPerSecond += 1;
var now = Date.now();
socket.elapsedTime += now - socket.lastCallTime;
diff --git a/src/middleware/render.js b/src/middleware/render.js
index ecd0ce8a5d..88e9879887 100644
--- a/src/middleware/render.js
+++ b/src/middleware/render.js
@@ -9,7 +9,6 @@ var plugins = require('../plugins');
var translator = require('../../public/src/modules/translator');
module.exports = function (middleware) {
-
middleware.processRender = function (req, res, next) {
// res.render post-processing, modified from here: https://gist.github.com/mrlannigan/5051687
var render = res.render;
@@ -24,11 +23,11 @@ module.exports = function (middleware) {
};
options = options || {};
- if ('function' === typeof options) {
+ if (typeof options === 'function') {
fn = options;
options = {};
}
- if ('function' !== typeof fn) {
+ if (typeof fn !== 'function') {
fn = defaultFn;
}
@@ -37,15 +36,15 @@ module.exports = function (middleware) {
function (next) {
options.loggedIn = !!req.uid;
options.relative_path = nconf.get('relative_path');
- options.template = {name: template};
+ options.template = { name: template };
options.template[template] = true;
options.url = (req.baseUrl + req.path).replace(/^\/api/, '');
options.bodyClass = buildBodyClass(req);
- plugins.fireHook('filter:' + template + '.build', {req: req, res: res, templateData: options}, next);
+ plugins.fireHook('filter:' + template + '.build', { req: req, res: res, templateData: options }, next);
},
function (data, next) {
- plugins.fireHook('filter:middleware.render', {req: res, res: res, templateData: data.templateData}, next);
+ plugins.fireHook('filter:middleware.render', { req: res, res: res, templateData: data.templateData }, next);
},
function (data, next) {
options = data.templateData;
@@ -72,7 +71,7 @@ module.exports = function (middleware) {
},
footer: function (next) {
renderHeaderFooter('renderFooter', req, res, options, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -89,7 +88,7 @@ module.exports = function (middleware) {
return '';
});
next(null, translated);
- }
+ },
], fn);
};
@@ -107,7 +106,7 @@ module.exports = function (middleware) {
}
function translate(str, req, res, next) {
- var language = res.locals.config && res.locals.config.userLang || 'en-GB';
+ var language = (res.locals.config && res.locals.config.userLang) || 'en-GB';
language = req.query.lang ? validator.escape(String(req.query.lang)) : language;
translator.translate(str, language, function (translated) {
next(null, translator.unescape(translated));
@@ -124,10 +123,9 @@ module.exports = function (middleware) {
winston.error(err.message);
p = '';
}
-
+ p = validator.escape(String(p));
parts[index] = index ? parts[0] + '-' + p : 'page-' + (p || 'home');
});
return parts.join(' ');
}
-
};
diff --git a/src/middleware/user.js b/src/middleware/user.js
index c2c3bd9dd6..85b5d6e808 100644
--- a/src/middleware/user.js
+++ b/src/middleware/user.js
@@ -1,18 +1,17 @@
'use strict';
var async = require('async');
-var nconf = require('nconf');
+var nconf = require('nconf');
var meta = require('../meta');
var user = require('../user');
var privileges = require('../privileges');
var controllers = {
- helpers: require('../controllers/helpers')
+ helpers: require('../controllers/helpers'),
};
module.exports = function (middleware) {
-
middleware.checkGlobalPrivacySettings = function (req, res, next) {
if (!req.user && !!parseInt(meta.config.privateUserInfo, 10)) {
return middleware.authenticate(req, res, next);
@@ -44,7 +43,7 @@ module.exports = function (middleware) {
} else {
next(null, false);
}
- }
+ },
], function (err, allowed) {
if (err || allowed) {
return next(err);
@@ -142,20 +141,18 @@ module.exports = function (middleware) {
return next();
}
- res.status(403).render('403', {title: '[[global:403.title]]'});
+ res.status(403).render('403', { title: '[[global:403.title]]' });
};
middleware.registrationComplete = function (req, res, next) {
// If the user's session contains registration data, redirect the user to complete registration
if (!req.session.hasOwnProperty('registration')) {
return next();
+ }
+ if (!req.path.endsWith('/register/complete')) {
+ controllers.helpers.redirect(res, '/register/complete');
} else {
- if (!req.path.endsWith('/register/complete')) {
- controllers.helpers.redirect(res, '/register/complete');
- } else {
- return next();
- }
+ return next();
}
};
-
};
diff --git a/src/navigation/admin.js b/src/navigation/admin.js
index ab1c5aff42..0917e9e524 100644
--- a/src/navigation/admin.js
+++ b/src/navigation/admin.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var plugins = require('../plugins');
@@ -36,14 +36,14 @@ admin.save = function (data, callback) {
},
function (next) {
db.sortedSetAdd('navigation:enabled', order, items, next);
- }
+ },
], callback);
};
admin.getAdmin = function (callback) {
async.parallel({
enabled: admin.get,
- available: getAvailable
+ available: getAvailable,
}, callback);
};
diff --git a/src/navigation/index.js b/src/navigation/index.js
index 5563c44c4b..2cb24f3a9f 100644
--- a/src/navigation/index.js
+++ b/src/navigation/index.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var nconf = require('nconf');
var admin = require('./admin');
@@ -38,4 +38,4 @@ navigation.get = function (callback) {
};
-module.exports = navigation;
\ No newline at end of file
+module.exports = navigation;
diff --git a/src/notifications.js b/src/notifications.js
index b99700be01..31960dc2f1 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -16,7 +16,6 @@ var plugins = require('./plugins');
var utils = require('../public/src/utils');
(function (Notifications) {
-
Notifications.init = function () {
winston.verbose('[notifications.init] Registering jobs.');
new cron('*/30 * * * *', Notifications.prune, null, true);
@@ -143,7 +142,7 @@ var utils = require('../public/src/utils');
},
function (next) {
db.setObject('notifications:' + data.nid, data, next);
- }
+ },
], function (err) {
callback(err, data);
});
@@ -172,7 +171,7 @@ var utils = require('../public/src/utils');
setTimeout(function () {
batch.processArray(uids, function (uids, next) {
pushToUids(uids, notification, next);
- }, {interval: 1000}, function (err) {
+ }, { interval: 1000 }, function (err) {
if (err) {
winston.error(err.stack);
}
@@ -189,7 +188,7 @@ var utils = require('../public/src/utils');
async.waterfall([
function (next) {
- plugins.fireHook('filter:notification.push', {notification: notification, uids: uids}, next);
+ plugins.fireHook('filter:notification.push', { notification: notification, uids: uids }, next);
},
function (data, next) {
uids = data.uids;
@@ -219,9 +218,9 @@ var utils = require('../public/src/utils');
});
}
- plugins.fireHook('action:notification.pushed', {notification: notification, uids: uids});
+ plugins.fireHook('action:notification.pushed', { notification: notification, uids: uids });
next();
- }
+ },
], callback);
}
@@ -254,7 +253,7 @@ var utils = require('../public/src/utils');
async.parallel([
async.apply(db.sortedSetRemove, 'notifications', nid),
- async.apply(db.delete, 'notifications:' + nid)
+ async.apply(db.delete, 'notifications:' + nid),
], function (err) {
if (err) {
winston.error('Encountered error rescinding notification (' + nid + '): ' + err.message);
@@ -288,7 +287,7 @@ var utils = require('../public/src/utils');
async.parallel([
async.apply(db.sortedSetRemove, 'uid:' + uid + ':notifications:read', nid),
- async.apply(db.sortedSetAdd, 'uid:' + uid + ':notifications:unread', notification.datetime, nid)
+ async.apply(db.sortedSetAdd, 'uid:' + uid + ':notifications:unread', notification.datetime, nid),
], callback);
});
};
@@ -325,7 +324,7 @@ var utils = require('../public/src/utils');
});
db.getObjectsFields(notificationKeys, ['nid', 'datetime'], next);
- }
+ },
], function (err, notificationData) {
if (err) {
return callback(err);
@@ -351,7 +350,7 @@ var utils = require('../public/src/utils');
},
function (next) {
db.sortedSetAdd('uid:' + uid + ':notifications:read', datetimes, nids, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -373,8 +372,7 @@ var utils = require('../public/src/utils');
};
Notifications.prune = function () {
- var week = 604800000,
- numPruned = 0;
+ var week = 604800000;
var cutoffTime = Date.now() - week;
@@ -391,15 +389,13 @@ var utils = require('../public/src/utils');
return 'notifications:' + nid;
});
- numPruned = nids.length;
-
async.parallel([
function (next) {
db.sortedSetRemove('notifications', nids, next);
},
function (next) {
db.deleteAll(keys, next);
- }
+ },
], function (err) {
if (err) {
return winston.error('Encountered error pruning notifications: ' + err.message);
@@ -411,13 +407,17 @@ var utils = require('../public/src/utils');
Notifications.merge = function (notifications, callback) {
// When passed a set of notification objects, merge any that can be merged
var mergeIds = [
- 'notifications:upvoted_your_post_in',
- 'notifications:user_started_following_you',
- 'notifications:user_posted_to',
- 'notifications:user_flagged_post_in',
- 'new_register'
- ],
- isolated, differentiators, differentiator, modifyIndex, set;
+ 'notifications:upvoted_your_post_in',
+ 'notifications:user_started_following_you',
+ 'notifications:user_posted_to',
+ 'notifications:user_flagged_post_in',
+ 'new_register',
+ ];
+ var isolated;
+ var differentiators;
+ var differentiator;
+ var modifyIndex;
+ var set;
notifications = mergeIds.reduce(function (notifications, mergeId) {
isolated = notifications.filter(function (notifObj) {
@@ -456,35 +456,35 @@ var utils = require('../public/src/utils');
return notifications;
}
- switch(mergeId) {
+ switch (mergeId) {
// intentional fall-through
- case 'notifications:upvoted_your_post_in':
- case 'notifications:user_started_following_you':
- case 'notifications:user_posted_to':
- case 'notifications:user_flagged_post_in':
- var usernames = set.map(function (notifObj) {
- return notifObj && notifObj.user && notifObj.user.username;
- }).filter(function (username, idx, array) {
- return array.indexOf(username) === idx;
- });
- var numUsers = usernames.length;
+ case 'notifications:upvoted_your_post_in':
+ case 'notifications:user_started_following_you':
+ case 'notifications:user_posted_to':
+ case 'notifications:user_flagged_post_in':
+ var usernames = set.map(function (notifObj) {
+ return notifObj && notifObj.user && notifObj.user.username;
+ }).filter(function (username, idx, array) {
+ return array.indexOf(username) === idx;
+ });
+ var numUsers = usernames.length;
- var title = S(notifications[modifyIndex].topicTitle || '').decodeHTMLEntities().s;
- var titleEscaped = title.replace(/%/g, '%').replace(/,/g, ',');
- titleEscaped = titleEscaped ? (', ' + titleEscaped) : '';
+ var title = S(notifications[modifyIndex].topicTitle || '').decodeHTMLEntities().s;
+ var titleEscaped = title.replace(/%/g, '%').replace(/,/g, ',');
+ titleEscaped = titleEscaped ? (', ' + titleEscaped) : '';
- if (numUsers === 2) {
- notifications[modifyIndex].bodyShort = '[[' + mergeId + '_dual, ' + usernames.join(', ') + titleEscaped + ']]';
- } else if (numUsers > 2) {
- notifications[modifyIndex].bodyShort = '[[' + mergeId + '_multiple, ' + usernames[0] + ', ' + (numUsers - 1) + titleEscaped + ']]';
- }
+ if (numUsers === 2) {
+ notifications[modifyIndex].bodyShort = '[[' + mergeId + '_dual, ' + usernames.join(', ') + titleEscaped + ']]';
+ } else if (numUsers > 2) {
+ notifications[modifyIndex].bodyShort = '[[' + mergeId + '_multiple, ' + usernames[0] + ', ' + (numUsers - 1) + titleEscaped + ']]';
+ }
- notifications[modifyIndex].path = set[set.length - 1].path;
- break;
+ notifications[modifyIndex].path = set[set.length - 1].path;
+ break;
- case 'new_register':
- notifications[modifyIndex].bodyShort = '[[notifications:' + mergeId + '_multiple, ' + set.length + ']]';
- break;
+ case 'new_register':
+ notifications[modifyIndex].bodyShort = '[[notifications:' + mergeId + '_multiple, ' + set.length + ']]';
+ break;
}
// Filter out duplicates
@@ -501,11 +501,10 @@ var utils = require('../public/src/utils');
}, notifications);
plugins.fireHook('filter:notifications.merge', {
- notifications: notifications
+ notifications: notifications,
}, function (err, data) {
callback(err, data.notifications);
});
};
-
}(exports));
diff --git a/src/pagination.js b/src/pagination.js
index ba7dbc8436..3e57c5b201 100644
--- a/src/pagination.js
+++ b/src/pagination.js
@@ -7,12 +7,12 @@ var pagination = {};
pagination.create = function (currentPage, pageCount, queryObj) {
if (pageCount <= 1) {
return {
- prev: {page: 1, active: currentPage > 1},
- next: {page: 1, active: currentPage < pageCount},
+ prev: { page: 1, active: currentPage > 1 },
+ next: { page: 1, active: currentPage < pageCount },
rel: [],
pages: [],
currentPage: 1,
- pageCount: 1
+ pageCount: 1,
};
}
pageCount = parseInt(pageCount, 10);
@@ -26,7 +26,8 @@ pagination.create = function (currentPage, pageCount, queryObj) {
if (startPage > pageCount - 5) {
startPage -= 2 - (pageCount - currentPage);
}
- for(var i = 0; i < 5; ++i) {
+ var i;
+ for (i = 0; i < 5; i += 1) {
pagesToShow.push(startPage + i);
}
@@ -42,38 +43,38 @@ pagination.create = function (currentPage, pageCount, queryObj) {
var pages = pagesToShow.map(function (page) {
queryObj.page = page;
- return {page: page, active: page === currentPage, qs: qs.stringify(queryObj)};
+ return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) };
});
- for (i = pages.length - 1; i > 0; --i) {
+ for (i = pages.length - 1; i > 0; i -= 1) {
if (pages[i].page - 2 === pages[i - 1].page) {
- pages.splice(i, 0, {page: pages[i].page - 1, active: false, qs: qs.stringify(queryObj)});
+ pages.splice(i, 0, { page: pages[i].page - 1, active: false, qs: qs.stringify(queryObj) });
} else if (pages[i].page - 1 !== pages[i - 1].page) {
- pages.splice(i, 0, {separator: true});
+ pages.splice(i, 0, { separator: true });
}
}
- var data = {rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount};
+ var data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount };
queryObj.page = previous;
- data.prev = {page: previous, active: currentPage > 1, qs: qs.stringify(queryObj)};
+ data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) };
queryObj.page = next;
- data.next = {page: next, active: currentPage < pageCount, qs: qs.stringify(queryObj)};
+ data.next = { page: next, active: currentPage < pageCount, qs: qs.stringify(queryObj) };
if (currentPage < pageCount) {
data.rel.push({
rel: 'next',
- href: '?page=' + next
+ href: '?page=' + next,
});
}
if (currentPage > 1) {
data.rel.push({
rel: 'prev',
- href: '?page=' + previous
+ href: '?page=' + previous,
});
}
return data;
};
-module.exports = pagination;
\ No newline at end of file
+module.exports = pagination;
diff --git a/src/password.js b/src/password.js
index 2744cbefba..d4fd1b0f8d 100644
--- a/src/password.js
+++ b/src/password.js
@@ -4,17 +4,17 @@
var fork = require('child_process').fork;
module.hash = function (rounds, password, callback) {
- forkChild({type: 'hash', rounds: rounds, password: password}, callback);
+ forkChild({ type: 'hash', rounds: rounds, password: password }, callback);
};
module.compare = function (password, hash, callback) {
- forkChild({type: 'compare', password: password, hash: hash}, callback);
+ forkChild({ type: 'compare', password: password, hash: hash }, callback);
};
function forkChild(message, callback) {
var forkProcessParams = {};
- if(global.v8debug || parseInt(process.execArgv.indexOf('--debug'), 10) !== -1) {
- forkProcessParams = {execArgv: ['--debug=' + (5859), '--nolazy']};
+ if (global.v8debug || parseInt(process.execArgv.indexOf('--debug'), 10) !== -1) {
+ forkProcessParams = { execArgv: ['--debug=' + (5859), '--nolazy'] };
}
var child = fork('./bcrypt', [], forkProcessParams);
@@ -30,4 +30,4 @@
}
return module;
-}(exports));
\ No newline at end of file
+}(exports));
diff --git a/src/plugins.js b/src/plugins.js
index 15f4b91650..7c2ecaee25 100644
--- a/src/plugins.js
+++ b/src/plugins.js
@@ -108,7 +108,7 @@ var middleware;
if (Plugins.versionWarning.length && nconf.get('isPrimary') === 'true') {
process.stdout.write('\n');
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++) {
+ for (var x = 0, numPlugins = Plugins.versionWarning.length; x < numPlugins; x += 1) {
process.stdout.write(' * '.yellow + Plugins.versionWarning[x] + '\n');
}
process.stdout.write('\n');
@@ -116,18 +116,17 @@ var middleware;
Object.keys(Plugins.loadedHooks).forEach(function (hook) {
var hooks = Plugins.loadedHooks[hook];
- hooks = hooks.sort(function (a, b) {
+ hooks.sort(function (a, b) {
return a.priority - b.priority;
});
});
next();
- }
+ },
], callback);
};
Plugins.reloadRoutes = function (callback) {
- callback = callback || function () {};
var router = express.Router();
router.hotswapId = 'plugins';
@@ -136,9 +135,10 @@ var middleware;
};
var controllers = require('./controllers');
- Plugins.fireHook('static:app.load', {app: app, router: router, middleware: middleware, controllers: controllers}, function (err) {
+ Plugins.fireHook('static:app.load', { app: app, router: router, middleware: middleware, controllers: controllers }, function (err) {
if (err) {
- return winston.error('[plugins] Encountered error while executing post-router plugins hooks: ' + err.message);
+ winston.error('[plugins] Encountered error while executing post-router plugins hooks: ' + err.message);
+ return callback(err);
}
hotswap.replace('plugins', router);
@@ -148,8 +148,8 @@ var middleware;
};
Plugins.getTemplates = function (callback) {
- var templates = {},
- tplName;
+ var templates = {};
+ var tplName;
async.waterfall([
async.apply(db.getSortedSetRange, 'plugins:active', 0, -1),
@@ -166,7 +166,7 @@ var middleware;
},
function (paths, next) {
async.map(paths, Plugins.loadPluginInfo, next);
- }
+ },
], function (err, plugins) {
if (err) {
return callback(err);
@@ -180,7 +180,7 @@ var middleware;
if (pluginTemplates) {
pluginTemplates.forEach(function (pluginTemplate) {
if (pluginTemplate.endsWith('.tpl')) {
- tplName = "/" + pluginTemplate.replace(templatesPath, '').substring(1);
+ tplName = '/' + pluginTemplate.replace(templatesPath, '').substring(1);
if (templates.hasOwnProperty(tplName)) {
winston.verbose('[plugins] ' + tplName + ' replaced by ' + plugin.id);
@@ -191,12 +191,10 @@ var middleware;
winston.warn('[plugins] Skipping ' + pluginTemplate + ' by plugin ' + plugin.id);
}
});
+ } else if (err) {
+ winston.error(err);
} else {
- if (err) {
- winston.error(err);
- } else {
- winston.warn('[plugins/' + plugin.id + '] A templates directory was defined for this plugin, but was not found.');
- }
+ winston.warn('[plugins/' + plugin.id + '] A templates directory was defined for this plugin, but was not found.');
}
next(false);
@@ -214,7 +212,7 @@ var middleware;
var url = (nconf.get('registry') || 'https://packages.nodebb.org') + '/api/v1/plugins/' + id;
require('request')(url, {
- json: true
+ json: true,
}, function (err, res, body) {
if (res.statusCode === 404 || !body.payload) {
return callback(err, {});
@@ -238,7 +236,7 @@ var middleware;
var url = (nconf.get('registry') || 'https://packages.nodebb.org') + '/api/v1/plugins' + (matching !== false ? '?version=' + version : '');
require('request')(url, {
- json: true
+ json: true,
}, function (err, res, body) {
if (err) {
winston.error('Error parsing plugins : ' + err.message);
@@ -253,11 +251,11 @@ var middleware;
var pluginMap = {};
var dependencies = require(path.join(nconf.get('base_dir'), 'package.json')).dependencies;
apiReturn = apiReturn || [];
- for(var i = 0; i < apiReturn.length; ++i) {
+ for (var i = 0; i < apiReturn.length; i += 1) {
apiReturn[i].id = apiReturn[i].name;
apiReturn[i].installed = false;
apiReturn[i].active = false;
- apiReturn[i].url = apiReturn[i].url ? apiReturn[i].url : apiReturn[i].repository ? apiReturn[i].repository.url : '';
+ apiReturn[i].url = apiReturn[i].url || (apiReturn[i].repository ? apiReturn[i].repository.url : '');
pluginMap[apiReturn[i].name] = apiReturn[i];
}
@@ -313,13 +311,12 @@ var middleware;
}
pluginArray.sort(function (a, b) {
- if (a.name > b.name ) {
+ if (a.name > b.name) {
return 1;
- } else if (a.name < b.name ) {
+ } else if (a.name < b.name) {
return -1;
- } else {
- return 0;
}
+ return 0;
});
callback(null, pluginArray);
@@ -373,7 +370,7 @@ var middleware;
pluginData.error = false;
next(null, pluginData);
});
- }
+ },
], function (err, pluginData) {
if (err) {
return next(); // Silently fail
@@ -385,8 +382,7 @@ var middleware;
}, function (err) {
next(err, plugins);
});
- }
+ },
], callback);
};
-
}(exports));
diff --git a/src/plugins/hooks.js b/src/plugins/hooks.js
index b8e5af0e46..12303555fc 100644
--- a/src/plugins/hooks.js
+++ b/src/plugins/hooks.js
@@ -1,13 +1,13 @@
'use strict';
-var winston = require('winston'),
- async = require('async');
+var winston = require('winston');
+var async = require('async');
module.exports = function (Plugins) {
Plugins.deprecatedHooks = {
'filter:user.custom_fields': null, // remove in v1.1.0
'filter:post.save': 'filter:post.create',
- 'filter:user.profileLinks': 'filter:user.profileMenu'
+ 'filter:user.profileLinks': 'filter:user.profileMenu',
};
/*
`data` is an object consisting of (* is required):
@@ -44,7 +44,7 @@ module.exports = function (Plugins) {
if (parts.length > 2) {
parts.pop();
}
- var hook = parts.join(':');
+ parts.join(':');
}
if (data.hook && data.method) {
@@ -57,10 +57,9 @@ module.exports = function (Plugins) {
method = data.method.split('.').reduce(function (memo, prop) {
if (memo && memo[prop]) {
return memo[prop];
- } else {
- // Couldn't find method by path, aborting
- return null;
}
+ // Couldn't find method by path, aborting
+ return null;
}, Plugins.libraries[data.id]);
// Write the actual method reference to the hookObj
@@ -76,6 +75,13 @@ module.exports = function (Plugins) {
}
};
+ Plugins.unregisterHook = function (id, hook, method) {
+ var hooks = Plugins.loadedHooks[hook] || [];
+ Plugins.loadedHooks[hook] = hooks.filter(function (hookData) {
+ return hookData && hookData.id !== id && hookData.method !== method;
+ });
+ };
+
Plugins.fireHook = function (hook, params, callback) {
callback = typeof callback === 'function' ? callback : function () {};
@@ -83,18 +89,18 @@ module.exports = function (Plugins) {
var hookType = hook.split(':')[0];
switch (hookType) {
- case 'filter':
- fireFilterHook(hook, hookList, params, callback);
- break;
- case 'action':
- fireActionHook(hook, hookList, params, callback);
- break;
- case 'static':
- fireStaticHook(hook, hookList, params, callback);
- break;
- default:
- winston.warn('[plugins] Unknown hookType: ' + hookType + ', hook : ' + hook);
- break;
+ case 'filter':
+ fireFilterHook(hook, hookList, params, callback);
+ break;
+ case 'action':
+ fireActionHook(hook, hookList, params, callback);
+ break;
+ case 'static':
+ fireStaticHook(hook, hookList, params, callback);
+ break;
+ default:
+ winston.warn('[plugins] Unknown hookType: ' + hookType + ', hook : ' + hook);
+ break;
}
};
@@ -126,7 +132,6 @@ module.exports = function (Plugins) {
return callback();
}
async.each(hookList, function (hookObj, next) {
-
if (typeof hookObj.method !== 'function') {
if (global.env === 'development') {
winston.warn('[plugins] Expected method for hook \'' + hook + '\' in plugin \'' + hookObj.id + '\' not found, skipping.');
@@ -160,7 +165,7 @@ module.exports = function (Plugins) {
next.apply(null, arguments);
}
});
- } catch(err) {
+ } catch (err) {
winston.error('[plugins] Error executing \'' + hook + '\' in plugin \'' + hookObj.id + '\'');
winston.error(err);
clearTimeout(timeoutId);
diff --git a/src/plugins/install.js b/src/plugins/install.js
index 840d46008a..1e0fe0838c 100644
--- a/src/plugins/install.js
+++ b/src/plugins/install.js
@@ -13,7 +13,6 @@ var pubsub = require('../pubsub');
module.exports = function (Plugins) {
-
if (nconf.get('isPrimary') === 'true') {
pubsub.on('plugins:toggleInstall', function (data) {
if (data.hostname !== os.hostname()) {
@@ -52,18 +51,18 @@ module.exports = function (Plugins) {
meta.reloadRequired = true;
Plugins.fireHook(isActive ? 'action:plugin.deactivate' : 'action:plugin.activate', id);
next();
- }
+ },
], function (err) {
if (err) {
winston.warn('[plugins] Could not toggle active state on plugin \'' + id + '\'');
return callback(err);
}
- callback(null, {id: id, active: !isActive});
+ callback(null, { id: id, active: !isActive });
});
};
Plugins.toggleInstall = function (id, version, callback) {
- pubsub.publish('plugins:toggleInstall', {hostname: os.hostname(), id: id, version: version});
+ pubsub.publish('plugins:toggleInstall', { hostname: os.hostname(), id: id, version: version });
toggleInstall(id, version, callback);
};
@@ -81,7 +80,7 @@ module.exports = function (Plugins) {
},
function (active, next) {
if (active) {
- Plugins.toggleActive(id, function (err, status) {
+ Plugins.toggleActive(id, function (err) {
next(err);
});
return;
@@ -97,7 +96,7 @@ module.exports = function (Plugins) {
function (pluginData, next) {
Plugins.fireHook('action:plugin.' + type, id);
next(null, pluginData);
- }
+ },
], callback);
}
@@ -113,7 +112,7 @@ module.exports = function (Plugins) {
}
Plugins.upgrade = function (id, version, callback) {
- pubsub.publish('plugins:upgrade', {hostname: os.hostname(), id: id, version: version});
+ pubsub.publish('plugins:upgrade', { hostname: os.hostname(), id: id, version: version });
upgrade(id, version, callback);
};
@@ -126,7 +125,7 @@ module.exports = function (Plugins) {
function (isActive, next) {
meta.reloadRequired = isActive;
next(null, isActive);
- }
+ },
], callback);
}
@@ -145,4 +144,4 @@ module.exports = function (Plugins) {
Plugins.getActive = function (callback) {
db.getSortedSetRange('plugins:active', 0, -1, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/plugins/load.js b/src/plugins/load.js
index c6a9429667..3c1c61df73 100644
--- a/src/plugins/load.js
+++ b/src/plugins/load.js
@@ -61,7 +61,7 @@ module.exports = function (Plugins) {
async.apply(mapSoundpack, pluginData),
], next);
}, next);
- }
+ },
], callback);
};
@@ -145,7 +145,7 @@ module.exports = function (Plugins) {
} else {
callback();
}
- } catch(err) {
+ } catch (err) {
winston.error(err.stack);
winston.warn('[plugins] Unable to parse library for: ' + pluginData.id);
callback();
@@ -153,6 +153,8 @@ module.exports = function (Plugins) {
}
function mapStaticDirectories(pluginData, pluginPath, callback) {
+ var validMappedPath = /^[\w\-_]+$/;
+
function mapStaticDirs(mappedPath, callback) {
if (Plugins.staticDirs[mappedPath]) {
winston.warn('[plugins/' + pluginData.id + '] Mapped path (' + mappedPath + ') already specified!');
@@ -175,8 +177,6 @@ module.exports = function (Plugins) {
}
}
- var validMappedPath = /^[\w\-_]+$/;
-
pluginData.staticDirs = pluginData.staticDirs || {};
var dirs = Object.keys(pluginData.staticDirs);
@@ -230,7 +230,7 @@ module.exports = function (Plugins) {
pluginData.modules.forEach(function (file) {
if (strip) {
- modules[file.replace(new RegExp('\.?(\/[^\/]+){' + strip + '}\/'), '')] = path.join('./node_modules/', pluginData.id, file);
+ modules[file.replace(new RegExp('.?(/[^/]+){' + strip + '}/'), '')] = path.join('./node_modules/', pluginData.id, file);
} else {
modules[path.basename(file)] = path.join('./node_modules/', pluginData.id, file);
}
@@ -302,11 +302,10 @@ module.exports = function (Plugins) {
if (!atRootLevel && relPath) {
winston.verbose('[plugins/load] File not found: ' + fullPath + ' (Ascending)');
return resolveModulePath(path.join(__dirname, '../..', relPath));
- } else {
- // Already at root level, file was simply not found
- winston.warn('[plugins/load] File not found: ' + fullPath + ' (Ignoring)');
- return null;
}
+ // Already at root level, file was simply not found
+ winston.warn('[plugins/load] File not found: ' + fullPath + ' (Ignoring)');
+ return null;
}
}
@@ -317,7 +316,7 @@ module.exports = function (Plugins) {
},
plugin: function (next) {
fs.readFile(path.join(pluginPath, 'plugin.json'), next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -335,7 +334,7 @@ module.exports = function (Plugins) {
pluginData.repository = packageData.repository;
pluginData.nbbpm = packageData.nbbpm;
pluginData.path = pluginPath;
- } catch(err) {
+ } catch (err) {
var pluginDir = pluginPath.split(path.sep);
pluginDir = pluginDir[pluginDir.length - 1];
diff --git a/src/posts.js b/src/posts.js
index 3a7d2d7e19..c7e7ec3e0a 100644
--- a/src/posts.js
+++ b/src/posts.js
@@ -11,7 +11,6 @@ var privileges = require('./privileges');
var plugins = require('./plugins');
(function (Posts) {
-
require('./posts/create')(Posts);
require('./posts/delete')(Posts);
require('./posts/edit')(Posts);
@@ -44,7 +43,7 @@ var plugins = require('./plugins');
var keys = [];
- for (var x = 0, numPids = pids.length; x < numPids; ++x) {
+ for (var x = 0, numPids = pids.length; x < numPids; x += 1) {
keys.push('post:' + pids[x]);
}
@@ -66,7 +65,7 @@ var plugins = require('./plugins');
}, next);
},
function (posts, next) {
- plugins.fireHook('filter:post.getPosts', {posts: posts, uid: uid}, next);
+ plugins.fireHook('filter:post.getPosts', { posts: posts, uid: uid }, next);
},
function (data, next) {
if (!data || !Array.isArray(data.posts)) {
@@ -74,7 +73,7 @@ var plugins = require('./plugins');
}
data.posts = data.posts.filter(Boolean);
next(null, data.posts);
- }
+ },
], callback);
};
@@ -87,11 +86,11 @@ var plugins = require('./plugins');
privileges.posts.filter('read', pids, uid, next);
},
function (pids, next) {
- Posts.getPostSummaryByPids(pids, uid, {stripTags: false}, next);
+ Posts.getPostSummaryByPids(pids, uid, { stripTags: false }, next);
},
function (posts, next) {
- next(null, {posts: posts, nextStart: stop + 1});
- }
+ next(null, { posts: posts, nextStart: stop + 1 });
+ },
], callback);
};
@@ -123,7 +122,7 @@ var plugins = require('./plugins');
data.pid = pid;
- plugins.fireHook('filter:post.getFields', {posts: [data], fields: fields}, function (err, data) {
+ plugins.fireHook('filter:post.getFields', { posts: [data], fields: fields }, function (err, data) {
callback(err, (data && Array.isArray(data.posts) && data.posts.length) ? data.posts[0] : null);
});
});
@@ -142,7 +141,7 @@ var plugins = require('./plugins');
if (err) {
return callback(err);
}
- plugins.fireHook('filter:post.getFields', {posts: posts, fields: fields}, function (err, data) {
+ plugins.fireHook('filter:post.getFields', { posts: posts, fields: fields }, function (err, data) {
callback(err, (data && Array.isArray(data.posts)) ? data.posts : null);
});
});
@@ -154,7 +153,7 @@ var plugins = require('./plugins');
return callback(err);
}
var data = {
- pid: pid
+ pid: pid,
};
data[field] = value;
plugins.fireHook('action:post.setFields', data);
@@ -212,12 +211,12 @@ var plugins = require('./plugins');
db[method](sets, pids, next);
},
function (indices, next) {
- for (var i = 0; i < indices.length; ++i) {
+ for (var i = 0; i < indices.length; i += 1) {
indices[i] = utils.isNumber(indices[i]) ? parseInt(indices[i], 10) + 1 : 0;
}
next(null, indices);
- }
+ },
], callback);
};
@@ -247,12 +246,12 @@ var plugins = require('./plugins');
return next();
}
db.sortedSetAdd('tid:' + postData.tid + ':posts:votes', postData.votes, postData.pid, next);
- }
+ },
], next);
},
function (next) {
- Posts.setPostFields(postData.pid, {upvotes: postData.upvotes, downvotes: postData.downvotes}, next);
- }
+ Posts.setPostFields(postData.pid, { upvotes: postData.upvotes, downvotes: postData.downvotes }, next);
+ },
], function (err) {
callback(err);
});
@@ -266,6 +265,4 @@ var plugins = require('./plugins');
}
}
};
-
-
}(exports));
diff --git a/src/posts/bookmarks.js b/src/posts/bookmarks.js
index b60da91c77..6038a50b54 100644
--- a/src/posts/bookmarks.js
+++ b/src/posts/bookmarks.js
@@ -6,7 +6,6 @@ var db = require('../database');
var plugins = require('../plugins');
module.exports = function (Posts) {
-
Posts.bookmark = function (pid, uid, callback) {
toggleBookmark('bookmark', pid, uid, callback);
};
@@ -30,7 +29,7 @@ module.exports = function (Posts) {
},
hasBookmarked: function (next) {
Posts.hasBookmarked(pid, uid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -61,7 +60,7 @@ module.exports = function (Posts) {
function (count, next) {
results.postData.bookmarks = count;
Posts.setPostField(pid, 'bookmarks', count, next);
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -73,12 +72,12 @@ module.exports = function (Posts) {
pid: pid,
uid: uid,
owner: results.owner,
- current: current
+ current: current,
});
callback(null, {
post: results.postData,
- isBookmarked: isBookmarking
+ isBookmarked: isBookmarking,
});
});
});
diff --git a/src/posts/cache.js b/src/posts/cache.js
index 62277c46e3..c73e1c8d92 100644
--- a/src/posts/cache.js
+++ b/src/posts/cache.js
@@ -1,10 +1,12 @@
+'use strict';
+
var LRU = require('lru-cache');
var meta = require('../meta');
var cache = LRU({
max: parseInt(meta.config.postCacheSize, 10) || 1048576,
length: function (n) { return n.length; },
- maxAge: 1000 * 60 * 60
+ maxAge: 1000 * 60 * 60,
});
-module.exports = cache;
\ No newline at end of file
+module.exports = cache;
diff --git a/src/posts/category.js b/src/posts/category.js
index 9c877d91dd..cb9a2566c4 100644
--- a/src/posts/category.js
+++ b/src/posts/category.js
@@ -8,7 +8,6 @@ var db = require('../database');
var topics = require('../topics');
module.exports = function (Posts) {
-
Posts.getCidByPid = function (pid, callback) {
async.waterfall([
function (next) {
@@ -16,7 +15,7 @@ module.exports = function (Posts) {
},
function (tid, next) {
topics.getTopicField(tid, 'cid', next);
- }
+ },
], callback);
};
@@ -49,7 +48,7 @@ module.exports = function (Posts) {
return map[post.tid];
});
next(null, cids);
- }
+ },
], callback);
};
@@ -82,4 +81,4 @@ module.exports = function (Posts) {
});
}
};
-};
\ No newline at end of file
+};
diff --git a/src/posts/create.js b/src/posts/create.js
index 3484bc424e..e8e24a5585 100644
--- a/src/posts/create.js
+++ b/src/posts/create.js
@@ -12,7 +12,6 @@ var categories = require('../categories');
var utils = require('../../public/src/utils');
module.exports = function (Posts) {
-
Posts.create = function (data, callback) {
// This is an internal method, consider using Topics.reply instead
var uid = data.uid;
@@ -36,14 +35,13 @@ module.exports = function (Posts) {
db.incrObjectField('global', 'nextPid', next);
},
function (pid, next) {
-
postData = {
- 'pid': pid,
- 'uid': uid,
- 'tid': tid,
- 'content': content,
- 'timestamp': timestamp,
- 'deleted': 0
+ pid: pid,
+ uid: uid,
+ tid: tid,
+ content: content,
+ timestamp: timestamp,
+ deleted: 0,
};
if (data.toPid) {
@@ -61,7 +59,7 @@ module.exports = function (Posts) {
plugins.fireHook('filter:post.save', postData, next);
},
function (postData, next) {
- plugins.fireHook('filter:post.create', {post: postData, data: data}, next);
+ plugins.fireHook('filter:post.create', { post: postData, data: data }, next);
},
function (data, next) {
postData = data.post;
@@ -93,12 +91,12 @@ module.exports = function (Posts) {
}
async.parallel([
async.apply(db.sortedSetAdd, 'pid:' + postData.toPid + ':replies', timestamp, postData.pid),
- async.apply(db.incrObjectField, 'post:' + postData.toPid, 'replies')
+ async.apply(db.incrObjectField, 'post:' + postData.toPid, 'replies'),
], next);
},
function (next) {
db.incrObjectField('global', 'postCount', next);
- }
+ },
], function (err) {
if (err) {
return next(err);
@@ -110,9 +108,8 @@ module.exports = function (Posts) {
postData.isMain = isMain;
plugins.fireHook('action:post.save', _.clone(postData));
next(null, postData);
- }
+ },
], callback);
};
};
-
diff --git a/src/posts/delete.js b/src/posts/delete.js
index 7a1d3d0cc8..63f511481b 100644
--- a/src/posts/delete.js
+++ b/src/posts/delete.js
@@ -10,15 +10,14 @@ var notifications = require('../notifications');
var plugins = require('../plugins');
module.exports = function (Posts) {
-
Posts.delete = function (pid, uid, callback) {
var postData;
async.waterfall([
function (next) {
- plugins.fireHook('filter:post.delete', {pid: pid, uid: uid}, next);
+ plugins.fireHook('filter:post.delete', { pid: pid, uid: uid }, next);
},
function (data, next) {
- Posts.setPostFields(pid, {deleted: 1, deleterUid: uid}, next);
+ Posts.setPostFields(pid, { deleted: 1, deleterUid: uid }, next);
},
function (next) {
Posts.getPostFields(pid, ['pid', 'tid', 'uid', 'timestamp'], next);
@@ -37,13 +36,13 @@ module.exports = function (Posts) {
},
function (next) {
topics.updateTeaser(postData.tid, next);
- }
+ },
], next);
},
function (results, next) {
plugins.fireHook('action:post.delete', pid);
next(null, postData);
- }
+ },
], callback);
};
@@ -51,10 +50,10 @@ module.exports = function (Posts) {
var postData;
async.waterfall([
function (next) {
- plugins.fireHook('filter:post.restore', {pid: pid, uid: uid}, next);
+ plugins.fireHook('filter:post.restore', { pid: pid, uid: uid }, next);
},
function (data, next) {
- Posts.setPostFields(pid, {deleted: 0, deleterUid: 0}, next);
+ Posts.setPostFields(pid, { deleted: 0, deleterUid: 0 }, next);
},
function (next) {
Posts.getPostFields(pid, ['pid', 'tid', 'uid', 'content', 'timestamp'], next);
@@ -74,13 +73,13 @@ module.exports = function (Posts) {
},
function (next) {
topics.updateTeaser(postData.tid, next);
- }
+ },
], next);
},
function (results, next) {
plugins.fireHook('action:post.restore', _.clone(postData));
next(null, postData);
- }
+ },
], callback);
};
@@ -109,7 +108,7 @@ module.exports = function (Posts) {
} else {
next();
}
- }
+ },
], callback);
}
@@ -122,7 +121,7 @@ module.exports = function (Posts) {
if (!exists) {
return callback();
}
- plugins.fireHook('filter:post.purge', {pid: pid, uid: uid}, next);
+ plugins.fireHook('filter:post.purge', { pid: pid, uid: uid }, next);
},
function (data, next) {
async.parallel([
@@ -146,7 +145,7 @@ module.exports = function (Posts) {
},
function (next) {
Posts.dismissFlag(pid, next);
- }
+ },
], function (err) {
if (err) {
return next(err);
@@ -154,7 +153,7 @@ module.exports = function (Posts) {
plugins.fireHook('action:post.purge', pid);
db.delete('post:' + pid, next);
});
- }
+ },
], callback);
};
@@ -169,7 +168,7 @@ module.exports = function (Posts) {
db.sortedSetsRemove([
'tid:' + postData.tid + ':posts',
'tid:' + postData.tid + ':posts:votes',
- 'uid:' + postData.uid + ':posts'
+ 'uid:' + postData.uid + ':posts',
], pid, next);
},
function (next) {
@@ -203,9 +202,9 @@ module.exports = function (Posts) {
},
function (next) {
notifications.rescind('new_post:tid:' + postData.tid + ':pid:' + pid + ':uid:' + postData.uid, next);
- }
+ },
], next);
- }
+ },
], function (err) {
callback(err);
});
@@ -252,7 +251,7 @@ module.exports = function (Posts) {
},
downvoters: function (next) {
db.getSetMembers('pid:' + pid + ':downvote', next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -275,7 +274,7 @@ module.exports = function (Posts) {
},
function (next) {
db.deleteAll(['pid:' + pid + ':upvote', 'pid:' + pid + ':downvote'], next);
- }
+ },
], callback);
});
}
@@ -290,10 +289,8 @@ module.exports = function (Posts) {
}
async.parallel([
async.apply(db.sortedSetRemove, 'pid:' + toPid + ':replies', pid),
- async.apply(db.decrObjectField, 'post:' + toPid, 'replies')
+ async.apply(db.decrObjectField, 'post:' + toPid, 'replies'),
], callback);
});
}
-
-
};
diff --git a/src/posts/edit.js b/src/posts/edit.js
index b989b24f8f..863888a6ce 100644
--- a/src/posts/edit.js
+++ b/src/posts/edit.js
@@ -14,7 +14,6 @@ var pubsub = require('../pubsub');
var utils = require('../../public/src/utils');
module.exports = function (Posts) {
-
pubsub.on('post:edit', function (pid) {
cache.del(pid);
});
@@ -45,7 +44,7 @@ module.exports = function (Posts) {
if (data.handle) {
postData.handle = data.handle;
}
- plugins.fireHook('filter:post.edit', {req: data.req, post: postData, data: data, uid: data.uid}, next);
+ plugins.fireHook('filter:post.edit', { req: data.req, post: postData, data: data, uid: data.uid }, next);
},
function (result, next) {
postData = result.post;
@@ -58,7 +57,7 @@ module.exports = function (Posts) {
},
topic: function (next) {
editMainPost(data, postData, next);
- }
+ },
}, next);
},
function (_results, next) {
@@ -76,7 +75,7 @@ module.exports = function (Posts) {
function (postData, next) {
results.post = postData;
next(null, results);
- }
+ },
], callback);
};
@@ -90,7 +89,7 @@ module.exports = function (Posts) {
},
isMain: function (next) {
Posts.isMain(data.pid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -101,7 +100,7 @@ module.exports = function (Posts) {
tid: tid,
cid: results.topic.cid,
isMainPost: false,
- renamed: false
+ renamed: false,
});
}
@@ -109,7 +108,7 @@ module.exports = function (Posts) {
tid: tid,
cid: results.topic.cid,
uid: postData.uid,
- mainPid: data.pid
+ mainPid: data.pid,
};
if (title) {
@@ -123,7 +122,7 @@ module.exports = function (Posts) {
async.waterfall([
function (next) {
- plugins.fireHook('filter:topic.edit', {req: data.req, topic: topicData, data: data}, next);
+ plugins.fireHook('filter:topic.edit', { req: data.req, topic: topicData, data: data }, next);
},
function (results, next) {
db.setObject('topic:' + tid, results.topic, next);
@@ -147,12 +146,10 @@ module.exports = function (Posts) {
slug: topicData.slug,
isMainPost: true,
renamed: title !== results.topic.title,
- tags: tags
+ tags: tags,
});
- }
+ },
], callback);
});
}
-
-
};
diff --git a/src/posts/flags.js b/src/posts/flags.js
index e81da20f95..214a155278 100644
--- a/src/posts/flags.js
+++ b/src/posts/flags.js
@@ -9,7 +9,6 @@ var user = require('../user');
var analytics = require('../analytics');
module.exports = function (Posts) {
-
Posts.flag = function (post, uid, reason, callback) {
if (!parseInt(uid, 10) || !reason) {
return callback();
@@ -19,7 +18,7 @@ module.exports = function (Posts) {
function (next) {
async.parallel({
hasFlagged: async.apply(Posts.isFlaggedByUser, post.pid, uid),
- exists: async.apply(Posts.exists, post.pid)
+ exists: async.apply(Posts.exists, post.pid),
}, next);
},
function (results, next) {
@@ -53,17 +52,17 @@ module.exports = function (Posts) {
async.parallel([
async.apply(db.sortedSetIncrBy, 'users:flags', 1, post.uid),
async.apply(db.incrObjectField, 'user:' + post.uid, 'flags'),
- async.apply(db.sortedSetAdd, 'uid:' + post.uid + ':flag:pids', now, post.pid)
+ async.apply(db.sortedSetAdd, 'uid:' + post.uid + ':flag:pids', now, post.pid),
], next);
} else {
next();
}
- }
+ },
], next);
},
function (data, next) {
openNewFlag(post.pid, uid, next);
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -80,7 +79,7 @@ module.exports = function (Posts) {
}
if (count === 1) { // Only update state on new flag
Posts.updateFlagData(uid, pid, {
- state: 'open'
+ state: 'open',
}, callback);
} else {
callback();
@@ -107,7 +106,7 @@ module.exports = function (Posts) {
if (parseInt(postData.flags, 10) > 0) {
async.parallel([
async.apply(db.sortedSetIncrBy, 'users:flags', -postData.flags, postData.uid),
- async.apply(db.incrObjectFieldBy, 'user:' + postData.uid, 'flags', -postData.flags)
+ async.apply(db.incrObjectFieldBy, 'user:' + postData.uid, 'flags', -postData.flags),
], next);
} else {
next();
@@ -120,7 +119,7 @@ module.exports = function (Posts) {
db.sortedSetsRemove([
'posts:flagged',
'posts:flags:count',
- 'uid:' + postData.uid + ':flag:pids'
+ 'uid:' + postData.uid + ':flag:pids',
], pid, next);
},
function (next) {
@@ -135,22 +134,22 @@ module.exports = function (Posts) {
var nid = 'post_flag:' + pid + ':uid:' + uid;
async.parallel([
async.apply(db.delete, 'notifications:' + nid),
- async.apply(db.sortedSetRemove, 'notifications', 'post_flag:' + pid + ':uid:' + uid)
+ async.apply(db.sortedSetRemove, 'notifications', 'post_flag:' + pid + ':uid:' + uid),
], next);
}, next);
});
},
- async.apply(db.delete, 'pid:' + pid + ':flag:uids')
+ async.apply(db.delete, 'pid:' + pid + ':flag:uids'),
], next);
},
async.apply(db.deleteObjectField, 'post:' + pid, 'flags'),
async.apply(db.delete, 'pid:' + pid + ':flag:uid:reason'),
- async.apply(db.deleteObjectFields, 'post:' + pid, ['flag:state', 'flag:assignee', 'flag:notes', 'flag:history'])
+ async.apply(db.deleteObjectFields, 'post:' + pid, ['flag:state', 'flag:assignee', 'flag:notes', 'flag:history']),
], next);
},
function (results, next) {
db.sortedSetsRemoveRangeByScore(['users:flags'], '-inf', 0, next);
- }
+ },
], callback);
};
@@ -176,7 +175,7 @@ module.exports = function (Posts) {
async.waterfall([
function (next) {
if (Array.isArray(set)) {
- db.getSortedSetRevIntersect({sets: set, start: start, stop: -1, aggregate: 'MAX'}, next);
+ db.getSortedSetRevIntersect({ sets: set, start: start, stop: -1, aggregate: 'MAX' }, next);
} else {
db.getSortedSetRevRange(set, start, -1, next);
}
@@ -194,8 +193,8 @@ module.exports = function (Posts) {
function (posts, next) {
var count = posts.length;
var end = stop - start + 1;
- next(null, {posts: posts.slice(0, stop === -1 ? undefined : end), count: count});
- }
+ next(null, { posts: posts.slice(0, stop === -1 ? undefined : end), count: count });
+ },
], callback);
};
@@ -209,8 +208,8 @@ module.exports = function (Posts) {
}, next);
},
posts: function (next) {
- Posts.getPostSummaryByPids(pids, uid, {stripTags: false, extraFields: ['flags', 'flag:assignee', 'flag:state', 'flag:notes', 'flag:history']}, next);
- }
+ Posts.getPostSummaryByPids(pids, uid, { stripTags: false, extraFields: ['flags', 'flag:assignee', 'flag:state', 'flag:notes', 'flag:history'] }, next);
+ },
}, next);
},
function (results, next) {
@@ -219,7 +218,7 @@ module.exports = function (Posts) {
var uid = uidReason.split(':')[0];
var reason = uidReason.substr(uidReason.indexOf(':') + 1);
user.getUserFields(uid, ['username', 'userslug', 'picture'], function (err, userData) {
- next(err, {user: userData, reason: reason});
+ next(err, { user: userData, reason: reason });
});
}, next);
}, function (err, reasons) {
@@ -240,14 +239,15 @@ module.exports = function (Posts) {
function (posts, next) {
// Parse out flag data into its own object inside each post hash
async.map(posts, function (postObj, next) {
- for(var prop in postObj) {
- postObj.flagData = postObj.flagData || {};
+ for (var prop in postObj) {
+ if (postObj.hasOwnProperty(prop)) {
+ postObj.flagData = postObj.flagData || {};
- if (postObj.hasOwnProperty(prop) && prop.startsWith('flag:')) {
- postObj.flagData[prop.slice(5)] = postObj[prop];
+ if (prop.startsWith('flag:')) {
+ postObj.flagData[prop.slice(5)] = postObj[prop];
- if (prop === 'flag:state') {
- switch(postObj[prop]) {
+ if (prop === 'flag:state') {
+ switch (postObj[prop]) {
case 'open':
postObj.flagData.labelClass = 'info';
break;
@@ -260,10 +260,11 @@ module.exports = function (Posts) {
case 'rejected':
postObj.flagData.labelClass = 'danger';
break;
+ }
}
- }
- delete postObj[prop];
+ delete postObj[prop];
+ }
}
}
@@ -280,7 +281,7 @@ module.exports = function (Posts) {
setImmediate(next.bind(null, null, postObj));
}
}, next);
- }
+ },
], callback);
}
@@ -296,14 +297,14 @@ module.exports = function (Posts) {
}
// Track new additions
- for(prop in flagObj) {
+ for (prop in flagObj) {
if (flagObj.hasOwnProperty(prop) && !postData.hasOwnProperty('flag:' + prop) && flagObj[prop].length) {
changes.push(prop);
}
}
// Track changed items
- for(prop in postData) {
+ for (prop in postData) {
if (
postData.hasOwnProperty(prop) && prop.startsWith('flag:') &&
flagObj.hasOwnProperty(prop.slice(5)) &&
@@ -324,23 +325,23 @@ module.exports = function (Posts) {
var history = JSON.parse(postData['flag:history'] || '[]');
changes.forEach(function (property) {
- switch(property) {
- case 'assignee': // intentional fall-through
- case 'state':
- history.unshift({
- uid: uid,
- type: property,
- value: flagObj[property],
- timestamp: Date.now()
- });
- break;
+ switch (property) {
+ case 'assignee': // intentional fall-through
+ case 'state':
+ history.unshift({
+ uid: uid,
+ type: property,
+ value: flagObj[property],
+ timestamp: Date.now(),
+ });
+ break;
- case 'notes':
- history.unshift({
- uid: uid,
- type: property,
- timestamp: Date.now()
- });
+ case 'notes':
+ history.unshift({
+ uid: uid,
+ type: property,
+ timestamp: Date.now(),
+ });
}
});
@@ -400,7 +401,7 @@ module.exports = function (Posts) {
} else {
setImmediate(next);
}
- }
+ },
], function (err) {
next(err, event);
});
diff --git a/src/posts/parse.js b/src/posts/parse.js
index e4b4cc7d3c..8ac2028bbd 100644
--- a/src/posts/parse.js
+++ b/src/posts/parse.js
@@ -1,5 +1,6 @@
'use strict';
+var async = require('async');
var nconf = require('nconf');
var url = require('url');
var winston = require('winston');
@@ -13,45 +14,40 @@ var translator = require('../../public/src/modules/translator');
var urlRegex = /href="([^"]+)"/g;
module.exports = function (Posts) {
-
Posts.parsePost = function (postData, callback) {
- postData.content = postData.content || '';
+ postData.content = String(postData.content || '');
if (postData.pid && cache.has(String(postData.pid))) {
postData.content = cache.get(String(postData.pid));
return callback(null, postData);
}
- // Casting post content into a string, just in case
- if (typeof postData.content !== 'string') {
- postData.content = postData.content.toString();
- }
+ async.waterfall([
+ function (next) {
+ plugins.fireHook('filter:parse.post', { postData: postData }, next);
+ },
+ function (data, next) {
+ data.postData.content = translator.escape(data.postData.content);
- plugins.fireHook('filter:parse.post', {postData: postData}, function (err, data) {
- if (err) {
- return callback(err);
- }
-
- data.postData.content = translator.escape(data.postData.content);
-
- if (global.env === 'production' && data.postData.pid) {
- cache.set(String(data.postData.pid), data.postData.content);
- }
-
- callback(null, data.postData);
- });
+ if (global.env === 'production' && data.postData.pid) {
+ cache.set(String(data.postData.pid), data.postData.content);
+ }
+ next(null, data.postData);
+ },
+ ], callback);
};
Posts.parseSignature = function (userData, uid, callback) {
userData.signature = sanitizeSignature(userData.signature || '');
- plugins.fireHook('filter:parse.signature', {userData: userData, uid: uid}, callback);
+ plugins.fireHook('filter:parse.signature', { userData: userData, uid: uid }, callback);
};
Posts.relativeToAbsolute = function (content) {
// Turns relative links in post body to absolute urls
- var parsed, current, absolute;
-
- while ((current = urlRegex.exec(content)) !== null) {
+ var parsed;
+ var current = urlRegex.exec(content);
+ var absolute;
+ while (current !== null) {
if (current[1]) {
try {
parsed = url.parse(current[1]);
@@ -66,18 +62,19 @@ module.exports = function (Posts) {
content = content.slice(0, current.index + 6) + absolute + content.slice(current.index + 6 + current[1].length);
}
- } catch(err) {
+ } catch (err) {
winston.verbose(err.messsage);
}
}
+ current = urlRegex.exec(content);
}
return content;
};
function sanitizeSignature(signature) {
- var string = S(signature),
- tagsToStrip = [];
+ var string = S(signature);
+ var tagsToStrip = [];
if (parseInt(meta.config['signatures:disableLinks'], 10) === 1) {
tagsToStrip.push('a');
diff --git a/src/posts/recent.js b/src/posts/recent.js
index 5cc5cd1fae..320febff19 100644
--- a/src/posts/recent.js
+++ b/src/posts/recent.js
@@ -9,7 +9,7 @@ module.exports = function (Posts) {
var terms = {
day: 86400000,
week: 604800000,
- month: 2592000000
+ month: 2592000000,
};
Posts.getRecentPosts = function (uid, start, stop, term, callback) {
@@ -28,8 +28,8 @@ module.exports = function (Posts) {
privileges.posts.filter('read', pids, uid, next);
},
function (pids, next) {
- Posts.getPostSummaryByPids(pids, uid, {stripTags: true}, next);
- }
+ Posts.getPostSummaryByPids(pids, uid, { stripTags: true }, next);
+ },
], callback);
};
@@ -48,7 +48,7 @@ module.exports = function (Posts) {
return uid && array.indexOf(uid) === index;
});
next(null, uids);
- }
+ },
], callback);
- };
+ };
};
diff --git a/src/posts/summary.js b/src/posts/summary.js
index 2173057e3a..93e322229d 100644
--- a/src/posts/summary.js
+++ b/src/posts/summary.js
@@ -13,7 +13,6 @@ var utils = require('../../public/src/utils');
module.exports = function (Posts) {
-
Posts.getPostSummaryByPids = function (pids, uid, options, callback) {
if (!Array.isArray(pids) || !pids.length) {
return callback(null, []);
@@ -50,7 +49,7 @@ module.exports = function (Posts) {
},
topicsAndCategories: function (next) {
getTopicAndCategories(topicKeys, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -81,11 +80,11 @@ module.exports = function (Posts) {
parsePosts(posts, options, next);
},
function (posts, next) {
- plugins.fireHook('filter:post.getPostSummaryByPids', {posts: posts, uid: uid}, next);
+ plugins.fireHook('filter:post.getPostSummaryByPids', { posts: posts, uid: uid }, next);
},
function (data, next) {
next(null, data.posts);
- }
+ },
], callback);
};
@@ -129,14 +128,14 @@ module.exports = function (Posts) {
});
categories.getCategoriesFields(cids, ['cid', 'name', 'icon', 'slug', 'parentCid', 'bgColor', 'color'], function (err, categories) {
- callback(err, {topics: topics, categories: categories});
+ callback(err, { topics: topics, categories: categories });
});
});
}
function toObject(key, data) {
var obj = {};
- for(var i = 0; i < data.length; ++i) {
+ for (var i = 0; i < data.length; i += 1) {
obj[data[i][key]] = data[i];
}
return obj;
diff --git a/src/posts/tools.js b/src/posts/tools.js
index 82d55b1192..c395eae457 100644
--- a/src/posts/tools.js
+++ b/src/posts/tools.js
@@ -30,7 +30,7 @@ module.exports = function (Posts) {
function (deleted, next) {
if (parseInt(deleted, 10) === 1 && isDelete) {
return next(new Error('[[error:post-already-deleted]]'));
- } else if(parseInt(deleted, 10) !== 1 && !isDelete) {
+ } else if (parseInt(deleted, 10) !== 1 && !isDelete) {
return next(new Error('[[error:post-already-restored]]'));
}
@@ -52,7 +52,7 @@ module.exports = function (Posts) {
Posts.parsePost(postData, next);
});
}
- }
+ },
], callback);
}
@@ -67,9 +67,8 @@ module.exports = function (Posts) {
}
cache.del(pid);
Posts.purge(pid, uid, next);
- }
+ },
], callback);
};
-
};
diff --git a/src/posts/topics.js b/src/posts/topics.js
index 0653c880e6..eca6da493a 100644
--- a/src/posts/topics.js
+++ b/src/posts/topics.js
@@ -7,7 +7,6 @@ var topics = require('../topics');
var utils = require('../../public/src/utils');
module.exports = function (Posts) {
-
Posts.getPostsFromSet = function (set, start, stop, uid, reverse, callback) {
async.waterfall([
function (next) {
@@ -15,7 +14,7 @@ module.exports = function (Posts) {
},
function (pids, next) {
Posts.getPostsByPids(pids, uid, next);
- }
+ },
], callback);
};
@@ -29,7 +28,7 @@ module.exports = function (Posts) {
},
function (mainPid, next) {
next(null, parseInt(pid, 10) === parseInt(mainPid, 10));
- }
+ },
], callback);
};
@@ -40,7 +39,7 @@ module.exports = function (Posts) {
},
function (tid, next) {
topics.getTopicFields(tid, fields, next);
- }
+ },
], callback);
};
@@ -66,7 +65,7 @@ module.exports = function (Posts) {
});
topics.getTopicsFields(tids, ['slug'], next);
- }
+ },
}, next);
},
function (results, next) {
@@ -81,8 +80,7 @@ module.exports = function (Posts) {
});
next(null, paths);
- }
+ },
], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/posts/user.js b/src/posts/user.js
index 7f387ef894..59906bf2ca 100644
--- a/src/posts/user.js
+++ b/src/posts/user.js
@@ -9,7 +9,6 @@ var meta = require('../meta');
var plugins = require('../plugins');
module.exports = function (Posts) {
-
Posts.getUserInfoForPosts = function (uids, uid, callback) {
var groupsMap = {};
var userData;
@@ -25,7 +24,7 @@ module.exports = function (Posts) {
return groupTitle && array.indexOf(groupTitle) === index;
});
groups.getGroupsData(groupTitles, next);
- }
+ },
], function (err, groupsData) {
if (err) {
return callback(err);
@@ -38,7 +37,7 @@ module.exports = function (Posts) {
slug: group.slug,
labelColor: group.labelColor,
icon: group.icon,
- userTitle: group.userTitle
+ userTitle: group.userTitle,
};
}
});
@@ -72,8 +71,8 @@ module.exports = function (Posts) {
Posts.parseSignature(userData, uid, next);
},
customProfileInfo: function (next) {
- plugins.fireHook('filter:posts.custom_profile_info', {profile: [], uid: userData.uid}, next);
- }
+ plugins.fireHook('filter:posts.custom_profile_info', { profile: [], uid: userData.uid }, next);
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -95,7 +94,7 @@ module.exports = function (Posts) {
uid = parseInt(uid, 10);
if (Array.isArray(pid)) {
if (!uid) {
- return callback(null, pid.map(function () {return false;}));
+ return callback(null, pid.map(function () { return false; }));
}
Posts.getPostsFields(pid, ['uid'], function (err, posts) {
if (err) {
@@ -118,7 +117,7 @@ module.exports = function (Posts) {
Posts.isModerator = function (pids, uid, callback) {
if (!parseInt(uid, 10)) {
- return callback(null, pids.map(function () {return false;}));
+ return callback(null, pids.map(function () { return false; }));
}
Posts.getCidsByPids(pids, function (err, cids) {
if (err) {
@@ -127,4 +126,4 @@ module.exports = function (Posts) {
user.isModerator(uid, cids, callback);
});
};
-};
\ No newline at end of file
+};
diff --git a/src/posts/votes.js b/src/posts/votes.js
index 428685257a..ddc860f5b6 100644
--- a/src/posts/votes.js
+++ b/src/posts/votes.js
@@ -8,7 +8,6 @@ var user = require('../user');
var plugins = require('../plugins');
module.exports = function (Posts) {
-
var votesInProgress = {};
Posts.upvote = function (pid, uid, callback) {
@@ -64,7 +63,7 @@ module.exports = function (Posts) {
Posts.hasVoted = function (pid, uid, callback) {
if (!parseInt(uid, 10)) {
- return callback(null, {upvoted: false, downvoted: false});
+ return callback(null, { upvoted: false, downvoted: false });
}
db.isMemberOfSets(['pid:' + pid + ':upvote', 'pid:' + pid + ':downvote'], uid, function (err, hasVoted) {
@@ -72,19 +71,19 @@ module.exports = function (Posts) {
return callback(err);
}
- callback (null, {upvoted: hasVoted[0], downvoted: hasVoted[1]});
+ callback(null, { upvoted: hasVoted[0], downvoted: hasVoted[1] });
});
};
Posts.getVoteStatusByPostIDs = function (pids, uid, callback) {
if (!parseInt(uid, 10)) {
var data = pids.map(function () { return false; });
- return callback(null, {upvotes: data, downvotes: data});
+ return callback(null, { upvotes: data, downvotes: data });
}
var upvoteSets = [];
var downvoteSets = [];
- for (var i = 0; i < pids.length; ++i) {
+ for (var i = 0; i < pids.length; i += 1) {
upvoteSets.push('pid:' + pids[i] + ':upvote');
downvoteSets.push('pid:' + pids[i] + ':downvote');
}
@@ -95,7 +94,7 @@ module.exports = function (Posts) {
},
downvotes: function (next) {
db.isMemberOfSets(downvoteSets, uid, next);
- }
+ },
}, callback);
};
@@ -144,7 +143,7 @@ module.exports = function (Posts) {
},
reputation: function (next) {
user.getUserField(uid, 'reputation', next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -154,15 +153,15 @@ module.exports = function (Posts) {
return callback(new Error('self-vote'));
}
- if (command === 'downvote' && parseInt(results.reputation) < parseInt(meta.config['privileges:downvote'], 10)) {
+ if (command === 'downvote' && parseInt(results.reputation, 10) < parseInt(meta.config['privileges:downvote'], 10)) {
return callback(new Error('[[error:not-enough-reputation-to-downvote]]'));
}
- var voteStatus = results.voteStatus,
- hook,
- current = voteStatus.upvoted ? 'upvote' : 'downvote';
+ var voteStatus = results.voteStatus;
+ var hook;
+ var current = voteStatus.upvoted ? 'upvote' : 'downvote';
- if (voteStatus.upvoted && command === 'downvote' || voteStatus.downvoted && command === 'upvote') { // e.g. User *has* upvoted, and clicks downvote
+ if ((voteStatus.upvoted && command === 'downvote') || (voteStatus.downvoted && command === 'upvote')) { // e.g. User *has* upvoted, and clicks downvote
hook = command;
} else if (voteStatus.upvoted || voteStatus.downvoted) { // e.g. User *has* upvoted, clicks upvote (so we "unvote")
hook = 'unvote';
@@ -175,7 +174,7 @@ module.exports = function (Posts) {
pid: pid,
uid: uid,
owner: results.owner,
- current: current
+ current: current,
});
if (!voteStatus || (!voteStatus.upvoted && !voteStatus.downvoted)) {
@@ -224,11 +223,11 @@ module.exports = function (Posts) {
adjustPostVotes(postData, uid, type, unvote, function (err) {
callback(err, {
user: {
- reputation: newreputation
+ reputation: newreputation,
},
post: postData,
upvote: type === 'upvote' && !unvote,
- downvote: type === 'downvote' && !unvote
+ downvote: type === 'downvote' && !unvote,
});
});
});
@@ -248,7 +247,7 @@ module.exports = function (Posts) {
},
function (next) {
db.setRemove('pid:' + postData.pid + ':' + notType, uid, next);
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -260,7 +259,7 @@ module.exports = function (Posts) {
},
downvotes: function (next) {
db.setCount('pid:' + postData.pid + ':downvote', next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
diff --git a/src/privileges.js b/src/privileges.js
index d933d72877..cccbd089d6 100644
--- a/src/privileges.js
+++ b/src/privileges.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var privileges = module.exports;
@@ -14,7 +14,7 @@ privileges.userPrivilegeList = [
'upload:post:image',
'upload:post:file',
'purge',
- 'mods'
+ 'mods',
];
privileges.groupPrivilegeList = [
@@ -29,7 +29,7 @@ privileges.groupPrivilegeList = [
'groups:upload:post:image',
'groups:upload:post:file',
'groups:purge',
- 'groups:moderate'
+ 'groups:moderate',
];
privileges.privilegeList = privileges.userPrivilegeList.concat(privileges.groupPrivilegeList);
diff --git a/src/privileges/categories.js b/src/privileges/categories.js
index 67b004e19e..6678f5d5aa 100644
--- a/src/privileges/categories.js
+++ b/src/privileges/categories.js
@@ -11,32 +11,31 @@ var helpers = require('./helpers');
var plugins = require('../plugins');
module.exports = function (privileges) {
-
privileges.categories = {};
privileges.categories.list = function (cid, callback) {
// Method used in admin/category controller to show all users/groups with privs in that given cid
var privilegeLabels = [
- {name: 'Find Category'},
- {name: 'Access Category'},
- {name: 'Access Topics'},
- {name: 'Create Topics'},
- {name: 'Reply to Topics'},
- {name: 'Edit Posts'},
- {name: 'Delete Posts'},
- {name: 'Delete Topics'},
- {name: 'Upload Images'},
- {name: 'Upload Files'},
- {name: 'Purge'},
- {name: 'Moderate'}
+ { name: 'Find Category' },
+ { name: 'Access Category' },
+ { name: 'Access Topics' },
+ { name: 'Create Topics' },
+ { name: 'Reply to Topics' },
+ { name: 'Edit Posts' },
+ { name: 'Delete Posts' },
+ { name: 'Delete Topics' },
+ { name: 'Upload Images' },
+ { name: 'Upload Files' },
+ { name: 'Purge' },
+ { name: 'Moderate' },
];
async.parallel({
labels: function (next) {
async.parallel({
users: async.apply(plugins.fireHook, 'filter:privileges.list_human', privilegeLabels),
- groups: async.apply(plugins.fireHook, 'filter:privileges.groups.list_human', privilegeLabels)
+ groups: async.apply(plugins.fireHook, 'filter:privileges.groups.list_human', privilegeLabels),
}, next);
},
users: function (next) {
@@ -50,7 +49,6 @@ module.exports = function (privileges) {
}), next);
},
function (memberSets, next) {
-
memberSets = memberSets.map(function (set) {
return set.map(function (uid) {
return parseInt(uid, 10);
@@ -66,14 +64,14 @@ module.exports = function (privileges) {
memberData.forEach(function (member) {
member.privileges = {};
- for(var x = 0,numPrivs = userPrivileges.length; x < numPrivs; x++) {
+ for (var x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) {
member.privileges[userPrivileges[x]] = memberSets[x].indexOf(parseInt(member.uid, 10)) !== -1;
}
});
next(null, memberData);
});
- }
+ },
], next);
},
groups: function (next) {
@@ -87,7 +85,6 @@ module.exports = function (privileges) {
}), next);
},
function (memberSets, next) {
-
var uniqueGroups = _.unique(_.flatten(memberSets));
groups.getGroups('groups:createtime', 0, -1, function (err, groupNames) {
@@ -99,7 +96,7 @@ module.exports = function (privileges) {
return groupName.indexOf(':privileges:') === -1 && uniqueGroups.indexOf(groupName) !== -1;
});
- groupNames = groups.getEphemeralGroups().concat(groupNames);
+ groupNames = groups.ephemeralGroups.concat(groupNames);
var registeredUsersIndex = groupNames.indexOf('registered-users');
if (registeredUsersIndex !== -1) {
groupNames.splice(0, 0, groupNames.splice(registeredUsersIndex, 1)[0]);
@@ -117,7 +114,7 @@ module.exports = function (privileges) {
var memberData = groupNames.map(function (member) {
memberPrivs = {};
- for(var x = 0,numPrivs = groupPrivileges.length; x < numPrivs; x++) {
+ for (var x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) {
memberPrivs[groupPrivileges[x]] = memberSets[x].indexOf(member) !== -1;
}
return {
@@ -141,9 +138,9 @@ module.exports = function (privileges) {
next(null, member);
});
}, next);
- }
+ },
], next);
- }
+ },
}, function (err, payload) {
if (err) {
return callback(err);
@@ -158,34 +155,36 @@ module.exports = function (privileges) {
privileges.categories.get = function (cid, uid, callback) {
var privs = ['topics:create', 'topics:read', 'read'];
- async.parallel({
- privileges: function (next) {
- helpers.isUserAllowedTo(privs, uid, cid, next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ privileges: function (next) {
+ helpers.isUserAllowedTo(privs, uid, cid, next);
+ },
+ isAdministrator: function (next) {
+ user.isAdministrator(uid, next);
+ },
+ isModerator: function (next) {
+ user.isModerator(uid, cid, next);
+ },
+ }, next);
},
- isAdministrator: function (next) {
- user.isAdministrator(uid, next);
- },
- isModerator: function (next) {
- user.isModerator(uid, cid, next);
- }
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
- var privData = _.object(privs, results.privileges);
- var isAdminOrMod = results.isAdministrator || results.isModerator;
+ function (results, next) {
+ var privData = _.object(privs, results.privileges);
+ var isAdminOrMod = results.isAdministrator || results.isModerator;
- plugins.fireHook('filter:privileges.categories.get', {
- 'topics:create': privData['topics:create'] || isAdminOrMod,
- 'topics:read': privData['topics:read'] || isAdminOrMod,
- read: privData.read || isAdminOrMod,
- cid: cid,
- uid: uid,
- editable: isAdminOrMod,
- view_deleted: isAdminOrMod,
- isAdminOrMod: isAdminOrMod
- }, callback);
- });
+ plugins.fireHook('filter:privileges.categories.get', {
+ 'topics:create': privData['topics:create'] || isAdminOrMod,
+ 'topics:read': privData['topics:read'] || isAdminOrMod,
+ read: privData.read || isAdminOrMod,
+ cid: cid,
+ uid: uid,
+ editable: isAdminOrMod,
+ view_deleted: isAdminOrMod,
+ isAdminOrMod: isAdminOrMod,
+ }, next);
+ },
+ ], callback);
};
privileges.categories.isAdminOrMod = function (cid, uid, callback) {
@@ -198,7 +197,7 @@ module.exports = function (privileges) {
},
function (next) {
user.isAdministrator(uid, next);
- }
+ },
], callback);
};
@@ -216,29 +215,29 @@ module.exports = function (privileges) {
return callback(null, false);
}
- categories.getCategoryField(cid, 'disabled', function (err, disabled) {
- if (err) {
- return callback(err);
- }
-
- if (parseInt(disabled, 10) === 1) {
- return callback(null, false);
- }
-
- helpers.some([
- function (next) {
- helpers.isUserAllowedTo(privilege, uid, [cid], function (err, results) {
- next(err, Array.isArray(results) && results.length ? results[0] : false);
- });
- },
- function (next) {
- user.isModerator(uid, cid, next);
- },
- function (next) {
- user.isAdministrator(uid, next);
+ async.waterfall([
+ function (next) {
+ categories.getCategoryField(cid, 'disabled', next);
+ },
+ function (disabled, next) {
+ if (parseInt(disabled, 10) === 1) {
+ return callback(null, false);
}
- ], callback);
- });
+ helpers.some([
+ function (next) {
+ helpers.isUserAllowedTo(privilege, uid, [cid], function (err, results) {
+ next(err, Array.isArray(results) && results.length ? results[0] : false);
+ });
+ },
+ function (next) {
+ user.isModerator(uid, cid, next);
+ },
+ function (next) {
+ user.isAdministrator(uid, next);
+ },
+ ], next);
+ },
+ ], callback);
};
privileges.categories.filterCids = function (privilege, cids, uid, callback) {
@@ -250,18 +249,19 @@ module.exports = function (privileges) {
return array.indexOf(cid) === index;
});
- privileges.categories.getBase(privilege, cids, uid, function (err, results) {
- if (err) {
- return callback(err);
- }
+ async.waterfall([
+ function (next) {
+ privileges.categories.getBase(privilege, cids, uid, next);
+ },
+ function (results, next) {
+ cids = cids.filter(function (cid, index) {
+ return !results.categories[index].disabled &&
+ (results.allowedTo[index] || results.isAdmin || results.isModerators[index]);
+ });
- cids = cids.filter(function (cid, index) {
- return !results.categories[index].disabled &&
- (results.allowedTo[index] || results.isAdmin || results.isModerators[index]);
- });
-
- callback(null, cids.filter(Boolean));
- });
+ next(null, cids.filter(Boolean));
+ },
+ ], callback);
};
privileges.categories.getBase = function (privilege, cids, uid, callback) {
@@ -277,7 +277,7 @@ module.exports = function (privileges) {
},
isAdmin: function (next) {
user.isAdministrator(uid, next);
- }
+ },
}, callback);
};
@@ -290,26 +290,27 @@ module.exports = function (privileges) {
return array.indexOf(uid) === index;
});
- async.parallel({
- allowedTo: function (next) {
- helpers.isUsersAllowedTo(privilege, uids, cid, next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ allowedTo: function (next) {
+ helpers.isUsersAllowedTo(privilege, uids, cid, next);
+ },
+ isModerators: function (next) {
+ user.isModerator(uids, cid, next);
+ },
+ isAdmin: function (next) {
+ user.isAdministrator(uids, next);
+ },
+ }, next);
},
- isModerators: function (next) {
- user.isModerator(uids, cid, next);
+ function (results, next) {
+ uids = uids.filter(function (uid, index) {
+ return results.allowedTo[index] || results.isModerators[index] || results.isAdmin[index];
+ });
+ next(null, uids);
},
- isAdmin: function (next) {
- user.isAdministrator(uids, next);
- }
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
-
- uids = uids.filter(function (uid, index) {
- return results.allowedTo[index] || results.isModerators[index] || results.isAdmin[index];
- });
- callback(null, uids);
- });
+ ], callback);
};
privileges.categories.give = function (privileges, cid, groupName, callback) {
@@ -327,23 +328,24 @@ module.exports = function (privileges) {
}
privileges.categories.canMoveAllTopics = function (currentCid, targetCid, uid, callback) {
- async.parallel({
- isAdministrator: function (next) {
- user.isAdministrator(uid, next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ isAdministrator: function (next) {
+ user.isAdministrator(uid, next);
+ },
+ moderatorOfCurrent: function (next) {
+ user.isModerator(uid, currentCid, next);
+ },
+ moderatorOfTarget: function (next) {
+ user.isModerator(uid, targetCid, next);
+ },
+ }, next);
},
- moderatorOfCurrent: function (next) {
- user.isModerator(uid, currentCid, next);
+ function (results, next) {
+ next(null, results.isAdministrator || (results.moderatorOfCurrent && results.moderatorOfTarget));
},
- moderatorOfTarget: function (next) {
- user.isModerator(uid, targetCid, next);
- }
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
-
- callback(null, results.isAdministrator || (results.moderatorOfCurrent && results.moderatorOfTarget));
- });
+ ], callback);
};
privileges.categories.userPrivileges = function (cid, uid, callback) {
@@ -372,7 +374,7 @@ module.exports = function (privileges) {
},
mods: function (next) {
user.isModerator(uid, cid, next);
- }
+ },
}, callback);
};
@@ -399,8 +401,7 @@ module.exports = function (privileges) {
},
'groups:topics:read': function (next) {
groups.isMember(groupName, 'cid:' + cid + ':privileges:groups:topics:read', next);
- }
+ },
}, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/privileges/helpers.js b/src/privileges/helpers.js
index 9df9d8cd7b..23f555f89d 100644
--- a/src/privileges/helpers.js
+++ b/src/privileges/helpers.js
@@ -31,8 +31,9 @@ function isUserAllowedToCids(privilege, uid, cids, callback) {
return isGuestAllowedToCids(privilege, cids, callback);
}
- var userKeys = [], groupKeys = [];
- for (var i = 0; i < cids.length; ++i) {
+ var userKeys = [];
+ var groupKeys = [];
+ for (var i = 0; i < cids.length; i += 1) {
userKeys.push('cid:' + cids[i] + ':privileges:' + privilege);
groupKeys.push('cid:' + cids[i] + ':privileges:groups:' + privilege);
}
@@ -43,14 +44,14 @@ function isUserAllowedToCids(privilege, uid, cids, callback) {
},
hasGroupPrivilege: function (next) {
groups.isMemberOfGroupsList(uid, groupKeys, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
}
var result = [];
- for (var i = 0; i < cids.length; ++i) {
+ for (var i = 0; i < cids.length; i += 1) {
result.push(results.hasUserPrivilege[i] || results.hasGroupPrivilege[i]);
}
@@ -63,8 +64,9 @@ function isUserAllowedToPrivileges(privileges, uid, cid, callback) {
return isGuestAllowedToPrivileges(privileges, cid, callback);
}
- var userKeys = [], groupKeys = [];
- for (var i = 0; i < privileges.length; ++i) {
+ var userKeys = [];
+ var groupKeys = [];
+ for (var i = 0; i < privileges.length; i += 1) {
userKeys.push('cid:' + cid + ':privileges:' + privileges[i]);
groupKeys.push('cid:' + cid + ':privileges:groups:' + privileges[i]);
}
@@ -75,14 +77,14 @@ function isUserAllowedToPrivileges(privileges, uid, cid, callback) {
},
hasGroupPrivilege: function (next) {
groups.isMemberOfGroupsList(uid, groupKeys, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
}
var result = [];
- for (var i = 0; i < privileges.length; ++i) {
+ for (var i = 0; i < privileges.length; i += 1) {
result.push(results.hasUserPrivilege[i] || results.hasGroupPrivilege[i]);
}
@@ -98,14 +100,14 @@ helpers.isUsersAllowedTo = function (privilege, uids, cid, callback) {
},
hasGroupPrivilege: function (next) {
groups.isMembersOfGroupList(uids, 'cid:' + cid + ':privileges:groups:' + privilege, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
}
var result = [];
- for(var i = 0; i < uids.length; ++i) {
+ for (var i = 0; i < uids.length; i += 1) {
result.push(results.hasUserPrivilege[i] || results.hasGroupPrivilege[i]);
}
@@ -115,7 +117,7 @@ helpers.isUsersAllowedTo = function (privilege, uids, cid, callback) {
function isGuestAllowedToCids(privilege, cids, callback) {
var groupKeys = [];
- for (var i = 0; i < cids.length; ++i) {
+ for (var i = 0; i < cids.length; i += 1) {
groupKeys.push('cid:' + cids[i] + ':privileges:groups:' + privilege);
}
@@ -124,11 +126,11 @@ function isGuestAllowedToCids(privilege, cids, callback) {
function isGuestAllowedToPrivileges(privileges, cid, callback) {
var groupKeys = [];
- for (var i = 0; i < privileges.length; ++i) {
+ for (var i = 0; i < privileges.length; i += 1) {
groupKeys.push('cid:' + cid + ':privileges:groups:' + privileges[i]);
}
groups.isMemberOfGroups('guests', groupKeys, callback);
}
-module.exports = helpers;
\ No newline at end of file
+module.exports = helpers;
diff --git a/src/privileges/posts.js b/src/privileges/posts.js
index d68edc6e14..8a31ad4129 100644
--- a/src/privileges/posts.js
+++ b/src/privileges/posts.js
@@ -11,7 +11,6 @@ var helpers = require('./helpers');
var plugins = require('../plugins');
module.exports = function (privileges) {
-
privileges.posts = {};
privileges.posts.get = function (pids, uid, callback) {
@@ -32,7 +31,7 @@ module.exports = function (privileges) {
read: async.apply(helpers.isUserAllowedTo, 'read', uid, cids),
'posts:edit': async.apply(helpers.isUserAllowedTo, 'posts:edit', uid, cids),
}, next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -40,7 +39,7 @@ module.exports = function (privileges) {
var privileges = [];
- for (var i = 0; i < pids.length; ++i) {
+ for (var i = 0; i < pids.length; i += 1) {
var isAdminOrMod = results.isAdmin || results.isModerator[i];
var editable = isAdminOrMod || (results.isOwner[i] && results['posts:edit'][i]);
@@ -50,7 +49,7 @@ module.exports = function (privileges) {
move: isAdminOrMod,
isAdminOrMod: isAdminOrMod,
'topics:read': results['topics:read'][i] || isAdminOrMod,
- read: results.read[i] || isAdminOrMod
+ read: results.read[i] || isAdminOrMod,
});
}
@@ -91,7 +90,6 @@ module.exports = function (privileges) {
topics.getTopicsFields(tids, ['deleted', 'cid'], next);
},
function (topicData, next) {
-
topicData.forEach(function (topic, index) {
if (topic) {
tidToTopic[tids[index]] = topic;
@@ -111,7 +109,6 @@ module.exports = function (privileges) {
privileges.categories.getBase(privilege, cids, uid, next);
},
function (results, next) {
-
var isModOf = {};
cids = cids.filter(function (cid, index) {
isModOf[cid] = results.isModerators[index];
@@ -130,24 +127,24 @@ module.exports = function (privileges) {
plugins.fireHook('filter:privileges.posts.filter', {
privilege: privilege,
uid: uid,
- pids: pids
+ pids: pids,
}, function (err, data) {
next(err, data ? data.pids : null);
});
- }
+ },
], callback);
};
privileges.posts.canEdit = function (pid, uid, callback) {
async.parallel({
isEditable: async.apply(isPostEditable, pid, uid),
- isAdminOrMod: async.apply(isAdminOrMod, pid, uid)
+ isAdminOrMod: async.apply(isAdminOrMod, pid, uid),
}, function (err, results) {
if (err) {
return callback(err);
}
if (results.isAdminOrMod) {
- return callback(null, {flag: true});
+ return callback(null, { flag: true });
}
callback(null, results.isEditable);
@@ -166,33 +163,33 @@ module.exports = function (privileges) {
isAdminOrMod: async.apply(isAdminOrMod, pid, uid),
isLocked: async.apply(topics.isLocked, postData.tid),
isOwner: async.apply(posts.isOwner, pid, uid),
- 'posts:delete': async.apply(privileges.posts.can, 'posts:delete', pid, uid)
+ 'posts:delete': async.apply(privileges.posts.can, 'posts:delete', pid, uid),
}, next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
}
if (results.isAdminOrMod) {
- return callback(null, {flag: true});
+ return callback(null, { flag: true });
}
if (results.isLocked) {
- return callback(null, {flag: false, message: '[[error:topic-locked]]'});
+ return callback(null, { flag: false, message: '[[error:topic-locked]]' });
}
if (!results['posts:delete']) {
- return callback(null, {flag: false, message: '[[error:no-privileges]]'});
+ return callback(null, { flag: false, message: '[[error:no-privileges]]' });
}
var postDeleteDuration = parseInt(meta.config.postDeleteDuration, 10);
if (postDeleteDuration && (Date.now() - parseInt(postData.timestamp, 10) > postDeleteDuration * 1000)) {
- return callback(null, {flag: false, message: '[[error:post-delete-duration-expired, ' + meta.config.postDeleteDuration + ']]'});
+ return callback(null, { flag: false, message: '[[error:post-delete-duration-expired, ' + meta.config.postDeleteDuration + ']]' });
}
var deleterUid = parseInt(postData.deleterUid, 10) || 0;
var flag = results.isOwner && (deleterUid === 0 || deleterUid === parseInt(postData.uid, 10));
- callback(null, {flag: flag, message: '[[error:no-privileges]]'});
+ callback(null, { flag: flag, message: '[[error:no-privileges]]' });
});
};
@@ -214,42 +211,40 @@ module.exports = function (privileges) {
async.parallel({
purge: async.apply(privileges.categories.isUserAllowedTo, 'purge', cid, uid),
owner: async.apply(posts.isOwner, pid, uid),
- isAdminOrMod: async.apply(privileges.categories.isAdminOrMod, cid, uid)
+ isAdminOrMod: async.apply(privileges.categories.isAdminOrMod, cid, uid),
}, next);
},
function (results, next) {
next(null, results.isAdminOrMod || (results.purge && results.owner));
- }
+ },
], callback);
};
function isPostEditable(pid, uid, callback) {
- var tid;
async.waterfall([
function (next) {
posts.getPostFields(pid, ['tid', 'timestamp'], next);
},
function (postData, next) {
- tid = postData.tid;
var postEditDuration = parseInt(meta.config.postEditDuration, 10);
if (postEditDuration && Date.now() - parseInt(postData.timestamp, 10) > postEditDuration * 1000) {
- return callback(null, {flag: false, message: '[[error:post-edit-duration-expired, ' + meta.config.postEditDuration + ']]'});
+ return callback(null, { flag: false, message: '[[error:post-edit-duration-expired, ' + meta.config.postEditDuration + ']]' });
}
topics.isLocked(postData.tid, next);
},
function (isLocked, next) {
if (isLocked) {
- return callback(null, {flag: false, message: '[[error:topic-locked]]'});
+ return callback(null, { flag: false, message: '[[error:topic-locked]]' });
}
async.parallel({
owner: async.apply(posts.isOwner, pid, uid),
- edit: async.apply(privileges.posts.can, 'posts:edit', pid, uid)
+ edit: async.apply(privileges.posts.can, 'posts:edit', pid, uid),
}, next);
},
function (result, next) {
- next(null, {flag: result.owner && result.edit, message: '[[error:no-privileges]]'});
- }
+ next(null, { flag: result.owner && result.edit, message: '[[error:no-privileges]]' });
+ },
], callback);
}
@@ -266,7 +261,7 @@ module.exports = function (privileges) {
},
function (next) {
user.isAdministrator(uid, next);
- }
+ },
], callback);
}
-};
\ No newline at end of file
+};
diff --git a/src/privileges/topics.js b/src/privileges/topics.js
index 2350299e72..f44383eed8 100644
--- a/src/privileges/topics.js
+++ b/src/privileges/topics.js
@@ -12,7 +12,6 @@ var categories = require('../categories');
var plugins = require('../plugins');
module.exports = function (privileges) {
-
privileges.topics = {};
privileges.topics.get = function (tid, uid, callback) {
@@ -26,9 +25,9 @@ module.exports = function (privileges) {
privileges: async.apply(helpers.isUserAllowedTo, privs, uid, topic.cid),
isAdministrator: async.apply(user.isAdministrator, uid),
isModerator: async.apply(user.isModerator, uid, topic.cid),
- disabled: async.apply(categories.getCategoryField, topic.cid, 'disabled')
+ disabled: async.apply(categories.getCategoryField, topic.cid, 'disabled'),
}, next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -57,7 +56,7 @@ module.exports = function (privileges) {
isAdminOrMod: isAdminOrMod,
disabled: disabled,
tid: tid,
- uid: uid
+ uid: uid,
}, callback);
});
};
@@ -69,7 +68,7 @@ module.exports = function (privileges) {
},
function (cid, next) {
privileges.categories.can(privilege, cid, uid, next);
- }
+ },
], callback);
};
@@ -94,7 +93,6 @@ module.exports = function (privileges) {
privileges.categories.getBase(privilege, cids, uid, next);
},
function (results, next) {
-
var isModOf = {};
cids = cids.filter(function (cid, index) {
isModOf[cid] = results.isModerators[index];
@@ -112,11 +110,11 @@ module.exports = function (privileges) {
plugins.fireHook('filter:privileges.topics.filter', {
privilege: privilege,
uid: uid,
- tids: tids
+ tids: tids,
}, function (err, data) {
next(err, data ? data.tids : null);
});
- }
+ },
], callback);
};
@@ -146,7 +144,7 @@ module.exports = function (privileges) {
},
isAdmins: function (next) {
user.isAdministrator(uids, next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -159,7 +157,7 @@ module.exports = function (privileges) {
next(null, uids);
});
- }
+ },
], callback);
};
@@ -172,12 +170,12 @@ module.exports = function (privileges) {
async.parallel({
purge: async.apply(privileges.categories.isUserAllowedTo, 'purge', cid, uid),
owner: async.apply(topics.isOwner, tid, uid),
- isAdminOrMod: async.apply(privileges.categories.isAdminOrMod, cid, uid)
+ isAdminOrMod: async.apply(privileges.categories.isAdminOrMod, cid, uid),
}, next);
},
function (results, next) {
next(null, results.isAdminOrMod || (results.purge && results.owner));
- }
+ },
], callback);
};
@@ -193,9 +191,9 @@ module.exports = function (privileges) {
isModerator: async.apply(user.isModerator, uid, topicData.cid),
isAdministrator: async.apply(user.isAdministrator, uid),
isOwner: async.apply(topics.isOwner, tid, uid),
- 'topics:delete': async.apply(helpers.isUserAllowedTo, 'topics:delete', uid, [topicData.cid])
+ 'topics:delete': async.apply(helpers.isUserAllowedTo, 'topics:delete', uid, [topicData.cid]),
}, next);
- }
+ },
], function (err, results) {
if (err) {
return callback(err);
@@ -232,7 +230,7 @@ module.exports = function (privileges) {
},
function (next) {
privileges.topics.isAdminOrMod(tid, uid, next);
- }
+ },
], callback);
};
@@ -249,7 +247,7 @@ module.exports = function (privileges) {
},
function (next) {
user.isAdministrator(uid, next);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/privileges/users.js b/src/privileges/users.js
index 82553647a4..ed72efb147 100644
--- a/src/privileges/users.js
+++ b/src/privileges/users.js
@@ -7,7 +7,6 @@ var groups = require('../groups');
var plugins = require('../plugins');
module.exports = function (privileges) {
-
privileges.users = {};
privileges.users.isAdministrator = function (uid, callback) {
@@ -29,18 +28,16 @@ module.exports = function (privileges) {
privileges.users.isModerator = function (uid, cid, callback) {
if (Array.isArray(cid)) {
isModeratorOfCategories(cid, uid, callback);
+ } else if (Array.isArray(uid)) {
+ isModeratorsOfCategory(cid, uid, callback);
} else {
- if (Array.isArray(uid)) {
- isModeratorsOfCategory(cid, uid, callback);
- } else {
- isModeratorOfCategory(cid, uid, callback);
- }
+ isModeratorOfCategory(cid, uid, callback);
}
};
function isModeratorOfCategories(cids, uid, callback) {
if (!parseInt(uid, 10)) {
- return filterIsModerator(cids, uid, cids.map(function () {return false;}), callback);
+ return filterIsModerator(cids, uid, cids.map(function () { return false; }), callback);
}
privileges.users.isGlobalModerator(uid, function (err, isGlobalModerator) {
@@ -48,7 +45,7 @@ module.exports = function (privileges) {
return callback(err);
}
if (isGlobalModerator) {
- return filterIsModerator(cids, uid, cids.map(function () {return true;}), callback);
+ return filterIsModerator(cids, uid, cids.map(function () { return true; }), callback);
}
@@ -66,16 +63,16 @@ module.exports = function (privileges) {
async.parallel({
user: async.apply(groups.isMemberOfGroups, uid, groupNames),
- group: async.apply(groups.isMemberOfGroupsList, uid, groupListNames)
+ group: async.apply(groups.isMemberOfGroupsList, uid, groupListNames),
}, function (err, checks) {
if (err) {
return callback(err);
}
var isMembers = checks.user.map(function (isMember, idx) {
- return isMember || checks.group[idx];
- }),
- map = {};
+ return isMember || checks.group[idx];
+ });
+ var map = {};
uniqueCids.forEach(function (cid, index) {
map[cid] = isMembers[index];
@@ -94,7 +91,7 @@ module.exports = function (privileges) {
async.parallel([
async.apply(privileges.users.isGlobalModerator, uids),
async.apply(groups.isMembers, uids, 'cid:' + cid + ':privileges:mods'),
- async.apply(groups.isMembersOfGroupList, uids, 'cid:' + cid + ':privileges:groups:moderate')
+ async.apply(groups.isMembersOfGroupList, uids, 'cid:' + cid + ':privileges:groups:moderate'),
], function (err, checks) {
if (err) {
return callback(err);
@@ -112,7 +109,7 @@ module.exports = function (privileges) {
async.parallel([
async.apply(privileges.users.isGlobalModerator, uid),
async.apply(groups.isMember, uid, 'cid:' + cid + ':privileges:mods'),
- async.apply(groups.isMemberOfGroupList, uid, 'cid:' + cid + ':privileges:groups:moderate')
+ async.apply(groups.isMemberOfGroupList, uid, 'cid:' + cid + ':privileges:groups:moderate'),
], function (err, checks) {
if (err) {
return callback(err);
@@ -124,11 +121,11 @@ module.exports = function (privileges) {
}
function filterIsModerator(cid, uid, isModerator, callback) {
- plugins.fireHook('filter:user.isModerator', {uid: uid, cid: cid, isModerator: isModerator}, function (err, data) {
+ plugins.fireHook('filter:user.isModerator', { uid: uid, cid: cid, isModerator: isModerator }, function (err, data) {
if (err) {
return callback(err);
}
- if (Array.isArray(uid) && !Array.isArray(data.isModerator) || Array.isArray(cid) && !Array.isArray(data.isModerator)) {
+ if ((Array.isArray(uid) || Array.isArray(cid)) && !Array.isArray(data.isModerator)) {
return callback(new Error('filter:user.isModerator - i/o mismatch'));
}
@@ -150,7 +147,7 @@ module.exports = function (privileges) {
},
isTargetAdmin: function (next) {
privileges.users.isAdministrator(uid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -160,5 +157,4 @@ module.exports = function (privileges) {
callback(null, canEdit);
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/pubsub.js b/src/pubsub.js
index f5c6c2f0ed..b33a03b6bf 100644
--- a/src/pubsub.js
+++ b/src/pubsub.js
@@ -26,7 +26,7 @@ var PubSub = function () {
try {
var msg = JSON.parse(message);
self.emit(msg.event, msg.data);
- } catch(err) {
+ } catch (err) {
winston.error(err.stack);
}
});
@@ -37,7 +37,7 @@ util.inherits(PubSub, EventEmitter);
PubSub.prototype.publish = function (event, data) {
if (this.pubClient) {
- this.pubClient.publish(channelName, JSON.stringify({event: event, data: data}));
+ this.pubClient.publish(channelName, JSON.stringify({ event: event, data: data }));
} else {
this.emit(event, data);
}
@@ -45,4 +45,4 @@ PubSub.prototype.publish = function (event, data) {
var pubsub = new PubSub();
-module.exports = pubsub;
\ No newline at end of file
+module.exports = pubsub;
diff --git a/src/reset.js b/src/reset.js
index d237059f8e..f709c4188b 100644
--- a/src/reset.js
+++ b/src/reset.js
@@ -82,15 +82,15 @@ function resetSettings(callback) {
function resetTheme(themeId, callback) {
var meta = require('./meta');
var fs = require('fs');
-
- fs.access('node_modules/' + themeId + '/package.json', function (err, fd) {
+
+ fs.access('node_modules/' + themeId + '/package.json', function (err) {
if (err) {
winston.warn('[reset] Theme `%s` is not installed on this forum', themeId);
callback(new Error('theme-not-found'));
} else {
meta.themes.set({
type: 'local',
- id: themeId
+ id: themeId,
}, function (err) {
if (err) {
winston.warn('[reset] Failed to reset theme to ' + themeId);
@@ -99,7 +99,7 @@ function resetTheme(themeId, callback) {
}
callback();
- });
+ });
}
});
}
@@ -109,7 +109,7 @@ function resetThemes(callback) {
meta.themes.set({
type: 'local',
- id: 'nodebb-theme-persona'
+ id: 'nodebb-theme-persona',
}, function (err) {
winston.info('[reset] Theme reset to Persona');
callback(err);
@@ -129,18 +129,16 @@ function resetPlugin(pluginId, callback) {
} else {
next();
}
- }
+ },
], function (err) {
if (err) {
winston.error('[reset] Could not disable plugin: %s encountered error %s', pluginId, err.message);
+ } else if (active) {
+ winston.info('[reset] Plugin `%s` disabled', pluginId);
} else {
- if (active) {
- winston.info('[reset] Plugin `%s` disabled', pluginId);
- } else {
- winston.warn('[reset] Plugin `%s` was not active on this forum', pluginId);
- winston.info('[reset] No action taken.');
- err = new Error('plugin-not-active');
- }
+ winston.warn('[reset] Plugin `%s` was not active on this forum', pluginId);
+ winston.info('[reset] No action taken.');
+ err = new Error('plugin-not-active');
}
callback(err);
@@ -161,4 +159,4 @@ function resetWidgets(callback) {
});
}
-module.exports = Reset;
\ No newline at end of file
+module.exports = Reset;
diff --git a/src/rewards/admin.js b/src/rewards/admin.js
index ec5a26d5aa..60f335ef86 100644
--- a/src/rewards/admin.js
+++ b/src/rewards/admin.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var plugins = require('../plugins');
@@ -7,9 +7,7 @@ var db = require('../database');
var rewards = module.exports;
rewards.save = function (data, callback) {
-
async.each(data, function save(data, next) {
-
if (!Object.keys(data.rewards).length) {
return next();
}
@@ -26,7 +24,6 @@ rewards.save = function (data, callback) {
}
},
function (rid, next) {
-
data.id = rid;
async.series([
@@ -41,11 +38,10 @@ rewards.save = function (data, callback) {
},
function (next) {
db.setObject('rewards:id:' + data.id + ':rewards', rewardsData, next);
- }
+ },
], next);
- }
+ },
], next);
-
}, function (err) {
if (err) {
return callback(err);
@@ -65,7 +61,7 @@ rewards.delete = function (data, callback) {
},
function (next) {
db.delete('rewards:id:' + data.id + ':rewards', next);
- }
+ },
], callback);
};
@@ -80,7 +76,7 @@ rewards.get = function (callback) {
},
rewards: function (next) {
plugins.fireHook('filter:rewards.rewards', [], next);
- }
+ },
}, callback);
};
@@ -105,7 +101,7 @@ function saveConditions(data, callback) {
async.each(Object.keys(rewardsPerCondition), function (condition, next) {
db.setAdd('condition:' + condition + ':rewards', rewardsPerCondition[condition], next);
}, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -121,7 +117,7 @@ function getActiveRewards(callback) {
},
rewards: function (next) {
db.getObject('rewards:id:' + id + ':rewards', next);
- }
+ },
}, function (err, data) {
if (data.main) {
data.main.disabled = data.main.disabled === 'true';
diff --git a/src/rewards/index.js b/src/rewards/index.js
index e2bc024f13..38105dd5ff 100644
--- a/src/rewards/index.js
+++ b/src/rewards/index.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var db = require('../database');
@@ -44,7 +44,7 @@ rewards.checkConditionAndRewardUser = function (uid, condition, method, callback
giveRewards(uid, eligible, next);
});
- }
+ },
], callback);
};
@@ -100,7 +100,7 @@ function checkCondition(reward, method, callback) {
return callback(err);
}
- plugins.fireHook('filter:rewards.checkConditional:' + reward.conditional, {left: value, right: reward.value}, function (err, bool) {
+ plugins.fireHook('filter:rewards.checkConditional:' + reward.conditional, { left: value, right: reward.value }, function (err, bool) {
callback(err || bool);
});
});
@@ -113,7 +113,7 @@ function giveRewards(uid, rewards, callback) {
}
async.each(rewards, function (reward, next) {
- plugins.fireHook('action:rewards.award:' + reward.rid, {uid: uid, reward: rewardData[rewards.indexOf(reward)]});
+ plugins.fireHook('action:rewards.award:' + reward.rid, { uid: uid, reward: rewardData[rewards.indexOf(reward)] });
db.sortedSetIncrBy('uid:' + uid + ':rewards', 1, reward.id, next);
}, callback);
});
diff --git a/src/routes/accounts.js b/src/routes/accounts.js
index ae80b8aa4a..a462399b40 100644
--- a/src/routes/accounts.js
+++ b/src/routes/accounts.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var helpers = require('./helpers');
var setupPageRoute = helpers.setupPageRoute;
diff --git a/src/routes/admin.js b/src/routes/admin.js
index 0611eede70..35ad84203d 100644
--- a/src/routes/admin.js
+++ b/src/routes/admin.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var express = require('express');
diff --git a/src/routes/api.js b/src/routes/api.js
index 98c884c237..9b5a7f77c7 100644
--- a/src/routes/api.js
+++ b/src/routes/api.js
@@ -1,28 +1,27 @@
-"use strict";
+'use strict';
var express = require('express');
var uploadsController = require('../controllers/uploads');
-module.exports = function (app, middleware, controllers) {
-
+module.exports = function (app, middleware, controllers) {
var router = express.Router();
app.use('/api', router);
router.get('/config', middleware.applyCSRF, controllers.api.getConfig);
router.get('/widgets/render', controllers.api.renderWidgets);
- router.get('/me', middleware.checkGlobalPrivacySettings, controllers.api.getCurrentUser);
- router.get('/user/uid/:uid', middleware.checkGlobalPrivacySettings, controllers.api.getUserByUID);
- router.get('/user/username/:username', middleware.checkGlobalPrivacySettings, controllers.api.getUserByUsername);
- router.get('/user/email/:email', middleware.checkGlobalPrivacySettings, controllers.api.getUserByEmail);
+ router.get('/me', middleware.checkGlobalPrivacySettings, controllers.user.getCurrentUser);
+ router.get('/user/uid/:uid', middleware.checkGlobalPrivacySettings, controllers.user.getUserByUID);
+ router.get('/user/username/:username', middleware.checkGlobalPrivacySettings, controllers.user.getUserByUsername);
+ router.get('/user/email/:email', middleware.checkGlobalPrivacySettings, controllers.user.getUserByEmail);
router.get('/:type/pid/:id', controllers.api.getObject);
router.get('/:type/tid/:id', controllers.api.getObject);
router.get('/:type/cid/:id', controllers.api.getObject);
router.get('/categories/:cid/moderators', controllers.api.getModerators);
- router.get('/recent/posts/:term?', controllers.api.getRecentPosts);
+ router.get('/recent/posts/:term?', controllers.posts.getRecentPosts);
router.get('/unread/:filter?/total', middleware.authenticate, controllers.unread.unreadTotal);
router.get('/topic/teaser/:topic_id', controllers.topics.teaser);
router.get('/topic/pagination/:topic_id', controllers.topics.pagination);
@@ -36,6 +35,5 @@ module.exports = function (app, middleware, controllers) {
router.post('/user/:userslug/uploadcover', middlewares.concat([middleware.authenticate, middleware.checkGlobalPrivacySettings, middleware.checkAccountPermissions]), controllers.accounts.edit.uploadCoverPicture);
router.post('/groups/uploadpicture', middlewares.concat([middleware.authenticate]), controllers.groups.uploadCover);
-
};
diff --git a/src/routes/authentication.js b/src/routes/authentication.js
index c6f1359fc2..0e1d2aa6e2 100644
--- a/src/routes/authentication.js
+++ b/src/routes/authentication.js
@@ -1,17 +1,17 @@
+'use strict';
+
(function (Auth) {
- "use strict";
+ var passport = require('passport');
+ var passportLocal = require('passport-local').Strategy;
+ var nconf = require('nconf');
+ var winston = require('winston');
+ var express = require('express');
- var passport = require('passport'),
- passportLocal = require('passport-local').Strategy,
- nconf = require('nconf'),
- winston = require('winston'),
- express = require('express'),
+ var controllers = require('../controllers');
+ var plugins = require('../plugins');
+ var hotswap = require('../hotswap');
- controllers = require('../controllers'),
- plugins = require('../plugins'),
- hotswap = require('../hotswap'),
-
- loginStrategies = [];
+ var loginStrategies = [];
Auth.initialize = function (app, middleware) {
app.use(passport.initialize());
@@ -40,7 +40,7 @@
winston.warn('[authentication] Login override detected, skipping local login strategy.');
plugins.fireHook('action:auth.overrideLogin');
} else {
- passport.use(new passportLocal({passReqToCallback: true}, controllers.authentication.localLogin));
+ passport.use(new passportLocal({ passReqToCallback: true }, controllers.authentication.localLogin));
}
plugins.fireHook('filter:auth.init', loginStrategies, function (err) {
@@ -53,13 +53,13 @@
if (strategy.url) {
router.get(strategy.url, passport.authenticate(strategy.name, {
scope: strategy.scope,
- prompt: strategy.prompt || undefined
+ prompt: strategy.prompt || undefined,
}));
}
router.get(strategy.callbackURL, passport.authenticate(strategy.name, {
successReturnToOrRedirect: nconf.get('relative_path') + (strategy.successUrl !== undefined ? strategy.successUrl : '/'),
- failureRedirect: nconf.get('relative_path') + (strategy.failureUrl !== undefined ? strategy.failureUrl : '/login')
+ failureRedirect: nconf.get('relative_path') + (strategy.failureUrl !== undefined ? strategy.failureUrl : '/login'),
}));
});
@@ -82,8 +82,7 @@
passport.deserializeUser(function (uid, done) {
done(null, {
- uid: uid
+ uid: uid,
});
});
-
}(exports));
diff --git a/src/routes/debug.js b/src/routes/debug.js
index 9c5efe6c93..2ec3f23934 100644
--- a/src/routes/debug.js
+++ b/src/routes/debug.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var express = require('express');
var nconf = require('nconf');
@@ -7,9 +7,8 @@ var user = require('../user');
var categories = require('../categories');
var topics = require('../topics');
var posts = require('../posts');
-var db = require('../database');
-module.exports = function (app, middleware, controllers) {
+module.exports = function (app) {
var router = express.Router();
router.get('/uid/:uid', function (req, res) {
@@ -26,7 +25,7 @@ module.exports = function (app, middleware, controllers) {
res.send(data);
} else {
res.status(404).json({
- error: "User doesn't exist!"
+ error: "User doesn't exist!",
});
}
});
diff --git a/src/routes/feeds.js b/src/routes/feeds.js
index 9521e65ce8..5e3d75c34d 100644
--- a/src/routes/feeds.js
+++ b/src/routes/feeds.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var rss = require('rss');
@@ -13,7 +13,7 @@ var meta = require('../meta');
var helpers = require('../controllers/helpers');
var privileges = require('../privileges');
-module.exports = function (app, middleware, controllers) {
+module.exports = function (app, middleware) {
app.get('/topic/:topic_id.rss', middleware.maintenanceMode, generateForTopic);
app.get('/category/:category_id.rss', middleware.maintenanceMode, generateForCategory);
app.get('/recent.rss', middleware.maintenanceMode, generateForRecent);
@@ -41,7 +41,7 @@ function generateForTopic(req, res, callback) {
},
topic: function (next) {
topics.getTopicData(tid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -56,7 +56,7 @@ function generateForTopic(req, res, callback) {
}
userPrivileges = results.privileges;
topics.getTopicWithPosts(results.topic, 'tid:' + tid + ':posts', req.uid, 0, 25, false, next);
- }
+ },
], function (err, topicData) {
if (err) {
return callback(err);
@@ -75,7 +75,7 @@ function generateForTopic(req, res, callback) {
site_url: nconf.get('url') + '/topic/' + topicData.slug,
image_url: image_url,
author: author,
- ttl: 60
+ ttl: 60,
});
var dateStamp;
@@ -92,7 +92,7 @@ function generateForTopic(req, res, callback) {
description: postData.content,
url: nconf.get('url') + '/post/' + postData.pid,
author: postData.user ? postData.user.username : '',
- date: dateStamp
+ date: dateStamp,
});
}
});
@@ -117,7 +117,7 @@ function generateForUserTopics(req, res, callback) {
return callback();
}
user.getUserFields(uid, ['uid', 'username'], next);
- }
+ },
], function (err, userData) {
if (err) {
return callback(err);
@@ -128,7 +128,7 @@ function generateForUserTopics(req, res, callback) {
title: 'Topics by ' + userData.username,
description: 'A list of topics that are posted by ' + userData.username,
feed_url: '/user/' + userslug + '/topics.rss',
- site_url: '/user/' + userslug + '/topics'
+ site_url: '/user/' + userslug + '/topics',
}, 'uid:' + userData.uid + ':topics', req, res, callback);
});
}
@@ -152,9 +152,9 @@ function generateForCategory(req, res, next) {
reverse: true,
start: 0,
stop: 25,
- uid: req.uid
+ uid: req.uid,
}, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -168,7 +168,7 @@ function generateForCategory(req, res, next) {
feed_url: '/category/' + cid + '.rss',
site_url: '/category/' + results.category.cid,
}, results.category.topics, next);
- }
+ },
], function (err, feed) {
if (err) {
return next(err);
@@ -186,7 +186,7 @@ function generateForRecent(req, res, next) {
title: 'Recently Active Topics',
description: 'A list of topics that have been active within the past 24 hours',
feed_url: '/recent.rss',
- site_url: '/recent'
+ site_url: '/recent',
}, 'topics:recent', req, res, next);
}
@@ -198,7 +198,7 @@ function generateForPopular(req, res, next) {
daily: 'day',
weekly: 'week',
monthly: 'month',
- alltime: 'alltime'
+ alltime: 'alltime',
};
var term = terms[req.params.term] || 'day';
@@ -212,9 +212,9 @@ function generateForPopular(req, res, next) {
title: 'Popular Topics',
description: 'A list of topics that are sorted by post count',
feed_url: '/popular/' + (req.params.term || 'daily') + '.rss',
- site_url: '/popular/' + (req.params.term || 'daily')
+ site_url: '/popular/' + (req.params.term || 'daily'),
}, topics, next);
- }
+ },
], function (err, feed) {
if (err) {
return next(err);
@@ -232,7 +232,7 @@ function generateForTopics(options, set, req, res, next) {
},
function (data, next) {
generateTopicsFeed(options, data.topics, next);
- }
+ },
], function (err, feed) {
if (err) {
return next(err);
@@ -242,7 +242,6 @@ function generateForTopics(options, set, req, res, next) {
}
function generateTopicsFeed(feedOptions, feedTopics, callback) {
-
feedOptions.ttl = 60;
feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url;
feedOptions.site_url = nconf.get('url') + feedOptions.site_url;
@@ -259,7 +258,7 @@ function generateTopicsFeed(feedOptions, feedTopics, callback) {
var feedItem = {
title: topicData.title,
url: nconf.get('url') + '/topic/' + topicData.slug,
- date: new Date(parseInt(topicData.lastposttime, 10)).toUTCString()
+ date: new Date(parseInt(topicData.lastposttime, 10)).toUTCString(),
};
if (topicData.teaser && topicData.teaser.user) {
@@ -306,7 +305,7 @@ function generateForRecentPosts(req, res, next) {
title: 'Recent Posts',
description: 'A list of recent posts',
feed_url: '/recentposts.rss',
- site_url: '/recentposts'
+ site_url: '/recentposts',
}, posts);
sendFeed(feed, res);
@@ -328,7 +327,7 @@ function generateForCategoryRecentPosts(req, res, next) {
},
posts: function (next) {
categories.getRecentReplies(cid, req.uid, 20, next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
@@ -345,7 +344,7 @@ function generateForCategoryRecentPosts(req, res, next) {
title: results.category.name + ' Recent Posts',
description: 'A list of recent posts from ' + results.category.name,
feed_url: '/category/' + cid + '/recentposts.rss',
- site_url: '/category/' + cid + '/recentposts'
+ site_url: '/category/' + cid + '/recentposts',
}, results.posts);
sendFeed(feed, res);
@@ -369,7 +368,7 @@ function generateForPostsFeed(feedOptions, posts) {
description: postData.content,
url: nconf.get('url') + '/post/' + postData.pid,
author: postData.user ? postData.user.username : '',
- date: new Date(parseInt(postData.timestamp, 10)).toUTCString()
+ date: new Date(parseInt(postData.timestamp, 10)).toUTCString(),
});
});
@@ -392,7 +391,7 @@ function generateForTag(req, res, next) {
feed_url: '/tags/' + tag + '.rss',
site_url: '/tags/' + tag,
start: start,
- stop: stop
+ stop: stop,
}, 'tag:' + tag + ':topics', req, res, next);
}
@@ -401,4 +400,3 @@ function sendFeed(feed, res) {
res.type('xml').set('Content-Length', Buffer.byteLength(xml)).send(xml);
}
-
diff --git a/src/routes/helpers.js b/src/routes/helpers.js
index 2379c7ebf1..8452b7f6d9 100644
--- a/src/routes/helpers.js
+++ b/src/routes/helpers.js
@@ -9,4 +9,4 @@ helpers.setupPageRoute = function (router, name, middleware, middlewares, contro
router.get('/api' + name, middlewares, controller);
};
-module.exports = helpers;
\ No newline at end of file
+module.exports = helpers;
diff --git a/src/routes/index.js b/src/routes/index.js
index b49a429420..57b1d5c942 100644
--- a/src/routes/index.js
+++ b/src/routes/index.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var nconf = require('nconf');
var winston = require('winston');
@@ -85,11 +85,11 @@ function groupRoutes(app, middleware, controllers) {
setupPageRoute(app, '/groups/:slug/members', middleware, middlewares, controllers.groups.members);
}
-module.exports = function (app, middleware, hotswapIds) {
+module.exports = function (app, middleware, hotswapIds, callback) {
var routers = [
express.Router(), // plugin router
express.Router(), // main app router
- express.Router() // auth router
+ express.Router(), // auth router
];
var router = routers[1];
var pluginRouter = routers[0];
@@ -97,8 +97,11 @@ module.exports = function (app, middleware, hotswapIds) {
var relativePath = nconf.get('relative_path');
var ensureLoggedIn = require('connect-ensure-login');
+ var idx;
+ var x;
+
if (Array.isArray(hotswapIds) && hotswapIds.length) {
- for(var idx,x = 0; x < hotswapIds.length; x++) {
+ for (x = 0; x < hotswapIds.length; x += 1) {
idx = routers.push(express.Router()) - 1;
routers[idx].hotswapId = hotswapIds[x];
}
@@ -132,7 +135,7 @@ module.exports = function (app, middleware, hotswapIds) {
userRoutes(router, middleware, controllers);
groupRoutes(router, middleware, controllers);
- for(var x = 0; x < routers.length; x++) {
+ for (x = 0; x < routers.length; x += 1) {
app.use(relativePath, routers[x]);
}
@@ -154,7 +157,7 @@ module.exports = function (app, middleware, hotswapIds) {
if (path.resolve(__dirname, '../../public/uploads') !== nconf.get('upload_path')) {
statics.unshift({ route: '/assets/uploads', path: nconf.get('upload_path') });
}
-
+
statics.forEach(function (obj) {
app.use(relativePath + obj.route, express.static(obj.path, staticOptions));
});
@@ -180,7 +183,7 @@ module.exports = function (app, middleware, hotswapIds) {
];
app.use(relativePath, function (req, res, next) {
if (deprecatedPaths.some(function (path) { return req.path.startsWith(path); })) {
- winston.warn('[deprecated] Accessing `' + req.path.slice(1) + '` from `/` is deprecated. ' +
+ winston.warn('[deprecated] Accessing `' + req.path.slice(1) + '` from `/` is deprecated. ' +
'Use `/assets' + req.path + '` to access this file.');
res.redirect(relativePath + '/assets' + req.path + '?' + meta.config['cache-buster']);
} else {
@@ -195,19 +198,20 @@ module.exports = function (app, middleware, hotswapIds) {
});
app.use(relativePath + '/assets/vendor/jquery/timeago/locales', middleware.processTimeagoLocales);
- app.use(controllers.handle404);
- app.use(controllers.handleURIErrors);
- app.use(controllers.handleErrors);
+ app.use(controllers['404'].handle404);
+ app.use(controllers.errors.handleURIErrors);
+ app.use(controllers.errors.handleErrors);
// Add plugin routes
async.series([
async.apply(plugins.reloadRoutes),
async.apply(authRoutes.reloadRoutes),
- async.apply(user.addInterstitials)
+ async.apply(user.addInterstitials),
], function (err) {
if (err) {
- return winston.error(err);
+ return callback(err);
}
winston.info('Routes added');
+ callback();
});
};
diff --git a/src/routes/meta.js b/src/routes/meta.js
index cb089f1200..de0bb52406 100644
--- a/src/routes/meta.js
+++ b/src/routes/meta.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
module.exports = function (app, middleware, controllers) {
app.get('/sitemap.xml', controllers.sitemap.render);
@@ -8,4 +8,5 @@ module.exports = function (app, middleware, controllers) {
app.get('/robots.txt', controllers.robots);
app.get('/manifest.json', controllers.manifest);
app.get('/css/previews/:theme', controllers.admin.themes.get);
+ app.get('/osd.xml', controllers.osd.handle);
};
diff --git a/src/search.js b/src/search.js
index d77b1f58f0..ffe33c8ef5 100644
--- a/src/search.js
+++ b/src/search.js
@@ -17,7 +17,6 @@ var search = {};
module.exports = search;
search.search = function (data, callback) {
-
var start = process.hrtime();
var searchIn = data.searchIn || 'titlesposts';
@@ -37,7 +36,7 @@ search.search = function (data, callback) {
result.search_query = validator.escape(String(data.query || ''));
result.time = (process.elapsedTimeSince(start) / 1000).toFixed(2);
next(null, result);
- }
+ },
], callback);
};
@@ -49,7 +48,7 @@ function searchInContent(data, callback) {
},
searchUids: function (next) {
getSearchUids(data, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -69,7 +68,7 @@ function searchInContent(data, callback) {
} else {
next(null, []);
}
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -77,7 +76,7 @@ function searchInContent(data, callback) {
var matchCount = 0;
if (!results || (!results.pids.length && !results.tids.length)) {
- return callback(null, {posts: [], matchCount: matchCount, pageCount: 1});
+ return callback(null, { posts: [], matchCount: matchCount, pageCount: 1 });
}
async.waterfall([
@@ -106,8 +105,8 @@ function searchInContent(data, callback) {
posts.getPostSummaryByPids(pids, data.uid, {}, next);
},
function (posts, next) {
- next(null, {posts: posts, matchCount: matchCount, pageCount: Math.max(1, Math.ceil(parseInt(matchCount, 10) / 10))});
- }
+ next(null, { posts: posts, matchCount: matchCount, pageCount: Math.max(1, Math.ceil(parseInt(matchCount, 10) / 10)) });
+ },
], callback);
});
});
@@ -227,9 +226,9 @@ function getMatchedPosts(pids, data, callback) {
} else {
setImmediate(next);
}
- }
+ },
}, next);
- }
+ },
], function (err, results) {
if (err) {
return next(err);
@@ -249,11 +248,10 @@ function getMatchedPosts(pids, data, callback) {
next(null, topicsData);
});
- }
+ },
}, next);
},
function (results, next) {
-
posts.forEach(function (post, index) {
if (results.topics && results.topics[index]) {
post.topic = results.topics[index];
@@ -275,7 +273,7 @@ function getMatchedPosts(pids, data, callback) {
});
next(null, posts);
- }
+ },
], callback);
}
@@ -296,7 +294,7 @@ function filterByPostcount(posts, postCount, repliesFilter) {
}
function filterByTimerange(posts, timeRange, timeFilter) {
- timeRange = parseInt(timeRange) * 1000;
+ timeRange = parseInt(timeRange, 10) * 1000;
if (timeRange) {
var time = Date.now() - timeRange;
if (timeFilter === 'newer') {
@@ -380,7 +378,7 @@ function getSearchCids(data, callback) {
},
function (cids, next) {
privileges.categories.filterCids('read', cids, data.uid, next);
- }
+ },
], callback);
return;
}
@@ -399,7 +397,7 @@ function getSearchCids(data, callback) {
} else {
next(null, []);
}
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -424,10 +422,10 @@ function getChildrenCids(cids, uid, callback) {
childrenCategories.forEach(function (childrens) {
categories.flattenCategories(allCategories, childrens);
- childrenCids = childrenCids.concat(allCategories.map(function (category) {
- return category && category.cid;
- }));
- });
+ childrenCids = childrenCids.concat(allCategories.map(function (category) {
+ return category && category.cid;
+ }));
+ });
callback(null, childrenCids);
});
@@ -446,7 +444,7 @@ search.searchQuery = function (index, content, cids, uids, callback) {
index: index,
content: content,
cid: cids,
- uid: uids
+ uid: uids,
}, callback);
};
diff --git a/src/settings.js b/src/settings.js
index 6f6cad2854..b9642c0dce 100644
--- a/src/settings.js
+++ b/src/settings.js
@@ -1,9 +1,13 @@
-"use strict";
+'use strict';
var meta = require('./meta');
function expandObjBy(obj1, obj2) {
- var key, val1, val2, xorValIsArray, changed = false;
+ var key;
+ var val1;
+ var val2;
+ var xorValIsArray;
+ var changed = false;
for (key in obj2) {
if (obj2.hasOwnProperty(key)) {
val2 = obj2[key];
@@ -23,7 +27,8 @@ function expandObjBy(obj1, obj2) {
}
function trim(obj1, obj2) {
- var key, val1;
+ var key;
+ var val1;
for (key in obj1) {
if (obj1.hasOwnProperty(key)) {
val1 = obj1[key];
@@ -106,8 +111,8 @@ Settings.prototype.sync = function (callback) {
@param callback Gets called when done.
*/
Settings.prototype.persist = function (callback) {
- var conf = this.cfg._,
- _this = this;
+ var conf = this.cfg._;
+ var _this = this;
if (typeof conf === 'object') {
conf = JSON.stringify(conf);
}
@@ -126,19 +131,19 @@ Settings.prototype.persist = function (callback) {
@returns Object The setting to be used.
*/
Settings.prototype.get = function (key, def) {
- var obj = this.cfg._,
- parts = (key || '').split('.'),
- part;
- for (var i = 0; i < parts.length; i++) {
+ var obj = this.cfg._;
+ var parts = (key || '').split('.');
+ var part;
+ for (var i = 0; i < parts.length; i += 1) {
part = parts[i];
if (part && obj != null) {
obj = obj[part];
}
}
- if (obj === void 0) {
- if (def === void 0) {
+ if (obj === undefined) {
+ if (def === undefined) {
def = this.defCfg;
- for (var j = 0; j < parts.length; j++) {
+ for (var j = 0; j < parts.length; j += 1) {
part = parts[j];
if (part && def != null) {
def = def[part];
@@ -165,7 +170,7 @@ Settings.prototype.getWrapper = function () {
Settings.prototype.createWrapper = function (version, settings) {
return {
v: version,
- _: settings
+ _: settings,
};
};
@@ -183,15 +188,18 @@ Settings.prototype.createDefaultWrapper = function () {
@param val The value to set.
*/
Settings.prototype.set = function (key, val) {
- var part, obj, parts;
+ var part;
+ var obj;
+ var 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++) {
- if (part = parts[i]) {
+ for (var i = 0, _len = parts.length - 1; i < _len; i += 1) {
+ part = parts[i];
+ if (part) {
if (!obj.hasOwnProperty(part)) {
obj[part] = {};
}
diff --git a/src/sitemap.js b/src/sitemap.js
index ec068d71d3..d6f6fa39fe 100644
--- a/src/sitemap.js
+++ b/src/sitemap.js
@@ -14,23 +14,23 @@ var utils = require('../public/src/utils');
var sitemap = {
maps: {
- topics: []
- }
+ topics: [],
+ },
};
sitemap.render = function (callback) {
var numTopics = parseInt(meta.config.sitemapTopics, 10) || 500;
var returnData = {
- url: nconf.get('url'),
- topics: []
- };
+ url: nconf.get('url'),
+ topics: [],
+ };
var numPages;
async.waterfall([
async.apply(db.getSortedSetRange, 'topics:recent', 0, -1),
function (tids, next) {
privileges.topics.filterTids('read', tids, 0, next);
- }
+ },
], function (err, tids) {
if (err) {
numPages = 1;
@@ -38,7 +38,7 @@ sitemap.render = function (callback) {
numPages = Math.ceil(tids.length / numTopics);
}
- for(var x = 1; x <= numPages; x++) {
+ for (var x = 1; x <= numPages; x += 1) {
returnData.topics.push(x);
}
@@ -55,31 +55,31 @@ sitemap.getPages = function (callback) {
}
var urls = [{
- url: '',
- changefreq: 'weekly',
- priority: 0.6
- }, {
- url: '/recent',
- changefreq: 'daily',
- priority: 0.4
- }, {
- url: '/users',
- changefreq: 'daily',
- priority: 0.4
- }, {
- url: '/groups',
- changefreq: 'daily',
- priority: 0.4
- }];
+ url: '',
+ changefreq: 'weekly',
+ priority: 0.6,
+ }, {
+ url: '/recent',
+ changefreq: 'daily',
+ priority: 0.4,
+ }, {
+ url: '/users',
+ changefreq: 'daily',
+ priority: 0.4,
+ }, {
+ url: '/groups',
+ changefreq: 'daily',
+ priority: 0.4,
+ }];
- plugins.fireHook('filter:sitemap.getPages', {urls: urls}, function (err, data) {
+ plugins.fireHook('filter:sitemap.getPages', { urls: urls }, function (err, data) {
if (err) {
return callback(err);
}
sitemap.maps.pages = sm.createSitemap({
hostname: nconf.get('url'),
cacheTime: 1000 * 60 * 60 * 24, // Cached for 24 hours
- urls: data.urls
+ urls: data.urls,
});
sitemap.maps.pages.toXML(callback);
@@ -105,7 +105,7 @@ sitemap.getCategories = function (callback) {
categoryUrls.push({
url: '/category/' + category.slug,
changefreq: 'weekly',
- priority: 0.4
+ priority: 0.4,
});
}
});
@@ -113,7 +113,7 @@ sitemap.getCategories = function (callback) {
sitemap.maps.categories = sm.createSitemap({
hostname: nconf.get('url'),
cacheTime: 1000 * 60 * 60 * 24, // Cached for 24 hours
- urls: categoryUrls
+ urls: categoryUrls,
});
sitemap.maps.categories.toXML(callback);
@@ -147,7 +147,7 @@ sitemap.getTopicPage = function (page, callback) {
},
function (tids, next) {
topics.getTopicsFields(tids, ['tid', 'title', 'slug', 'lastposttime'], next);
- }
+ },
], function (err, topics) {
if (err) {
return callback(err);
@@ -159,7 +159,7 @@ sitemap.getTopicPage = function (page, callback) {
url: '/topic/' + topic.slug,
lastmodISO: utils.toISOString(topic.lastposttime),
changefreq: 'daily',
- priority: 0.6
+ priority: 0.6,
});
}
});
@@ -167,7 +167,7 @@ sitemap.getTopicPage = function (page, callback) {
sitemap.maps.topics[page - 1] = sm.createSitemap({
hostname: nconf.get('url'),
cacheTime: 1000 * 60 * 60, // Cached for 1 hour
- urls: topicUrls
+ urls: topicUrls,
});
sitemap.maps.topics[page - 1].toXML(callback);
diff --git a/src/social.js b/src/social.js
index 0c71daadba..71780b5b81 100644
--- a/src/social.js
+++ b/src/social.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var plugins = require('./plugins');
var db = require('./database');
@@ -15,20 +15,20 @@ social.getPostSharing = function (callback) {
var networks = [
{
- id: "facebook",
- name: "Facebook",
- class: "fa-facebook"
+ id: 'facebook',
+ name: 'Facebook',
+ class: 'fa-facebook',
},
{
- id: "twitter",
- name: "Twitter",
- class: "fa-twitter"
+ id: 'twitter',
+ name: 'Twitter',
+ class: 'fa-twitter',
},
{
- id: "google",
- name: "Google+",
- class: "fa-google-plus"
- }
+ id: 'google',
+ name: 'Google+',
+ class: 'fa-google-plus',
+ },
];
async.waterfall([
@@ -48,7 +48,7 @@ social.getPostSharing = function (callback) {
social.postSharing = networks;
next(null, networks);
});
- }
+ },
], callback);
};
@@ -78,8 +78,8 @@ social.setActivePostSharingNetworks = function (networkIDs, callback) {
function (next) {
social.postSharing = null;
next();
- }
+ },
], callback);
};
-module.exports = social;
\ No newline at end of file
+module.exports = social;
diff --git a/src/socket.io/admin.js b/src/socket.io/admin.js
index 987f607ec9..9eba77f39b 100644
--- a/src/socket.io/admin.js
+++ b/src/socket.io/admin.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var winston = require('winston');
@@ -33,7 +33,7 @@ var SocketAdmin = {
email: {},
analytics: {},
logs: {},
- errors: {}
+ errors: {},
};
SocketAdmin.before = function (socket, method, data, next) {
@@ -50,7 +50,7 @@ SocketAdmin.reload = function (socket, data, callback) {
events.log({
type: 'restart',
uid: socket.uid,
- ip: socket.ip
+ ip: socket.ip,
});
meta.restart();
callback();
@@ -65,13 +65,13 @@ SocketAdmin.restart = function (socket, data, callback) {
events.log({
type: 'build',
uid: socket.uid,
- ip: socket.ip
+ ip: socket.ip,
});
events.log({
type: 'restart',
uid: socket.uid,
- ip: socket.ip
+ ip: socket.ip,
});
meta.restart();
@@ -93,17 +93,18 @@ SocketAdmin.themes.set = function (socket, data, callback) {
return callback(new Error('[[error:invalid-data]]'));
}
- var wrappedCallback = function (err) {
- if (err) {
- return callback(err);
- }
- meta.themes.set(data, callback);
- };
- if (data.type === 'bootswatch') {
- wrappedCallback();
- } else {
- widgets.reset(wrappedCallback);
- }
+ async.waterfall([
+ function (next) {
+ if (data.type === 'bootswatch') {
+ setImmediate(next);
+ } else {
+ widgets.reset(next);
+ }
+ },
+ function (next) {
+ meta.themes.set(data, next);
+ },
+ ], callback);
};
SocketAdmin.plugins.toggleActive = function (socket, plugin_id, callback) {
@@ -125,7 +126,7 @@ SocketAdmin.plugins.orderActivePlugins = function (socket, data, callback) {
if (plugin && plugin.name) {
db.sortedSetAdd('plugins:active', plugin.order || 0, plugin.name, next);
} else {
- next();
+ setImmediate(next);
}
}, callback);
};
@@ -148,7 +149,7 @@ SocketAdmin.config.set = function (socket, data, callback) {
}
var _data = {};
_data[data.key] = data.value;
- SocketAdmin.config.setMultiple(socket, data, callback);
+ SocketAdmin.config.setMultiple(socket, _data, callback);
};
SocketAdmin.config.setMultiple = function (socket, data, callback) {
@@ -166,14 +167,14 @@ SocketAdmin.config.setMultiple = function (socket, data, callback) {
if (data.hasOwnProperty(field)) {
setting = {
key: field,
- value: data[field]
+ value: data[field],
};
plugins.fireHook('action:config.set', setting);
- logger.monitorConfig({io: index.server}, setting);
+ logger.monitorConfig({ io: index.server }, setting);
}
}
setImmediate(next);
- }
+ },
], callback);
};
@@ -199,11 +200,15 @@ SocketAdmin.email.test = function (socket, data, callback) {
emailer.send(data.template, socket.uid, {
subject: '[' + site_title + '] Test Email',
site_title: site_title,
- url: nconf.get('url')
+ url: nconf.get('url'),
}, callback);
};
SocketAdmin.analytics.get = function (socket, data, callback) {
+ if (!data || !data.graph || !data.units) {
+ return callback(new Error('[[error:invalid-data]]'));
+ }
+
// Default returns views from past 24 hours, by hour
if (data.units === 'days') {
data.amount = 30;
@@ -211,34 +216,30 @@ SocketAdmin.analytics.get = function (socket, data, callback) {
data.amount = 24;
}
- if (data && data.graph && data.units && data.amount) {
- if (data.graph === 'traffic') {
- async.parallel({
- uniqueVisitors: function (next) {
- if (data.units === 'days') {
- analytics.getDailyStatsForSet('analytics:uniquevisitors', data.until || Date.now(), data.amount, next);
- } else {
- analytics.getHourlyStatsForSet('analytics:uniquevisitors', data.until || Date.now(), data.amount, next);
- }
- },
- pageviews: function (next) {
- if (data.units === 'days') {
- analytics.getDailyStatsForSet('analytics:pageviews', data.until || Date.now(), data.amount, next);
- } else {
- analytics.getHourlyStatsForSet('analytics:pageviews', data.until || Date.now(), data.amount, next);
- }
- },
- monthlyPageViews: function (next) {
- analytics.getMonthlyPageViews(next);
+ if (data.graph === 'traffic') {
+ async.parallel({
+ uniqueVisitors: function (next) {
+ if (data.units === 'days') {
+ analytics.getDailyStatsForSet('analytics:uniquevisitors', data.until || Date.now(), data.amount, next);
+ } else {
+ analytics.getHourlyStatsForSet('analytics:uniquevisitors', data.until || Date.now(), data.amount, next);
}
- }, function (err, data) {
- data.pastDay = data.pageviews.reduce(function (a, b) {return parseInt(a, 10) + parseInt(b, 10);});
- data.pageviews[data.pageviews.length - 1] = parseInt(data.pageviews[data.pageviews.length - 1], 10) + analytics.getUnwrittenPageviews();
- callback(err, data);
- });
- }
- } else {
- callback(new Error('Invalid analytics call'));
+ },
+ pageviews: function (next) {
+ if (data.units === 'days') {
+ analytics.getDailyStatsForSet('analytics:pageviews', data.until || Date.now(), data.amount, next);
+ } else {
+ analytics.getHourlyStatsForSet('analytics:pageviews', data.until || Date.now(), data.amount, next);
+ }
+ },
+ monthlyPageViews: function (next) {
+ analytics.getMonthlyPageViews(next);
+ },
+ }, function (err, data) {
+ data.pastDay = data.pageviews.reduce(function (a, b) { return parseInt(a, 10) + parseInt(b, 10); });
+ data.pageviews[data.pageviews.length - 1] = parseInt(data.pageviews[data.pageviews.length - 1], 10) + analytics.getUnwrittenPageviews();
+ callback(err, data);
+ });
}
};
@@ -259,13 +260,15 @@ SocketAdmin.deleteAllEvents = function (socket, data, callback) {
};
SocketAdmin.getSearchDict = function (socket, data, callback) {
- user.getSettings(socket.uid, function (err, settings) {
- if (err) {
- return callback(err);
- }
- var lang = settings.userLang || meta.config.defaultLang || 'en-GB';
- getAdminSearchDict(lang, callback);
- });
+ async.waterfall([
+ function (next) {
+ user.getSettings(socket.uid, next);
+ },
+ function (settings, next) {
+ var lang = settings.userLang || meta.config.defaultLang || 'en-GB';
+ getAdminSearchDict(lang, next);
+ },
+ ], callback);
};
SocketAdmin.deleteAllSessions = function (socket, data, callback) {
diff --git a/src/socket.io/admin/categories.js b/src/socket.io/admin/categories.js
index e05f6db36e..50c2061038 100644
--- a/src/socket.io/admin/categories.js
+++ b/src/socket.io/admin/categories.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -22,12 +22,12 @@ Categories.getAll = function (socket, data, callback) {
async.apply(db.getSortedSetRange, 'categories:cid', 0, -1),
async.apply(categories.getCategoriesData),
function (categories, next) {
- //Hook changes, there is no req, and res
- plugins.fireHook('filter:admin.categories.get', {categories: categories}, next);
+ // Hook changes, there is no req, and res
+ plugins.fireHook('filter:admin.categories.get', { categories: categories }, next);
},
function (result, next) {
next(null, categories.getTree(result.categories, 0));
- }
+ },
], function (err, categoriesTree) {
if (err) {
return callback(err);
@@ -103,4 +103,4 @@ Categories.copyPrivilegesFrom = function (socket, data, callback) {
categories.copyPrivilegesFrom(data.fromCid, data.toCid, callback);
};
-module.exports = Categories;
\ No newline at end of file
+module.exports = Categories;
diff --git a/src/socket.io/admin/groups.js b/src/socket.io/admin/groups.js
index 6b9e404ae1..fdb50e0561 100644
--- a/src/socket.io/admin/groups.js
+++ b/src/socket.io/admin/groups.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var groups = require('../../groups');
@@ -15,7 +15,7 @@ Groups.create = function (socket, data, callback) {
groups.create({
name: data.name,
description: data.description,
- ownerUid: socket.uid
+ ownerUid: socket.uid,
}, callback);
};
@@ -33,7 +33,7 @@ Groups.join = function (socket, data, callback) {
return next(new Error('[[error:group-already-member]]'));
}
groups.join(data.groupName, data.uid, next);
- }
+ },
], callback);
};
@@ -55,7 +55,7 @@ Groups.leave = function (socket, data, callback) {
return next(new Error('[[error:group-not-member]]'));
}
groups.leave(data.groupName, data.uid, next);
- }
+ },
], callback);
};
@@ -67,4 +67,4 @@ Groups.update = function (socket, data, callback) {
groups.update(data.groupName, data.values, callback);
};
-module.exports = Groups;
\ No newline at end of file
+module.exports = Groups;
diff --git a/src/socket.io/admin/navigation.js b/src/socket.io/admin/navigation.js
index 2f4d9817b4..807b10ae85 100644
--- a/src/socket.io/admin/navigation.js
+++ b/src/socket.io/admin/navigation.js
@@ -1,10 +1,10 @@
-"use strict";
+'use strict';
-var navigationAdmin = require('../../navigation/admin'),
- SocketNavigation = {};
+var navigationAdmin = require('../../navigation/admin');
+var SocketNavigation = {};
SocketNavigation.save = function (socket, data, callback) {
navigationAdmin.save(data, callback);
};
-module.exports = SocketNavigation;
\ No newline at end of file
+module.exports = SocketNavigation;
diff --git a/src/socket.io/admin/rewards.js b/src/socket.io/admin/rewards.js
index 3d895a5281..8b845a33c1 100644
--- a/src/socket.io/admin/rewards.js
+++ b/src/socket.io/admin/rewards.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var rewardsAdmin = require('../../rewards/admin');
var SocketRewards = module.exports;
diff --git a/src/socket.io/admin/rooms.js b/src/socket.io/admin/rooms.js
index 2f6ab50698..544bdc04da 100644
--- a/src/socket.io/admin/rooms.js
+++ b/src/socket.io/admin/rooms.js
@@ -13,7 +13,7 @@ var stats = {};
var totals = {};
var SocketRooms = {
stats: stats,
- totals: totals
+ totals: totals,
};
@@ -22,7 +22,7 @@ pubsub.on('sync:stats:start', function () {
if (err) {
return winston.error(err);
}
- pubsub.publish('sync:stats:end', {stats: stats, id: os.hostname() + ':' + nconf.get('port')});
+ pubsub.publish('sync:stats:end', { stats: stats, id: os.hostname() + ':' + nconf.get('port') });
});
});
@@ -66,7 +66,7 @@ SocketRooms.getAll = function (socket, data, callback) {
recent: 0,
unread: 0,
topics: 0,
- category: 0
+ category: 0,
};
for (var instance in stats) {
@@ -81,7 +81,7 @@ SocketRooms.getAll = function (socket, data, callback) {
totals.users.category += stats[instance].users.category;
stats[instance].topics.forEach(function (topic) {
- totals.topics[topic.tid] = totals.topics[topic.tid] || {count: 0, tid: topic.tid};
+ totals.topics[topic.tid] = totals.topics[topic.tid] || { count: 0, tid: topic.tid };
totals.topics[topic.tid].count += topic.count;
});
}
@@ -89,7 +89,7 @@ SocketRooms.getAll = function (socket, data, callback) {
var topTenTopics = [];
Object.keys(totals.topics).forEach(function (tid) {
- topTenTopics.push({tid: tid, count: totals.topics[tid].count});
+ topTenTopics.push({ tid: tid, count: totals.topics[tid].count });
});
topTenTopics = topTenTopics.sort(function (a, b) {
@@ -109,11 +109,11 @@ SocketRooms.getAll = function (socket, data, callback) {
topTenTopics.forEach(function (topic, index) {
totals.topics[topic.tid] = {
value: topic.count || 0,
- title: validator.escape(String(titles[index].title))
+ title: validator.escape(String(titles[index].title)),
};
});
next(null, totals);
- }
+ },
], callback);
};
@@ -123,7 +123,7 @@ SocketRooms.getOnlineUserCount = function (io) {
if (io) {
for (var key in io.sockets.adapter.rooms) {
if (io.sockets.adapter.rooms.hasOwnProperty(key) && key.startsWith('uid_')) {
- ++ count;
+ count += 1;
}
}
}
@@ -143,9 +143,9 @@ SocketRooms.getLocalStats = function (callback) {
recent: 0,
unread: 0,
topics: 0,
- category: 0
+ category: 0,
},
- topics: {}
+ topics: {},
};
if (io) {
@@ -165,7 +165,7 @@ SocketRooms.getLocalStats = function (callback) {
tid = room.match(/^topic_(\d+)/);
if (tid) {
socketData.users.topics += roomClients[room].length;
- topTenTopics.push({tid: tid[1], count: roomClients[room].length});
+ topTenTopics.push({ tid: tid[1], count: roomClients[room].length });
} else if (room.match(/^category/)) {
socketData.users.category += roomClients[room].length;
}
@@ -183,4 +183,4 @@ SocketRooms.getLocalStats = function (callback) {
};
-module.exports = SocketRooms;
\ No newline at end of file
+module.exports = SocketRooms;
diff --git a/src/socket.io/admin/social.js b/src/socket.io/admin/social.js
index 77227ea760..5f422eff6b 100644
--- a/src/socket.io/admin/social.js
+++ b/src/socket.io/admin/social.js
@@ -1,10 +1,10 @@
-"use strict";
+'use strict';
-var social = require('../../social'),
- SocketSocial = {};
+var social = require('../../social');
+var SocketSocial = {};
SocketSocial.savePostSharingNetworks = function (socket, data, callback) {
social.setActivePostSharingNetworks(data, callback);
};
-module.exports = SocketSocial;
\ No newline at end of file
+module.exports = SocketSocial;
diff --git a/src/socket.io/admin/tags.js b/src/socket.io/admin/tags.js
index 4362159502..8fe50790eb 100644
--- a/src/socket.io/admin/tags.js
+++ b/src/socket.io/admin/tags.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var topics = require('../../topics');
diff --git a/src/socket.io/admin/user.js b/src/socket.io/admin/user.js
index 87a4c2d2ae..8770381aae 100644
--- a/src/socket.io/admin/user.js
+++ b/src/socket.io/admin/user.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var validator = require('validator');
@@ -13,7 +13,7 @@ var plugins = require('../../plugins');
var User = {};
User.makeAdmins = function (socket, uids, callback) {
- if(!Array.isArray(uids)) {
+ if (!Array.isArray(uids)) {
return callback(new Error('[[error:invalid-data]]'));
}
@@ -22,7 +22,7 @@ User.makeAdmins = function (socket, uids, callback) {
return callback(err);
}
- for(var i = 0; i < userData.length; i++) {
+ for (var i = 0; i < userData.length; i += 1) {
if (userData[i] && parseInt(userData[i].banned, 10) === 1) {
return callback(new Error('[[error:cant-make-banned-users-admin]]'));
}
@@ -35,7 +35,7 @@ User.makeAdmins = function (socket, uids, callback) {
};
User.removeAdmins = function (socket, uids, callback) {
- if(!Array.isArray(uids)) {
+ if (!Array.isArray(uids)) {
return callback(new Error('[[error:invalid-data]]'));
}
@@ -117,7 +117,7 @@ User.sendValidationEmail = function (socket, uids, callback) {
next();
}
}, next);
- }
+ },
], callback);
};
@@ -177,17 +177,17 @@ function deleteUsers(socket, uids, method, callback) {
type: 'user-delete',
uid: socket.uid,
targetUid: uid,
- ip: socket.ip
+ ip: socket.ip,
}, next);
},
function (next) {
plugins.fireHook('action:user.delete', {
callerUid: socket.uid,
uid: uid,
- ip: socket.ip
+ ip: socket.ip,
});
next();
- }
+ },
], next);
}, callback);
}
@@ -196,7 +196,7 @@ User.search = function (socket, data, callback) {
var searchData;
async.waterfall([
function (next) {
- user.search({query: data.query, searchBy: data.searchBy, uid: socket.uid}, next);
+ user.search({ query: data.query, searchBy: data.searchBy, uid: socket.uid }, next);
},
function (_searchData, next) {
searchData = _searchData;
@@ -220,7 +220,7 @@ User.search = function (socket, data, callback) {
}
});
next(null, searchData);
- }
+ },
], callback);
};
@@ -238,10 +238,10 @@ User.acceptRegistration = function (socket, data, callback) {
type: 'registration-approved',
uid: socket.uid,
ip: socket.ip,
- targetUid: uid
+ targetUid: uid,
});
next(null, uid);
- }
+ },
], callback);
};
@@ -258,7 +258,7 @@ User.rejectRegistration = function (socket, data, callback) {
username: data.username,
});
next();
- }
+ },
], callback);
};
diff --git a/src/socket.io/categories.js b/src/socket.io/categories.js
index 885af43516..1678b553bf 100644
--- a/src/socket.io/categories.js
+++ b/src/socket.io/categories.js
@@ -22,7 +22,7 @@ SocketCategories.get = function (socket, data, callback) {
async.apply(db.getSortedSetRange, 'categories:cid', 0, -1),
async.apply(categories.getCategoriesData),
], next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -39,12 +39,12 @@ SocketCategories.get = function (socket, data, callback) {
SocketCategories.getWatchedCategories = function (socket, data, callback) {
async.parallel({
categories: async.apply(categories.getCategoriesByPrivilege, 'cid:0:children', socket.uid, 'find'),
- ignoredCids: async.apply(user.getIgnoredCategories, socket.uid)
+ ignoredCids: async.apply(user.getIgnoredCategories, socket.uid),
}, function (err, results) {
if (err) {
return callback(err);
}
- var watchedCategories = results.categories.filter(function (category) {
+ var watchedCategories = results.categories.filter(function (category) {
return category && results.ignoredCids.indexOf(category.cid.toString()) === -1;
});
@@ -70,7 +70,7 @@ SocketCategories.loadMore = function (socket, data, callback) {
} else {
next();
}
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -94,7 +94,7 @@ SocketCategories.loadMore = function (socket, data, callback) {
var start = Math.max(0, parseInt(data.after, 10));
if (data.direction === -1) {
- start = start - (reverse ? infScrollTopicsPerPage : -infScrollTopicsPerPage);
+ start -= reverse ? infScrollTopicsPerPage : -infScrollTopicsPerPage;
}
var stop = start + infScrollTopicsPerPage - 1;
@@ -118,7 +118,7 @@ SocketCategories.loadMore = function (socket, data, callback) {
stop: stop,
uid: socket.uid,
targetUid: results.targetUid,
- settings: results.settings
+ settings: results.settings,
}, function (err, data) {
if (err) {
return callback(err);
@@ -129,7 +129,7 @@ SocketCategories.loadMore = function (socket, data, callback) {
data.privileges = results.privileges;
data.template = {
category: true,
- name: 'category'
+ name: 'category',
};
callback(null, data);
@@ -162,9 +162,9 @@ SocketCategories.getMoveCategories = function (socket, data, callback) {
},
function (cids, next) {
categories.getCategories(cids, socket.uid, next);
- }
+ },
], next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -204,16 +204,15 @@ function ignoreOrWatch(fn, socket, cid, callback) {
// filter to subcategories of cid
- var any = true;
- while (any) {
- any = false;
- categoryData.forEach(function (c) {
- if (cids.indexOf(c.cid) === -1 && cids.indexOf(c.parentCid) !== -1) {
- cids.push(c.cid);
- any = true;
- }
+ var cat;
+ do {
+ cat = categoryData.find(function (c) {
+ return cids.indexOf(c.cid) === -1 && cids.indexOf(c.parentCid) !== -1;
});
- }
+ if (cat) {
+ cids.push(cat.cid);
+ }
+ } while (cat);
async.each(cids, function (cid, next) {
fn(socket.uid, cid, next);
@@ -221,7 +220,7 @@ function ignoreOrWatch(fn, socket, cid, callback) {
},
function (next) {
topics.pushUnreadCount(socket.uid, next);
- }
+ },
], callback);
}
diff --git a/src/socket.io/groups.js b/src/socket.io/groups.js
index 47453b6e0a..ed6cb00180 100644
--- a/src/socket.io/groups.js
+++ b/src/socket.io/groups.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -42,7 +42,7 @@ SocketGroups.join = function (socket, data, callback) {
async.parallel({
isAdmin: async.apply(user.isAdministrator, socket.uid),
- groupData: async.apply(groups.getGroupData, data.groupName)
+ groupData: async.apply(groups.getGroupData, data.groupName),
}, next);
},
function (results, next) {
@@ -55,7 +55,7 @@ SocketGroups.join = function (socket, data, callback) {
} else {
groups.requestMembership(data.groupName, socket.uid, next);
}
- }
+ },
], callback);
};
@@ -75,7 +75,7 @@ function isOwner(next) {
return function (socket, data, callback) {
async.parallel({
isAdmin: async.apply(user.isAdministrator, socket.uid),
- isOwner: async.apply(groups.ownership.isOwner, socket.uid, data.groupName)
+ isOwner: async.apply(groups.ownership.isOwner, socket.uid, data.groupName),
}, function (err, results) {
if (err || (!results.isOwner && !results.isAdmin)) {
return callback(err || new Error('[[error:no-privileges]]'));
@@ -129,7 +129,7 @@ function acceptRejectAll(method, socket, data, callback) {
async.each(uids, function (uid, next) {
method(data.groupName, uid, next);
}, next);
- }
+ },
], callback);
}
@@ -158,7 +158,7 @@ SocketGroups.issueMassInvite = isOwner(function (socket, data, callback) {
async.eachSeries(uids, function (uid, next) {
groups.invite(data.groupName, uid, next);
}, next);
- }
+ },
], callback);
});
@@ -190,7 +190,7 @@ SocketGroups.kick = isOwner(function (socket, data, callback) {
},
function (isOwner, next) {
groups.kick(data.uid, data.groupName, isOwner, next);
- }
+ },
], callback);
});
@@ -232,7 +232,7 @@ SocketGroups.search = function (socket, data, callback) {
};
SocketGroups.loadMore = function (socket, data, callback) {
- if (!data.sort || !utils.isNumber(data.after) || parseInt(data.after, 10) < 0) {
+ if (!data.sort || !utils.isNumber(data.after) || parseInt(data.after, 10) < 0) {
return callback(new Error('[[error:invalid-data]]'));
}
@@ -259,9 +259,9 @@ SocketGroups.loadMoreMembers = function (socket, data, callback) {
function (users, next) {
next(null, {
users: users,
- nextStart: data.after + 10
+ nextStart: data.after + 10,
});
- }
+ },
], callback);
};
@@ -282,7 +282,7 @@ SocketGroups.cover.update = function (socket, data, callback) {
}
groups.updateCover(socket.uid, data, next);
- }
+ },
], callback);
};
@@ -301,7 +301,7 @@ SocketGroups.cover.remove = function (socket, data, callback) {
}
groups.removeCover(data, next);
- }
+ },
], callback);
};
diff --git a/src/socket.io/helpers.js b/src/socket.io/helpers.js
index 54c8152199..ce2ee7b30c 100644
--- a/src/socket.io/helpers.js
+++ b/src/socket.io/helpers.js
@@ -32,8 +32,8 @@ SocketHelpers.notifyNew = function (uid, type, result) {
filterTidCidIgnorers(uids, result.posts[0].topic.tid, result.posts[0].topic.cid, next);
},
function (uids, next) {
- plugins.fireHook('filter:sockets.sendNewPostToUids', {uidsTo: uids, uidFrom: uid, type: type}, next);
- }
+ plugins.fireHook('filter:sockets.sendNewPostToUids', { uidsTo: uids, uidFrom: uid, type: type }, next);
+ },
], function (err, data) {
if (err) {
return winston.error(err.stack);
@@ -64,7 +64,7 @@ function filterTidCidIgnorers(uids, tid, cid, callback) {
},
categoryIgnored: function (next) {
db.sortedSetScores('cid:' + cid + ':ignorers', uids, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -73,7 +73,7 @@ function filterTidCidIgnorers(uids, tid, cid, callback) {
(!results.topicFollowed[index] && !results.topicIgnored[index] && !results.categoryIgnored[index]);
});
next(null, uids);
- }
+ },
], callback);
}
@@ -98,7 +98,7 @@ SocketHelpers.sendNotificationToPostOwner = function (pid, fromuid, command, not
async.parallel({
username: async.apply(user.getUserField, fromuid, 'username'),
topicTitle: async.apply(topics.getTopicField, postData.tid, 'title'),
- postObj: async.apply(posts.parsePost, postData)
+ postObj: async.apply(posts.parsePost, postData),
}, next);
},
function (results, next) {
@@ -113,9 +113,9 @@ SocketHelpers.sendNotificationToPostOwner = function (pid, fromuid, command, not
nid: command + ':post:' + pid + ':uid:' + fromuid,
from: fromuid,
mergeId: notification + '|' + pid,
- topicTitle: results.topicTitle
+ topicTitle: results.topicTitle,
}, next);
- }
+ },
], function (err, notification) {
if (err) {
return winston.error(err);
@@ -154,9 +154,9 @@ SocketHelpers.sendNotificationToTopicOwner = function (tid, fromuid, command, no
bodyShort: '[[' + notification + ', ' + results.username + ', ' + titleEscaped + ']]',
path: '/topic/' + results.topicData.slug,
nid: command + ':tid:' + tid + ':uid:' + fromuid,
- from: fromuid
+ from: fromuid,
}, next);
- }
+ },
], function (err, notification) {
if (err) {
return winston.error(err);
diff --git a/src/socket.io/index.js b/src/socket.io/index.js
index 01a520585d..ccabf242fa 100644
--- a/src/socket.io/index.js
+++ b/src/socket.io/index.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var nconf = require('nconf');
@@ -23,7 +23,7 @@ Sockets.init = function (server) {
var SocketIO = require('socket.io');
var socketioWildcard = require('socketio-wildcard')();
io = new SocketIO({
- path: nconf.get('relative_path') + '/socket.io'
+ path: nconf.get('relative_path') + '/socket.io',
});
addRedisAdapter(io);
@@ -56,7 +56,7 @@ Sockets.init = function (server) {
}
io.listen(server, {
- transports: nconf.get('socket.io:transports')
+ transports: nconf.get('socket.io:transports'),
});
Sockets.server = io;
@@ -105,16 +105,15 @@ function onMessage(socket, payload) {
var methodToCall = parts.reduce(function (prev, cur) {
if (prev !== null && prev[cur]) {
return prev[cur];
- } else {
- return null;
}
+ return null;
}, Namespaces);
if (!methodToCall) {
if (process.env.NODE_ENV === 'development') {
winston.warn('[socket.io] Unrecognized message: ' + eventName);
}
- return callback({message: '[[error:invalid-event]]'});
+ return callback({ message: '[[error:invalid-event]]' });
}
socket.previousEvents = socket.previousEvents || [];
@@ -144,15 +143,15 @@ function onMessage(socket, payload) {
},
function (next) {
methodToCall(socket, params, next);
- }
+ },
], function (err, result) {
- callback(err ? {message: err.message} : null, result);
+ callback(err ? { message: err.message } : null, result);
});
}
function requireModules() {
var modules = ['admin', 'categories', 'groups', 'meta', 'modules',
- 'notifications', 'plugins', 'posts', 'topics', 'user', 'blacklist'
+ 'notifications', 'plugins', 'posts', 'topics', 'user', 'blacklist',
];
modules.forEach(function (module) {
@@ -175,7 +174,7 @@ function checkMaintenance(socket, callback) {
function validateSession(socket, callback) {
var req = socket.request;
if (!req.signedCookies || !req.signedCookies[nconf.get('sessionKey')]) {
- return callback(new Error('[[error:invalid-session]]'));
+ return callback();
}
db.sessionStore.get(req.signedCookies[nconf.get('sessionKey')], function (err, sessionData) {
if (err || !sessionData) {
@@ -210,7 +209,7 @@ function authorize(socket, callback) {
}
next();
});
- }
+ },
], callback);
}
@@ -220,7 +219,7 @@ function addRedisAdapter(io) {
var redis = require('../database/redis');
var pub = redis.connect();
var sub = redis.connect();
- io.adapter(redisAdapter({pubClient: pub, subClient: sub}));
+ io.adapter(redisAdapter({ pubClient: pub, subClient: sub }));
} else if (nconf.get('isCluster') === 'true') {
winston.warn('[socket.io] Clustering detected, you are advised to configure Redis as a websocket store.');
}
@@ -262,8 +261,7 @@ Sockets.reqFromSocket = function (socket, payload, event) {
secure: encrypted,
url: referer,
path: referer.substr(referer.indexOf(host) + host.length),
- headers: headers
+ headers: headers,
};
};
-
diff --git a/src/socket.io/meta.js b/src/socket.io/meta.js
index baa0abc0aa..398bf249f5 100644
--- a/src/socket.io/meta.js
+++ b/src/socket.io/meta.js
@@ -5,7 +5,7 @@ var user = require('../user');
var topics = require('../topics');
var SocketMeta = {
- rooms: {}
+ rooms: {},
};
SocketMeta.reconnected = function (socket, data, callback) {
diff --git a/src/socket.io/modules.js b/src/socket.io/modules.js
index 473a32e5d9..f0309e8d30 100644
--- a/src/socket.io/modules.js
+++ b/src/socket.io/modules.js
@@ -1,4 +1,5 @@
-"use strict";
+'use strict';
+
var async = require('async');
var validator = require('validator');
@@ -13,7 +14,7 @@ var user = require('../user');
var SocketModules = {
chats: {},
sounds: {},
- settings: {}
+ settings: {},
};
/* Chat */
@@ -31,7 +32,7 @@ SocketModules.chats.getRaw = function (socket, data, callback) {
return next(new Error('[[error:not-allowed]]'));
}
Messaging.getMessageField(data.mid, 'content', next);
- }
+ },
], callback);
};
@@ -66,7 +67,7 @@ SocketModules.chats.send = function (socket, data, callback) {
function (next) {
plugins.fireHook('filter:messaging.send', {
data: data,
- uid: socket.uid
+ uid: socket.uid,
}, function (err, results) {
data = results.data;
next(err);
@@ -82,7 +83,7 @@ SocketModules.chats.send = function (socket, data, callback) {
Messaging.notifyUsersInRoom(socket.uid, data.roomId, message);
user.updateOnlineUsers(socket.uid);
next(null, message);
- }
+ },
], callback);
};
@@ -92,9 +93,9 @@ function rateLimitExceeded(socket) {
var delay = meta.config.hasOwnProperty('chatMessageDelay') ? parseInt(meta.config.chatMessageDelay, 10) : 200;
if (now - socket.lastChatMessageTime < delay) {
return true;
- } else {
- socket.lastChatMessageTime = now;
}
+ socket.lastChatMessageTime = now;
+
return false;
}
@@ -120,7 +121,7 @@ SocketModules.chats.loadRoom = function (socket, data, callback) {
callerUid: socket.uid,
uid: data.uid || socket.uid,
roomId: data.roomId,
- isNew: false
+ isNew: false,
}),
}, next);
},
@@ -134,7 +135,7 @@ SocketModules.chats.loadRoom = function (socket, data, callback) {
results.roomData.maximumUsersInChatRoom = parseInt(meta.config.maximumUsersInChatRoom, 10) || 0;
results.roomData.showUserInput = !results.roomData.maximumUsersInChatRoom || results.roomData.maximumUsersInChatRoom > 2;
next(null, results.roomData);
- }
+ },
], callback);
};
@@ -168,7 +169,7 @@ SocketModules.chats.addUserToRoom = function (socket, data, callback) {
async.parallel({
settings: async.apply(user.getSettings, uid),
isAdminOrGlobalMod: async.apply(user.isAdminOrGlobalMod, socket.uid),
- isFollowing: async.apply(user.isFollowing, uid, socket.uid)
+ isFollowing: async.apply(user.isFollowing, uid, socket.uid),
}, next);
},
function (results, next) {
@@ -177,7 +178,7 @@ SocketModules.chats.addUserToRoom = function (socket, data, callback) {
}
Messaging.addUsersToRoom(socket.uid, [uid], data.roomId, next);
- }
+ },
], callback);
};
@@ -195,7 +196,7 @@ SocketModules.chats.removeUserFromRoom = function (socket, data, callback) {
}
Messaging.removeUsersFromRoom(socket.uid, [uid], data.roomId, next);
- }
+ },
], callback);
};
@@ -246,14 +247,14 @@ SocketModules.chats.markRead = function (socket, roomId, callback) {
}
async.parallel({
uidsInRoom: async.apply(Messaging.getUidsInRoom, roomId, 0, -1),
- markRead: async.apply(Messaging.markRead, socket.uid, roomId)
+ markRead: async.apply(Messaging.markRead, socket.uid, roomId),
}, function (err, results) {
if (err) {
return callback(err);
}
Messaging.pushUnreadCount(socket.uid);
- server.in('uid_' + socket.uid).emit('event:chats.markedAsRead', {roomId: roomId});
+ server.in('uid_' + socket.uid).emit('event:chats.markedAsRead', { roomId: roomId });
if (results.uidsInRoom.indexOf(socket.uid.toString()) === -1) {
return callback();
@@ -282,7 +283,7 @@ SocketModules.chats.markAllRead = function (socket, data, callback) {
function (next) {
Messaging.pushUnreadCount(socket.uid);
next();
- }
+ },
], callback);
};
@@ -299,12 +300,12 @@ SocketModules.chats.renameRoom = function (socket, data, callback) {
Messaging.getUidsInRoom(data.roomId, 0, -1, next);
},
function (uids, next) {
- var eventData = {roomId: data.roomId, newName: validator.escape(String(data.newName))};
+ var eventData = { roomId: data.roomId, newName: validator.escape(String(data.newName)) };
uids.forEach(function (uid) {
server.in('uid_' + uid).emit('event:chats.roomRename', eventData);
});
next();
- }
+ },
], callback);
};
@@ -334,7 +335,7 @@ SocketModules.chats.getMessages = function (socket, data, callback) {
uid: data.uid,
roomId: data.roomId,
start: parseInt(data.start, 10) || 0,
- count: 50
+ count: 50,
};
Messaging.getMessages(params, callback);
diff --git a/src/socket.io/notifications.js b/src/socket.io/notifications.js
index cc83b0b80b..66e5135ed6 100644
--- a/src/socket.io/notifications.js
+++ b/src/socket.io/notifications.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var user = require('../user');
@@ -29,8 +29,8 @@ SocketNotifs.loadMore = function (socket, data, callback) {
user.notifications.getAll(socket.uid, start, stop, next);
},
function (notifications, next) {
- next(null, {notifications: notifications, nextStart: stop});
- }
+ next(null, { notifications: notifications, nextStart: stop });
+ },
], callback);
};
diff --git a/src/socket.io/posts.js b/src/socket.io/posts.js
index 8ded335780..b4b5ac40cd 100644
--- a/src/socket.io/posts.js
+++ b/src/socket.io/posts.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
@@ -49,7 +49,7 @@ SocketPosts.reply = function (socket, data, callback) {
user.updateOnlineUsers(socket.uid);
socketHelpers.notifyNew(socket.uid, 'newPost', result);
- }
+ },
], callback);
};
@@ -69,7 +69,7 @@ SocketPosts.getRawPost = function (socket, pid, callback) {
return next(new Error('[[error:no-post]]'));
}
next(null, postData.content);
- }
+ },
], callback);
};
@@ -135,7 +135,7 @@ SocketPosts.getReplies = function (socket, pid, callback) {
},
privileges: function (next) {
privileges.posts.get(pids, socket.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -150,7 +150,7 @@ SocketPosts.getReplies = function (socket, pid, callback) {
posts.modifyPostByPrivilege(postData, postPrivileges.isAdminOrMod);
});
next(null, postData);
- }
+ },
], callback);
};
diff --git a/src/socket.io/posts/bookmarks.js b/src/socket.io/posts/bookmarks.js
index d0bb84256c..b77ce526a1 100644
--- a/src/socket.io/posts/bookmarks.js
+++ b/src/socket.io/posts/bookmarks.js
@@ -4,7 +4,6 @@
var helpers = require('./helpers');
module.exports = function (SocketPosts) {
-
SocketPosts.bookmark = function (socket, data, callback) {
helpers.postCommand(socket, 'bookmark', 'bookmarked', '', data, callback);
};
@@ -12,5 +11,4 @@ module.exports = function (SocketPosts) {
SocketPosts.unbookmark = function (socket, data, callback) {
helpers.postCommand(socket, 'unbookmark', 'bookmarked', '', data, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/posts/edit.js b/src/socket.io/posts/edit.js
index 54650961f9..5ab6973ce1 100644
--- a/src/socket.io/posts/edit.js
+++ b/src/socket.io/posts/edit.js
@@ -3,6 +3,7 @@
var async = require('async');
var validator = require('validator');
var _ = require('underscore');
+var S = require('string');
var posts = require('../../posts');
var groups = require('../../groups');
@@ -11,13 +12,17 @@ var meta = require('../../meta');
var websockets = require('../index');
module.exports = function (SocketPosts) {
-
SocketPosts.edit = function (socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[error:not-logged-in]]'));
} else if (!data || !data.pid || !data.content) {
return callback(new Error('[[error:invalid-data]]'));
- } else if (data.title && data.title.length < parseInt(meta.config.minimumTitleLength, 10)) {
+ }
+
+ // Trim and remove HTML (latter for composers that send in HTML, like redactor)
+ var contentLen = S(data.content).stripTags().s.trim().length;
+
+ if (data.title && data.title.length < parseInt(meta.config.minimumTitleLength, 10)) {
return callback(new Error('[[error:title-too-short, ' + meta.config.minimumTitleLength + ']]'));
} else if (data.title && data.title.length > parseInt(meta.config.maximumTitleLength, 10)) {
return callback(new Error('[[error:title-too-long, ' + meta.config.maximumTitleLength + ']]'));
@@ -25,9 +30,9 @@ module.exports = function (SocketPosts) {
return callback(new Error('[[error:not-enough-tags, ' + meta.config.minimumTagsPerTopic + ']]'));
} else if (data.tags && data.tags.length > parseInt(meta.config.maximumTagsPerTopic, 10)) {
return callback(new Error('[[error:too-many-tags, ' + meta.config.maximumTagsPerTopic + ']]'));
- } else if (!data.content || data.content.length < parseInt(meta.config.minimumPostLength, 10)) {
+ } else if (contentLen < parseInt(meta.config.minimumPostLength, 10)) {
return callback(new Error('[[error:content-too-short, ' + meta.config.minimumPostLength + ']]'));
- } else if (data.content.length > parseInt(meta.config.maximumPostLength, 10)) {
+ } else if (contentLen > parseInt(meta.config.maximumPostLength, 10)) {
return callback(new Error('[[error:content-too-long, ' + meta.config.maximumPostLength + ']]'));
}
@@ -47,11 +52,11 @@ module.exports = function (SocketPosts) {
uid: socket.uid,
ip: socket.ip,
oldTitle: validator.escape(String(result.topic.oldTitle)),
- newTitle: validator.escape(String(result.topic.title))
+ newTitle: validator.escape(String(result.topic.title)),
});
}
- if (parseInt(result.post.deleted) !== 1) {
+ if (parseInt(result.post.deleted, 10) !== 1) {
websockets.in('topic_' + result.topic.tid).emit('event:post_edited', result);
return callback(null, result.post);
}
@@ -60,7 +65,7 @@ module.exports = function (SocketPosts) {
'administrators',
'Global Moderators',
'cid:' + result.topic.cid + ':privileges:mods',
- 'cid:' + result.topic.cid + ':privileges:groups:moderate'
+ 'cid:' + result.topic.cid + ':privileges:groups:moderate',
], next);
},
function (results, next) {
@@ -69,7 +74,7 @@ module.exports = function (SocketPosts) {
websockets.in('uid_' + uid).emit('event:post_edited', editResult);
});
next(null, editResult.post);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/posts/flag.js b/src/socket.io/posts/flag.js
index 077b88bfc9..dccf302c43 100644
--- a/src/socket.io/posts/flag.js
+++ b/src/socket.io/posts/flag.js
@@ -14,7 +14,6 @@ var meta = require('../../meta');
var utils = require('../../../public/src/utils');
module.exports = function (SocketPosts) {
-
SocketPosts.flag = function (socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[error:not-logged-in]]'));
@@ -48,7 +47,7 @@ module.exports = function (SocketPosts) {
},
userData: function (next) {
user.getUserFields(socket.uid, ['username', 'reputation', 'banned'], next);
- }
+ },
}, next);
},
function (user, next) {
@@ -79,7 +78,7 @@ module.exports = function (SocketPosts) {
},
moderators: function (next) {
groups.getMembers('cid:' + post.topic.cid + ':privileges:mods', 0, -1, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -94,16 +93,16 @@ module.exports = function (SocketPosts) {
nid: 'post_flag:' + data.pid + ':uid:' + socket.uid,
from: socket.uid,
mergeId: 'notifications:user_flagged_post_in|' + data.pid,
- topicTitle: post.topic.title
+ topicTitle: post.topic.title,
}, function (err, notification) {
if (err || !notification) {
return next(err);
}
- plugins.fireHook('action:post.flag', {post: post, reason: data.reason, flaggingUser: flaggingUser});
+ plugins.fireHook('action:post.flag', { post: post, reason: data.reason, flaggingUser: flaggingUser });
notifications.push(notification, results.admins.concat(results.moderators).concat(results.globalMods), next);
});
- }
+ },
], callback);
};
@@ -120,7 +119,7 @@ module.exports = function (SocketPosts) {
return next(new Error('[[no-privileges]]'));
}
posts.dismissFlag(pid, next);
- }
+ },
], callback);
};
@@ -134,7 +133,7 @@ module.exports = function (SocketPosts) {
return next(new Error('[[no-privileges]]'));
}
posts.dismissAllFlags(next);
- }
+ },
], callback);
};
@@ -149,7 +148,7 @@ module.exports = function (SocketPosts) {
function (next) {
async.parallel([
async.apply(user.isAdminOrGlobalMod, socket.uid),
- async.apply(user.isModeratorOfAnyCategory, socket.uid)
+ async.apply(user.isModeratorOfAnyCategory, socket.uid),
], function (err, results) {
next(err, results[0] || results[1]);
});
@@ -166,7 +165,7 @@ module.exports = function (SocketPosts) {
}, payload);
posts.updateFlagData(socket.uid, data.pid, payload, next);
- }
+ },
], callback);
};
};
diff --git a/src/socket.io/posts/helpers.js b/src/socket.io/posts/helpers.js
index 4c04f82afc..c7b92488d5 100644
--- a/src/socket.io/posts/helpers.js
+++ b/src/socket.io/posts/helpers.js
@@ -26,7 +26,7 @@ helpers.postCommand = function (socket, command, eventName, notification, data,
},
deleted: function (next) {
posts.getPostField(data.pid, 'deleted', next);
- }
+ },
}, next);
},
function (results, next) {
@@ -46,11 +46,11 @@ helpers.postCommand = function (socket, command, eventName, notification, data,
filter:post.bookmark
filter:post.unbookmark
*/
- plugins.fireHook('filter:post.' + command, {data: data, uid: socket.uid}, next);
+ plugins.fireHook('filter:post.' + command, { data: data, uid: socket.uid }, next);
},
function (filteredData, next) {
executeCommand(socket, command, eventName, notification, filteredData.data, next);
- }
+ },
], callback);
};
@@ -71,6 +71,6 @@ function executeCommand(socket, command, eventName, notification, data, callback
socketHelpers.rescindUpvoteNotification(data.pid, socket.uid);
}
next(null, result);
- }
+ },
], callback);
-}
\ No newline at end of file
+}
diff --git a/src/socket.io/posts/move.js b/src/socket.io/posts/move.js
index 207db2aef5..6ef596c1c2 100644
--- a/src/socket.io/posts/move.js
+++ b/src/socket.io/posts/move.js
@@ -6,7 +6,6 @@ var topics = require('../../topics');
var socketHelpers = require('../helpers');
module.exports = function (SocketPosts) {
-
SocketPosts.movePost = function (socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[error:not-logged-in]]'));
@@ -30,8 +29,7 @@ module.exports = function (SocketPosts) {
function (next) {
socketHelpers.sendNotificationToPostOwner(data.pid, socket.uid, 'move', 'notifications:moved_your_post');
next();
- }
+ },
], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/posts/tools.js b/src/socket.io/posts/tools.js
index 571d84175b..ee393a42b9 100644
--- a/src/socket.io/posts/tools.js
+++ b/src/socket.io/posts/tools.js
@@ -13,7 +13,6 @@ var plugins = require('../../plugins');
var social = require('../../social');
module.exports = function (SocketPosts) {
-
SocketPosts.loadPostTools = function (socket, data, callback) {
if (!data || !data.pid || !data.cid) {
return callback(new Error('[[error:invalid-data]]'));
@@ -37,11 +36,11 @@ module.exports = function (SocketPosts) {
posts.hasBookmarked(data.pid, socket.uid, next);
},
tools: function (next) {
- plugins.fireHook('filter:post.tools', {pid: data.pid, uid: socket.uid, tools: []}, next);
+ plugins.fireHook('filter:post.tools', { pid: data.pid, uid: socket.uid, tools: [] }, next);
},
postSharing: function (next) {
social.getActivePostSharing(next);
- }
+ },
}, next);
},
function (results, next) {
@@ -54,7 +53,7 @@ module.exports = function (SocketPosts) {
results.posts.display_moderator_tools = results.posts.display_edit_tools || results.posts.display_delete_tools;
results.posts.display_move_tools = results.isAdminOrMod;
next(null, results);
- }
+ },
], callback);
};
@@ -85,11 +84,11 @@ module.exports = function (SocketPosts) {
type: 'post-delete',
uid: socket.uid,
pid: data.pid,
- ip: socket.ip
+ ip: socket.ip,
});
next();
- }
+ },
], callback);
};
@@ -103,18 +102,17 @@ module.exports = function (SocketPosts) {
posts.tools.restore(socket.uid, data.pid, next);
},
function (postData, next) {
-
websockets.in('topic_' + data.tid).emit('event:post_restored', postData);
events.log({
type: 'post-restore',
uid: socket.uid,
pid: data.pid,
- ip: socket.ip
+ ip: socket.ip,
});
setImmediate(next);
- }
+ },
], callback);
};
@@ -123,7 +121,7 @@ module.exports = function (SocketPosts) {
return callback(new Error('[[error:invalid-data]]'));
}
async.eachSeries(data.pids, function (pid, next) {
- SocketPosts.delete(socket, {pid: pid, tid: data.tid}, next);
+ SocketPosts.delete(socket, { pid: pid, tid: data.tid }, next);
}, callback);
};
@@ -132,7 +130,7 @@ module.exports = function (SocketPosts) {
return callback(new Error('[[error:invalid-data]]'));
}
async.eachSeries(data.pids, function (pid, next) {
- SocketPosts.purge(socket, {pid: pid, tid: data.tid}, next);
+ SocketPosts.purge(socket, { pid: pid, tid: data.tid }, next);
}, callback);
};
@@ -158,7 +156,7 @@ module.exports = function (SocketPosts) {
posts.getPostField(data.pid, 'toPid', next);
},
function (toPid, next) {
- postData = {pid: data.pid, toPid: toPid};
+ postData = { pid: data.pid, toPid: toPid };
posts.tools.purge(socket.uid, data.pid, next);
},
function (next) {
@@ -171,9 +169,9 @@ module.exports = function (SocketPosts) {
uid: socket.uid,
pid: data.pid,
ip: socket.ip,
- title: validator.escape(String(title))
+ title: validator.escape(String(title)),
}, next);
- }
+ },
], callback);
};
@@ -183,8 +181,8 @@ module.exports = function (SocketPosts) {
posts.getTopicFields(pid, ['tid', 'cid'], next);
},
function (topic, next) {
- socketTopics.doTopicAction('delete', 'event:topic_deleted', socket, {tids: [topic.tid], cid: topic.cid}, next);
- }
+ socketTopics.doTopicAction('delete', 'event:topic_deleted', socket, { tids: [topic.tid], cid: topic.cid }, next);
+ },
], callback);
}
@@ -197,8 +195,7 @@ module.exports = function (SocketPosts) {
posts.getTopicFields(pid, ['postcount'], function (err, topic) {
next(err, topic ? parseInt(topic.postcount, 10) === 1 : false);
});
- }
+ },
}, callback);
}
-
};
diff --git a/src/socket.io/posts/votes.js b/src/socket.io/posts/votes.js
index e3a9510aaa..0c12fe262d 100644
--- a/src/socket.io/posts/votes.js
+++ b/src/socket.io/posts/votes.js
@@ -9,7 +9,6 @@ var privileges = require('../../privileges');
var helpers = require('./helpers');
module.exports = function (SocketPosts) {
-
SocketPosts.getVoters = function (socket, data, callback) {
if (!data || !data.pid || !data.cid) {
return callback(new Error('[[error:invalid-data]]'));
@@ -30,7 +29,7 @@ module.exports = function (SocketPosts) {
},
downvoteUids: function (next) {
db.getSetMembers('pid:' + data.pid + ':downvote', next);
- }
+ },
}, next);
},
function (results, next) {
@@ -46,9 +45,9 @@ module.exports = function (SocketPosts) {
},
downvoteCount: function (next) {
next(null, results.downvoteUids.length);
- }
+ },
}, next);
- }
+ },
], callback);
};
@@ -62,7 +61,7 @@ module.exports = function (SocketPosts) {
return callback(err, []);
}
- async.map(data, function (uids, next) {
+ async.map(data, function (uids, next) {
var otherCount = 0;
if (uids.length > 6) {
otherCount = uids.length - 5;
@@ -71,7 +70,7 @@ module.exports = function (SocketPosts) {
user.getUsernamesByUids(uids, function (err, usernames) {
next(err, {
otherCount: otherCount,
- usernames: usernames
+ usernames: usernames,
});
});
}, callback);
@@ -89,4 +88,4 @@ module.exports = function (SocketPosts) {
SocketPosts.unvote = function (socket, data, callback) {
helpers.postCommand(socket, 'unvote', 'voted', '', data, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/topics.js b/src/socket.io/topics.js
index 2fdecf550f..3b8a69d0f4 100644
--- a/src/socket.io/topics.js
+++ b/src/socket.io/topics.js
@@ -1,4 +1,3 @@
-
'use strict';
var async = require('async');
@@ -9,7 +8,7 @@ var user = require('../user');
var apiController = require('../controllers/api');
var socketHelpers = require('./helpers');
-var SocketTopics = {};
+var SocketTopics = module.exports;
require('./topics/unread')(SocketTopics);
require('./topics/move')(SocketTopics);
@@ -26,18 +25,19 @@ SocketTopics.post = function (socket, data, callback) {
data.req = websockets.reqFromSocket(socket);
data.timestamp = Date.now();
- topics.post(data, function (err, result) {
- if (err) {
- return callback(err);
- }
+ async.waterfall([
+ function (next) {
+ topics.post(data, next);
+ },
+ function (result, next) {
+ next(null, result.topicData);
- callback(null, result.topicData);
+ socket.emit('event:new_post', { posts: [result.postData] });
+ socket.emit('event:new_topic', result.topicData);
- socket.emit('event:new_post', {posts: [result.postData]});
- socket.emit('event:new_topic', result.topicData);
-
- socketHelpers.notifyNew(socket.uid, 'newTopic', {posts: [result.postData], topic: result.topicData});
- });
+ socketHelpers.notifyNew(socket.uid, 'newTopic', { posts: [result.postData], topic: result.topicData });
+ },
+ ], callback);
};
SocketTopics.postcount = function (socket, tid, callback) {
@@ -64,7 +64,7 @@ SocketTopics.createTopicFromPosts = function (socket, data, callback) {
};
SocketTopics.changeWatching = function (socket, data, callback) {
- if (!data.tid || !data.type) {
+ if (!data || !data.tid || !data.type) {
return callback(new Error('[[error:invalid-data]]'));
}
var commands = ['follow', 'unfollow', 'ignore'];
@@ -93,20 +93,23 @@ SocketTopics.isFollowed = function (socket, tid, callback) {
};
SocketTopics.search = function (socket, data, callback) {
+ if (!data) {
+ return callback(new Error('[[error:invalid-data]]'));
+ }
topics.search(data.tid, data.term, callback);
};
SocketTopics.isModerator = function (socket, tid, callback) {
- topics.getTopicField(tid, 'cid', function (err, cid) {
- if (err) {
- return callback(err);
- }
- user.isModerator(socket.uid, cid, callback);
- });
+ async.waterfall([
+ function (next) {
+ topics.getTopicField(tid, 'cid', next);
+ },
+ function (cid, next) {
+ user.isModerator(socket.uid, cid, next);
+ },
+ ], callback);
};
SocketTopics.getTopic = function (socket, tid, callback) {
apiController.getTopicData(tid, socket.uid, callback);
};
-
-module.exports = SocketTopics;
diff --git a/src/socket.io/topics/infinitescroll.js b/src/socket.io/topics/infinitescroll.js
index a68d220609..b0d7407a0a 100644
--- a/src/socket.io/topics/infinitescroll.js
+++ b/src/socket.io/topics/infinitescroll.js
@@ -9,9 +9,8 @@ var utils = require('../../../public/src/utils');
var social = require('../../social');
module.exports = function (SocketTopics) {
-
SocketTopics.loadMore = function (socket, data, callback) {
- if (!data || !data.tid || !utils.isNumber(data.after) || parseInt(data.after, 10) < 0) {
+ if (!data || !data.tid || !utils.isNumber(data.after) || parseInt(data.after, 10) < 0) {
return callback(new Error('[[error:invalid-data]]'));
}
var userPrivileges;
@@ -24,7 +23,7 @@ module.exports = function (SocketTopics) {
},
topic: function (next) {
topics.getTopicFields(data.tid, ['postcount', 'deleted'], next);
- }
+ },
}, next);
},
function (results, next) {
@@ -47,12 +46,10 @@ module.exports = function (SocketTopics) {
if (reverse) {
start = results.topic.postcount - start;
}
+ } else if (reverse) {
+ start = results.topic.postcount - start - infScrollPostsPerPage - 1;
} else {
- if (reverse) {
- start = results.topic.postcount - start - infScrollPostsPerPage - 1;
- } else {
- start = start - infScrollPostsPerPage - 1;
- }
+ start = start - infScrollPostsPerPage - 1;
}
var stop = start + (infScrollPostsPerPage - 1);
@@ -72,7 +69,7 @@ module.exports = function (SocketTopics) {
},
postSharing: function (next) {
social.getActivePostSharing(next);
- }
+ },
}, next);
},
function (topicData, next) {
@@ -86,7 +83,7 @@ module.exports = function (SocketTopics) {
topics.modifyPostsByPrivilege(topicData, userPrivileges);
next(null, topicData);
- }
+ },
], callback);
};
@@ -122,5 +119,4 @@ module.exports = function (SocketTopics) {
topics.getTopicsFromSet(data.set, socket.uid, start, stop, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/topics/move.js b/src/socket.io/topics/move.js
index 938fe22792..9faffa910b 100644
--- a/src/socket.io/topics/move.js
+++ b/src/socket.io/topics/move.js
@@ -7,7 +7,6 @@ var privileges = require('../../privileges');
var socketHelpers = require('../helpers');
module.exports = function (SocketTopics) {
-
SocketTopics.move = function (socket, data, callback) {
if (!data || !Array.isArray(data.tids) || !data.cid) {
return callback(new Error('[[error:invalid-data]]'));
@@ -30,7 +29,7 @@ module.exports = function (SocketTopics) {
topicData = _topicData;
topicData.tid = tid;
topics.tools.move(tid, data.cid, socket.uid, next);
- }
+ },
], function (err) {
if (err) {
return next(err);
@@ -66,7 +65,7 @@ module.exports = function (SocketTopics) {
async.eachLimit(tids, 50, function (tid, next) {
topics.tools.move(tid, data.cid, socket.uid, next);
}, next);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/topics/tags.js b/src/socket.io/topics/tags.js
index 8829229ca8..0b7076fa20 100644
--- a/src/socket.io/topics/tags.js
+++ b/src/socket.io/topics/tags.js
@@ -6,7 +6,6 @@ var topics = require('../../topics');
var utils = require('../../../public/src/utils');
module.exports = function (SocketTopics) {
-
SocketTopics.isTagAllowed = function (socket, data, callback) {
if (!data || !data.cid || !data.tag) {
return callback(new Error('[[error:invalid-data]]'));
@@ -20,7 +19,7 @@ module.exports = function (SocketTopics) {
return next(null, true);
}
next(null, tagWhitelist.indexOf(data.tag) !== -1);
- }
+ },
], callback);
};
@@ -49,8 +48,8 @@ module.exports = function (SocketTopics) {
},
function (tags, next) {
tags = tags.filter(Boolean);
- next(null, {tags: tags, nextStart: stop + 1});
- }
+ next(null, { tags: tags, nextStart: stop + 1 });
+ },
], callback);
};
};
diff --git a/src/socket.io/topics/tools.js b/src/socket.io/topics/tools.js
index ede87d2599..74cdb68e7e 100644
--- a/src/socket.io/topics/tools.js
+++ b/src/socket.io/topics/tools.js
@@ -10,7 +10,6 @@ var plugins = require('../../plugins');
var socketHelpers = require('../helpers');
module.exports = function (SocketTopics) {
-
SocketTopics.loadTopicTools = function (socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]'));
@@ -27,13 +26,13 @@ module.exports = function (SocketTopics) {
},
privileges: function (next) {
privileges.topics.get(data.tid, socket.uid, next);
- }
+ },
}, next);
},
function (results, next) {
topic = results.topic;
topic.privileges = results.privileges;
- plugins.fireHook('filter:topic.thread_tools', {topic: results.topic, uid: socket.uid, tools: []}, next);
+ plugins.fireHook('filter:topic.thread_tools', { topic: results.topic, uid: socket.uid, tools: [] }, next);
},
function (data, next) {
topic.deleted = parseInt(topic.deleted, 10) === 1;
@@ -41,7 +40,7 @@ module.exports = function (SocketTopics) {
topic.pinned = parseInt(topic.pinned, 10) === 1;
topic.thread_tools = data.tools;
next(null, topic);
- }
+ },
], callback);
};
@@ -95,7 +94,7 @@ module.exports = function (SocketTopics) {
function (data, next) {
socketHelpers.emitToTopicAndCategory(event, data);
logTopicAction(action, socket, tid, next);
- }
+ },
], next);
}, callback);
};
@@ -115,9 +114,9 @@ module.exports = function (SocketTopics) {
uid: socket.uid,
ip: socket.ip,
tid: tid,
- title: validator.escape(String(title))
+ title: validator.escape(String(title)),
}, next);
- }
+ },
], callback);
}
@@ -128,5 +127,4 @@ module.exports = function (SocketTopics) {
topics.tools.orderPinnedTopics(socket.uid, data, callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/topics/unread.js b/src/socket.io/topics/unread.js
index 39c6485a26..8fa5651e32 100644
--- a/src/socket.io/topics/unread.js
+++ b/src/socket.io/topics/unread.js
@@ -6,7 +6,6 @@ var user = require('../../user');
var topics = require('../../topics');
module.exports = function (SocketTopics) {
-
SocketTopics.markAsRead = function (socket, tids, callback) {
if (!Array.isArray(tids) || !socket.uid) {
return callback(new Error('[[error:invalid-data]]'));
@@ -22,7 +21,7 @@ module.exports = function (SocketTopics) {
topics.markTopicNotificationsRead(tids, socket.uid);
}
next();
- }
+ },
], callback);
};
@@ -44,7 +43,7 @@ module.exports = function (SocketTopics) {
function (next) {
topics.pushUnreadCount(socket.uid);
next();
- }
+ },
], callback);
};
@@ -55,7 +54,7 @@ module.exports = function (SocketTopics) {
},
function (tids, next) {
SocketTopics.markAsRead(socket, tids, next);
- }
+ },
], callback);
};
@@ -70,7 +69,7 @@ module.exports = function (SocketTopics) {
function (next) {
topics.pushUnreadCount(socket.uid);
next();
- }
+ },
], callback);
};
@@ -110,14 +109,14 @@ module.exports = function (SocketTopics) {
},
function (next) {
topics.updateRecent(tid, Date.now(), next);
- }
+ },
], next);
}, next);
},
function (next) {
topics.pushUnreadCount(socket.uid);
next();
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/user.js b/src/socket.io/user.js
index 060c9e7b2e..78f696a19b 100644
--- a/src/socket.io/user.js
+++ b/src/socket.io/user.js
@@ -12,7 +12,7 @@ var meta = require('../meta');
var events = require('../events');
var emailer = require('../emailer');
var db = require('../database');
-var apiController = require('../controllers/api');
+var userController = require('../controllers/user');
var privileges = require('../privileges');
var SocketUser = {};
@@ -46,16 +46,16 @@ SocketUser.deleteAccount = function (socket, data, callback) {
user.deleteAccount(socket.uid, next);
},
function (next) {
- require('./index').server.sockets.emit('event:user_status_change', {uid: socket.uid, status: 'offline'});
+ require('./index').server.sockets.emit('event:user_status_change', { uid: socket.uid, status: 'offline' });
events.log({
type: 'user-delete',
uid: socket.uid,
targetUid: socket.uid,
- ip: socket.ip
+ ip: socket.ip,
});
next();
- }
+ },
], callback);
};
@@ -85,7 +85,7 @@ SocketUser.emailConfirm = function (socket, data, callback) {
}
user.email.sendValidationEmail(socket.uid, email, next);
- }
+ },
], callback);
};
@@ -120,7 +120,7 @@ SocketUser.reset.commit = function (socket, data, callback) {
function (next) {
async.parallel({
uid: async.apply(db.getObjectField, 'reset:uid', data.code),
- reset: async.apply(user.reset.commit, data.code, data.password)
+ reset: async.apply(user.reset.commit, data.code, data.password),
}, next);
},
function (results, next) {
@@ -128,7 +128,7 @@ SocketUser.reset.commit = function (socket, data, callback) {
events.log({
type: 'password-reset',
uid: uid,
- ip: socket.ip
+ ip: socket.ip,
});
user.getUserField(uid, 'username', next);
@@ -140,11 +140,11 @@ SocketUser.reset.commit = function (socket, data, callback) {
username: username,
date: parsedDate,
site_title: meta.config.title || 'NodeBB',
- subject: '[[email:reset.notify.subject]]'
+ subject: '[[email:reset.notify.subject]]',
});
next();
- }
+ },
], callback);
};
@@ -175,7 +175,7 @@ SocketUser.follow = function (socket, data, callback) {
nid: 'follow:' + data.uid + ':uid:' + socket.uid,
from: socket.uid,
path: '/uid/' + data.uid + '/followers',
- mergeId: 'notifications:user_started_following_you'
+ mergeId: 'notifications:user_started_following_you',
}, next);
},
function (notification, next) {
@@ -184,7 +184,7 @@ SocketUser.follow = function (socket, data, callback) {
}
notification.user = userData;
notifications.push(notification, [data.uid], next);
- }
+ },
], callback);
};
@@ -203,7 +203,7 @@ function toggleFollow(method, uid, theiruid, callback) {
plugins.fireHook('action:user.' + method, {
fromUid: uid,
- toUid: theiruid
+ toUid: theiruid,
});
callback();
});
@@ -223,7 +223,7 @@ SocketUser.saveSettings = function (socket, data, callback) {
return next(new Error('[[error:no-privileges]]'));
}
user.saveSettings(data.uid, data.settings, next);
- }
+ },
], callback);
};
@@ -257,7 +257,7 @@ SocketUser.getUnreadCounts = function (socket, data, callback) {
unreadTopicCount: async.apply(topics.getTotalUnread, socket.uid),
unreadNewTopicCount: async.apply(topics.getTotalUnread, socket.uid, 'new'),
unreadChatCount: async.apply(messaging.getUnreadCount, socket.uid),
- unreadNotificationCount: async.apply(user.notifications.getUnreadCount, socket.uid)
+ unreadNotificationCount: async.apply(user.notifications.getUnreadCount, socket.uid),
}, callback);
};
@@ -296,22 +296,22 @@ SocketUser.invite = function (socket, email, callback) {
}
user.sendInvitationEmail(socket.uid, email, next);
- }
+ },
], next);
- }
+ },
], callback);
};
SocketUser.getUserByUID = function (socket, uid, callback) {
- apiController.getUserDataByField(socket.uid, 'uid', uid, callback);
+ userController.getUserDataByField(socket.uid, 'uid', uid, callback);
};
SocketUser.getUserByUsername = function (socket, username, callback) {
- apiController.getUserDataByField(socket.uid, 'username', username, callback);
+ userController.getUserDataByField(socket.uid, 'username', username, callback);
};
SocketUser.getUserByEmail = function (socket, email, callback) {
- apiController.getUserDataByField(socket.uid, 'email', email, callback);
+ userController.getUserDataByField(socket.uid, 'email', email, callback);
};
SocketUser.setModerationNote = function (socket, data, callback) {
@@ -339,7 +339,7 @@ SocketUser.setModerationNote = function (socket, data, callback) {
} else {
db.deleteObjectField('user:' + data.uid, 'moderationNote', next);
}
- }
+ },
], callback);
};
diff --git a/src/socket.io/user/ban.js b/src/socket.io/user/ban.js
index 089720c59e..54ce94fd24 100644
--- a/src/socket.io/user/ban.js
+++ b/src/socket.io/user/ban.js
@@ -8,7 +8,6 @@ var events = require('../../events');
var plugins = require('../../plugins');
module.exports = function (SocketUser) {
-
SocketUser.banUsers = function (socket, data, callback) {
if (!data || !Array.isArray(data.uids)) {
return callback(new Error('[[error:invalid-data]]'));
@@ -24,7 +23,7 @@ module.exports = function (SocketUser) {
type: 'user-ban',
uid: socket.uid,
targetUid: uid,
- ip: socket.ip
+ ip: socket.ip,
}, next);
},
function (next) {
@@ -32,10 +31,10 @@ module.exports = function (SocketUser) {
callerUid: socket.uid,
ip: socket.ip,
uid: uid,
- until: data.until > 0 ? data.until : undefined
+ until: data.until > 0 ? data.until : undefined,
});
next();
- }
+ },
], next);
}, callback);
};
@@ -51,17 +50,17 @@ module.exports = function (SocketUser) {
type: 'user-unban',
uid: socket.uid,
targetUid: uid,
- ip: socket.ip
+ ip: socket.ip,
}, next);
},
function (next) {
plugins.fireHook('action:user.unbanned', {
callerUid: socket.uid,
ip: socket.ip,
- uid: uid
+ uid: uid,
});
next();
- }
+ },
], next);
}, callback);
};
@@ -80,7 +79,7 @@ module.exports = function (SocketUser) {
return next(new Error('[[error:no-privileges]]'));
}
async.each(uids, method, next);
- }
+ },
], callback);
}
@@ -98,7 +97,7 @@ module.exports = function (SocketUser) {
function (next) {
websockets.in('uid_' + uid).emit('event:banned');
next();
- }
+ },
], callback);
}
};
diff --git a/src/socket.io/user/picture.js b/src/socket.io/user/picture.js
index deceb70f8a..109b2635e1 100644
--- a/src/socket.io/user/picture.js
+++ b/src/socket.io/user/picture.js
@@ -9,7 +9,6 @@ var user = require('../../user');
var plugins = require('../../plugins');
module.exports = function (SocketUser) {
-
SocketUser.changePicture = function (socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[error:invalid-uid]]'));
@@ -26,31 +25,31 @@ module.exports = function (SocketUser) {
user.isAdminOrGlobalModOrSelf(socket.uid, data.uid, next);
},
function (next) {
- switch(type) {
- case 'default':
- next(null, '');
- break;
- case 'uploaded':
- user.getUserField(data.uid, 'uploadedpicture', next);
- break;
- default:
- plugins.fireHook('filter:user.getPicture', {
- uid: socket.uid,
- type: type,
- picture: undefined
- }, function (err, returnData) {
- if (err) {
- return next(err);
- }
+ switch (type) {
+ case 'default':
+ next(null, '');
+ break;
+ case 'uploaded':
+ user.getUserField(data.uid, 'uploadedpicture', next);
+ break;
+ default:
+ plugins.fireHook('filter:user.getPicture', {
+ uid: socket.uid,
+ type: type,
+ picture: undefined,
+ }, function (err, returnData) {
+ if (err) {
+ return next(err);
+ }
- next(null, returnData.picture || '');
- });
- break;
+ next(null, returnData.picture || '');
+ });
+ break;
}
},
function (picture, next) {
user.setUserField(data.uid, 'picture', picture, next);
- }
+ },
], callback);
};
@@ -67,7 +66,7 @@ module.exports = function (SocketUser) {
},
function (uploadedImage, next) {
next(null, uploadedImage ? uploadedImage.url : null);
- }
+ },
], callback);
};
@@ -97,9 +96,9 @@ module.exports = function (SocketUser) {
user.setUserFields(data.uid, {
uploadedpicture: '',
- picture: userData.uploadedpicture === userData.picture ? '' : userData.picture // if current picture is uploaded picture, reset to user icon
+ picture: userData.uploadedpicture === userData.picture ? '' : userData.picture, // if current picture is uploaded picture, reset to user icon
}, next);
- }
+ },
], callback);
};
@@ -111,9 +110,9 @@ module.exports = function (SocketUser) {
async.parallel({
list: async.apply(plugins.fireHook, 'filter:user.listPictures', {
uid: data.uid,
- pictures: []
+ pictures: [],
}),
- uploaded: async.apply(user.getUserField, data.uid, 'uploadedpicture')
+ uploaded: async.apply(user.getUserField, data.uid, 'uploadedpicture'),
}, function (err, data) {
if (err) {
return callback(err);
@@ -123,11 +122,11 @@ module.exports = function (SocketUser) {
data.list.pictures.push({
type: 'uploaded',
url: data.uploaded,
- text: '[[user:uploaded_picture]]'
+ text: '[[user:uploaded_picture]]',
});
}
callback(null, data.list.pictures);
});
};
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/user/profile.js b/src/socket.io/user/profile.js
index 392c7559b7..8e88edb1e5 100644
--- a/src/socket.io/user/profile.js
+++ b/src/socket.io/user/profile.js
@@ -8,7 +8,6 @@ var events = require('../../events');
var privileges = require('../../privileges');
module.exports = function (SocketUser) {
-
SocketUser.changeUsernameEmail = function (socket, data, callback) {
if (!data || !data.uid || !socket.uid) {
return callback(new Error('[[error:invalid-data]]'));
@@ -20,7 +19,7 @@ module.exports = function (SocketUser) {
},
function (next) {
SocketUser.updateProfile(socket, data, next);
- }
+ },
], callback);
};
@@ -34,10 +33,10 @@ module.exports = function (SocketUser) {
},
function (next) {
user.updateCoverPicture(data, next);
- }
+ },
], callback);
};
-
+
SocketUser.uploadCroppedPicture = function (socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]'));
@@ -48,7 +47,7 @@ module.exports = function (SocketUser) {
},
function (next) {
user.uploadCroppedPicture(data, next);
- }
+ },
], callback);
};
@@ -63,7 +62,7 @@ module.exports = function (SocketUser) {
},
function (next) {
user.removeCoverPicture(data, next);
- }
+ },
], callback);
};
@@ -77,7 +76,7 @@ module.exports = function (SocketUser) {
} else {
next(null, false);
}
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -114,7 +113,7 @@ module.exports = function (SocketUser) {
type: 'password-change',
uid: socket.uid,
targetUid: data.uid,
- ip: socket.ip
+ ip: socket.ip,
});
callback();
});
@@ -146,7 +145,7 @@ module.exports = function (SocketUser) {
},
canEdit: function (next) {
privileges.users.canEdit(socket.uid, data.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -175,17 +174,15 @@ module.exports = function (SocketUser) {
}
if (userData.email !== oldUserData.email) {
- log('email-change', {oldEmail: oldUserData.email, newEmail: userData.email});
+ log('email-change', { oldEmail: oldUserData.email, newEmail: userData.email });
}
if (userData.username !== oldUserData.username) {
- log('username-change', {oldUsername: oldUserData.username, newUsername: userData.username});
+ log('username-change', { oldUsername: oldUserData.username, newUsername: userData.username });
}
next(null, userData);
- }
+ },
], callback);
};
-
-
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/user/search.js b/src/socket.io/user/search.js
index 9c3774089d..7d51ead4cf 100644
--- a/src/socket.io/user/search.js
+++ b/src/socket.io/user/search.js
@@ -5,7 +5,6 @@ var meta = require('../../meta');
var pagination = require('../../pagination');
module.exports = function (SocketUser) {
-
SocketUser.search = function (socket, data, callback) {
if (!data) {
return callback(new Error('[[error:invalid-data]]'));
@@ -21,7 +20,7 @@ module.exports = function (SocketUser) {
onlineOnly: data.onlineOnly,
bannedOnly: data.bannedOnly,
flaggedOnly: data.flaggedOnly,
- uid: socket.uid
+ uid: socket.uid,
}, function (err, result) {
if (err) {
return callback(err);
@@ -31,5 +30,4 @@ module.exports = function (SocketUser) {
callback(null, result);
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/socket.io/user/status.js b/src/socket.io/user/status.js
index b3530ffc7d..8849f0210e 100644
--- a/src/socket.io/user/status.js
+++ b/src/socket.io/user/status.js
@@ -6,7 +6,6 @@ var user = require('../../user');
var websockets = require('../index');
module.exports = function (SocketUser) {
-
SocketUser.checkStatus = function (socket, uid, callback) {
if (!socket.uid) {
return callback(new Error('[[error:invalid-uid]]'));
@@ -17,7 +16,7 @@ module.exports = function (SocketUser) {
},
function (userData, next) {
next(null, user.getStatus(userData));
- }
+ },
], callback);
};
@@ -31,7 +30,7 @@ module.exports = function (SocketUser) {
return callback(new Error('[[error:invalid-user-status]]'));
}
- var data = {status: status};
+ var data = { status: status };
if (status !== 'offline') {
data.lastonline = Date.now();
}
@@ -43,11 +42,11 @@ module.exports = function (SocketUser) {
function (next) {
var data = {
uid: socket.uid,
- status: status
+ status: status,
};
websockets.server.emit('event:user_status_change', data);
next(null, data);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/start.js b/src/start.js
index 06ffc93589..87c0d2bf70 100644
--- a/src/start.js
+++ b/src/start.js
@@ -35,7 +35,7 @@ start.start = function () {
},
function (next) {
require('./upgrade').check(next);
- }
+ },
], function (err) {
next(err);
});
@@ -53,25 +53,25 @@ start.start = function () {
}
webserver.listen(next);
- }
+ },
], function (err) {
if (err) {
- switch(err.message) {
- case 'schema-out-of-date':
- winston.warn('Your NodeBB schema is out-of-date. Please run the following command to bring your dataset up to spec:');
- winston.warn(' ./nodebb upgrade');
- break;
- case 'dependencies-out-of-date':
- winston.warn('One or more of NodeBB\'s dependent packages are out-of-date. Please run the following command to update them:');
- winston.warn(' ./nodebb upgrade');
- break;
- case 'dependencies-missing':
- winston.warn('One or more of NodeBB\'s dependent packages are missing. Please run the following command to update them:');
- winston.warn(' ./nodebb upgrade');
- break;
- default:
- winston.error(err);
- break;
+ switch (err.message) {
+ case 'schema-out-of-date':
+ winston.warn('Your NodeBB schema is out-of-date. Please run the following command to bring your dataset up to spec:');
+ winston.warn(' ./nodebb upgrade');
+ break;
+ case 'dependencies-out-of-date':
+ winston.warn('One or more of NodeBB\'s dependent packages are out-of-date. Please run the following command to update them:');
+ winston.warn(' ./nodebb upgrade');
+ break;
+ case 'dependencies-missing':
+ winston.warn('One or more of NodeBB\'s dependent packages are missing. Please run the following command to update them:');
+ winston.warn(' ./nodebb upgrade');
+ break;
+ default:
+ winston.error(err);
+ break;
}
// Either way, bad stuff happened. Abort start.
@@ -80,7 +80,7 @@ start.start = function () {
if (process.send) {
process.send({
- action: 'listening'
+ action: 'listening',
});
}
});
@@ -126,8 +126,8 @@ function addProcessHandlers() {
var meta = require('./meta');
switch (message.action) {
- case 'reload':
- meta.reload();
+ case 'reload':
+ meta.reload();
break;
}
});
@@ -144,7 +144,7 @@ function restart() {
if (process.send) {
winston.info('[app] Restarting...');
process.send({
- action: 'restart'
+ action: 'restart',
});
} else {
winston.error('[app] Could not restart server. Shutting down.');
diff --git a/src/topics.js b/src/topics.js
index 75aeb46564..164200016d 100644
--- a/src/topics.js
+++ b/src/topics.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var _ = require('underscore');
@@ -13,7 +13,6 @@ var privileges = require('./privileges');
var social = require('./social');
(function (Topics) {
-
require('./topics/data')(Topics);
require('./topics/create')(Topics);
require('./topics/delete')(Topics);
@@ -50,7 +49,7 @@ var social = require('./social');
},
function (settings, next) {
next(null, Math.ceil((parseInt(postCount, 10) - 1) / settings.postsPerPage));
- }
+ },
], callback);
};
@@ -68,8 +67,8 @@ var social = require('./social');
Topics.getTopics(tids, uid, next);
},
function (topics, next) {
- next(null, {topics: topics, nextStart: stop + 1});
- }
+ next(null, { topics: topics, nextStart: stop + 1 });
+ },
], callback);
};
@@ -80,7 +79,7 @@ var social = require('./social');
},
function (tids, next) {
Topics.getTopicsByTids(tids, uid, next);
- }
+ },
], callback);
};
@@ -89,7 +88,9 @@ var social = require('./social');
return callback(null, []);
}
- var uids, cids, topics;
+ var uids;
+ var cids;
+ var topics;
async.waterfall([
function (next) {
@@ -129,14 +130,14 @@ var social = require('./social');
},
tags: function (next) {
Topics.getTopicsTagsObjects(tids, next);
- }
+ },
}, next);
},
function (results, next) {
var users = _.object(uids, results.users);
var categories = _.object(cids, results.categories);
- for (var i = 0; i < topics.length; ++i) {
+ for (var i = 0; i < topics.length; i += 1) {
if (topics[i]) {
topics[i].category = categories[topics[i].cid];
topics[i].user = users[topics[i].uid];
@@ -160,11 +161,11 @@ var social = require('./social');
return topic && topic.category && !topic.category.disabled;
});
- plugins.fireHook('filter:topics.get', {topics: topics, uid: uid}, next);
+ plugins.fireHook('filter:topics.get', { topics: topics, uid: uid }, next);
},
function (data, next) {
next(null, data.topics);
- }
+ },
], callback);
};
@@ -174,11 +175,12 @@ var social = require('./social');
async.parallel({
posts: async.apply(getMainPostAndReplies, topicData, set, uid, start, stop, reverse),
category: async.apply(Topics.getCategoryData, topicData.tid),
- threadTools: async.apply(plugins.fireHook, 'filter:topic.thread_tools', {topic: topicData, uid: uid, tools: []}),
+ threadTools: async.apply(plugins.fireHook, 'filter:topic.thread_tools', { topic: topicData, uid: uid, tools: [] }),
isFollowing: async.apply(Topics.isFollowing, [topicData.tid], uid),
isIgnoring: async.apply(Topics.isIgnoring, [topicData.tid], uid),
bookmark: async.apply(Topics.getUserBookmark, topicData.tid, uid),
postSharing: async.apply(social.getActivePostSharing),
+ deleter: async.apply(getDeleter, topicData),
related: function (next) {
async.waterfall([
function (next) {
@@ -187,9 +189,9 @@ var social = require('./social');
function (tags, next) {
topicData.tags = tags;
Topics.getRelatedTopics(topicData, uid, next);
- }
+ },
], next);
- }
+ },
}, next);
},
function (results, next) {
@@ -201,6 +203,8 @@ var social = require('./social');
topicData.isIgnoring = results.isIgnoring[0];
topicData.bookmark = results.bookmark;
topicData.postSharing = results.postSharing;
+ topicData.deleter = results.deleter;
+ topicData.deletedTimestampISO = utils.toISOString(topicData.deletedTimestamp);
topicData.related = results.related || [];
topicData.unreplied = parseInt(topicData.postcount, 10) === 1;
@@ -210,11 +214,11 @@ var social = require('./social');
topicData.icons = [];
- plugins.fireHook('filter:topic.get', {topic: topicData, uid: uid}, next);
+ plugins.fireHook('filter:topic.get', { topic: topicData, uid: uid }, next);
},
function (data, next) {
next(null, data.topic);
- }
+ },
], callback);
};
@@ -222,9 +226,9 @@ var social = require('./social');
async.waterfall([
function (next) {
if (stop > 0) {
- stop--;
+ stop -= 1;
if (start > 0) {
- start --;
+ start -= 1;
}
}
@@ -253,10 +257,17 @@ var social = require('./social');
Topics.calculatePostIndices(replies, start, stop, topic.postcount, reverse);
Topics.addPostData(posts, uid, next);
- }
+ },
], callback);
}
+ function getDeleter(topicData, callback) {
+ if (!topicData.deleterUid) {
+ return setImmediate(callback, null, null);
+ }
+ user.getUserFields(topicData.deleterUid, ['username', 'userslug', 'picture'], callback);
+ }
+
Topics.getMainPost = function (tid, uid, callback) {
Topics.getMainPosts([tid], uid, function (err, mainPosts) {
callback(err, Array.isArray(mainPosts) && mainPosts.length ? mainPosts[0] : null);
@@ -313,11 +324,10 @@ var social = require('./social');
if (plugins.hasListeners('filter:topic.search')) {
plugins.fireHook('filter:topic.search', {
tid: tid,
- term: term
+ term: term,
}, callback);
} else {
- callback(new Error('no-plugins-available'), []);
+ callback(new Error('[[error:no-plugins-available]]'), []);
}
};
-
}(exports));
diff --git a/src/topics/bookmarks.js b/src/topics/bookmarks.js
index 8ec80cfdcb..b47d5f2278 100644
--- a/src/topics/bookmarks.js
+++ b/src/topics/bookmarks.js
@@ -7,7 +7,6 @@ var db = require('../database');
var posts = require('../posts');
module.exports = function (Topics) {
-
Topics.getUserBookmark = function (tid, uid, callback) {
db.sortedSetScore('tid:' + tid + ':bookmarks', uid, callback);
};
@@ -44,13 +43,13 @@ module.exports = function (Topics) {
},
function (bookmarks, next) {
var forkedPosts = pids.map(function (pid) {
- return {pid: pid, tid: tid};
+ return { pid: pid, tid: tid };
});
var uidData = bookmarks.map(function (bookmark) {
return {
uid: bookmark.value,
- bookmark: bookmark.score
+ bookmark: bookmark.score,
};
});
@@ -63,8 +62,8 @@ module.exports = function (Topics) {
var bookmark = data.bookmark;
bookmark = bookmark < maxIndex ? bookmark : maxIndex;
- for (var i = 0; i < postIndices.length && postIndices[i] < data.bookmark; ++i) {
- --bookmark;
+ for (var i = 0; i < postIndices.length && postIndices[i] < data.bookmark; i += 1) {
+ bookmark -= 1;
}
if (parseInt(bookmark, 10) !== parseInt(data.bookmark, 10)) {
@@ -74,10 +73,9 @@ module.exports = function (Topics) {
}
});
}, next);
- }
+ },
], function (err) {
callback(err);
});
};
-
};
diff --git a/src/topics/create.js b/src/topics/create.js
index bf62266ecf..da16489f05 100644
--- a/src/topics/create.js
+++ b/src/topics/create.js
@@ -15,7 +15,6 @@ var privileges = require('../privileges');
var categories = require('../categories');
module.exports = function (Topics) {
-
Topics.create = function (data, callback) {
// This is an internal method, consider using Topics.post instead
var timestamp = data.timestamp || Date.now();
@@ -30,26 +29,26 @@ module.exports = function (Topics) {
},
function (tid, next) {
topicData = {
- 'tid': tid,
- 'uid': data.uid,
- 'cid': data.cid,
- 'mainPid': 0,
- 'title': data.title,
- 'slug': tid + '/' + (utils.slugify(data.title) || 'topic'),
- 'timestamp': timestamp,
- 'lastposttime': 0,
- 'postcount': 0,
- 'viewcount': 0,
- 'locked': 0,
- 'deleted': 0,
- 'pinned': 0
+ tid: tid,
+ uid: data.uid,
+ cid: data.cid,
+ mainPid: 0,
+ title: data.title,
+ slug: tid + '/' + (utils.slugify(data.title) || 'topic'),
+ timestamp: timestamp,
+ lastposttime: 0,
+ postcount: 0,
+ viewcount: 0,
+ locked: 0,
+ deleted: 0,
+ pinned: 0,
};
if (data.thumb) {
topicData.thumb = data.thumb;
}
- plugins.fireHook('filter:topic.create', {topic: topicData, data: data}, next);
+ plugins.fireHook('filter:topic.create', { topic: topicData, data: data }, next);
},
function (data, next) {
topicData = data.topic;
@@ -61,7 +60,7 @@ module.exports = function (Topics) {
db.sortedSetsAdd([
'topics:tid',
'cid:' + topicData.cid + ':tids',
- 'cid:' + topicData.cid + ':uid:' + topicData.uid + ':tids'
+ 'cid:' + topicData.cid + ':uid:' + topicData.uid + ':tids',
], timestamp, topicData.tid, next);
},
function (next) {
@@ -78,13 +77,13 @@ module.exports = function (Topics) {
},
function (next) {
Topics.createTags(data.tags, topicData.tid, timestamp, next);
- }
+ },
], next);
},
function (results, next) {
plugins.fireHook('action:topic.save', topicData);
next(null, topicData.tid);
- }
+ },
], callback);
};
@@ -160,7 +159,7 @@ module.exports = function (Topics) {
},
topicData: function (next) {
Topics.getTopicsByTids([postData.tid], uid, next);
- }
+ },
}, next);
},
function (data, next) {
@@ -182,9 +181,9 @@ module.exports = function (Topics) {
next(null, {
topicData: data.topicData,
- postData: data.postData
+ postData: data.postData,
});
- }
+ },
], callback);
};
@@ -248,7 +247,7 @@ module.exports = function (Topics) {
content: content,
toPid: data.toPid,
timestamp: data.timestamp,
- ip: data.req ? data.req.ip : null
+ ip: data.req ? data.req.ip : null,
}, next);
},
function (_postData, next) {
@@ -272,7 +271,7 @@ module.exports = function (Topics) {
plugins.fireHook('action:topic.reply', postData);
next(null, postData);
- }
+ },
], callback);
};
@@ -299,7 +298,7 @@ module.exports = function (Topics) {
},
content: function (next) {
posts.parsePost(postData, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -323,14 +322,14 @@ module.exports = function (Topics) {
postData.topic.title = validator.escape(String(postData.topic.title));
next(null, postData);
- }
+ },
], callback);
}
function check(item, min, max, minError, maxError, callback) {
// Trim and remove HTML (latter for composers that send in HTML, like redactor)
if (typeof item === 'string') {
- item = S(item.trim()).stripTags().s;
+ item = S(item).stripTags().s.trim();
}
if (!item || item.length < parseInt(min, 10)) {
@@ -356,5 +355,4 @@ module.exports = function (Topics) {
}
callback();
}
-
};
diff --git a/src/topics/data.js b/src/topics/data.js
index a0196e1508..17e060f679 100644
--- a/src/topics/data.js
+++ b/src/topics/data.js
@@ -7,7 +7,6 @@ var categories = require('../categories');
var utils = require('../../public/src/utils');
module.exports = function (Topics) {
-
Topics.getTopicField = function (tid, field, callback) {
db.getObjectField('topic:' + tid, field, callback);
};
@@ -40,7 +39,7 @@ module.exports = function (Topics) {
Topics.getTopicsData = function (tids, callback) {
var keys = [];
- for (var i = 0; i < tids.length; ++i) {
+ for (var i = 0; i < tids.length; i += 1) {
keys.push('topic:' + tids[i]);
}
@@ -88,4 +87,7 @@ module.exports = function (Topics) {
db.deleteObjectField('topic:' + tid, field, callback);
};
-};
\ No newline at end of file
+ Topics.deleteTopicFields = function (tid, fields, callback) {
+ db.deleteObjectFields('topic:' + tid, fields, callback);
+ };
+};
diff --git a/src/topics/delete.js b/src/topics/delete.js
index 91c1bf53e3..082244f96d 100644
--- a/src/topics/delete.js
+++ b/src/topics/delete.js
@@ -10,79 +10,91 @@ var batch = require('../batch');
module.exports = function (Topics) {
-
Topics.delete = function (tid, uid, callback) {
- Topics.getTopicFields(tid, ['cid'], function (err, topicData) {
- if (err) {
- return callback(err);
- }
-
- async.parallel([
- function (next) {
- Topics.setTopicField(tid, 'deleted', 1, next);
- },
- function (next) {
- db.sortedSetsRemove(['topics:recent', 'topics:posts', 'topics:views'], tid, next);
- },
- function (next) {
- Topics.getPids(tid, function (err, pids) {
- if (err) {
- return next(err);
- }
- db.sortedSetRemove('cid:' + topicData.cid + ':pids', pids, next);
- });
- }
- ], function (err) {
- callback(err);
- });
+ async.parallel([
+ function (next) {
+ Topics.setTopicFields(tid, {
+ deleted: 1,
+ deleterUid: uid,
+ deletedTimestamp: Date.now(),
+ }, next);
+ },
+ function (next) {
+ db.sortedSetsRemove(['topics:recent', 'topics:posts', 'topics:views'], tid, next);
+ },
+ function (next) {
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ cid: function (next) {
+ Topics.getTopicField(tid, 'cid', next);
+ },
+ pids: function (next) {
+ Topics.getPids(tid, next);
+ },
+ }, next);
+ },
+ function (results, next) {
+ db.sortedSetRemove('cid:' + results.cid + ':pids', results.pids, next);
+ },
+ ], next);
+ },
+ ], function (err) {
+ callback(err);
});
};
Topics.restore = function (tid, uid, callback) {
- Topics.getTopicFields(tid, ['cid', 'lastposttime', 'postcount', 'viewcount'], function (err, topicData) {
- if (err) {
- return callback(err);
- }
-
- async.parallel([
- function (next) {
- Topics.setTopicField(tid, 'deleted', 0, next);
- },
- function (next) {
- Topics.updateRecent(tid, topicData.lastposttime, next);
- },
- function (next) {
- db.sortedSetAdd('topics:posts', topicData.postcount, tid, next);
- },
- function (next) {
- db.sortedSetAdd('topics:views', topicData.viewcount, tid, next);
- },
- function (next) {
- Topics.getPids(tid, function (err, pids) {
- if (err) {
- return callback(err);
- }
-
- posts.getPostsFields(pids, ['pid', 'timestamp', 'deleted'], function (err, postData) {
- if (err) {
- return next(err);
- }
- postData = postData.filter(function (post) {
- return post && parseInt(post.deleted, 10) !== 1;
- });
- var pidsToAdd = [], scores = [];
- postData.forEach(function (post) {
- pidsToAdd.push(post.pid);
- scores.push(post.timestamp);
- });
- db.sortedSetAdd('cid:' + topicData.cid + ':pids', scores, pidsToAdd, next);
- });
- });
- }
- ], function (err) {
- callback(err);
- });
- });
+ var topicData;
+ async.waterfall([
+ function (next) {
+ Topics.getTopicFields(tid, ['cid', 'lastposttime', 'postcount', 'viewcount'], next);
+ },
+ function (_topicData, next) {
+ topicData = _topicData;
+ async.parallel([
+ function (next) {
+ Topics.setTopicField(tid, 'deleted', 0, next);
+ },
+ function (next) {
+ Topics.deleteTopicFields(tid, ['deleterUid', 'deletedTimestamp'], next);
+ },
+ function (next) {
+ Topics.updateRecent(tid, topicData.lastposttime, next);
+ },
+ function (next) {
+ db.sortedSetAdd('topics:posts', topicData.postcount, tid, next);
+ },
+ function (next) {
+ db.sortedSetAdd('topics:views', topicData.viewcount, tid, next);
+ },
+ function (next) {
+ async.waterfall([
+ function (next) {
+ Topics.getPids(tid, next);
+ },
+ function (pids, next) {
+ posts.getPostsFields(pids, ['pid', 'timestamp', 'deleted'], next);
+ },
+ function (postData, next) {
+ postData = postData.filter(function (post) {
+ return post && parseInt(post.deleted, 10) !== 1;
+ });
+ var pidsToAdd = [];
+ var scores = [];
+ postData.forEach(function (post) {
+ pidsToAdd.push(post.pid);
+ scores.push(post.timestamp);
+ });
+ db.sortedSetAdd('cid:' + topicData.cid + ':pids', scores, pidsToAdd, next);
+ },
+ ], next);
+ },
+ ], function (err) {
+ next(err);
+ });
+ },
+ ], callback);
};
Topics.purgePostsAndTopic = function (tid, uid, callback) {
@@ -97,14 +109,14 @@ module.exports = function (Topics) {
async.eachLimit(pids, 10, function (pid, next) {
posts.purge(pid, uid, next);
}, next);
- }, {alwaysStartAt: 0}, next);
+ }, { alwaysStartAt: 0 }, next);
},
function (next) {
posts.purge(mainPid, uid, next);
},
function (next) {
Topics.purge(tid, uid, next);
- }
+ },
], callback);
};
@@ -122,7 +134,7 @@ module.exports = function (Topics) {
'tid:' + tid + ':posts',
'tid:' + tid + ':posts:votes',
'tid:' + tid + ':bookmarks',
- 'tid:' + tid + ':posters'
+ 'tid:' + tid + ':posters',
], next);
},
function (next) {
@@ -136,16 +148,16 @@ module.exports = function (Topics) {
},
function (next) {
reduceCounters(tid, next);
- }
- ], next);
- }
- ], function (err) {
- if (err) {
- return callback(err);
- }
- plugins.fireHook('action:topic.purge', tid);
- db.delete('topic:' + tid, callback);
- });
+ },
+ ], function (err) {
+ next(err);
+ });
+ },
+ function (next) {
+ plugins.fireHook('action:topic.purge', tid);
+ db.delete('topic:' + tid, next);
+ },
+ ], callback);
};
function deleteFromFollowersIgnorers(tid, callback) {
@@ -153,7 +165,7 @@ module.exports = function (Topics) {
function (next) {
async.parallel({
followers: async.apply(db.getSetMembers, 'tid:' + tid + ':followers'),
- ignorers: async.apply(db.getSetMembers, 'tid:' + tid + ':ignorers')
+ ignorers: async.apply(db.getSetMembers, 'tid:' + tid + ':ignorers'),
}, next);
},
function (results, next) {
@@ -164,29 +176,33 @@ module.exports = function (Topics) {
return 'uid:' + uid + 'ignored_tids';
});
db.sortedSetsRemove(followerKeys.concat(ignorerKeys), tid, next);
- }
+ },
], callback);
}
function deleteTopicFromCategoryAndUser(tid, callback) {
- Topics.getTopicFields(tid, ['cid', 'uid'], function (err, topicData) {
- if (err) {
- return callback(err);
- }
- async.parallel([
- function (next) {
- db.sortedSetsRemove([
- 'cid:' + topicData.cid + ':tids',
- 'cid:' + topicData.cid + ':tids:pinned',
- 'cid:' + topicData.cid + ':tids:posts',
- 'cid:' + topicData.cid + ':uid:' + topicData.uid + ':tids',
- 'uid:' + topicData.uid + ':topics'
- ], tid, next);
- },
- function (next) {
- user.decrementUserFieldBy(topicData.uid, 'topiccount', 1, next);
- }
- ], callback);
+ async.waterfall([
+ function (next) {
+ Topics.getTopicFields(tid, ['cid', 'uid'], next);
+ },
+ function (topicData, next) {
+ async.parallel([
+ function (next) {
+ db.sortedSetsRemove([
+ 'cid:' + topicData.cid + ':tids',
+ 'cid:' + topicData.cid + ':tids:pinned',
+ 'cid:' + topicData.cid + ':tids:posts',
+ 'cid:' + topicData.cid + ':uid:' + topicData.uid + ':tids',
+ 'uid:' + topicData.uid + ':topics',
+ ], tid, next);
+ },
+ function (next) {
+ user.decrementUserFieldBy(topicData.uid, 'topiccount', 1, next);
+ },
+ ], next);
+ },
+ ], function (err) {
+ callback(err);
});
}
@@ -197,27 +213,29 @@ module.exports = function (Topics) {
db.incrObjectFieldBy('global', 'topicCount', incr, next);
},
function (next) {
- Topics.getTopicFields(tid, ['cid', 'postcount'], function (err, topicData) {
- if (err) {
- return next(err);
- }
- topicData.postcount = parseInt(topicData.postcount, 10);
- topicData.postcount = topicData.postcount || 0;
- var postCountChange = incr * topicData.postcount;
+ async.waterfall([
+ function (next) {
+ Topics.getTopicFields(tid, ['cid', 'postcount'], next);
+ },
+ function (topicData, next) {
+ topicData.postcount = parseInt(topicData.postcount, 10);
+ topicData.postcount = topicData.postcount || 0;
+ var postCountChange = incr * topicData.postcount;
- async.parallel([
- function (next) {
- db.incrObjectFieldBy('global', 'postCount', postCountChange, next);
- },
- function (next) {
- db.incrObjectFieldBy('category:' + topicData.cid, 'post_count', postCountChange, next);
- },
- function (next) {
- db.incrObjectFieldBy('category:' + topicData.cid, 'topic_count', incr, next);
- }
- ], next);
- });
- }
+ async.parallel([
+ function (next) {
+ db.incrObjectFieldBy('global', 'postCount', postCountChange, next);
+ },
+ function (next) {
+ db.incrObjectFieldBy('category:' + topicData.cid, 'post_count', postCountChange, next);
+ },
+ function (next) {
+ db.incrObjectFieldBy('category:' + topicData.cid, 'topic_count', incr, next);
+ },
+ ], next);
+ },
+ ], next);
+ },
], callback);
}
};
diff --git a/src/topics/follow.js b/src/topics/follow.js
index 4775cdb9bc..a3b1041b13 100644
--- a/src/topics/follow.js
+++ b/src/topics/follow.js
@@ -16,7 +16,6 @@ var emailer = require('../emailer');
var plugins = require('../plugins');
module.exports = function (Topics) {
-
Topics.toggleFollow = function (tid, uid, callback) {
callback = callback || function () {};
var isFollowing;
@@ -40,7 +39,7 @@ module.exports = function (Topics) {
},
function (next) {
next(null, !isFollowing);
- }
+ },
], callback);
};
@@ -75,9 +74,9 @@ module.exports = function (Topics) {
method2(tid, uid, next);
},
function (next) {
- plugins.fireHook(hook, {uid: uid, tid: tid});
+ plugins.fireHook(hook, { uid: uid, tid: tid });
next();
- }
+ },
], callback);
}
@@ -104,7 +103,7 @@ module.exports = function (Topics) {
},
function (next) {
db.sortedSetAdd(set2, Date.now(), tid, next);
- }
+ },
], callback);
}
@@ -115,7 +114,7 @@ module.exports = function (Topics) {
},
function (next) {
db.sortedSetRemove(set2, tid, next);
- }
+ },
], callback);
}
@@ -158,7 +157,7 @@ module.exports = function (Topics) {
return uid && !isIgnoring[index];
});
next(null, readingUids);
- }
+ },
], callback);
};
@@ -233,7 +232,7 @@ module.exports = function (Topics) {
tid: postData.topic.tid,
from: exceptUid,
mergeId: 'notifications:user_posted_to|' + postData.topic.tid,
- topicTitle: title
+ topicTitle: title,
}, next);
},
function (notification, next) {
@@ -248,7 +247,7 @@ module.exports = function (Topics) {
async.eachLimit(followers, 3, function (toUid, next) {
async.parallel({
userData: async.apply(user.getUserFields, toUid, ['username', 'userslug']),
- userSettings: async.apply(user.getSettings, toUid)
+ userSettings: async.apply(user.getSettings, toUid),
}, function (err, data) {
if (err) {
return next(err);
@@ -266,7 +265,7 @@ module.exports = function (Topics) {
url: nconf.get('url') + '/topic/' + postData.topic.tid,
topicSlug: postData.topic.slug,
postCount: postData.topic.postcount,
- base_url: nconf.get('url')
+ base_url: nconf.get('url'),
}, next);
} else {
winston.debug('[topics.notifyFollowers] uid ' + toUid + ' does not have post notifications enabled, skipping.');
@@ -275,7 +274,7 @@ module.exports = function (Topics) {
});
});
next();
- }
+ },
], callback);
};
};
diff --git a/src/topics/fork.js b/src/topics/fork.js
index d882cddf00..396ae3d63b 100644
--- a/src/topics/fork.js
+++ b/src/topics/fork.js
@@ -2,9 +2,8 @@
'use strict';
var async = require('async');
-var winston = require('winston');
+
var db = require('../database');
-var user = require('../user');
var posts = require('../posts');
var privileges = require('../privileges');
var plugins = require('../plugins');
@@ -12,7 +11,6 @@ var meta = require('../meta');
module.exports = function (Topics) {
-
Topics.createTopicFromPosts = function (uid, title, pids, fromTid, callback) {
if (title) {
title = title.trim();
@@ -46,17 +44,17 @@ module.exports = function (Topics) {
},
isAdminOrMod: function (next) {
privileges.categories.isAdminOrMod(cid, uid, next);
- }
+ },
}, next);
},
function (results, next) {
if (!results.isAdminOrMod) {
return next(new Error('[[error:no-privileges]]'));
}
- Topics.create({uid: results.postData.uid, title: title, cid: cid}, next);
+ Topics.create({ uid: results.postData.uid, title: title, cid: cid }, next);
},
function (results, next) {
- Topics.updateTopicBookmarks(fromTid, pids, function () { next( null, results );} );
+ Topics.updateTopicBookmarks(fromTid, pids, function () { next(null, results); });
},
function (_tid, next) {
function move(pid, next) {
@@ -76,7 +74,7 @@ module.exports = function (Topics) {
},
function (next) {
Topics.getTopicData(tid, next);
- }
+ },
], callback);
};
@@ -122,20 +120,20 @@ module.exports = function (Topics) {
},
function (next) {
Topics.addPostToTopic(tid, postData, next);
- }
+ },
], next);
},
function (results, next) {
async.parallel([
async.apply(updateRecentTopic, tid),
- async.apply(updateRecentTopic, postData.tid)
+ async.apply(updateRecentTopic, postData.tid),
], next);
- }
+ },
], function (err) {
if (err) {
return callback(err);
}
- plugins.fireHook('action:post.move', {post: postData, tid: tid});
+ plugins.fireHook('action:post.move', { post: postData, tid: tid });
callback();
});
};
@@ -153,7 +151,7 @@ module.exports = function (Topics) {
}
async.parallel([
async.apply(db.incrObjectFieldBy, 'category:' + topicData[0].cid, 'post_count', -1),
- async.apply(db.incrObjectFieldBy, 'category:' + topicData[1].cid, 'post_count', 1)
+ async.apply(db.incrObjectFieldBy, 'category:' + topicData[1].cid, 'post_count', 1),
], callback);
});
}
@@ -171,9 +169,7 @@ module.exports = function (Topics) {
},
function (timestamp, next) {
Topics.updateTimestamp(tid, timestamp, next);
- }
+ },
], callback);
}
-
-
};
diff --git a/src/topics/popular.js b/src/topics/popular.js
index 452f897581..e6d78ad4b4 100644
--- a/src/topics/popular.js
+++ b/src/topics/popular.js
@@ -5,7 +5,6 @@ var async = require('async');
var privileges = require('../privileges');
module.exports = function (Topics) {
-
Topics.getPopular = function (term, uid, count, callback) {
count = parseInt(count, 10) || 20;
@@ -19,7 +18,7 @@ module.exports = function (Topics) {
},
function (tids, next) {
getTopics(tids, uid, count, next);
- }
+ },
], callback);
};
@@ -46,7 +45,7 @@ module.exports = function (Topics) {
},
function (tids, next) {
Topics.getTopicsByTids(tids, uid, next);
- }
+ },
], callback);
}
};
diff --git a/src/topics/posts.js b/src/topics/posts.js
index 97b6f71162..909de0caa4 100644
--- a/src/topics/posts.js
+++ b/src/topics/posts.js
@@ -12,7 +12,6 @@ var meta = require('../meta');
var plugins = require('../plugins');
module.exports = function (Topics) {
-
Topics.onNewPostMade = function (postData, callback) {
async.series([
function (next) {
@@ -23,7 +22,7 @@ module.exports = function (Topics) {
},
function (next) {
Topics.addPostToTopic(postData.tid, postData, next);
- }
+ },
], callback);
};
@@ -36,14 +35,14 @@ module.exports = function (Topics) {
},
postCount: function (next) {
Topics.getTopicField(tid, 'postcount', next);
- }
+ },
}, next);
},
function (results, next) {
Topics.calculatePostIndices(results.posts, start, stop, results.postCount, reverse);
Topics.addPostData(results.posts, uid, next);
- }
+ },
], callback);
};
@@ -78,7 +77,7 @@ module.exports = function (Topics) {
userData[uids[index]] = user;
});
next(null, userData);
- }
+ },
], callback);
}
@@ -95,7 +94,6 @@ module.exports = function (Topics) {
getPostUserData('uid', function (uids, next) {
posts.getUserInfoForPosts(uids, uid, next);
}, next);
-
},
editors: function (next) {
getPostUserData('editor', function (uids, next) {
@@ -104,7 +102,7 @@ module.exports = function (Topics) {
},
parents: function (next) {
Topics.addParentPosts(postData, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -128,12 +126,12 @@ module.exports = function (Topics) {
});
plugins.fireHook('filter:topics.addPostData', {
posts: postData,
- uid: uid
+ uid: uid,
}, next);
},
function (data, next) {
next(null, data.posts);
- }
+ },
], callback);
};
@@ -167,8 +165,8 @@ module.exports = function (Topics) {
async.apply(posts.getPostsFields, parentPids, ['uid']),
function (_parentPosts, next) {
parentPosts = _parentPosts;
- var parentUids = parentPosts.map(function (postObj) {
- return parseInt(postObj.uid, 10);
+ var parentUids = parentPosts.map(function (postObj) {
+ return parseInt(postObj.uid, 10);
}).filter(function (uid, idx, users) {
return users.indexOf(uid) === idx;
});
@@ -182,14 +180,14 @@ module.exports = function (Topics) {
});
var parents = {};
parentPosts.forEach(function (post, i) {
- parents[parentPids[i]] = {username: usersMap[post.uid]};
+ parents[parentPids[i]] = { username: usersMap[post.uid] };
});
postData.forEach(function (post) {
post.parent = parents[post.toPid];
});
next();
- }
+ },
], callback);
};
@@ -219,7 +217,7 @@ module.exports = function (Topics) {
},
function (mainPost, next) {
next(null, parseInt(mainPost.pid, 10) && parseInt(mainPost.deleted, 10) !== 1 ? mainPost.pid.toString() : null);
- }
+ },
], callback);
};
@@ -249,9 +247,9 @@ module.exports = function (Topics) {
if (!isDeleted) {
latestPid = pids[0];
}
- ++index;
+ index += 1;
_next();
- }
+ },
], next);
},
function () {
@@ -281,7 +279,7 @@ module.exports = function (Topics) {
var downvotes = parseInt(postData.downvotes, 10) || 0;
var votes = upvotes - downvotes;
db.sortedSetAdd('tid:' + tid + ':posts:votes', votes, postData.pid, next);
- }
+ },
], function (err) {
next(err);
});
@@ -292,7 +290,7 @@ module.exports = function (Topics) {
},
function (count, next) {
Topics.updateTeaser(tid, next);
- }
+ },
], callback);
};
@@ -301,7 +299,7 @@ module.exports = function (Topics) {
function (next) {
db.sortedSetsRemove([
'tid:' + tid + ':posts',
- 'tid:' + tid + ':posts:votes'
+ 'tid:' + tid + ':posts:votes',
], postData.pid, next);
},
function (next) {
@@ -309,7 +307,7 @@ module.exports = function (Topics) {
},
function (count, next) {
Topics.updateTeaser(tid, next);
- }
+ },
], callback);
};
@@ -322,7 +320,7 @@ module.exports = function (Topics) {
},
pids: function (next) {
db.getSortedSetRange('tid:' + tid + ':posts', 0, -1, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -330,7 +328,7 @@ module.exports = function (Topics) {
results.pids = [results.mainPid].concat(results.pids);
}
next(null, results.pids);
- }
+ },
], callback);
};
@@ -354,7 +352,7 @@ module.exports = function (Topics) {
},
function (value, next) {
db.sortedSetAdd(set, value, tid, next);
- }
+ },
], callback);
}
@@ -369,7 +367,7 @@ module.exports = function (Topics) {
},
function (tid, next) {
Topics.getTopicField(tid, field, next);
- }
+ },
], callback);
};
@@ -380,12 +378,11 @@ module.exports = function (Topics) {
},
function (tid, next) {
Topics.getTopicData(tid, next);
- }
+ },
], callback);
};
Topics.getPostCount = function (tid, callback) {
db.getObjectField('topic:' + tid, 'postcount', callback);
};
-
};
diff --git a/src/topics/recent.js b/src/topics/recent.js
index 23ca9ff5ba..dbecd035b4 100644
--- a/src/topics/recent.js
+++ b/src/topics/recent.js
@@ -7,20 +7,20 @@ var db = require('../database');
var plugins = require('../plugins');
var privileges = require('../privileges');
var user = require('../user');
-var categories = require('../categories');
+var categories = require('../categories');
module.exports = function (Topics) {
var terms = {
day: 86400000,
week: 604800000,
month: 2592000000,
- year: 31104000000
+ year: 31104000000,
};
Topics.getRecentTopics = function (cid, uid, start, stop, filter, callback) {
var recentTopics = {
- nextStart : 0,
- topics: []
+ nextStart: 0,
+ topics: [],
};
async.waterfall([
@@ -43,7 +43,7 @@ module.exports = function (Topics) {
recentTopics.topics = topicData;
recentTopics.nextStart = stop + 1;
next(null, recentTopics);
- }
+ },
], callback);
};
@@ -72,21 +72,20 @@ module.exports = function (Topics) {
},
topicData: function (next) {
Topics.getTopicsFields(tids, ['tid', 'cid'], next);
- }
+ },
}, next);
},
function (results, next) {
tids = results.topicData.filter(function (topic) {
if (topic) {
return results.ignoredCids.indexOf(topic.cid.toString()) === -1;
- } else {
- return false;
}
+ return false;
}).map(function (topic) {
return topic.tid;
});
next(null, tids);
- }
+ },
], callback);
}
@@ -100,8 +99,8 @@ module.exports = function (Topics) {
Topics.getTopics(tids, uid, next);
},
function (topics, next) {
- next(null, {topics: topics, nextStart: stop + 1});
- }
+ next(null, { topics: topics, nextStart: stop + 1 });
+ },
], callback);
};
@@ -128,12 +127,12 @@ module.exports = function (Topics) {
return next();
}
Topics.updateRecent(tid, timestamp, next);
- }
+ },
], next);
},
function (next) {
Topics.setTopicField(tid, 'lastposttime', timestamp, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -142,7 +141,7 @@ module.exports = function (Topics) {
Topics.updateRecent = function (tid, timestamp, callback) {
callback = callback || function () {};
if (plugins.hasListeners('filter:topics.updateRecent')) {
- plugins.fireHook('filter:topics.updateRecent', {tid: tid, timestamp: timestamp}, function (err, data) {
+ plugins.fireHook('filter:topics.updateRecent', { tid: tid, timestamp: timestamp }, function (err, data) {
if (err) {
return callback(err);
}
diff --git a/src/topics/suggested.js b/src/topics/suggested.js
index d51d51827b..d69471744f 100644
--- a/src/topics/suggested.js
+++ b/src/topics/suggested.js
@@ -8,7 +8,6 @@ var categories = require('../categories');
var search = require('../search');
module.exports = function (Topics) {
-
Topics.getSuggestedTopics = function (tid, uid, start, stop, callback) {
async.parallel({
tagTids: function (next) {
@@ -19,7 +18,7 @@ module.exports = function (Topics) {
},
categoryTids: function (next) {
getCategoryTids(tid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -51,7 +50,7 @@ module.exports = function (Topics) {
},
function (data, next) {
next(null, _.unique(_.flatten(data)));
- }
+ },
], callback);
}
@@ -62,7 +61,7 @@ module.exports = function (Topics) {
},
function (title, next) {
search.searchQuery('topic', title, [], [], next);
- }
+ },
], callback);
}
@@ -73,8 +72,7 @@ module.exports = function (Topics) {
},
function (cid, next) {
categories.getTopicIds(cid, 'cid:' + cid + ':tids', true, 0, 9, next);
- }
+ },
], callback);
}
-
-};
\ No newline at end of file
+};
diff --git a/src/topics/tags.js b/src/topics/tags.js
index a360de290e..d10c127ac0 100644
--- a/src/topics/tags.js
+++ b/src/topics/tags.js
@@ -11,7 +11,6 @@ var utils = require('../../public/src/utils');
module.exports = function (Topics) {
-
Topics.createTags = function (tags, tid, timestamp, callback) {
callback = callback || function () {};
@@ -21,7 +20,7 @@ module.exports = function (Topics) {
async.waterfall([
function (next) {
- plugins.fireHook('filter:tags.filter', {tags: tags, tid: tid}, next);
+ plugins.fireHook('filter:tags.filter', { tags: tags, tid: tid }, next);
},
function (data, next) {
tags = data.tags.slice(0, meta.config.maximumTagsPerTopic || 5);
@@ -41,14 +40,14 @@ module.exports = function (Topics) {
async.parallel([
async.apply(db.setAdd, 'topic:' + tid + ':tags', tags),
- async.apply(db.sortedSetsAdd, keys, timestamp, tid)
+ async.apply(db.sortedSetsAdd, keys, timestamp, tid),
], function (err) {
next(err);
});
},
function (next) {
async.each(tags, updateTagCount, next);
- }
+ },
], callback);
};
@@ -68,7 +67,7 @@ module.exports = function (Topics) {
return tagWhitelist.indexOf(tag) !== -1;
});
next(null, tags);
- }
+ },
], callback);
}
@@ -91,7 +90,7 @@ module.exports = function (Topics) {
return next();
}
db.sortedSetAdd('tags:topic:count', 0, tag, next);
- }
+ },
], callback);
};
@@ -112,7 +111,7 @@ module.exports = function (Topics) {
count = count || 0;
db.sortedSetAdd('tags:topic:count', count, tag, next);
- }
+ },
], callback);
}
@@ -146,7 +145,7 @@ module.exports = function (Topics) {
db.deleteAll(tags.map(function (tag) {
return 'tag:' + tag;
}), next);
- }
+ },
], callback);
};
@@ -176,7 +175,7 @@ module.exports = function (Topics) {
},
function (tags, next) {
Topics.getTagData(tags, next);
- }
+ },
], callback);
};
@@ -195,7 +194,7 @@ module.exports = function (Topics) {
tag.bgColor = tagData[index] ? tagData[index].bgColor : '';
});
next(null, tags);
- }
+ },
], callback);
};
@@ -231,7 +230,7 @@ module.exports = function (Topics) {
uniqueTopicTags = _.uniq(_.flatten(topicTags));
var tags = uniqueTopicTags.map(function (tag) {
- return {value: tag};
+ return { value: tag };
});
async.parallel({
@@ -240,7 +239,7 @@ module.exports = function (Topics) {
},
counts: function (next) {
db.sortedSetScores('tags:topic:count', uniqueTopicTags, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -252,12 +251,12 @@ module.exports = function (Topics) {
topicTags.forEach(function (tags, index) {
if (Array.isArray(tags)) {
- topicTags[index] = tags.map(function (tag) {return tagData[tag];});
+ topicTags[index] = tags.map(function (tag) { return tagData[tag]; });
}
});
next(null, topicTags);
- }
+ },
], callback);
};
@@ -272,7 +271,7 @@ module.exports = function (Topics) {
},
function (timestamp, next) {
Topics.createTags(tags, tid, timestamp, next);
- }
+ },
], callback);
};
@@ -297,9 +296,9 @@ module.exports = function (Topics) {
async.each(tags, function (tag, next) {
updateTagCount(tag, next);
}, next);
- }
+ },
], next);
- }
+ },
], function (err) {
callback(err);
});
@@ -313,17 +312,17 @@ module.exports = function (Topics) {
async.waterfall([
function (next) {
if (plugins.hasListeners('filter:topics.searchTags')) {
- plugins.fireHook('filter:topics.searchTags', {data: data}, next);
+ plugins.fireHook('filter:topics.searchTags', { data: data }, next);
} else {
findMatches(data.query, 0, next);
}
},
function (result, next) {
- plugins.fireHook('filter:tags.search', {data: data, matches: result.matches}, next);
+ plugins.fireHook('filter:tags.search', { data: data, matches: result.matches }, next);
},
function (result, next) {
next(null, result.matches);
- }
+ },
], callback);
};
@@ -335,14 +334,14 @@ module.exports = function (Topics) {
async.waterfall([
function (next) {
if (plugins.hasListeners('filter:topics.autocompleteTags')) {
- plugins.fireHook('filter:topics.autocompleteTags', {data: data}, next);
+ plugins.fireHook('filter:topics.autocompleteTags', { data: data }, next);
} else {
findMatches(data.query, data.cid, next);
}
},
function (result, next) {
next(null, result.matches);
- }
+ },
], callback);
};
@@ -366,7 +365,7 @@ module.exports = function (Topics) {
query = query.toLowerCase();
var matches = [];
- for(var i = 0; i < tags.length; ++i) {
+ for (var i = 0; i < tags.length; i += 1) {
if (tags[i].toLowerCase().startsWith(query)) {
matches.push(tags[i]);
if (matches.length > 19) {
@@ -378,8 +377,8 @@ module.exports = function (Topics) {
matches = matches.sort(function (a, b) {
return a > b;
});
- next(null, {matches: matches});
- }
+ next(null, { matches: matches });
+ },
], callback);
}
@@ -387,7 +386,7 @@ module.exports = function (Topics) {
var searchResult = {
tags: [],
matchCount: 0,
- pageCount: 1
+ pageCount: 1,
};
if (!data || !data.query || !data.query.length) {
@@ -404,11 +403,11 @@ module.exports = function (Topics) {
},
tagData: function (next) {
tags = tags.map(function (tag) {
- return {value: tag};
+ return { value: tag };
});
Topics.getTagData(tags, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -422,13 +421,13 @@ module.exports = function (Topics) {
searchResult.matchCount = results.tagData.length;
searchResult.pageCount = 1;
next(null, searchResult);
- }
+ },
], callback);
};
Topics.getRelatedTopics = function (topicData, uid, callback) {
if (plugins.hasListeners('filter:topic.getRelatedTopics')) {
- return plugins.fireHook('filter:topic.getRelatedTopics', {topic: topicData, uid: uid}, callback);
+ return plugins.fireHook('filter:topic.getRelatedTopics', { topic: topicData, uid: uid }, callback);
}
var maximumTopics = parseInt(meta.config.maximumRelatedTopics, 10) || 0;
@@ -453,7 +452,7 @@ module.exports = function (Topics) {
return topic && !topic.deleted && parseInt(topic.uid, 10) !== parseInt(uid, 10);
});
next(null, topics);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/topics/teaser.js b/src/topics/teaser.js
index 1467dd194f..aa64d7780f 100644
--- a/src/topics/teaser.js
+++ b/src/topics/teaser.js
@@ -12,7 +12,6 @@ var plugins = require('../plugins');
var utils = require('../../public/src/utils');
module.exports = function (Topics) {
-
Topics.getTeasers = function (topics, callback) {
if (!Array.isArray(topics) || !topics.length) {
return callback(null, []);
@@ -30,19 +29,19 @@ module.exports = function (Topics) {
delete topic.teaserPid;
}
- switch(meta.config.teaserPost) {
- case 'first':
- teaserPids.push(topic.mainPid);
- break;
+ switch (meta.config.teaserPost) {
+ case 'first':
+ teaserPids.push(topic.mainPid);
+ break;
- case 'last-post':
- teaserPids.push(topic.teaserPid || topic.mainPid);
- break;
+ case 'last-post':
+ teaserPids.push(topic.teaserPid || topic.mainPid);
+ break;
- case 'last-reply': // intentional fall-through
- default:
- teaserPids.push(topic.teaserPid);
- break;
+ case 'last-reply': // intentional fall-through
+ default:
+ teaserPids.push(topic.teaserPid);
+ break;
}
}
});
@@ -95,11 +94,11 @@ module.exports = function (Topics) {
return tidToPost[topic.tid];
});
- plugins.fireHook('filter:teasers.get', {teasers: teasers}, next);
+ plugins.fireHook('filter:teasers.get', { teasers: teasers }, next);
},
function (data, next) {
next(null, data.teasers);
- }
+ },
], callback);
};
@@ -113,7 +112,7 @@ module.exports = function (Topics) {
},
function (topics, next) {
Topics.getTeasers(topics, next);
- }
+ },
], callback);
};
@@ -137,4 +136,4 @@ module.exports = function (Topics) {
}
});
};
-};
\ No newline at end of file
+};
diff --git a/src/topics/thumb.js b/src/topics/thumb.js
index a5ca38ed3e..574ca302ad 100644
--- a/src/topics/thumb.js
+++ b/src/topics/thumb.js
@@ -16,7 +16,6 @@ var file = require('../file');
var plugins = require('../plugins');
module.exports = function (Topics) {
-
Topics.resizeAndUploadThumb = function (data, callback) {
if (!data.thumb || !validator.isURL(data.thumb)) {
return callback();
@@ -30,7 +29,6 @@ module.exports = function (Topics) {
request.head(data.thumb, next);
},
function (res, body, next) {
-
var type = res.headers['content-type'];
if (!type.match(/image./)) {
return next(new Error('[[error:invalid-file]]'));
@@ -54,7 +52,7 @@ module.exports = function (Topics) {
path: pathToUpload,
extension: path.extname(pathToUpload),
width: size,
- height: size
+ height: size,
}, next);
},
function (next) {
@@ -63,13 +61,13 @@ module.exports = function (Topics) {
return callback();
}
- plugins.fireHook('filter:uploadImage', {image: {path: pathToUpload, name: ''}, uid: data.uid}, next);
+ plugins.fireHook('filter:uploadImage', { image: { path: pathToUpload, name: '' }, uid: data.uid }, next);
},
function (uploadedFile, next) {
deleteFile(pathToUpload);
data.thumb = uploadedFile.url;
next();
- }
+ },
], function (err) {
if (err) {
deleteFile(pathToUpload);
@@ -87,5 +85,4 @@ module.exports = function (Topics) {
});
}
}
-
};
diff --git a/src/topics/tools.js b/src/topics/tools.js
index cccffa8c75..f83a5f91f0 100644
--- a/src/topics/tools.js
+++ b/src/topics/tools.js
@@ -10,7 +10,6 @@ var privileges = require('../privileges');
module.exports = function (Topics) {
-
var topicTools = {};
Topics.tools = topicTools;
@@ -46,7 +45,7 @@ module.exports = function (Topics) {
if (parseInt(topicData.deleted, 10) === 1 && isDelete) {
return callback(new Error('[[error:topic-already-deleted]]'));
- } else if(parseInt(topicData.deleted, 10) !== 1 && !isDelete) {
+ } else if (parseInt(topicData.deleted, 10) !== 1 && !isDelete) {
return callback(new Error('[[error:topic-already-restored]]'));
}
@@ -65,11 +64,11 @@ module.exports = function (Topics) {
tid: tid,
cid: topicData.cid,
isDelete: isDelete,
- uid: uid
+ uid: uid,
};
next(null, data);
- }
+ },
], callback);
}
@@ -98,8 +97,8 @@ module.exports = function (Topics) {
Topics.purgePostsAndTopic(tid, uid, next);
},
function (next) {
- next(null, {tid: tid, cid: cid, uid: uid});
- }
+ next(null, { tid: tid, cid: cid, uid: uid });
+ },
], callback);
};
@@ -139,13 +138,13 @@ module.exports = function (Topics) {
tid: tid,
isLocked: lock,
uid: uid,
- cid: cid
+ cid: cid,
};
plugins.fireHook('action:topic.lock', data);
next(null, data);
- }
+ },
], callback);
}
@@ -185,16 +184,16 @@ module.exports = function (Topics) {
async.parallel([
async.apply(db.sortedSetAdd, 'cid:' + topicData.cid + ':tids:pinned', Date.now(), tid),
async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids', tid),
- async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids:posts', tid)
+ async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids:posts', tid),
], next);
} else {
async.parallel([
async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids:pinned', tid),
async.apply(db.sortedSetAdd, 'cid:' + topicData.cid + ':tids', topicData.lastposttime, tid),
- async.apply(db.sortedSetAdd, 'cid:' + topicData.cid + ':tids:posts', topicData.postcount, tid)
+ async.apply(db.sortedSetAdd, 'cid:' + topicData.cid + ':tids:posts', topicData.postcount, tid),
], next);
}
- }
+ },
], next);
},
function (results, next) {
@@ -202,13 +201,13 @@ module.exports = function (Topics) {
tid: tid,
isPinned: pin,
uid: uid,
- cid: topicData.cid
+ cid: topicData.cid,
};
plugins.fireHook('action:topic.pin', data);
next(null, data);
- }
+ },
], callback);
}
@@ -225,7 +224,7 @@ module.exports = function (Topics) {
var uniqueCids = _.unique(topicData.map(function (topicData) {
return topicData && parseInt(topicData.cid, 10);
}));
-
+
if (uniqueCids.length > 1 || !uniqueCids.length || !uniqueCids[0]) {
return next(new Error('[[error:invalid-data]]'));
}
@@ -248,10 +247,10 @@ module.exports = function (Topics) {
} else {
setImmediate(next);
}
- }
- ], next);
+ },
+ ], next);
}, next);
- }
+ },
], callback);
};
@@ -272,7 +271,7 @@ module.exports = function (Topics) {
db.sortedSetsRemove([
'cid:' + topicData.cid + ':tids',
'cid:' + topicData.cid + ':tids:pinned',
- 'cid:' + topicData.cid + ':tids:posts' // post count
+ 'cid:' + topicData.cid + ':tids:posts', // post count
], tid, next);
},
function (next) {
@@ -286,10 +285,10 @@ module.exports = function (Topics) {
function (next) {
topic.postcount = topic.postcount || 0;
db.sortedSetAdd('cid:' + cid + ':tids:posts', topic.postcount, tid, next);
- }
+ },
], next);
}
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -307,9 +306,9 @@ module.exports = function (Topics) {
function (next) {
Topics.setTopicFields(tid, {
cid: cid,
- oldCid: oldCid
+ oldCid: oldCid,
}, next);
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -318,12 +317,10 @@ module.exports = function (Topics) {
tid: tid,
fromCid: oldCid,
toCid: cid,
- uid: uid
+ uid: uid,
});
callback();
});
});
};
-
-
};
diff --git a/src/topics/unread.js b/src/topics/unread.js
index e61ca46d59..b2f5b199d1 100644
--- a/src/topics/unread.js
+++ b/src/topics/unread.js
@@ -12,7 +12,6 @@ var meta = require('../meta');
var utils = require('../../public/src/utils');
module.exports = function (Topics) {
-
Topics.getTotalUnread = function (uid, filter, callback) {
if (!callback) {
callback = filter;
@@ -25,11 +24,10 @@ module.exports = function (Topics) {
Topics.getUnreadTopics = function (cid, uid, start, stop, filter, callback) {
-
var unreadTopics = {
showSelect: true,
- nextStart : 0,
- topics: []
+ nextStart: 0,
+ topics: [],
};
async.waterfall([
@@ -59,12 +57,13 @@ module.exports = function (Topics) {
unreadTopics.topics = topicData;
unreadTopics.nextStart = stop + 1;
next(null, unreadTopics);
- }
+ },
], callback);
};
Topics.unreadCutoff = function () {
- return Date.now() - (parseInt(meta.config.unreadCutoff, 10) || 2) * 86400000;
+ var cutoff = parseInt(meta.config.unreadCutoff, 10) || 2;
+ return Date.now() - (cutoff * 86400000);
};
Topics.getUnreadTids = function (cid, uid, filter, callback) {
@@ -97,7 +96,7 @@ module.exports = function (Topics) {
},
tids_unread: function (next) {
db.getSortedSetRevRangeWithScores('uid:' + uid + ':tids_unread', 0, -1, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -122,10 +121,10 @@ module.exports = function (Topics) {
return false;
}
switch (filter) {
- case 'new':
- return !userRead[recentTopic.value];
- default:
- return !userRead[recentTopic.value] || recentTopic.score > userRead[recentTopic.value];
+ case 'new':
+ return !userRead[recentTopic.value];
+ default:
+ return !userRead[recentTopic.value] || recentTopic.score > userRead[recentTopic.value];
}
}).map(function (topic) {
return topic.value;
@@ -140,11 +139,10 @@ module.exports = function (Topics) {
}
},
function (tids, next) {
-
tids = tids.slice(0, 200);
filterTopics(uid, tids, cid, ignoredCids, filter, next);
- }
+ },
], callback);
};
@@ -168,7 +166,7 @@ module.exports = function (Topics) {
return next(null, []);
}
db.sortedSetScores('uid:' + uid + ':followed_tids', tids, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -181,7 +179,7 @@ module.exports = function (Topics) {
return topic.tid;
});
next(null, tids);
- }
+ },
], callback);
}
@@ -208,7 +206,7 @@ module.exports = function (Topics) {
Topics.markAsRead = function (tids, uid, callback) {
callback = callback || function () {};
if (!Array.isArray(tids) || !tids.length) {
- return callback();
+ return setImmediate(callback, null, false);
}
tids = tids.filter(function (tid, index, array) {
@@ -216,14 +214,14 @@ module.exports = function (Topics) {
});
if (!tids.length) {
- return callback(null, false);
+ return setImmediate(callback, null, false);
}
async.waterfall([
function (next) {
async.parallel({
topicScores: async.apply(db.sortedSetScores, 'topics:recent', tids),
- userScores: async.apply(db.sortedSetScores, 'uid:' + uid + ':tids_read', tids)
+ userScores: async.apply(db.sortedSetScores, 'uid:' + uid + ':tids_read', tids),
}, next);
},
function (results, next) {
@@ -243,7 +241,7 @@ module.exports = function (Topics) {
async.parallel({
markRead: async.apply(db.sortedSetAdd, 'uid:' + uid + ':tids_read', scores, tids),
markUnread: async.apply(db.sortedSetRemove, 'uid:' + uid + ':tids_unread', tids),
- topicData: async.apply(Topics.getTopicsFields, tids, ['cid'])
+ topicData: async.apply(Topics.getTopicsFields, tids, ['cid']),
}, next);
},
function (results, next) {
@@ -257,7 +255,7 @@ module.exports = function (Topics) {
},
function (next) {
next(null, true);
- }
+ },
], callback);
};
@@ -272,7 +270,7 @@ module.exports = function (Topics) {
},
function (markedRead, next) {
db.delete('uid:' + uid + ':tids_unread', next);
- }
+ },
], callback);
};
@@ -292,7 +290,7 @@ module.exports = function (Topics) {
function (next) {
user.notifications.pushCount(uid);
next();
- }
+ },
], callback);
};
@@ -303,7 +301,7 @@ module.exports = function (Topics) {
},
function (cid, next) {
categories.markAsUnreadForAll(cid, next);
- }
+ },
], callback);
};
@@ -323,7 +321,7 @@ module.exports = function (Topics) {
},
tids_unread: function (next) {
db.sortedSetScores('uid:' + uid + ':tids_unread', tids, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -359,7 +357,7 @@ module.exports = function (Topics) {
},
function (next) {
db.sortedSetAdd('uid:' + uid + ':tids_unread', Date.now(), tid, next);
- }
+ },
], callback);
};
@@ -374,5 +372,4 @@ module.exports = function (Topics) {
callback(null, tids);
});
};
-
};
diff --git a/src/topics/user.js b/src/topics/user.js
index ab56a5f778..d0a8d21426 100644
--- a/src/topics/user.js
+++ b/src/topics/user.js
@@ -1,13 +1,8 @@
-
-
'use strict';
-var async = require('async');
var db = require('../database');
-var posts = require('../posts');
module.exports = function (Topics) {
-
Topics.isOwner = function (tid, uid, callback) {
uid = parseInt(uid, 10);
if (!uid) {
@@ -21,4 +16,4 @@ module.exports = function (Topics) {
Topics.getUids = function (tid, callback) {
db.getSortedSetRevRangeByScore('tid:' + tid + ':posters', 0, -1, '+inf', 1, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/upgrade.js b/src/upgrade.js
index 4aca187a7a..0ab9984646 100644
--- a/src/upgrade.js
+++ b/src/upgrade.js
@@ -1,6 +1,5 @@
-"use strict";
+'use strict';
-/* globals console, require */
var db = require('./database');
var async = require('async');
@@ -13,7 +12,7 @@ var schemaDate;
var thisSchemaDate;
// IMPORTANT: REMEMBER TO UPDATE VALUE OF latestSchema
-var latestSchema = Date.UTC(2016, 10, 22);
+var latestSchema = Date.UTC(2017, 1, 28);
Upgrade.check = function (callback) {
db.get('schemaDate', function (err, value) {
@@ -53,7 +52,7 @@ Upgrade.upgrade = function (callback) {
return next(err);
}
- if(!value) {
+ if (!value) {
db.set('schemaDate', latestSchema, function () {
next();
});
@@ -131,7 +130,7 @@ Upgrade.upgrade = function (callback) {
},
function (next) {
db.deleteObjectField('post:' + id, 'reputation', next);
- }
+ },
], next);
}, next);
}, {}, next);
@@ -187,7 +186,7 @@ Upgrade.upgrade = function (callback) {
console.log('processing pid: ' + postData.pid + ' toPid: ' + postData.toPid);
async.parallel([
async.apply(db.sortedSetAdd, 'pid:' + postData.toPid + ':replies', postData.timestamp, postData.pid),
- async.apply(db.incrObjectField, 'post:' + postData.toPid, 'replies')
+ async.apply(db.incrObjectField, 'post:' + postData.toPid, 'replies'),
], next);
}, next);
});
@@ -242,23 +241,23 @@ Upgrade.upgrade = function (callback) {
async.waterfall([
async.apply(db.getObjectField, 'user:' + uid + ':settings', 'userLang'),
function (language, next) {
- ++i;
+ i += 1;
if (!language) {
return setImmediate(next);
}
newLanguage = language.replace('_', '-').replace('@', '-x-');
if (newLanguage !== language) {
- ++j;
+ j += 1;
user.setSetting(uid, 'userLang', newLanguage, next);
} else {
setImmediate(next);
}
- }
+ },
], next);
}, next);
}, next);
- }
+ },
], function (err) {
if (err) {
return next(err);
@@ -297,7 +296,7 @@ Upgrade.upgrade = function (callback) {
async.parallel([
async.apply(db.sortedSetAdd, 'cid:' + topicData.cid + ':tids:pinned', Date.now(), topicData.tid),
async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids', topicData.tid),
- async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids:posts', topicData.tid)
+ async.apply(db.sortedSetRemove, 'cid:' + topicData.cid + ':tids:posts', topicData.tid),
], next);
}, next);
});
@@ -314,17 +313,129 @@ Upgrade.upgrade = function (callback) {
next();
}
},
+ function (next) {
+ thisSchemaDate = Date.UTC(2017, 1, 25);
+ var schemaName = '[2017/2/25] Update global and user sound settings';
+
+ if (schemaDate < thisSchemaDate) {
+ updatesMade = true;
+ winston.verbose(schemaName);
+
+ var meta = require('./meta');
+ var batch = require('./batch');
+
+ var map = {
+ 'notification.mp3': 'Default | Deedle-dum',
+ 'waterdrop-high.mp3': 'Default | Water drop (high)',
+ 'waterdrop-low.mp3': 'Default | Water drop (low)',
+ };
+
+ async.parallel([
+ function (cb) {
+ var keys = ['chat-incoming', 'chat-outgoing', 'notification'];
+
+ db.getObject('settings:sounds', function (err, settings) {
+ if (err || !settings) {
+ return cb(err);
+ }
+
+ keys.forEach(function (key) {
+ if (settings[key] && settings[key].indexOf(' | ') === -1) {
+ settings[key] = map[settings[key]] || '';
+ }
+ });
+
+ meta.configs.setMultiple(settings, cb);
+ });
+ },
+ function (cb) {
+ var keys = ['notificationSound', 'incomingChatSound', 'outgoingChatSound'];
+
+ batch.processSortedSet('users:joindate', function (ids, next) {
+ async.each(ids, function (uid, next) {
+ db.getObject('user:' + uid + ':settings', function (err, settings) {
+ if (err || !settings) {
+ return next(err);
+ }
+ var newSettings = {};
+ keys.forEach(function (key) {
+ if (settings[key] && settings[key].indexOf(' | ') === -1) {
+ newSettings[key] = map[settings[key]] || '';
+ }
+ });
+
+ if (Object.keys(newSettings).length) {
+ db.setObject('user:' + uid + ':settings', newSettings, next);
+ } else {
+ setImmediate(next);
+ }
+ });
+ }, next);
+ }, cb);
+ },
+ ], function (err) {
+ if (err) {
+ return next(err);
+ }
+ winston.info(schemaName + ' - done');
+ Upgrade.update(thisSchemaDate, next);
+ });
+ } else {
+ winston.info(schemaName + ' - skipped!');
+ next();
+ }
+ },
+ function (next) {
+ thisSchemaDate = Date.UTC(2017, 1, 28);
+ var schemaName = '[2017/2/28] Update urls in config to `/assets`';
+
+ if (schemaDate < thisSchemaDate) {
+ updatesMade = true;
+ winston.info(schemaName);
+ async.waterfall([
+ function (cb) {
+ db.getObject('config', cb);
+ },
+ function (config, cb) {
+ if (!config) {
+ return cb();
+ }
+
+ var keys = ['brand:favicon', 'brand:touchicon', 'og:image', 'brand:logo:url', 'defaultAvatar', 'profile:defaultCovers'];
+
+ keys.forEach(function (key) {
+ var oldValue = config[key];
+
+ if (!oldValue || typeof oldValue !== 'string') {
+ return;
+ }
+
+ config[key] = oldValue.replace(/(?:\/assets)?\/(images|uploads)\//g, '/assets/$1/');
+ });
+
+ db.setObject('config', config, cb);
+ },
+ function (next) {
+ winston.info(schemaName + ' - done');
+ Upgrade.update(thisSchemaDate, next);
+ },
+ ], next);
+ } else {
+ winston.info(schemaName + ' - skipped!');
+ next();
+ }
+ },
// Add new schema updates here
// IMPORTANT: REMEMBER TO UPDATE VALUE OF latestSchema IN LINE 24!!!
], function (err) {
if (!err) {
- if(updatesMade) {
+ if (updatesMade) {
winston.info('[upgrade] Schema update complete!');
} else {
winston.info('[upgrade] Schema already up to date!');
}
} else {
- switch(err.message) {
+ switch (err.message) {
case 'upgrade-not-possible':
winston.error('[upgrade] NodeBB upgrade could not complete, as your database schema is too far out of date.');
winston.error('[upgrade] Please ensure that you did not skip any minor version upgrades.');
diff --git a/src/user.js b/src/user.js
index 00e5824690..48098feadf 100644
--- a/src/user.js
+++ b/src/user.js
@@ -6,382 +6,324 @@ var _ = require('underscore');
var groups = require('./groups');
var plugins = require('./plugins');
var db = require('./database');
-var topics = require('./topics');
var privileges = require('./privileges');
var meta = require('./meta');
-(function (User) {
+var User = module.exports;
- User.email = require('./user/email');
- User.notifications = require('./user/notifications');
- User.reset = require('./user/reset');
- User.digest = require('./user/digest');
+User.email = require('./user/email');
+User.notifications = require('./user/notifications');
+User.reset = require('./user/reset');
+User.digest = require('./user/digest');
- require('./user/data')(User);
- require('./user/auth')(User);
- require('./user/bans')(User);
- require('./user/create')(User);
- require('./user/posts')(User);
- require('./user/topics')(User);
- require('./user/categories')(User);
- require('./user/follow')(User);
- require('./user/profile')(User);
- require('./user/admin')(User);
- require('./user/delete')(User);
- require('./user/settings')(User);
- require('./user/search')(User);
- require('./user/jobs')(User);
- require('./user/picture')(User);
- require('./user/approval')(User);
- require('./user/invite')(User);
- require('./user/password')(User);
- require('./user/info')(User);
-
- User.updateLastOnlineTime = function (uid, callback) {
- callback = callback || function () {};
- db.getObjectFields('user:' + uid, ['status', 'lastonline'], function (err, userData) {
- var now = Date.now();
- if (err || userData.status === 'offline' || now - parseInt(userData.lastonline, 10) < 300000) {
- return callback(err);
- }
- User.setUserField(uid, 'lastonline', now, callback);
- });
- };
-
- User.updateOnlineUsers = function (uid, callback) {
- callback = callback || function () {};
+require('./user/data')(User);
+require('./user/auth')(User);
+require('./user/bans')(User);
+require('./user/create')(User);
+require('./user/posts')(User);
+require('./user/topics')(User);
+require('./user/categories')(User);
+require('./user/follow')(User);
+require('./user/profile')(User);
+require('./user/admin')(User);
+require('./user/delete')(User);
+require('./user/settings')(User);
+require('./user/search')(User);
+require('./user/jobs')(User);
+require('./user/picture')(User);
+require('./user/approval')(User);
+require('./user/invite')(User);
+require('./user/password')(User);
+require('./user/info')(User);
+require('./user/online')(User);
+User.getUidsFromSet = function (set, start, stop, callback) {
+ if (set === 'users:online') {
+ var count = parseInt(stop, 10) === -1 ? stop : stop - start + 1;
var now = Date.now();
- async.waterfall([
- function (next) {
- db.sortedSetScore('users:online', uid, next);
- },
- function (userOnlineTime, next) {
- if (now - parseInt(userOnlineTime, 10) < 300000) {
- return callback();
- }
- db.sortedSetAdd('users:online', now, uid, next);
- },
- function (next) {
- topics.pushUnreadCount(uid);
- plugins.fireHook('action:user.online', {uid: uid, timestamp: now});
- next();
- }
- ], callback);
- };
+ db.getSortedSetRevRangeByScore(set, start, count, '+inf', now - 300000, callback);
+ } else {
+ db.getSortedSetRevRange(set, start, stop, callback);
+ }
+};
- User.getUidsFromSet = function (set, start, stop, callback) {
- if (set === 'users:online') {
- var count = parseInt(stop, 10) === -1 ? stop : stop - start + 1;
- var now = Date.now();
- db.getSortedSetRevRangeByScore(set, start, count, '+inf', now - 300000, callback);
- } else {
- db.getSortedSetRevRange(set, start, stop, callback);
- }
- };
+User.getUsersFromSet = function (set, uid, start, stop, callback) {
+ async.waterfall([
+ function (next) {
+ User.getUidsFromSet(set, start, stop, next);
+ },
+ function (uids, next) {
+ User.getUsers(uids, uid, next);
+ },
+ ], callback);
+};
- User.getUsersFromSet = function (set, uid, start, stop, callback) {
- async.waterfall([
- function (next) {
- User.getUidsFromSet(set, start, stop, next);
- },
- function (uids, next) {
- User.getUsers(uids, uid, next);
- }
- ], callback);
- };
-
- User.getUsersWithFields = function (uids, fields, uid, callback) {
- async.waterfall([
- function (next) {
- plugins.fireHook('filter:users.addFields', {fields: fields}, next);
- },
- function (data, next) {
- data.fields = data.fields.filter(function (field, index, array) {
- return array.indexOf(field) === index;
- });
-
- async.parallel({
- userData: function (next) {
- User.getUsersFields(uids, data.fields, next);
- },
- isAdmin: function (next) {
- User.isAdministrator(uids, next);
- }
- }, next);
- },
- function (results, next) {
- results.userData.forEach(function (user, index) {
- if (user) {
- user.status = User.getStatus(user);
- user.administrator = results.isAdmin[index];
- user.banned = parseInt(user.banned, 10) === 1;
- user.banned_until = parseInt(user['banned:expire'], 10) || 0;
- user.banned_until_readable = user.banned_until ? new Date(user.banned_until).toString() : 'Not Banned';
- user['email:confirmed'] = parseInt(user['email:confirmed'], 10) === 1;
- }
- });
- plugins.fireHook('filter:userlist.get', {users: results.userData, uid: uid}, next);
- },
- function (data, next) {
- next(null, data.users);
- }
- ], callback);
- };
-
- User.getUsers = function (uids, uid, callback) {
- var fields = ['uid', 'username', 'userslug', 'picture', 'status', 'flags',
- 'banned', 'banned:expire', 'joindate', 'postcount', 'reputation', 'email:confirmed', 'lastonline'];
-
- User.getUsersWithFields(uids, fields, uid, callback);
- };
-
- User.getStatus = function (userData) {
- var isOnline = (Date.now() - parseInt(userData.lastonline, 10)) < 300000;
- return isOnline ? (userData.status || 'online') : 'offline';
- };
-
- User.isOnline = function (uid, callback) {
- if (Array.isArray(uid)) {
- db.sortedSetScores('users:online', uid, function (err, lastonline) {
- if (err) {
- return callback(err);
- }
- var now = Date.now();
- var isOnline = uid.map(function (uid, index) {
- return now - lastonline[index] < 300000;
- });
- callback(null, isOnline);
+User.getUsersWithFields = function (uids, fields, uid, callback) {
+ async.waterfall([
+ function (next) {
+ plugins.fireHook('filter:users.addFields', { fields: fields }, next);
+ },
+ function (data, next) {
+ data.fields = data.fields.filter(function (field, index, array) {
+ return array.indexOf(field) === index;
});
- } else {
- db.sortedSetScore('users:online', uid, function (err, lastonline) {
- if (err) {
- return callback(err);
+
+ async.parallel({
+ userData: function (next) {
+ User.getUsersFields(uids, data.fields, next);
+ },
+ isAdmin: function (next) {
+ User.isAdministrator(uids, next);
+ },
+ }, next);
+ },
+ function (results, next) {
+ results.userData.forEach(function (user, index) {
+ if (user) {
+ user.status = User.getStatus(user);
+ user.administrator = results.isAdmin[index];
+ user.banned = parseInt(user.banned, 10) === 1;
+ user.banned_until = parseInt(user['banned:expire'], 10) || 0;
+ user.banned_until_readable = user.banned_until ? new Date(user.banned_until).toString() : 'Not Banned';
+ user['email:confirmed'] = parseInt(user['email:confirmed'], 10) === 1;
}
- var isOnline = Date.now() - parseInt(lastonline, 10) < 300000;
- callback(null, isOnline);
});
- }
+ plugins.fireHook('filter:userlist.get', { users: results.userData, uid: uid }, next);
+ },
+ function (data, next) {
+ next(null, data.users);
+ },
+ ], callback);
+};
- };
+User.getUsers = function (uids, uid, callback) {
+ var fields = ['uid', 'username', 'userslug', 'picture', 'status', 'flags',
+ 'banned', 'banned:expire', 'joindate', 'postcount', 'reputation', 'email:confirmed', 'lastonline'];
- User.exists = function (uid, callback) {
- db.isSortedSetMember('users:joindate', uid, callback);
- };
+ User.getUsersWithFields(uids, fields, uid, callback);
+};
- User.existsBySlug = function (userslug, callback) {
- User.getUidByUserslug(userslug, function (err, exists) {
- callback(err, !! exists);
- });
- };
+User.getStatus = function (userData) {
+ var isOnline = (Date.now() - parseInt(userData.lastonline, 10)) < 300000;
+ return isOnline ? (userData.status || 'online') : 'offline';
+};
- User.getUidByUsername = function (username, callback) {
- if (!username) {
- return callback(null, 0);
- }
- db.sortedSetScore('username:uid', username, callback);
- };
+User.exists = function (uid, callback) {
+ db.isSortedSetMember('users:joindate', uid, callback);
+};
- User.getUidsByUsernames = function (usernames, callback) {
- db.sortedSetScores('username:uid', usernames, callback);
- };
+User.existsBySlug = function (userslug, callback) {
+ User.getUidByUserslug(userslug, function (err, exists) {
+ callback(err, !!exists);
+ });
+};
- User.getUidByUserslug = function (userslug, callback) {
- if (!userslug) {
- return callback(null, 0);
- }
- db.sortedSetScore('userslug:uid', userslug, callback);
- };
+User.getUidByUsername = function (username, callback) {
+ if (!username) {
+ return callback(null, 0);
+ }
+ db.sortedSetScore('username:uid', username, callback);
+};
- User.getUsernamesByUids = function (uids, callback) {
- User.getUsersFields(uids, ['username'], function (err, users) {
- if (err) {
- return callback(err);
- }
+User.getUidsByUsernames = function (usernames, callback) {
+ db.sortedSetScores('username:uid', usernames, callback);
+};
+User.getUidByUserslug = function (userslug, callback) {
+ if (!userslug) {
+ return callback(null, 0);
+ }
+ db.sortedSetScore('userslug:uid', userslug, callback);
+};
+
+User.getUsernamesByUids = function (uids, callback) {
+ async.waterfall([
+ function (next) {
+ User.getUsersFields(uids, ['username'], next);
+ },
+ function (users, next) {
users = users.map(function (user) {
return user.username;
});
- callback(null, users);
- });
- };
+ next(null, users);
+ },
+ ], callback);
+};
- User.getUsernameByUserslug = function (slug, callback) {
- async.waterfall([
- function (next) {
- User.getUidByUserslug(slug, next);
- },
- function (uid, next) {
- User.getUserField(uid, 'username', next);
+User.getUsernameByUserslug = function (slug, callback) {
+ async.waterfall([
+ function (next) {
+ User.getUidByUserslug(slug, next);
+ },
+ function (uid, next) {
+ User.getUserField(uid, 'username', next);
+ },
+ ], callback);
+};
+
+User.getUidByEmail = function (email, callback) {
+ db.sortedSetScore('email:uid', email.toLowerCase(), callback);
+};
+
+User.getUidsByEmails = function (emails, callback) {
+ emails = emails.map(function (email) {
+ return email && email.toLowerCase();
+ });
+ db.sortedSetScores('email:uid', emails, callback);
+};
+
+User.getUsernameByEmail = function (email, callback) {
+ async.waterfall([
+ function (next) {
+ db.sortedSetScore('email:uid', email.toLowerCase(), next);
+ },
+ function (uid, next) {
+ User.getUserField(uid, 'username', next);
+ },
+ ], callback);
+};
+
+User.isModerator = function (uid, cid, callback) {
+ privileges.users.isModerator(uid, cid, callback);
+};
+
+User.isModeratorOfAnyCategory = function (uid, callback) {
+ User.getModeratedCids(uid, function (err, cids) {
+ callback(err, Array.isArray(cids) ? !!cids.length : false);
+ });
+};
+
+User.isAdministrator = function (uid, callback) {
+ privileges.users.isAdministrator(uid, callback);
+};
+
+User.isGlobalModerator = function (uid, callback) {
+ privileges.users.isGlobalModerator(uid, callback);
+};
+
+User.isAdminOrGlobalMod = function (uid, callback) {
+ async.parallel({
+ isAdmin: async.apply(User.isAdministrator, uid),
+ isGlobalMod: async.apply(User.isGlobalModerator, uid),
+ }, function (err, results) {
+ callback(err, results ? (results.isAdmin || results.isGlobalMod) : false);
+ });
+};
+
+User.isAdminOrSelf = function (callerUid, uid, callback) {
+ isSelfOrMethod(callerUid, uid, User.isAdministrator, callback);
+};
+
+User.isAdminOrGlobalModOrSelf = function (callerUid, uid, callback) {
+ isSelfOrMethod(callerUid, uid, User.isAdminOrGlobalMod, callback);
+};
+
+function isSelfOrMethod(callerUid, uid, method, callback) {
+ if (parseInt(callerUid, 10) === parseInt(uid, 10)) {
+ return callback();
+ }
+ async.waterfall([
+ function (next) {
+ method(callerUid, next);
+ },
+ function (isPass, next) {
+ if (!isPass) {
+ return next(new Error('[[error:no-privileges]]'));
}
- ], callback);
- };
+ next();
+ },
+ ], callback);
+}
- User.getUidByEmail = function (email, callback) {
- db.sortedSetScore('email:uid', email.toLowerCase(), callback);
- };
+User.getAdminsandGlobalMods = function (callback) {
+ async.waterfall([
+ function (next) {
+ async.parallel([
+ async.apply(groups.getMembers, 'administrators', 0, -1),
+ async.apply(groups.getMembers, 'Global Moderators', 0, -1),
+ ], next);
+ },
+ function (results, next) {
+ User.getUsersData(_.union(results), next);
+ },
+ ], callback);
+};
- User.getUidsByEmails = function (emails, callback) {
- emails = emails.map(function (email) {
- return email && email.toLowerCase();
- });
- db.sortedSetScores('email:uid', emails, callback);
- };
+User.getAdminsandGlobalModsandModerators = function (callback) {
+ async.waterfall([
+ function (next) {
+ async.parallel([
+ async.apply(groups.getMembers, 'administrators', 0, -1),
+ async.apply(groups.getMembers, 'Global Moderators', 0, -1),
+ async.apply(User.getModeratorUids),
+ ], next);
+ },
+ function (results, next) {
+ User.getUsersData(_.union.apply(_, results), next);
+ },
+ ], callback);
+};
- User.getUsernameByEmail = function (email, callback) {
- db.sortedSetScore('email:uid', email.toLowerCase(), function (err, uid) {
- if (err) {
- return callback(err);
- }
- User.getUserField(uid, 'username', callback);
- });
- };
-
- User.isModerator = function (uid, cid, callback) {
- privileges.users.isModerator(uid, cid, callback);
- };
-
- User.isModeratorOfAnyCategory = function (uid, callback) {
- User.getModeratedCids(uid, function (err, cids) {
- callback(err, Array.isArray(cids) ? !!cids.length : false);
- });
- };
-
- User.isAdministrator = function (uid, callback) {
- privileges.users.isAdministrator(uid, callback);
- };
-
- User.isGlobalModerator = function (uid, callback) {
- privileges.users.isGlobalModerator(uid, callback);
- };
-
- User.isAdminOrGlobalMod = function (uid, callback) {
- async.parallel({
- isAdmin: async.apply(User.isAdministrator, uid),
- isGlobalMod: async.apply(User.isGlobalModerator, uid)
- }, function (err, results) {
- callback(err, results ? (results.isAdmin || results.isGlobalMod) : false);
- });
- };
-
- User.isAdminOrSelf = function (callerUid, uid, callback) {
- if (parseInt(callerUid, 10) === parseInt(uid, 10)) {
- return callback();
- }
- User.isAdministrator(callerUid, function (err, isAdmin) {
- if (err || !isAdmin) {
- return callback(err || new Error('[[error:no-privileges]]'));
- }
- callback();
- });
- };
-
- User.isAdminOrGlobalModOrSelf = function (callerUid, uid, callback) {
- if (parseInt(callerUid, 10) === parseInt(uid, 10)) {
- return callback();
- }
- User.isAdminOrGlobalMod(callerUid, function (err, isAdminOrGlobalMod) {
- if (err || !isAdminOrGlobalMod) {
- return callback(err || new Error('[[error:no-privileges]]'));
- }
- callback();
- });
- };
-
- User.getAdminsandGlobalMods = function (callback) {
- async.parallel({
- admins: async.apply(groups.getMembers, 'administrators', 0, -1),
- mods: async.apply(groups.getMembers, 'Global Moderators', 0, -1)
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
- var uids = results.admins.concat(results.mods).filter(function (uid, index, array) {
- return uid && array.indexOf(uid) === index;
+User.getModeratorUids = function (callback) {
+ async.waterfall([
+ async.apply(db.getSortedSetRange, 'categories:cid', 0, -1),
+ function (cids, next) {
+ var groupNames = cids.map(function (cid) {
+ return 'cid:' + cid + ':privileges:mods';
});
- User.getUsersData(uids, callback);
- });
- };
- User.getAdminsandGlobalModsandModerators = function (callback) {
- async.parallel([
- async.apply(groups.getMembers, 'administrators', 0, -1),
- async.apply(groups.getMembers, 'Global Moderators', 0, -1),
- async.apply(User.getModeratorUids)
- ], function (err, results) {
- if (err) {
- return callback(err);
- }
+ groups.getMembersOfGroups(groupNames, next);
+ },
+ function (memberSets, next) {
+ next(null, _.union.apply(_, memberSets));
+ },
+ ], callback);
+};
- User.getUsersData(_.union.apply(_, results), callback);
- });
- };
+User.getModeratedCids = function (uid, callback) {
+ var cids;
+ async.waterfall([
+ function (next) {
+ db.getSortedSetRange('categories:cid', 0, -1, next);
+ },
+ function (_cids, next) {
+ cids = _cids;
+ User.isModerator(uid, cids, next);
+ },
+ function (isMods, next) {
+ cids = cids.filter(function (cid, index) {
+ return cid && isMods[index];
+ });
+ next(null, cids);
+ },
+ ], callback);
+};
- User.getModeratorUids = function (callback) {
- async.waterfall([
- async.apply(db.getSortedSetRange, 'categories:cid', 0, -1),
- function (cids, next) {
- var groupNames = cids.map(function (cid) {
- return 'cid:' + cid + ':privileges:mods';
- });
-
- groups.getMembersOfGroups(groupNames, function (err, memberSets) {
- if (err) {
- return next(err);
- }
-
- next(null, _.union.apply(_, memberSets));
- });
- }
- ], callback);
- };
-
- User.getModeratedCids = function (uid, callback) {
- var cids;
- async.waterfall([
- function (next) {
- db.getSortedSetRange('categories:cid', 0, -1, next);
- },
- function (_cids, next) {
- cids = _cids;
- User.isModerator(uid, cids, next);
- },
- function (isMods, next) {
- cids = cids.filter(function (cid, index) {
- return cid && isMods[index];
- });
- next(null, cids);
- }
- ], callback);
- };
-
- User.addInterstitials = function (callback) {
- plugins.registerHook('core', {
- hook: 'filter:register.interstitial',
- method: function (data, callback) {
- if (meta.config.termsOfUse && !data.userData.acceptTos) {
- data.interstitials.push({
- template: 'partials/acceptTos',
- data: {
- termsOfUse: meta.config.termsOfUse
- },
- callback: function (userData, formData, next) {
- if (formData['agree-terms'] === 'on') {
- userData.acceptTos = true;
- }
-
- next(userData.acceptTos ? null : new Error('[[register:terms_of_use_error]]'));
+User.addInterstitials = function (callback) {
+ plugins.registerHook('core', {
+ hook: 'filter:register.interstitial',
+ method: function (data, callback) {
+ if (meta.config.termsOfUse && !data.userData.acceptTos) {
+ data.interstitials.push({
+ template: 'partials/acceptTos',
+ data: {
+ termsOfUse: meta.config.termsOfUse,
+ },
+ callback: function (userData, formData, next) {
+ if (formData['agree-terms'] === 'on') {
+ userData.acceptTos = true;
}
- });
- }
- callback(null, data);
+ next(userData.acceptTos ? null : new Error('[[register:terms_of_use_error]]'));
+ },
+ });
}
- });
- callback();
- };
+ callback(null, data);
+ },
+ });
+ callback();
+};
-}(exports));
diff --git a/src/user/admin.js b/src/user/admin.js
index 8b5a6ebef4..1d6cd8c7ad 100644
--- a/src/user/admin.js
+++ b/src/user/admin.js
@@ -8,7 +8,6 @@ var plugins = require('../plugins');
var winston = require('winston');
module.exports = function (User) {
-
User.logIP = function (uid, ip) {
var now = Date.now();
db.sortedSetAdd('uid:' + uid + ':ip', now, ip || 'Unknown');
@@ -18,13 +17,7 @@ module.exports = function (User) {
};
User.getIPs = function (uid, stop, callback) {
- db.getSortedSetRevRange('uid:' + uid + ':ip', 0, stop, function (err, ips) {
- if (err) {
- return callback(err);
- }
-
- callback(null, ips);
- });
+ db.getSortedSetRevRange('uid:' + uid + ':ip', 0, stop, callback);
};
User.getUsersCSV = function (callback) {
@@ -39,7 +32,7 @@ module.exports = function (User) {
uids = users.map(function (user) {
return user.score;
});
- plugins.fireHook('filter:user.csvFields', {fields: ['uid', 'email', 'username']}, next);
+ plugins.fireHook('filter:user.csvFields', { fields: ['uid', 'email', 'username'] }, next);
},
function (data, next) {
User.getUsersFields(uids, data.fields, next);
@@ -52,7 +45,7 @@ module.exports = function (User) {
});
next(null, csvContent);
- }
+ },
], callback);
};
diff --git a/src/user/approval.js b/src/user/approval.js
index 2f9d9f847a..cbb1ba08b4 100644
--- a/src/user/approval.js
+++ b/src/user/approval.js
@@ -14,7 +14,6 @@ var utils = require('../../public/src/utils');
var plugins = require('../plugins');
module.exports = function (User) {
-
User.addToApprovalQueue = function (userData, callback) {
userData.userslug = utils.slugify(userData.username);
async.waterfall([
@@ -29,9 +28,9 @@ module.exports = function (User) {
username: userData.username,
email: userData.email,
ip: userData.ip,
- hashedPassword: hashedPassword
+ hashedPassword: hashedPassword,
};
- plugins.fireHook('filter:user.addToApprovalQueue', {data: data, userData: userData}, next);
+ plugins.fireHook('filter:user.addToApprovalQueue', { data: data, userData: userData }, next);
},
function (results, next) {
db.setObject('registration:queue:name:' + userData.username, results.data, next);
@@ -41,7 +40,7 @@ module.exports = function (User) {
},
function (next) {
sendNotificationToAdmins(userData.username, next);
- }
+ },
], callback);
};
@@ -52,12 +51,12 @@ module.exports = function (User) {
bodyShort: '[[notifications:new_register, ' + username + ']]',
nid: 'new_register:' + username,
path: '/admin/manage/registration',
- mergeId: 'new_register'
+ mergeId: 'new_register',
}, next);
},
function (notification, next) {
notifications.pushGroup(notification, 'administrators', next);
- }
+ },
], callback);
}
@@ -93,7 +92,7 @@ module.exports = function (User) {
username: username,
subject: subject,
template: 'registration_accepted',
- uid: uid
+ uid: uid,
};
emailer.send('registration_accepted', uid, data, next);
@@ -101,7 +100,7 @@ module.exports = function (User) {
},
function (next) {
next(null, uid);
- }
+ },
], callback);
};
@@ -115,7 +114,7 @@ module.exports = function (User) {
async.each(uids, function (uid, next) {
notifications.markRead(nid, uid, next);
}, next);
- }
+ },
], callback);
}
@@ -126,14 +125,14 @@ module.exports = function (User) {
},
function (next) {
markNotificationRead(username, next);
- }
+ },
], callback);
};
function removeFromQueue(username, callback) {
async.parallel([
async.apply(db.sortedSetRemove, 'registration:queue', username),
- async.apply(db.delete, 'registration:queue:name:' + username)
+ async.apply(db.delete, 'registration:queue:name:' + username),
], function (err) {
callback(err);
});
@@ -191,7 +190,7 @@ module.exports = function (User) {
'&email=' + encodeURIComponent(user.email) +
'&username=' + encodeURIComponent(user.username) +
'&f=json',
- json: true
+ json: true,
}, function (err, response, body) {
if (err) {
return next();
@@ -205,20 +204,18 @@ module.exports = function (User) {
next();
});
- }
+ },
], function (err) {
next(err, user);
});
}, next);
},
function (users, next) {
- plugins.fireHook('filter:user.getRegistrationQueue', {users: users}, next);
+ plugins.fireHook('filter:user.getRegistrationQueue', { users: users }, next);
},
function (results, next) {
next(null, results.users);
- }
+ },
], callback);
};
-
-
};
diff --git a/src/user/auth.js b/src/user/auth.js
index 219c468304..29a79f39c4 100644
--- a/src/user/auth.js
+++ b/src/user/auth.js
@@ -37,10 +37,10 @@ module.exports = function (User) {
events.log({
type: 'account-locked',
uid: uid,
- ip: ip
+ ip: ip,
});
next(new Error('[[error:account-locked]]'));
- }
+ },
], callback);
};
@@ -51,7 +51,7 @@ module.exports = function (User) {
User.auth.resetLockout = function (uid, callback) {
async.parallel([
async.apply(db.delete, 'loginAttempts:' + uid),
- async.apply(db.delete, 'lockout:' + uid)
+ async.apply(db.delete, 'lockout:' + uid),
], callback);
};
@@ -78,8 +78,8 @@ module.exports = function (User) {
});
// Revoke any sessions that have expired, return filtered list
- var expiredSids = [],
- expired;
+ var expiredSids = [];
+ var expired;
sessions = sessions.filter(function (sessionObj, idx) {
expired = !sessionObj || !sessionObj.hasOwnProperty('passport') ||
@@ -98,7 +98,7 @@ module.exports = function (User) {
}, function (err) {
next(err, sessions);
});
- }
+ },
], function (err, sessions) {
callback(err, sessions ? sessions.map(function (sessObj) {
sessObj.meta.datetimeISO = new Date(sessObj.meta.datetime).toISOString();
@@ -128,7 +128,7 @@ module.exports = function (User) {
}
},
async.apply(db.sortedSetRemove, 'uid:' + uid + ':sessions', sessionId),
- async.apply(db.sessionStore.destroy.bind(db.sessionStore), sessionId)
+ async.apply(db.sessionStore.destroy.bind(db.sessionStore), sessionId),
], callback);
});
};
@@ -140,14 +140,13 @@ module.exports = function (User) {
async.each(sids, function (sid, next) {
User.auth.revokeSession(sid, uid, next);
}, next);
- }
+ },
], callback);
};
User.auth.deleteAllSessions = function (callback) {
var _ = require('underscore');
batch.processSortedSet('users:joindate', function (uids, next) {
-
var sessionKeys = uids.map(function (uid) {
return 'uid:' + uid + ':sessions';
});
@@ -169,10 +168,10 @@ module.exports = function (User) {
async.each(sids, function (sid, next) {
db.sessionStore.destroy(sid, next);
}, next);
- }
+ },
], next);
- }
+ },
], next);
- }, {batch: 1000}, callback);
+ }, { batch: 1000 }, callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/user/bans.js b/src/user/bans.js
index 8667641c46..dc70d012dd 100644
--- a/src/user/bans.js
+++ b/src/user/bans.js
@@ -1,8 +1,8 @@
'use strict';
var async = require('async');
+
var db = require('../database');
-var plugins = require('../plugins');
module.exports = function (User) {
User.ban = function (uid, until, reason, callback) {
@@ -27,7 +27,7 @@ module.exports = function (User) {
var tasks = [
async.apply(User.setUserField, uid, 'banned', 1),
async.apply(db.sortedSetAdd, 'users:banned', now, uid),
- async.apply(db.sortedSetAdd, 'uid:' + uid + ':bans', now, until)
+ async.apply(db.sortedSetAdd, 'uid:' + uid + ':bans', now, until),
];
if (until > 0 && now < until) {
@@ -49,11 +49,11 @@ module.exports = function (User) {
User.unban = function (uid, callback) {
async.waterfall([
function (next) {
- User.setUserFields(uid, {banned: 0, 'banned:expire': 0}, next);
+ User.setUserFields(uid, { banned: 0, 'banned:expire': 0 }, next);
},
function (next) {
db.sortedSetsRemove(['users:banned', 'users:banned:expire'], uid, next);
- }
+ },
], callback);
};
@@ -75,11 +75,11 @@ module.exports = function (User) {
async.parallel([
async.apply(db.sortedSetRemove.bind(db), 'users:banned:expire', uid),
async.apply(db.sortedSetRemove.bind(db), 'users:banned', uid),
- async.apply(User.setUserFields, uid, {banned:0, 'banned:expire': 0})
+ async.apply(User.setUserFields, uid, { banned: 0, 'banned:expire': 0 }),
], function (err) {
next(err, false);
});
- }
+ },
], callback);
};
diff --git a/src/user/categories.js b/src/user/categories.js
index fee8fc8bb0..8a4b26199f 100644
--- a/src/user/categories.js
+++ b/src/user/categories.js
@@ -6,7 +6,6 @@ var db = require('../database');
var categories = require('../categories');
module.exports = function (User) {
-
User.getIgnoredCategories = function (uid, callback) {
db.getSortedSetRange('uid:' + uid + ':ignored:cids', 0, -1, callback);
};
@@ -18,7 +17,7 @@ module.exports = function (User) {
},
all: function (next) {
db.getSortedSetRange('categories:cid', 0, -1, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -48,7 +47,7 @@ module.exports = function (User) {
},
function (next) {
db.sortedSetAdd('cid:' + cid + ':ignorers', Date.now(), uid, next);
- }
+ },
], callback);
};
@@ -69,7 +68,7 @@ module.exports = function (User) {
},
function (next) {
db.sortedSetRemove('cid:' + cid + ':ignorers', uid, next);
- }
+ },
], callback);
};
-};
\ No newline at end of file
+};
diff --git a/src/user/create.js b/src/user/create.js
index 67d6baf3cd..2620cb67d3 100644
--- a/src/user/create.js
+++ b/src/user/create.js
@@ -9,7 +9,6 @@ var groups = require('../groups');
var meta = require('../meta');
module.exports = function (User) {
-
User.create = function (data, callback) {
data.username = data.username.trim();
data.userslug = utils.slugify(data.username);
@@ -18,31 +17,31 @@ module.exports = function (User) {
}
User.isDataValid(data, function (err) {
- if (err) {
+ if (err) {
return callback(err);
}
var timestamp = data.timestamp || Date.now();
var userData = {
- 'username': data.username,
- 'userslug': data.userslug,
- 'email': data.email || '',
- 'joindate': timestamp,
- 'lastonline': timestamp,
- 'picture': '',
- 'fullname': data.fullname || '',
- 'location': '',
- 'birthday': '',
- 'website': '',
- 'signature': '',
- 'uploadedpicture': '',
- 'profileviews': 0,
- 'reputation': 0,
- 'postcount': 0,
- 'topiccount': 0,
- 'lastposttime': 0,
- 'banned': 0,
- 'status': 'online'
+ username: data.username,
+ userslug: data.userslug,
+ email: data.email || '',
+ joindate: timestamp,
+ lastonline: timestamp,
+ picture: '',
+ fullname: data.fullname || '',
+ location: '',
+ birthday: '',
+ website: '',
+ signature: '',
+ uploadedpicture: '',
+ profileviews: 0,
+ reputation: 0,
+ postcount: 0,
+ topiccount: 0,
+ lastposttime: 0,
+ banned: 0,
+ status: 'online',
};
async.parallel({
@@ -50,8 +49,8 @@ module.exports = function (User) {
renameUsername(userData, next);
},
userData: function (next) {
- plugins.fireHook('filter:user.create', {user: userData, data: data}, next);
- }
+ plugins.fireHook('filter:user.create', { user: userData, data: data }, next);
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -106,7 +105,7 @@ module.exports = function (User) {
if (userData.email) {
async.parallel([
async.apply(db.sortedSetAdd, 'email:uid', userData.uid, userData.email.toLowerCase()),
- async.apply(db.sortedSetAdd, 'email:sorted', 0, userData.email.toLowerCase() + ':' + userData.uid)
+ async.apply(db.sortedSetAdd, 'email:sorted', 0, userData.email.toLowerCase() + ':' + userData.uid),
], next);
if (parseInt(userData.uid, 10) !== 1 && parseInt(meta.config.requireEmailConfirmation, 10) === 1) {
@@ -128,13 +127,13 @@ module.exports = function (User) {
async.parallel([
async.apply(User.setUserField, userData.uid, 'password', hash),
- async.apply(User.reset.updateExpiry, userData.uid)
+ async.apply(User.reset.updateExpiry, userData.uid),
], next);
});
},
function (next) {
User.updateDigestSetting(userData.uid, meta.config.dailyDigestFreq, next);
- }
+ },
], next);
},
function (results, next) {
@@ -143,7 +142,7 @@ module.exports = function (User) {
}
plugins.fireHook('action:user.create', userData);
next(null, userData.uid);
- }
+ },
], callback);
});
});
@@ -179,7 +178,7 @@ module.exports = function (User) {
} else {
next();
}
- }
+ },
}, function (err) {
callback(err);
});
@@ -225,5 +224,4 @@ module.exports = function (User) {
});
});
}
-
};
diff --git a/src/user/data.js b/src/user/data.js
index cbaf066ded..120da7e3a2 100644
--- a/src/user/data.js
+++ b/src/user/data.js
@@ -1,5 +1,6 @@
'use strict';
+var async = require('async');
var validator = require('validator');
var nconf = require('nconf');
var winston = require('winston');
@@ -9,7 +10,6 @@ var plugins = require('../plugins');
var utils = require('../../public/src/utils');
module.exports = function (User) {
-
var iconBackgrounds = ['#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3',
'#009688', '#1b5e20', '#33691e', '#827717', '#e65100', '#ff5722', '#795548', '#607d8b'];
@@ -55,13 +55,14 @@ module.exports = function (User) {
addField('lastonline');
}
- db.getObjectsFields(keys, fields, function (err, users) {
- if (err) {
- return callback(err);
- }
-
- modifyUserData(users, fieldsToRemove, callback);
- });
+ async.waterfall([
+ function (next) {
+ db.getObjectsFields(keys, fields, next);
+ },
+ function (users, next) {
+ modifyUserData(users, fieldsToRemove, next);
+ },
+ ], callback);
};
User.getMultipleUserFields = function (uids, fields, callback) {
@@ -84,13 +85,14 @@ module.exports = function (User) {
return 'user:' + uid;
});
- db.getObjects(keys, function (err, users) {
- if (err) {
- return callback(err);
- }
-
- modifyUserData(users, [], callback);
- });
+ async.waterfall([
+ function (next) {
+ db.getObjects(keys, next);
+ },
+ function (users, next) {
+ modifyUserData(users, [], next);
+ },
+ ], callback);
};
function modifyUserData(users, fieldsToRemove, callback) {
@@ -117,7 +119,8 @@ module.exports = function (User) {
}
if (user.picture && user.picture === user.uploadedpicture) {
- user.picture = user.uploadedpicture = user.picture.startsWith('http') ? user.picture : nconf.get('relative_path') + user.picture;
+ user.uploadedpicture = user.picture.startsWith('http') ? user.picture : nconf.get('relative_path') + user.picture;
+ user.picture = user.uploadedpicture;
} else if (user.uploadedpicture) {
user.uploadedpicture = user.uploadedpicture.startsWith('http') ? user.uploadedpicture : nconf.get('relative_path') + user.uploadedpicture;
}
@@ -126,7 +129,7 @@ module.exports = function (User) {
user.status = User.getStatus(user);
}
- for(var i = 0; i < fieldsToRemove.length; ++i) {
+ for (var i = 0; i < fieldsToRemove.length; i += 1) {
user[fieldsToRemove[i]] = undefined;
}
@@ -152,52 +155,53 @@ module.exports = function (User) {
User.setUserField = function (uid, field, value, callback) {
callback = callback || function () {};
- db.setObjectField('user:' + uid, field, value, function (err) {
- if (err) {
- return callback(err);
- }
- plugins.fireHook('action:user.set', {uid: uid, field: field, value: value, type: 'set'});
- callback();
- });
+ async.waterfall([
+ function (next) {
+ db.setObjectField('user:' + uid, field, value, next);
+ },
+ function (next) {
+ plugins.fireHook('action:user.set', { uid: uid, field: field, value: value, type: 'set' });
+ next();
+ },
+ ], callback);
};
User.setUserFields = function (uid, data, callback) {
callback = callback || function () {};
- db.setObject('user:' + uid, data, function (err) {
- if (err) {
- return callback(err);
- }
- for (var field in data) {
- if (data.hasOwnProperty(field)) {
- plugins.fireHook('action:user.set', {uid: uid, field: field, value: data[field], type: 'set'});
+ async.waterfall([
+ function (next) {
+ db.setObject('user:' + uid, data, next);
+ },
+ function (next) {
+ for (var field in data) {
+ if (data.hasOwnProperty(field)) {
+ plugins.fireHook('action:user.set', { uid: uid, field: field, value: data[field], type: 'set' });
+ }
}
- }
- callback();
- });
+ next();
+ },
+ ], callback);
};
User.incrementUserFieldBy = function (uid, field, value, callback) {
- callback = callback || function () {};
- db.incrObjectFieldBy('user:' + uid, field, value, function (err, value) {
- if (err) {
- return callback(err);
- }
- plugins.fireHook('action:user.set', {uid: uid, field: field, value: value, type: 'increment'});
-
- callback(null, value);
- });
+ incrDecrUserFieldBy(uid, field, value, 'increment', callback);
};
User.decrementUserFieldBy = function (uid, field, value, callback) {
- callback = callback || function () {};
- db.incrObjectFieldBy('user:' + uid, field, -value, function (err, value) {
- if (err) {
- return callback(err);
- }
- plugins.fireHook('action:user.set', {uid: uid, field: field, value: value, type: 'decrement'});
-
- callback(null, value);
- });
+ incrDecrUserFieldBy(uid, field, -value, 'decrement', callback);
};
+ function incrDecrUserFieldBy(uid, field, value, type, callback) {
+ callback = callback || function () {};
+ async.waterfall([
+ function (next) {
+ db.incrObjectFieldBy('user:' + uid, field, value, next);
+ },
+ function (value, next) {
+ plugins.fireHook('action:user.set', { uid: uid, field: field, value: value, type: type });
+
+ next(null, value);
+ },
+ ], callback);
+ }
};
diff --git a/src/user/delete.js b/src/user/delete.js
index e648c5dfb0..7392192c8b 100644
--- a/src/user/delete.js
+++ b/src/user/delete.js
@@ -10,7 +10,6 @@ var plugins = require('../plugins');
var batch = require('../batch');
module.exports = function (User) {
-
User.delete = function (callerUid, uid, callback) {
if (!parseInt(uid, 10)) {
return callback(new Error('[[error:invalid-uid]]'));
@@ -25,7 +24,7 @@ module.exports = function (User) {
},
function (next) {
User.deleteAccount(uid, next);
- }
+ },
], callback);
};
@@ -34,7 +33,7 @@ module.exports = function (User) {
async.eachSeries(ids, function (pid, next) {
posts.purge(pid, callerUid, next);
}, next);
- }, {alwaysStartAt: 0}, callback);
+ }, { alwaysStartAt: 0 }, callback);
}
function deleteTopics(callerUid, uid, callback) {
@@ -42,7 +41,7 @@ module.exports = function (User) {
async.eachSeries(ids, function (tid, next) {
topics.purge(tid, callerUid, next);
}, next);
- }, {alwaysStartAt: 0}, callback);
+ }, { alwaysStartAt: 0 }, callback);
}
User.deleteAccount = function (uid, callback) {
@@ -57,9 +56,9 @@ module.exports = function (User) {
}
User.getUserFields(uid, ['username', 'userslug', 'fullname', 'email'], next);
},
- function (_userData, next) {
+ function (_userData, next) {
userData = _userData;
- plugins.fireHook('static:user.delete', {uid: uid}, next);
+ plugins.fireHook('static:user.delete', { uid: uid }, next);
},
function (next) {
deleteVotes(uid, next);
@@ -88,7 +87,7 @@ module.exports = function (User) {
if (userData.email) {
async.parallel([
async.apply(db.sortedSetRemove, 'email:uid', userData.email.toLowerCase()),
- async.apply(db.sortedSetRemove, 'email:sorted', userData.email.toLowerCase() + ':' + uid)
+ async.apply(db.sortedSetRemove, 'email:sorted', userData.email.toLowerCase() + ':' + uid),
], next);
} else {
next();
@@ -104,7 +103,7 @@ module.exports = function (User) {
'users:notvalidated',
'digest:day:uids',
'digest:week:uids',
- 'digest:month:uids'
+ 'digest:month:uids',
], uid, next);
},
function (next) {
@@ -123,7 +122,7 @@ module.exports = function (User) {
'uid:' + uid + ':chat:rooms', 'uid:' + uid + ':chat:rooms:unread',
'uid:' + uid + ':upvote', 'uid:' + uid + ':downvote',
'uid:' + uid + ':ignored:cids', 'uid:' + uid + ':flag:pids',
- 'uid:' + uid + ':sessions', 'uid:' + uid + ':sessionUUID:sessionId'
+ 'uid:' + uid + ':sessions', 'uid:' + uid + ':sessionUUID:sessionId',
];
db.deleteAll(keys, next);
},
@@ -135,12 +134,12 @@ module.exports = function (User) {
},
function (next) {
groups.leaveAllGroups(uid, next);
- }
+ },
], next);
},
function (results, next) {
db.deleteAll(['followers:' + uid, 'following:' + uid, 'user:' + uid], next);
- }
+ },
], callback);
};
@@ -149,7 +148,7 @@ module.exports = function (User) {
function (next) {
async.parallel({
upvotedPids: async.apply(db.getSortedSetRange, 'uid:' + uid + ':upvote', 0, -1),
- downvotedPids: async.apply(db.getSortedSetRange, 'uid:' + uid + ':downvote', 0, -1)
+ downvotedPids: async.apply(db.getSortedSetRange, 'uid:' + uid + ':downvote', 0, -1),
}, next);
},
function (pids, next) {
@@ -160,7 +159,7 @@ module.exports = function (User) {
async.eachSeries(pids, function (pid, next) {
posts.unvote(pid, uid, next);
}, next);
- }
+ },
], function (err) {
callback(err);
});
@@ -181,9 +180,9 @@ module.exports = function (User) {
async.parallel([
async.apply(db.sortedSetsRemove, roomKeys, uid),
- async.apply(db.deleteAll, userKeys)
+ async.apply(db.deleteAll, userKeys),
], next);
- }
+ },
], function (err) {
callback(err);
});
@@ -202,14 +201,14 @@ module.exports = function (User) {
},
function (next) {
db.delete('uid:' + uid + ':ip', next);
- }
+ },
], callback);
}
function deleteUserFromFollowers(uid, callback) {
async.parallel({
followers: async.apply(db.getSortedSetRange, 'followers:' + uid, 0, -1),
- following: async.apply(db.getSortedSetRange, 'following:' + uid, 0, -1)
+ following: async.apply(db.getSortedSetRange, 'following:' + uid, 0, -1),
}, function (err, results) {
function updateCount(uids, name, fieldName, next) {
async.each(uids, function (uid, next) {
@@ -238,7 +237,7 @@ module.exports = function (User) {
async.parallel([
async.apply(db.sortedSetsRemove, followerSets.concat(followingSets), uid),
async.apply(updateCount, results.following, 'followers:', 'followerCount'),
- async.apply(updateCount, results.followers, 'following:', 'followingCount')
+ async.apply(updateCount, results.followers, 'following:', 'followingCount'),
], callback);
});
}
diff --git a/src/user/digest.js b/src/user/digest.js
index 9c86aca26d..73cd773713 100644
--- a/src/user/digest.js
+++ b/src/user/digest.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict';
var async = require('async');
var winston = require('winston');
@@ -31,7 +31,7 @@ var utils = require('../../public/src/utils');
function (next) {
async.parallel({
topics: async.apply(topics.getLatestTopics, 0, 0, 9, interval),
- subscribers: async.apply(Digest.getSubscribers, interval)
+ subscribers: async.apply(Digest.getSubscribers, interval),
}, next);
},
function (data, next) {
@@ -52,7 +52,7 @@ var utils = require('../../public/src/utils');
data.interval = interval;
Digest.send(data, next);
- }
+ },
], function (err) {
if (err) {
winston.error('[user/jobs] Could not send digests (' + interval + '): ' + err.message);
@@ -72,12 +72,12 @@ var utils = require('../../public/src/utils');
function (subscribers, next) {
plugins.fireHook('filter:digest.subscribers', {
interval: interval,
- subscribers: subscribers
+ subscribers: subscribers,
}, next);
},
function (results, next) {
next(null, results.subscribers);
- }
+ },
], callback);
};
@@ -118,16 +118,15 @@ var utils = require('../../public/src/utils');
site_title: meta.config.title || meta.config.browserTitle || 'NodeBB',
notifications: notifications,
recent: data.topics.topics,
- interval: data.interval
+ interval: data.interval,
});
next();
- }
+ },
], next);
}, next);
- }
+ },
], function (err) {
callback(err);
});
};
-
}(module.exports));
diff --git a/src/user/email.js b/src/user/email.js
index 99d2d9693d..8b8919c73a 100644
--- a/src/user/email.js
+++ b/src/user/email.js
@@ -13,7 +13,6 @@ var meta = require('../meta');
var emailer = require('../emailer');
(function (UserEmail) {
-
UserEmail.exists = function (email, callback) {
user.getUidByEmail(email.toLowerCase(), function (err, exists) {
callback(err, !!exists);
@@ -53,11 +52,11 @@ var emailer = require('../emailer');
confirm_code = _confirm_code;
db.setObject('confirm:' + confirm_code, {
email: email.toLowerCase(),
- uid: uid
+ uid: uid,
}, next);
},
function (next) {
- db.expireAt('confirm:' + confirm_code, Math.floor(Date.now() / 1000 + 60 * 60 * 24), next);
+ db.expireAt('confirm:' + confirm_code, Math.floor((Date.now() / 1000) + (60 * 60 * 24)), next);
},
function (next) {
user.getUserField(uid, 'username', next);
@@ -73,27 +72,32 @@ var emailer = require('../emailer');
subject: subject,
template: 'welcome',
- uid: uid
+ uid: uid,
};
if (plugins.hasListeners('action:user.verify')) {
- plugins.fireHook('action:user.verify', {uid: uid, data: data});
+ plugins.fireHook('action:user.verify', { uid: uid, data: data });
next();
} else {
emailer.send('welcome', uid, data, next);
}
});
- }
+ },
+ function (next) {
+ next(null, confirm_code);
+ },
], callback);
};
UserEmail.confirm = function (code, callback) {
- db.getObject('confirm:' + code, function (err, confirmObj) {
- if (err) {
- return callback(new Error('[[error:parse-error]]'));
- }
-
- if (confirmObj && confirmObj.uid && confirmObj.email) {
+ async.waterfall([
+ function (next) {
+ db.getObject('confirm:' + code, next);
+ },
+ function (confirmObj, next) {
+ if (!confirmObj || !confirmObj.uid || !confirmObj.email) {
+ return next(new Error('[[error:invalid-data]]'));
+ }
async.series([
async.apply(user.setUserField, confirmObj.uid, 'email:confirmed', 1),
async.apply(db.delete, 'confirm:' + code),
@@ -102,15 +106,12 @@ var emailer = require('../emailer');
db.sortedSetRemove('users:notvalidated', confirmObj.uid, next);
},
function (next) {
- plugins.fireHook('action:user.email.confirmed', {uid: confirmObj.uid, email: confirmObj.email}, next);
- }
- ], function (err) {
- callback(err ? new Error('[[error:email-confirm-failed]]') : null);
- });
- } else {
- callback(new Error('[[error:invalid-data]]'));
- }
+ plugins.fireHook('action:user.email.confirmed', { uid: confirmObj.uid, email: confirmObj.email }, next);
+ },
+ ], next);
+ },
+ ], function (err) {
+ callback(err);
});
};
-
}(exports));
diff --git a/src/user/follow.js b/src/user/follow.js
index e6c9624018..fe3dc0931d 100644
--- a/src/user/follow.js
+++ b/src/user/follow.js
@@ -6,7 +6,6 @@ var plugins = require('../plugins');
var db = require('../database');
module.exports = function (User) {
-
User.follow = function (uid, followuid, callback) {
toggleFollow('follow', uid, followuid, callback);
};
@@ -44,7 +43,7 @@ module.exports = function (User) {
async.apply(db.sortedSetAdd, 'following:' + uid, now, theiruid),
async.apply(db.sortedSetAdd, 'followers:' + theiruid, now, uid),
async.apply(User.incrementUserFieldBy, uid, 'followingCount', 1),
- async.apply(User.incrementUserFieldBy, theiruid, 'followerCount', 1)
+ async.apply(User.incrementUserFieldBy, theiruid, 'followerCount', 1),
], next);
} else {
if (!isFollowing) {
@@ -54,10 +53,10 @@ module.exports = function (User) {
async.apply(db.sortedSetRemove, 'following:' + uid, theiruid),
async.apply(db.sortedSetRemove, 'followers:' + theiruid, uid),
async.apply(User.decrementUserFieldBy, uid, 'followingCount', 1),
- async.apply(User.decrementUserFieldBy, theiruid, 'followerCount', 1)
+ async.apply(User.decrementUserFieldBy, theiruid, 'followerCount', 1),
], next);
}
- }
+ },
], callback);
}
@@ -82,12 +81,12 @@ module.exports = function (User) {
uids: uids,
uid: uid,
start: start,
- stop: stop
+ stop: stop,
}, next);
},
function (data, next) {
User.getUsers(data.uids, uid, next);
- }
+ },
], callback);
}
@@ -97,5 +96,4 @@ module.exports = function (User) {
}
db.isSortedSetMember('following:' + uid, theirid, callback);
};
-
};
diff --git a/src/user/info.js b/src/user/info.js
index 296dd9a723..4af1b77f35 100644
--- a/src/user/info.js
+++ b/src/user/info.js
@@ -11,7 +11,9 @@ var topics = require('../topics');
module.exports = function (User) {
User.getLatestBanInfo = function (uid, callback) {
// Simply retrieves the last record of the user's ban, even if they've been unbanned since then.
- var timestamp, expiry, reason;
+ var timestamp;
+ var expiry;
+ var reason;
async.waterfall([
async.apply(db.getSortedSetRevRangeWithScores, 'uid:' + uid + ':bans', 0, 0),
@@ -28,7 +30,7 @@ module.exports = function (User) {
function (_reason, next) {
reason = _reason && _reason.length ? _reason[0] : '';
next();
- }
+ },
], function (err) {
if (err) {
return callback(err);
@@ -39,7 +41,7 @@ module.exports = function (User) {
timestamp: timestamp,
expiry: parseInt(expiry, 10),
expiry_readable: new Date(parseInt(expiry, 10)).toString().replace(/:/g, '%3A'),
- reason: validator.escape(String(reason))
+ reason: validator.escape(String(reason)),
});
});
};
@@ -50,12 +52,12 @@ module.exports = function (User) {
async.parallel({
flags: async.apply(db.getSortedSetRevRangeWithScores, 'uid:' + uid + ':flag:pids', 0, 19),
bans: async.apply(db.getSortedSetRevRangeWithScores, 'uid:' + uid + ':bans', 0, 19),
- reasons: async.apply(db.getSortedSetRevRangeWithScores, 'banned:' + uid + ':reasons', 0, 19)
+ reasons: async.apply(db.getSortedSetRevRangeWithScores, 'banned:' + uid + ':reasons', 0, 19),
}, next);
},
function (data, next) {
getFlagMetadata(data, next);
- }
+ },
], function (err, data) {
if (err) {
return callback(err);
@@ -117,9 +119,9 @@ module.exports = function (User) {
function formatBanData(data) {
var reasons = data.reasons.reduce(function (memo, cur) {
- memo[cur.score] = cur.value;
- return memo;
- }, {});
+ memo[cur.score] = cur.value;
+ return memo;
+ }, {});
data.bans = data.bans.map(function (banObj) {
banObj.until = parseInt(banObj.value, 10);
diff --git a/src/user/invite.js b/src/user/invite.js
index 043bf62a7b..4e41b824a5 100644
--- a/src/user/invite.js
+++ b/src/user/invite.js
@@ -12,7 +12,6 @@ var utils = require('../../public/src/utils');
module.exports = function (User) {
-
User.getInvites = function (uid, callback) {
db.getSetMembers('invitation:uid:' + uid, callback);
};
@@ -37,11 +36,11 @@ module.exports = function (User) {
invitations = invitations.map(function (invites, index) {
return {
uid: uids[index],
- invitations: invites
+ invitations: invites,
};
});
next(null, invitations);
- }
+ },
], callback);
};
@@ -68,7 +67,7 @@ module.exports = function (User) {
},
function (next) {
db.setAdd('invitation:uids', uid, next);
- }
+ },
], function (err) {
next(err);
});
@@ -90,12 +89,12 @@ module.exports = function (User) {
registerLink: registerLink,
subject: subject,
username: username,
- template: 'invitation'
+ template: 'invitation',
};
emailer.sendToEmail('invitation', email, meta.config.defaultLang, data, next);
});
- }
+ },
], callback);
};
@@ -114,7 +113,7 @@ module.exports = function (User) {
}
next();
- }
+ },
], callback);
};
@@ -134,11 +133,11 @@ module.exports = function (User) {
},
function (next) {
db.delete('invitation:email:' + email, next);
- }
+ },
], function (err) {
next(err);
});
- }
+ },
], callback);
};
@@ -156,7 +155,7 @@ module.exports = function (User) {
},
function (next) {
db.delete('invitation:email:' + email, next);
- }
+ },
], callback);
};
@@ -173,8 +172,7 @@ module.exports = function (User) {
return db.setRemove('invitation:uids', uid, next);
}
setImmediate(next);
- }
+ },
], callback);
}
-
};
diff --git a/src/user/jobs.js b/src/user/jobs.js
index c01f2c613c..1eeeb5650e 100644
--- a/src/user/jobs.js
+++ b/src/user/jobs.js
@@ -22,12 +22,12 @@ module.exports = function (User) {
}
// Terminate any active cron jobs
- for(var jobId in jobs) {
+ for (var jobId in jobs) {
if (jobs.hasOwnProperty(jobId)) {
winston.verbose('[user/jobs] Terminating job (' + jobId + ')');
jobs[jobId].stop();
delete jobs[jobId];
- ++terminated;
+ terminated += 1;
}
}
winston.verbose('[user/jobs] ' + terminated + ' jobs terminated');
@@ -37,33 +37,31 @@ module.exports = function (User) {
User.digest.execute('day');
}, null, true);
winston.verbose('[user/jobs] Starting job (digest.daily)');
- ++started;
+ started += 1;
jobs['digest.weekly'] = new cronJob('0 ' + digestHour + ' * * 0', function () {
winston.verbose('[user/jobs] Digest job (weekly) started.');
User.digest.execute('week');
}, null, true);
winston.verbose('[user/jobs] Starting job (digest.weekly)');
- ++started;
+ started += 1;
jobs['digest.monthly'] = new cronJob('0 ' + digestHour + ' 1 * *', function () {
winston.verbose('[user/jobs] Digest job (monthly) started.');
User.digest.execute('month');
}, null, true);
winston.verbose('[user/jobs] Starting job (digest.monthly)');
- ++started;
+ started += 1;
jobs['reset.clean'] = new cronJob('0 0 * * *', User.reset.clean, null, true);
winston.verbose('[user/jobs] Starting job (reset.clean)');
- ++started;
+ started += 1;
winston.verbose('[user/jobs] ' + started + ' jobs started');
if (typeof callback === 'function') {
callback();
}
-
- return;
};
};
diff --git a/src/user/notifications.js b/src/user/notifications.js
index 7182c1a223..f830092b07 100644
--- a/src/user/notifications.js
+++ b/src/user/notifications.js
@@ -11,10 +11,9 @@ var notifications = require('../notifications');
var privileges = require('../privileges');
(function (UserNotifications) {
-
UserNotifications.get = function (uid, callback) {
if (!parseInt(uid, 10)) {
- return callback(null , {read: [], unread: []});
+ return callback(null, { read: [], unread: [] });
}
getNotifications(uid, 0, 9, function (err, notifications) {
if (err) {
@@ -54,7 +53,7 @@ var privileges = require('../privileges');
},
read: function (next) {
getNotificationsFromSet('uid:' + uid + ':notifications:read', true, uid, start, stop, next);
- }
+ },
}, callback);
}
@@ -64,7 +63,7 @@ var privileges = require('../privileges');
async.waterfall([
async.apply(db.getSortedSetRevRange, set, start, stop),
function (nids, next) {
- if(!Array.isArray(nids) || !nids.length) {
+ if (!Array.isArray(nids) || !nids.length) {
return callback(null, []);
}
@@ -89,7 +88,7 @@ var privileges = require('../privileges');
}
notifications.merge(notifs, next);
- }
+ },
], callback);
}
@@ -137,7 +136,7 @@ var privileges = require('../privileges');
});
db.getObjectsFields(keys, ['mergeId'], next);
- }
+ },
], function (err, mergeIds) {
// A missing (null) mergeId means that notification is counted separately.
mergeIds = mergeIds.map(function (set) {
@@ -146,7 +145,7 @@ var privileges = require('../privileges');
callback(err, mergeIds.reduce(function (count, cur, idx, arr) {
if (cur === null || idx === arr.indexOf(cur)) {
- ++count;
+ count += 1;
}
return count;
@@ -195,7 +194,7 @@ var privileges = require('../privileges');
},
function (next) {
db.delete('uid:' + uid + ':notifications:read', next);
- }
+ },
], callback);
};
@@ -229,9 +228,9 @@ var privileges = require('../privileges');
path: '/post/' + postData.pid,
nid: 'tid:' + postData.tid + ':uid:' + uid,
tid: postData.tid,
- from: uid
+ from: uid,
}, next);
- }
+ },
], function (err, notification) {
if (err) {
return winston.error(err);
@@ -254,7 +253,7 @@ var privileges = require('../privileges');
notifications.create({
bodyShort: meta.config.welcomeNotification,
path: path,
- nid: 'welcome_' + uid
+ nid: 'welcome_' + uid,
}, function (err, notification) {
if (err || !notification) {
return callback(err);
@@ -269,7 +268,7 @@ var privileges = require('../privileges');
bodyShort: '[[user:username_taken_workaround, ' + username + ']]',
image: 'brand:logo',
nid: 'username_taken:' + uid,
- datetime: Date.now()
+ datetime: Date.now(),
}, function (err, notification) {
if (!err && notification) {
notifications.push(notification, uid);
@@ -287,5 +286,4 @@ var privileges = require('../privileges');
websockets.in('uid_' + uid).emit('event:notifications.updateCount', count);
});
};
-
}(exports));
diff --git a/src/user/online.js b/src/user/online.js
new file mode 100644
index 0000000000..6cb19cd22f
--- /dev/null
+++ b/src/user/online.js
@@ -0,0 +1,70 @@
+'use strict';
+
+var async = require('async');
+
+var db = require('../database');
+var topics = require('../topics');
+var plugins = require('../plugins');
+
+module.exports = function (User) {
+ User.updateLastOnlineTime = function (uid, callback) {
+ callback = callback || function () {};
+ db.getObjectFields('user:' + uid, ['status', 'lastonline'], function (err, userData) {
+ var now = Date.now();
+ if (err || userData.status === 'offline' || now - parseInt(userData.lastonline, 10) < 300000) {
+ return callback(err);
+ }
+ User.setUserField(uid, 'lastonline', now, callback);
+ });
+ };
+
+ User.updateOnlineUsers = function (uid, callback) {
+ callback = callback || function () {};
+
+ var now = Date.now();
+ async.waterfall([
+ function (next) {
+ db.sortedSetScore('users:online', uid, next);
+ },
+ function (userOnlineTime, next) {
+ if (now - parseInt(userOnlineTime, 10) < 300000) {
+ return callback();
+ }
+ db.sortedSetAdd('users:online', now, uid, next);
+ },
+ function (next) {
+ topics.pushUnreadCount(uid);
+ plugins.fireHook('action:user.online', { uid: uid, timestamp: now });
+ next();
+ },
+ ], callback);
+ };
+
+ User.isOnline = function (uid, callback) {
+ var now = Date.now();
+ async.waterfall([
+ function (next) {
+ if (Array.isArray(uid)) {
+ db.sortedSetScores('users:online', uid, next);
+ } else {
+ db.sortedSetScore('users:online', uid, next);
+ }
+ },
+ function (lastonline, next) {
+ function checkOnline(lastonline) {
+ return now - lastonline < 300000;
+ }
+
+ var isOnline;
+ if (Array.isArray(uid)) {
+ isOnline = uid.map(function (uid, index) {
+ return checkOnline(lastonline[index]);
+ });
+ } else {
+ isOnline = checkOnline(lastonline);
+ }
+ next(null, isOnline);
+ },
+ ], callback);
+ };
+};
diff --git a/src/user/password.js b/src/user/password.js
index 8e9b7780e3..6cf5d8e5d5 100644
--- a/src/user/password.js
+++ b/src/user/password.js
@@ -7,7 +7,6 @@ var db = require('../database');
var Password = require('../password');
module.exports = function (User) {
-
User.hashPassword = function (password, callback) {
if (!password) {
return callback(null, password);
@@ -34,7 +33,7 @@ module.exports = function (User) {
Password.compare(password, hashedPassword, next);
});
- }
+ },
], callback);
};
@@ -43,5 +42,4 @@ module.exports = function (User) {
callback(err, !!hashedPassword);
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/user/picture.js b/src/user/picture.js
index 09b7d636e8..2b4f45d344 100644
--- a/src/user/picture.js
+++ b/src/user/picture.js
@@ -2,7 +2,6 @@
var async = require('async');
var fs = require('fs');
-var nconf = require('nconf');
var winston = require('winston');
var request = require('request');
var mime = require('mime');
@@ -14,9 +13,8 @@ var meta = require('../meta');
var db = require('../database');
module.exports = function (User) {
-
User.uploadPicture = function (uid, picture, callback) {
- User.uploadCroppedPicture({uid: uid, file: picture}, callback);
+ User.uploadCroppedPicture({ uid: uid, file: picture }, callback);
};
User.uploadFromUrl = function (uid, url, callback) {
@@ -46,18 +44,13 @@ module.exports = function (User) {
uid: uid,
image: {
url: url,
- name: ''
- }
+ name: '',
+ },
}, next);
},
function (image, next) {
- User.setUserFields(uid, {
- uploadedpicture: image.url,
- picture: image.url
- }, function (err) {
- next(err, image);
- });
- }
+ next(null, image);
+ },
], callback);
};
@@ -66,11 +59,10 @@ module.exports = function (User) {
};
User.updateCoverPicture = function (data, callback) {
-
var url;
var picture = {
name: 'profileCover',
- uid: data.uid
+ uid: data.uid,
};
if (!data.imageData && data.position) {
@@ -112,18 +104,17 @@ module.exports = function (User) {
} else {
setImmediate(next);
}
- }
+ },
], function (err) {
deleteFile(picture.path);
callback(err, {
- url: url
+ url: url,
});
});
};
User.uploadCroppedPicture = function (data, callback) {
-
- if (parseInt(meta.config.allowProfileImageUploads) !== 1) {
+ if (parseInt(meta.config.allowProfileImageUploads, 10) !== 1) {
return callback(new Error('[[error:profile-image-uploads-disabled]]'));
}
@@ -147,7 +138,7 @@ module.exports = function (User) {
var picture = {
name: 'profileAvatar',
- uid: data.uid
+ uid: data.uid,
};
async.waterfall([
@@ -168,7 +159,7 @@ module.exports = function (User) {
path: picture.path,
extension: extension,
width: imageDimension,
- height: imageDimension
+ height: imageDimension,
}, next);
},
function (next) {
@@ -180,9 +171,9 @@ module.exports = function (User) {
User.setUserFields(data.uid, {
uploadedpicture: uploadedImage.url,
- picture: uploadedImage.url
+ picture: uploadedImage.url,
}, next);
- }
+ },
], function (err) {
deleteFile(picture.path);
callback(err, uploadedImage);
@@ -208,7 +199,7 @@ module.exports = function (User) {
if (plugins.hasListeners('filter:uploadImage')) {
return plugins.fireHook('filter:uploadImage', {
image: image,
- uid: image.uid
+ uid: image.uid,
}, callback);
}
@@ -231,11 +222,11 @@ module.exports = function (User) {
},
function (upload, next) {
next(null, {
- url: nconf.get('relative_path') + upload.url,
+ url: upload.url,
path: upload.path,
- name: image.name
+ name: image.name,
});
- }
+ },
], callback);
}
diff --git a/src/user/posts.js b/src/user/posts.js
index 37b5e92b16..3f2d608ee1 100644
--- a/src/user/posts.js
+++ b/src/user/posts.js
@@ -6,7 +6,6 @@ var meta = require('../meta');
var privileges = require('../privileges');
module.exports = function (User) {
-
User.isReadyToPost = function (uid, cid, callback) {
if (parseInt(uid, 10) === 0) {
return callback();
@@ -21,7 +20,7 @@ module.exports = function (User) {
},
isAdminOrMod: function (next) {
privileges.categories.isAdminOrMod(cid, uid, next);
- }
+ },
}, function (err, results) {
if (err) {
return callback(err);
@@ -75,7 +74,7 @@ module.exports = function (User) {
},
function (next) {
User.updateLastOnlineTime(postData.uid, next);
- }
+ },
], callback);
};
@@ -101,5 +100,4 @@ module.exports = function (User) {
callback(err, Array.isArray(pids) ? pids : []);
});
};
-
-};
\ No newline at end of file
+};
diff --git a/src/user/profile.js b/src/user/profile.js
index 37b280612f..b2b3b7eb5f 100644
--- a/src/user/profile.js
+++ b/src/user/profile.js
@@ -11,25 +11,30 @@ var groups = require('../groups');
var plugins = require('../plugins');
module.exports = function (User) {
-
User.updateProfile = function (uid, data, callback) {
var fields = ['username', 'email', 'fullname', 'website', 'location',
'groupTitle', 'birthday', 'signature', 'aboutme'];
+ if (data.aboutme !== undefined && data.aboutme.length > meta.config.maximumAboutMeLength) {
+ return callback(new Error('[[error:about-me-too-long, ' + meta.config.maximumAboutMeLength + ']]'));
+ }
+
+ if (data.signature !== undefined && data.signature.length > meta.config.maximumSignatureLength) {
+ return callback(new Error('[[error:signature-too-long, ' + meta.config.maximumSignatureLength + ']]'));
+ }
+
async.waterfall([
function (next) {
- plugins.fireHook('filter:user.updateProfile', {uid: uid, data: data, fields: fields}, next);
+ plugins.fireHook('filter:user.updateProfile', { uid: uid, data: data, fields: fields }, next);
},
function (data, next) {
fields = data.fields;
data = data.data;
async.series([
- async.apply(isAboutMeValid, data),
- async.apply(isSignatureValid, data),
async.apply(isEmailAvailable, data, uid),
async.apply(isUsernameAvailable, data, uid),
- async.apply(isGroupTitleValid, data)
+ async.apply(isGroupTitleValid, data),
], function (err) {
next(err);
});
@@ -56,28 +61,12 @@ module.exports = function (User) {
}, next);
},
function (next) {
- plugins.fireHook('action:user.updateProfile', {data: data, uid: uid});
+ plugins.fireHook('action:user.updateProfile', { data: data, uid: uid });
User.getUserFields(uid, ['email', 'username', 'userslug', 'picture', 'icon:text', 'icon:bgColor'], next);
- }
+ },
], callback);
};
- function isAboutMeValid(data, callback) {
- if (data.aboutme !== undefined && data.aboutme.length > meta.config.maximumAboutMeLength) {
- callback(new Error('[[error:about-me-too-long, ' + meta.config.maximumAboutMeLength + ']]'));
- } else {
- callback();
- }
- }
-
- function isSignatureValid(data, callback) {
- if (data.signature !== undefined && data.signature.length > meta.config.maximumSignatureLength) {
- callback(new Error('[[error:signature-too-long, ' + meta.config.maximumSignatureLength + ']]'));
- } else {
- callback();
- }
- }
-
function isEmailAvailable(data, uid, callback) {
if (!data.email) {
return callback();
@@ -99,7 +88,7 @@ module.exports = function (User) {
},
function (available, next) {
next(!available ? new Error('[[error:email-taken]]') : null);
- }
+ },
], callback);
}
@@ -134,7 +123,7 @@ module.exports = function (User) {
},
function (exists, next) {
next(exists ? new Error('[[error:username-taken]]') : null);
- }
+ },
], callback);
}
@@ -159,7 +148,7 @@ module.exports = function (User) {
}
async.series([
async.apply(db.sortedSetRemove, 'email:uid', oldEmail.toLowerCase()),
- async.apply(db.sortedSetRemove, 'email:sorted', oldEmail.toLowerCase() + ':' + uid)
+ async.apply(db.sortedSetRemove, 'email:sorted', oldEmail.toLowerCase() + ':' + uid),
], function (err) {
next(err);
});
@@ -170,7 +159,7 @@ module.exports = function (User) {
db.sortedSetAdd('email:uid', uid, newEmail.toLowerCase(), next);
},
function (next) {
- db.sortedSetAdd('email:sorted', 0, newEmail.toLowerCase() + ':' + uid, next);
+ db.sortedSetAdd('email:sorted', 0, newEmail.toLowerCase() + ':' + uid, next);
},
function (next) {
db.sortedSetAdd('user:' + uid + ':emails', Date.now(), newEmail + ':' + Date.now(), next);
@@ -186,11 +175,11 @@ module.exports = function (User) {
},
function (next) {
db.sortedSetAdd('users:notvalidated', Date.now(), uid, next);
- }
+ },
], function (err) {
next(err);
});
- }
+ },
], callback);
}
@@ -216,7 +205,7 @@ module.exports = function (User) {
async.series([
async.apply(db.sortedSetRemove, 'username:sorted', userData.username.toLowerCase() + ':' + uid),
async.apply(db.sortedSetAdd, 'username:sorted', 0, newUsername.toLowerCase() + ':' + uid),
- async.apply(db.sortedSetAdd, 'user:' + uid + ':usernames', Date.now(), newUsername + ':' + Date.now())
+ async.apply(db.sortedSetAdd, 'user:' + uid + ':usernames', Date.now(), newUsername + ':' + Date.now()),
], next);
},
], callback);
@@ -241,7 +230,7 @@ module.exports = function (User) {
} else {
next();
}
- }
+ },
], callback);
}
@@ -252,7 +241,7 @@ module.exports = function (User) {
},
function (fullname, next) {
updateUidMapping('fullname', uid, newFullname, fullname, next);
- }
+ },
], callback);
}
@@ -282,11 +271,12 @@ module.exports = function (User) {
function (hashedPassword, next) {
async.parallel([
async.apply(User.setUserField, data.uid, 'password', hashedPassword),
- async.apply(User.reset.updateExpiry, data.uid)
+ async.apply(User.reset.updateExpiry, data.uid),
+ async.apply(User.auth.revokeAllSessions, data.uid),
], function (err) {
next(err);
});
- }
+ },
], callback);
};
};
diff --git a/src/user/reset.js b/src/user/reset.js
index 39bf1f0e07..ba0e18b513 100644
--- a/src/user/reset.js
+++ b/src/user/reset.js
@@ -1,16 +1,16 @@
'use strict';
-var async = require('async'),
- nconf = require('nconf'),
- winston = require('winston'),
+var async = require('async');
+var nconf = require('nconf');
+var winston = require('winston');
- user = require('../user'),
- utils = require('../../public/src/utils'),
- translator = require('../../public/src/modules/translator'),
+var user = require('../user');
+var utils = require('../../public/src/utils');
+var translator = require('../../public/src/modules/translator');
- db = require('../database'),
- meta = require('../meta'),
- emailer = require('../emailer');
+var db = require('../database');
+var meta = require('../meta');
+var emailer = require('../emailer');
(function (UserReset) {
var twoHours = 7200000;
@@ -28,7 +28,7 @@ var async = require('async'),
},
function (issueDate, next) {
next(null, parseInt(issueDate, 10) > Date.now() - twoHours);
- }
+ },
], callback);
};
@@ -36,7 +36,7 @@ var async = require('async'),
var code = utils.generateUUID();
async.parallel([
async.apply(db.setObjectField, 'reset:uid', code, uid),
- async.apply(db.sortedSetAdd, 'reset:issueDate', Date.now(), code)
+ async.apply(db.sortedSetAdd, 'reset:issueDate', Date.now(), code),
], function (err) {
callback(err, code);
});
@@ -48,11 +48,11 @@ var async = require('async'),
db.sortedSetScore('reset:issueDate:uid', uid, next);
},
function (score, next) {
- if (score > Date.now() - 1000 * 60) {
+ if (score > Date.now() - (1000 * 60)) {
return next(new Error('[[error:cant-reset-password-more-than-once-a-minute]]'));
}
next();
- }
+ },
], callback);
}
@@ -88,9 +88,9 @@ var async = require('async'),
reset_link: reset_link,
subject: subject,
template: 'reset',
- uid: uid
+ uid: uid,
}, next);
- }
+ },
], callback);
};
@@ -124,9 +124,9 @@ var async = require('async'),
async.apply(db.sortedSetRemove, 'reset:issueDate', code),
async.apply(db.sortedSetRemove, 'reset:issueDate:uid', uid),
async.apply(user.reset.updateExpiry, uid),
- async.apply(user.auth.resetLockout, uid)
+ async.apply(user.auth.resetLockout, uid),
], next);
- }
+ },
], callback);
};
@@ -148,7 +148,7 @@ var async = require('async'),
},
uids: function (next) {
db.getSortedSetRangeByScore('reset:issueDate:uid', 0, -1, '-inf', Date.now() - twoHours, next);
- }
+ },
}, next);
},
function (results, next) {
@@ -160,10 +160,9 @@ var async = require('async'),
async.parallel([
async.apply(db.deleteObjectFields, 'reset:uid', results.tokens),
async.apply(db.sortedSetRemove, 'reset:issueDate', results.tokens),
- async.apply(db.sortedSetRemove, 'reset:issueDate:uid', results.uids)
+ async.apply(db.sortedSetRemove, 'reset:issueDate:uid', results.uids),
], next);
- }
+ },
], callback);
};
-
}(exports));
diff --git a/src/user/search.js b/src/user/search.js
index 65d0e41a6a..4583e0e28f 100644
--- a/src/user/search.js
+++ b/src/user/search.js
@@ -7,7 +7,6 @@ var plugins = require('../plugins');
var db = require('../database');
module.exports = function (User) {
-
User.search = function (data, callback) {
var query = data.query || '';
var searchBy = data.searchBy || 'username';
@@ -34,7 +33,7 @@ module.exports = function (User) {
filterAndSortUids(uids, data, next);
},
function (uids, next) {
- plugins.fireHook('filter:users.search', {uids: uids, uid: uid}, next);
+ plugins.fireHook('filter:users.search', { uids: uids, uid: uid }, next);
},
function (data, next) {
var uids = data.uids;
@@ -54,7 +53,7 @@ module.exports = function (User) {
searchResult.timing = (process.elapsedTimeSince(startTime) / 1000).toFixed(2);
searchResult.users = userData;
next(null, searchResult);
- }
+ },
], callback);
};
@@ -135,9 +134,9 @@ module.exports = function (User) {
});
} else {
userData.sort(function (u1, u2) {
- if(u1[sortBy] < u2[sortBy]) {
+ if (u1[sortBy] < u2[sortBy]) {
return -1;
- } else if(u1[sortBy] > u2[sortBy]) {
+ } else if (u1[sortBy] > u2[sortBy]) {
return 1;
}
return 0;
@@ -156,9 +155,9 @@ module.exports = function (User) {
},
function (users, next) {
var diff = process.hrtime(start);
- var timing = (diff[0] * 1e3 + diff[1] / 1e6).toFixed(1);
- next(null, {timing: timing, users: users});
- }
+ var timing = ((diff[0] * 1e3) + (diff[1] / 1e6)).toFixed(1);
+ next(null, { timing: timing, users: users });
+ },
], callback);
}
};
diff --git a/src/user/settings.js b/src/user/settings.js
index 3d93a9724a..bef20e0087 100644
--- a/src/user/settings.js
+++ b/src/user/settings.js
@@ -7,7 +7,6 @@ var db = require('../database');
var plugins = require('../plugins');
module.exports = function (User) {
-
User.getSettings = function (uid, callback) {
if (!parseInt(uid, 10)) {
return onSettingsLoaded(0, {}, callback);
@@ -18,7 +17,7 @@ module.exports = function (User) {
return callback(err);
}
- onSettingsLoaded(uid, settings ? settings : {}, callback);
+ onSettingsLoaded(uid, settings || {}, callback);
});
};
@@ -36,7 +35,7 @@ module.exports = function (User) {
return callback(err);
}
- for (var i = 0; i < settings.length; ++i) {
+ for (var i = 0; i < settings.length; i += 1) {
settings[i] = settings[i] || {};
settings[i].uid = uids[i];
}
@@ -48,7 +47,7 @@ module.exports = function (User) {
};
function onSettingsLoaded(uid, settings, callback) {
- plugins.fireHook('filter:user.getSettings', {uid: uid, settings: settings}, function (err, data) {
+ plugins.fireHook('filter:user.getSettings', { uid: uid, settings: settings }, function (err, data) {
if (err) {
return callback(err);
}
@@ -75,7 +74,7 @@ module.exports = function (User) {
settings.restrictChat = parseInt(getSetting(settings, 'restrictChat', 0), 10) === 1;
settings.topicSearchEnabled = parseInt(getSetting(settings, 'topicSearchEnabled', 0), 10) === 1;
settings.delayImageLoading = parseInt(getSetting(settings, 'delayImageLoading', 1), 10) === 1;
- settings.bootswatchSkin = settings.bootswatchSkin || 'default';
+ settings.bootswatchSkin = settings.bootswatchSkin || meta.config.bootswatchSkin || 'default';
settings.scrollToMyPost = parseInt(getSetting(settings, 'scrollToMyPost', 1), 10) === 1;
callback(null, settings);
@@ -102,7 +101,7 @@ module.exports = function (User) {
data.userLang = data.userLang || meta.config.defaultLang;
- plugins.fireHook('action:user.saveSettings', {uid: uid, settings: data});
+ plugins.fireHook('action:user.saveSettings', { uid: uid, settings: data });
var settings = {
showemail: data.showemail,
@@ -120,11 +119,11 @@ module.exports = function (User) {
restrictChat: data.restrictChat,
topicSearchEnabled: data.topicSearchEnabled,
delayImageLoading: data.delayImageLoading,
- homePageRoute : ((data.homePageRoute === 'custom' ? data.homePageCustom : data.homePageRoute) || '').replace(/^\//, ''),
+ homePageRoute: ((data.homePageRoute === 'custom' ? data.homePageCustom : data.homePageRoute) || '').replace(/^\//, ''),
scrollToMyPost: data.scrollToMyPost,
notificationSound: data.notificationSound,
incomingChatSound: data.incomingChatSound,
- outgoingChatSound: data.outgoingChatSound
+ outgoingChatSound: data.outgoingChatSound,
};
if (data.bootswatchSkin) {
@@ -140,7 +139,7 @@ module.exports = function (User) {
},
function (next) {
User.getSettings(uid, next);
- }
+ },
], callback);
};
@@ -155,7 +154,7 @@ module.exports = function (User) {
} else {
next();
}
- }
+ },
], callback);
};
diff --git a/src/user/topics.js b/src/user/topics.js
index 53dade36e9..bd69e66e6f 100644
--- a/src/user/topics.js
+++ b/src/user/topics.js
@@ -4,7 +4,6 @@ var async = require('async');
var db = require('../database');
module.exports = function (User) {
-
User.getIgnoredTids = function (uid, start, stop, callback) {
db.getSortedSetRevRange('uid:' + uid + ':ignored_tids', start, stop, callback);
};
@@ -12,8 +11,7 @@ module.exports = function (User) {
User.addTopicIdToUser = function (uid, tid, timestamp, callback) {
async.parallel([
async.apply(db.sortedSetAdd, 'uid:' + uid + ':topics', timestamp, tid),
- async.apply(User.incrementUserFieldBy, uid, 'topiccount', 1)
+ async.apply(User.incrementUserFieldBy, uid, 'topiccount', 1),
], callback);
};
-
-};
\ No newline at end of file
+};
diff --git a/src/views/admin/general/sounds.tpl b/src/views/admin/general/sounds.tpl
index c7b8df97a7..e5c7fc848d 100644
--- a/src/views/admin/general/sounds.tpl
+++ b/src/views/admin/general/sounds.tpl
@@ -7,7 +7,7 @@
diff --git a/src/views/admin/settings/group.tpl b/src/views/admin/settings/group.tpl
index 1c0b660361..fd696cb5ad 100644
--- a/src/views/admin/settings/group.tpl
+++ b/src/views/admin/settings/group.tpl
@@ -43,7 +43,7 @@
[[admin/settings/group:default-cover-help]]
-
+