Merge pull request #5716 from NodeBB/import-export-ref

Import export cleanup
v1.18.x
Barış Soner Uşaklı 8 years ago committed by GitHub
commit 14ea9a0dd6

@ -1,16 +1,38 @@
'use strict'; 'use strict';
(function (exports) { (function (factory) {
/* globals define, utils, config */ if (typeof module === 'object' && module.exports) {
var relative_path = require('nconf').get('relative_path');
// export the class if we are in a Node-like system. module.exports = factory(require('../utils'), require('templates.js'), require('string'), relative_path);
if (typeof module === 'object' && module.exports === exports) { } else if (typeof define === 'function' && define.amd) {
exports = module.exports/* = SemVer*/; define('helpers', ['string'], function (string) {
return factory(utils, templates, string, config.relative_path);
});
} else {
window.helpers = factory(utils, templates, window.String, config.relative_path);
} }
}(function (utils, templates, S, relative_path) {
var helpers = {
displayMenuItem: displayMenuItem,
buildMetaTag: buildMetaTag,
buildLinkTag: buildLinkTag,
stringify: stringify,
escape: escape,
stripTags: stripTags,
generateCategoryBackground: generateCategoryBackground,
generateChildrenCategories: generateChildrenCategories,
generateTopicClass: generateTopicClass,
displayUserSearch: displayUserSearch,
membershipBtn: membershipBtn,
spawnPrivilegeStates: spawnPrivilegeStates,
localeToHTML: localeToHTML,
renderTopicImage: renderTopicImage,
renderDigestAvatar: renderDigestAvatar,
userAgentIcons: userAgentIcons,
register: register,
};
var helpers = exports; function displayMenuItem(data, index) {
helpers.displayMenuItem = function (data, index) {
var item = data.navigation[index]; var item = data.navigation[index];
if (!item) { if (!item) {
return false; return false;
@ -35,17 +57,17 @@
} }
return true; return true;
}; }
helpers.buildMetaTag = function (tag) { function buildMetaTag(tag) {
var name = tag.name ? 'name="' + tag.name + '" ' : ''; var name = tag.name ? 'name="' + tag.name + '" ' : '';
var property = tag.property ? 'property="' + tag.property + '" ' : ''; var property = tag.property ? 'property="' + tag.property + '" ' : '';
var content = tag.content ? 'content="' + tag.content.replace(/\n/g, ' ') + '" ' : ''; var content = tag.content ? 'content="' + tag.content.replace(/\n/g, ' ') + '" ' : '';
return '<meta ' + name + property + content + '/>\n\t'; return '<meta ' + name + property + content + '/>\n\t';
}; }
helpers.buildLinkTag = function (tag) { function buildLinkTag(tag) {
var link = tag.link ? 'link="' + tag.link + '" ' : ''; var link = tag.link ? 'link="' + tag.link + '" ' : '';
var rel = tag.rel ? 'rel="' + tag.rel + '" ' : ''; var rel = tag.rel ? 'rel="' + tag.rel + '" ' : '';
var type = tag.type ? 'type="' + tag.type + '" ' : ''; var type = tag.type ? 'type="' + tag.type + '" ' : '';
@ -53,29 +75,22 @@
var sizes = tag.sizes ? 'sizes="' + tag.sizes + '" ' : ''; var sizes = tag.sizes ? 'sizes="' + tag.sizes + '" ' : '';
return '<link ' + link + rel + type + sizes + href + '/>\n\t'; return '<link ' + link + rel + type + sizes + href + '/>\n\t';
}; }
helpers.stringify = function (obj) { function stringify(obj) {
// Turns the incoming object into a JSON string // Turns the incoming object into a JSON string
return JSON.stringify(obj).replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;').replace(/"/g, '&quot;'); return JSON.stringify(obj).replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;').replace(/"/g, '&quot;');
}; }
helpers.escape = function (str) { function escape(str) {
if (typeof utils !== 'undefined') { return utils.escapeHTML(str);
return utils.escapeHTML(str); }
}
return require('../utils').escapeHTML(str);
};
helpers.stripTags = function (str) { function stripTags(str) {
if (typeof window !== 'undefined' && window.S) {
return window.S(String(str)).stripTags().s;
}
var S = require('string');
return S(String(str)).stripTags().s; return S(String(str)).stripTags().s;
}; }
helpers.generateCategoryBackground = function (category) { function generateCategoryBackground(category) {
if (!category) { if (!category) {
return ''; return '';
} }
@ -97,11 +112,10 @@
} }
return style.join('; ') + ';'; return style.join('; ') + ';';
}; }
helpers.generateChildrenCategories = function (category) { function generateChildrenCategories(category) {
var html = ''; var html = '';
var relative_path = (typeof config !== 'undefined' ? config.relative_path : require('nconf').get('relative_path'));
if (!category || !category.children || !category.children.length) { if (!category || !category.children || !category.children.length) {
return html; return html;
} }
@ -117,9 +131,9 @@
}); });
html = html ? ('<span class="category-children">' + html + '</span>') : html; html = html ? ('<span class="category-children">' + html + '</span>') : html;
return html; return html;
}; }
helpers.generateTopicClass = function (topic) { function generateTopicClass(topic) {
var style = []; var style = [];
if (topic.locked) { if (topic.locked) {
@ -139,14 +153,14 @@
} }
return style.join(' '); return style.join(' ');
}; }
helpers.displayUserSearch = function (data, allowGuestUserSearching) { function displayUserSearch(data, allowGuestUserSearching) {
return data.loggedIn || allowGuestUserSearching === 'true'; return data.loggedIn || allowGuestUserSearching === 'true';
}; }
// Groups helpers // Groups helpers
helpers.membershipBtn = function (groupObj) { function membershipBtn(groupObj) {
if (groupObj.isMember && groupObj.name !== 'administrators') { if (groupObj.isMember && groupObj.name !== 'administrators') {
return '<button class="btn btn-danger" data-action="leave" data-group="' + groupObj.displayName + '"><i class="fa fa-times"></i> [[groups:membership.leave-group]]</button>'; return '<button class="btn btn-danger" data-action="leave" data-group="' + groupObj.displayName + '"><i class="fa fa-times"></i> [[groups:membership.leave-group]]</button>';
} }
@ -159,9 +173,9 @@
return '<button class="btn btn-success" data-action="join" data-group="' + groupObj.displayName + '"><i class="fa fa-plus"></i> [[groups:membership.join-group]]</button>'; return '<button class="btn btn-success" data-action="join" data-group="' + groupObj.displayName + '"><i class="fa fa-plus"></i> [[groups:membership.join-group]]</button>';
} }
return ''; return '';
}; }
helpers.spawnPrivilegeStates = function (member, privileges) { function spawnPrivilegeStates(member, privileges) {
var states = []; var states = [];
for (var priv in privileges) { for (var priv in privileges) {
if (privileges.hasOwnProperty(priv)) { if (privileges.hasOwnProperty(priv)) {
@ -174,21 +188,21 @@
return states.map(function (priv) { return states.map(function (priv) {
return '<td class="text-center" data-privilege="' + priv.name + '"><input type="checkbox"' + (priv.state ? ' checked' : '') + (member === 'guests' && priv.name === 'groups:moderate' ? ' disabled="disabled"' : '') + ' /></td>'; return '<td class="text-center" data-privilege="' + priv.name + '"><input type="checkbox"' + (priv.state ? ' checked' : '') + (member === 'guests' && priv.name === 'groups:moderate' ? ' disabled="disabled"' : '') + ' /></td>';
}).join(''); }).join('');
}; }
helpers.localeToHTML = function (locale, fallback) { function localeToHTML(locale, fallback) {
locale = locale || fallback || 'en-GB'; locale = locale || fallback || 'en-GB';
return locale.replace('_', '-'); return locale.replace('_', '-');
}; }
helpers.renderTopicImage = function (topicObj) { function renderTopicImage(topicObj) {
if (topicObj.thumb) { if (topicObj.thumb) {
return '<img src="' + topicObj.thumb + '" class="img-circle user-img" title="' + topicObj.user.username + '" />'; return '<img src="' + topicObj.thumb + '" class="img-circle user-img" title="' + topicObj.user.username + '" />';
} }
return '<img component="user/picture" data-uid="' + topicObj.user.uid + '" src="' + topicObj.user.picture + '" class="user-img" title="' + topicObj.user.username + '" />'; return '<img component="user/picture" data-uid="' + topicObj.user.uid + '" src="' + topicObj.user.picture + '" class="user-img" title="' + topicObj.user.username + '" />';
}; }
helpers.renderDigestAvatar = function (block) { function renderDigestAvatar(block) {
if (block.teaser) { if (block.teaser) {
if (block.teaser.user.picture) { if (block.teaser.user.picture) {
return '<img style="vertical-align: middle; width: 16px; height: 16px; padding-right: 1em;" src="' + block.teaser.user.picture + '" title="' + block.teaser.user.username + '" />'; return '<img style="vertical-align: middle; width: 16px; height: 16px; padding-right: 1em;" src="' + block.teaser.user.picture + '" title="' + block.teaser.user.username + '" />';
@ -199,9 +213,9 @@
return '<img style="vertical-align: middle; width: 16px; height: 16px; padding-right: 1em;" src="' + block.user.picture + '" title="' + block.user.username + '" />'; return '<img style="vertical-align: middle; width: 16px; height: 16px; padding-right: 1em;" src="' + block.user.picture + '" title="' + block.user.username + '" />';
} }
return '<div style="width: 16px; height: 16px; line-height: 16px; font-size: 10px; margin-right: 1em; background-color: ' + block.user['icon:bgColor'] + '; color: white; text-align: center; display: inline-block;">' + block.user['icon:text'] + '</div>'; return '<div style="width: 16px; height: 16px; line-height: 16px; font-size: 10px; margin-right: 1em; background-color: ' + block.user['icon:bgColor'] + '; color: white; text-align: center; display: inline-block;">' + block.user['icon:text'] + '</div>';
}; }
helpers.userAgentIcons = function (data) { function userAgentIcons(data) {
var icons = ''; var icons = '';
switch (data.platform) { switch (data.platform) {
@ -251,29 +265,13 @@
} }
return icons; return icons;
}; }
exports.register = function () {
var templates;
if (typeof module === 'object') {
templates = require('templates.js');
} else {
templates = window.templates;
}
function register() {
Object.keys(helpers).forEach(function (helperName) { Object.keys(helpers).forEach(function (helperName) {
templates.registerHelper(helperName, helpers[helperName]); templates.registerHelper(helperName, helpers[helperName]);
}); });
};
// export the class if we are in a Node-like system.
if (typeof module === 'object' && module.exports === exports) {
exports = module.exports/* = SemVer*/;
} else if (typeof define === 'function' && define.amd) {
// Use the define() function if we're in AMD land
define('helpers', exports);
} else if (typeof window === 'object') {
window.helpers = exports;
} }
}(typeof exports === 'object' ? exports : {}));
return helpers;
}));

@ -12,16 +12,16 @@ var Meta = module.exports;
Meta.reloadRequired = false; Meta.reloadRequired = false;
require('./meta/configs')(Meta); Meta.configs = require('./meta/configs');
require('./meta/themes')(Meta); Meta.themes = require('./meta/themes');
require('./meta/js')(Meta); Meta.js = require('./meta/js');
require('./meta/css')(Meta); Meta.css = require('./meta/css');
require('./meta/sounds')(Meta); Meta.sounds = require('./meta/sounds');
require('./meta/settings')(Meta); Meta.settings = require('./meta/settings');
require('./meta/logs')(Meta); Meta.logs = require('./meta/logs');
require('./meta/errors')(Meta); Meta.errors = require('./meta/errors');
require('./meta/tags')(Meta); Meta.tags = require('./meta/tags');
require('./meta/dependencies')(Meta); Meta.dependencies = require('./meta/dependencies');
Meta.templates = require('./meta/templates'); Meta.templates = require('./meta/templates');
Meta.blacklist = require('./meta/blacklist'); Meta.blacklist = require('./meta/blacklist');
Meta.languages = require('./meta/languages'); Meta.languages = require('./meta/languages');

@ -6,142 +6,142 @@ var nconf = require('nconf');
var db = require('../database'); var db = require('../database');
var pubsub = require('../pubsub'); var pubsub = require('../pubsub');
var Meta = require('../meta');
var cacheBuster = require('./cacheBuster'); var cacheBuster = require('./cacheBuster');
module.exports = function (Meta) { var Configs = module.exports;
Meta.config = {};
Meta.configs = {};
Meta.configs.init = function (callback) {
delete Meta.config;
async.waterfall([
function (next) {
Meta.configs.list(next);
},
function (config, next) {
cacheBuster.read(function (err, buster) {
if (err) {
return next(err);
}
config['cache-buster'] = 'v=' + (buster || Date.now());
Meta.config = config;
next();
});
},
], callback);
};
Meta.configs.list = function (callback) {
db.getObject('config', function (err, config) {
config = config || {};
config.version = nconf.get('version');
config.registry = nconf.get('registry');
callback(err, config);
});
};
Meta.configs.get = function (field, callback) {
db.getObjectField('config', field, callback);
};
Meta.configs.getFields = function (fields, callback) {
db.getObjectFields('config', fields, callback);
};
Meta.configs.set = function (field, value, callback) {
callback = callback || function () {};
if (!field) {
return callback(new Error('[[error:invalid-data]]'));
}
var data = {}; Meta.config = {};
data[field] = value;
Meta.configs.setMultiple(data, callback);
};
Meta.configs.setMultiple = function (data, callback) {
async.waterfall([
function (next) {
processConfig(data, next);
},
function (next) {
db.setObject('config', data, next);
},
function (next) {
updateConfig(data);
setImmediate(next);
},
], callback);
};
function processConfig(data, callback) { Configs.init = function (callback) {
if (data.customCSS) { Meta.config = null;
return saveRenderedCss(data, callback);
}
setImmediate(callback);
}
function saveRenderedCss(data, callback) { async.waterfall([
var less = require('less'); function (next) {
async.waterfall([ Configs.list(next);
function (next) { },
less.render(data.customCSS, { function (config, next) {
compress: true, cacheBuster.read(function (err, buster) {
}, next); if (err) {
}, return next(err);
function (lessObject, next) { }
data.renderedCustomCSS = lessObject.css;
setImmediate(next);
},
], callback);
}
function updateConfig(config) { config['cache-buster'] = 'v=' + (buster || Date.now());
updateLocalConfig(config);
pubsub.publish('config:update', config);
}
function updateLocalConfig(config) { Meta.config = config;
for (var field in config) { next();
if (config.hasOwnProperty(field)) { });
Meta.config[field] = config[field]; },
} ], callback);
} };
Configs.list = function (callback) {
db.getObject('config', function (err, config) {
config = config || {};
config.version = nconf.get('version');
config.registry = nconf.get('registry');
callback(err, config);
});
};
Configs.get = function (field, callback) {
db.getObjectField('config', field, callback);
};
Configs.getFields = function (fields, callback) {
db.getObjectFields('config', fields, callback);
};
Configs.set = function (field, value, callback) {
callback = callback || function () {};
if (!field) {
return callback(new Error('[[error:invalid-data]]'));
} }
pubsub.on('config:update', function onConfigReceived(config) { var data = {};
if (typeof config === 'object' && Meta.config) { data[field] = value;
updateLocalConfig(config); Configs.setMultiple(data, callback);
};
Configs.setMultiple = function (data, callback) {
async.waterfall([
function (next) {
processConfig(data, next);
},
function (next) {
db.setObject('config', data, next);
},
function (next) {
updateConfig(data);
setImmediate(next);
},
], callback);
};
function processConfig(data, callback) {
if (data.customCSS) {
return saveRenderedCss(data, callback);
}
setImmediate(callback);
}
function saveRenderedCss(data, callback) {
var less = require('less');
async.waterfall([
function (next) {
less.render(data.customCSS, {
compress: true,
}, next);
},
function (lessObject, next) {
data.renderedCustomCSS = lessObject.css;
setImmediate(next);
},
], callback);
}
function updateConfig(config) {
updateLocalConfig(config);
pubsub.publish('config:update', config);
}
function updateLocalConfig(config) {
for (var field in config) {
if (config.hasOwnProperty(field)) {
Meta.config[field] = config[field];
} }
}); }
}
Meta.configs.setOnEmpty = function (values, callback) { pubsub.on('config:update', function onConfigReceived(config) {
async.waterfall([ if (typeof config === 'object' && Meta.config) {
function (next) { updateLocalConfig(config);
db.getObject('config', next); }
}, });
function (data, next) {
data = data || {}; Configs.setOnEmpty = function (values, callback) {
var empty = {}; async.waterfall([
Object.keys(values).forEach(function (key) { function (next) {
if (!data.hasOwnProperty(key)) { db.getObject('config', next);
empty[key] = values[key]; },
} function (data, next) {
}); data = data || {};
if (Object.keys(empty).length) { var empty = {};
db.setObject('config', empty, next); Object.keys(values).forEach(function (key) {
} else { if (!data.hasOwnProperty(key)) {
setImmediate(next); empty[key] = values[key];
} }
}, });
], callback); if (Object.keys(empty).length) {
}; db.setObject('config', empty, next);
} else {
setImmediate(next);
}
},
], callback);
};
Meta.configs.remove = function (field, callback) { Configs.remove = function (field, callback) {
db.deleteObjectField('config', field, callback); db.deleteObjectField('config', field, callback);
};
}; };

@ -11,158 +11,156 @@ var db = require('../database');
var file = require('../file'); var file = require('../file');
var minifier = require('./minifier'); var minifier = require('./minifier');
module.exports = function (Meta) { var CSS = module.exports;
Meta.css = {};
var buildImports = {
var buildImports = { client: function (source) {
client: function (source) { return '@import "./theme";\n' + source + '\n' + [
return '@import "./theme";\n' + source + '\n' + [ '@import "font-awesome";',
'@import "font-awesome";', '@import (inline) "../public/vendor/jquery/css/smoothness/jquery-ui.css";',
'@import (inline) "../public/vendor/jquery/css/smoothness/jquery-ui.css";', '@import (inline) "../public/vendor/jquery/bootstrap-tagsinput/bootstrap-tagsinput.css";',
'@import (inline) "../public/vendor/jquery/bootstrap-tagsinput/bootstrap-tagsinput.css";', '@import (inline) "../public/vendor/colorpicker/colorpicker.css";',
'@import (inline) "../public/vendor/colorpicker/colorpicker.css";', '@import (inline) "../node_modules/cropperjs/dist/cropper.css";',
'@import (inline) "../node_modules/cropperjs/dist/cropper.css";', '@import "../../public/less/flags.less";',
'@import "../../public/less/flags.less";', '@import "../../public/less/blacklist.less";',
'@import "../../public/less/blacklist.less";', '@import "../../public/less/generics.less";',
'@import "../../public/less/generics.less";', '@import "../../public/less/mixins.less";',
'@import "../../public/less/mixins.less";', '@import "../../public/less/global.less";',
'@import "../../public/less/global.less";', ].map(function (str) {
].map(function (str) { return str.replace(/\//g, path.sep);
return str.replace(/\//g, path.sep); }).join('\n');
}).join('\n'); },
}, admin: function (source) {
admin: function (source) { return source + '\n' + [
return source + '\n' + [ '@import "font-awesome";',
'@import "font-awesome";', '@import "../public/less/admin/admin";',
'@import "../public/less/admin/admin";', '@import "../public/less/generics.less";',
'@import "../public/less/generics.less";', '@import (inline) "../public/vendor/colorpicker/colorpicker.css";',
'@import (inline) "../public/vendor/colorpicker/colorpicker.css";', '@import (inline) "../public/vendor/jquery/css/smoothness/jquery-ui.css";',
'@import (inline) "../public/vendor/jquery/css/smoothness/jquery-ui.css";', '@import (inline) "../public/vendor/jquery/bootstrap-tagsinput/bootstrap-tagsinput.css";',
'@import (inline) "../public/vendor/jquery/bootstrap-tagsinput/bootstrap-tagsinput.css";', '@import (inline) "../public/vendor/mdl/material.css";',
'@import (inline) "../public/vendor/mdl/material.css";', ].map(function (str) {
].map(function (str) { return str.replace(/\//g, path.sep);
return str.replace(/\//g, path.sep); }).join('\n');
}).join('\n'); },
}, };
};
function filterMissingFiles(filepaths, callback) { function filterMissingFiles(filepaths, callback) {
async.filter(filepaths, function (filepath, next) { async.filter(filepaths, function (filepath, next) {
file.exists(path.join(__dirname, '../../node_modules', filepath), function (err, exists) { file.exists(path.join(__dirname, '../../node_modules', filepath), function (err, exists) {
if (!exists) { if (!exists) {
winston.warn('[meta/css] File not found! ' + filepath); winston.warn('[meta/css] File not found! ' + filepath);
} }
next(err, exists);
});
}, callback);
}
function getImports(files, prefix, extension, callback) {
var pluginDirectories = [];
var source = '';
files.forEach(function (styleFile) {
if (styleFile.endsWith(extension)) {
source += prefix + path.sep + styleFile + '";';
} else {
pluginDirectories.push(styleFile);
}
});
async.each(pluginDirectories, function (directory, next) {
file.walk(directory, function (err, styleFiles) {
if (err) {
return next(err);
}
next(err, exists); styleFiles.forEach(function (styleFile) {
source += prefix + path.sep + styleFile + '";';
}); });
}, callback);
}
function getImports(files, prefix, extension, callback) { next();
var pluginDirectories = []; });
var source = ''; }, function (err) {
callback(err, source);
});
}
function getBundleMetadata(target, callback) {
var paths = [
path.join(__dirname, '../../node_modules'),
path.join(__dirname, '../../public/vendor/fontawesome/less'),
];
async.waterfall([
function (next) {
if (target !== 'client') {
return next(null, null);
}
files.forEach(function (styleFile) { db.getObjectFields('config', ['theme:type', 'theme:id'], next);
if (styleFile.endsWith(extension)) { },
source += prefix + path.sep + styleFile + '";'; function (themeData, next) {
} else { if (target === 'client') {
pluginDirectories.push(styleFile); var themeId = (themeData['theme:id'] || 'nodebb-theme-persona');
var baseThemePath = path.join(nconf.get('themes_path'), (themeData['theme:type'] && themeData['theme:type'] === 'local' ? themeId : 'nodebb-theme-vanilla'));
paths.unshift(baseThemePath);
} }
});
async.each(pluginDirectories, function (directory, next) { async.parallel({
file.walk(directory, function (err, styleFiles) { less: function (cb) {
if (err) { async.waterfall([
return next(err); function (next) {
} filterMissingFiles(plugins.lessFiles, next);
},
function (lessFiles, next) {
getImports(lessFiles, '\n@import ".', '.less', next);
},
], cb);
},
css: function (cb) {
async.waterfall([
function (next) {
filterMissingFiles(plugins.cssFiles, next);
},
function (cssFiles, next) {
getImports(cssFiles, '\n@import (inline) ".', '.css', next);
},
], cb);
},
}, next);
},
function (result, next) {
var cssImports = result.css;
var lessImports = result.less;
styleFiles.forEach(function (styleFile) { var imports = cssImports + '\n' + lessImports;
source += prefix + path.sep + styleFile + '";'; imports = buildImports[target](imports);
});
next(); next(null, imports);
}); },
}, function (err) { ], function (err, imports) {
callback(err, source); if (err) {
}); return callback(err);
} }
function getBundleMetadata(target, callback) { callback(null, { paths: paths, imports: imports });
var paths = [ });
path.join(__dirname, '../../node_modules'), }
path.join(__dirname, '../../public/vendor/fontawesome/less'),
]; CSS.buildBundle = function (target, fork, callback) {
async.waterfall([
async.waterfall([ function (next) {
function (next) { getBundleMetadata(target, next);
if (target !== 'client') { },
return next(null, null); function (data, next) {
} var minify = global.env !== 'development';
minifier.css.bundle(data.imports, data.paths, minify, fork, next);
db.getObjectFields('config', ['theme:type', 'theme:id'], next); },
}, function (bundle, next) {
function (themeData, next) { var filename = (target === 'client' ? 'stylesheet' : 'admin') + '.css';
if (target === 'client') {
var themeId = (themeData['theme:id'] || 'nodebb-theme-persona');
var baseThemePath = path.join(nconf.get('themes_path'), (themeData['theme:type'] && themeData['theme:type'] === 'local' ? themeId : 'nodebb-theme-vanilla'));
paths.unshift(baseThemePath);
}
async.parallel({
less: function (cb) {
async.waterfall([
function (next) {
filterMissingFiles(plugins.lessFiles, next);
},
function (lessFiles, next) {
getImports(lessFiles, '\n@import ".', '.less', next);
},
], cb);
},
css: function (cb) {
async.waterfall([
function (next) {
filterMissingFiles(plugins.cssFiles, next);
},
function (cssFiles, next) {
getImports(cssFiles, '\n@import (inline) ".', '.css', next);
},
], cb);
},
}, next);
},
function (result, next) {
var cssImports = result.css;
var lessImports = result.less;
var imports = cssImports + '\n' + lessImports;
imports = buildImports[target](imports);
next(null, imports);
},
], function (err, imports) {
if (err) {
return callback(err);
}
callback(null, { paths: paths, imports: imports }); fs.writeFile(path.join(__dirname, '../../build/public', filename), bundle.code, next);
}); },
} ], callback);
Meta.css.buildBundle = function (target, fork, callback) {
async.waterfall([
function (next) {
getBundleMetadata(target, next);
},
function (data, next) {
var minify = global.env !== 'development';
minifier.css.bundle(data.imports, data.paths, minify, fork, next);
},
function (bundle, next) {
var filename = (target === 'client' ? 'stylesheet' : 'admin') + '.css';
fs.writeFile(path.join(__dirname, '../../build/public', filename), bundle.code, next);
},
], callback);
};
}; };

@ -9,73 +9,72 @@ require('colors');
var pkg = require('../../package.json'); var pkg = require('../../package.json');
module.exports = function (Meta) { var Dependencies = module.exports;
Meta.dependencies = {};
var depsMissing = false;
var depsOutdated = false;
Meta.dependencies.check = function (callback) { var depsMissing = false;
var modules = Object.keys(pkg.dependencies); var depsOutdated = false;
winston.verbose('Checking dependencies for outdated modules'); Dependencies.check = function (callback) {
var modules = Object.keys(pkg.dependencies);
async.each(modules, Meta.dependencies.checkModule, function (err) { winston.verbose('Checking dependencies for outdated modules');
if (err) {
return callback(err);
}
if (depsMissing) { async.each(modules, Dependencies.checkModule, function (err) {
callback(new Error('dependencies-missing')); if (err) {
} else if (depsOutdated) { return callback(err);
callback(global.env !== 'development' ? new Error('dependencies-out-of-date') : null); }
} else {
callback(null); if (depsMissing) {
} callback(new Error('dependencies-missing'));
}); } else if (depsOutdated) {
}; callback(global.env !== 'development' ? new Error('dependencies-out-of-date') : null);
} else {
callback(null);
}
});
};
Meta.dependencies.checkModule = function (moduleName, callback) { Dependencies.checkModule = function (moduleName, callback) {
fs.readFile(path.join(__dirname, '../../node_modules/', moduleName, 'package.json'), { fs.readFile(path.join(__dirname, '../../node_modules/', moduleName, 'package.json'), {
encoding: 'utf-8', encoding: 'utf-8',
}, function (err, pkgData) { }, function (err, pkgData) {
if (err) { if (err) {
// If a bundled plugin/theme is not present, skip the dep check (#3384) // If a bundled plugin/theme is not present, skip the dep check (#3384)
if (err.code === 'ENOENT' && (moduleName === 'nodebb-rewards-essentials' || moduleName.startsWith('nodebb-plugin') || moduleName.startsWith('nodebb-theme'))) { if (err.code === 'ENOENT' && (moduleName === 'nodebb-rewards-essentials' || moduleName.startsWith('nodebb-plugin') || moduleName.startsWith('nodebb-theme'))) {
winston.warn('[meta/dependencies] Bundled plugin ' + moduleName + ' not found, skipping dependency check.'); winston.warn('[meta/dependencies] Bundled plugin ' + moduleName + ' not found, skipping dependency check.');
return callback(null, true); return callback(null, true);
}
return callback(err);
} }
return callback(err);
}
pkgData = Meta.dependencies.parseModuleData(moduleName, pkgData); pkgData = Dependencies.parseModuleData(moduleName, pkgData);
var satisfies = Meta.dependencies.doesSatisfy(pkgData, pkg.dependencies[moduleName]); var satisfies = Dependencies.doesSatisfy(pkgData, pkg.dependencies[moduleName]);
callback(null, satisfies); callback(null, satisfies);
}); });
}; };
Meta.dependencies.parseModuleData = function (moduleName, pkgData) { Dependencies.parseModuleData = function (moduleName, pkgData) {
try { try {
pkgData = JSON.parse(pkgData); pkgData = JSON.parse(pkgData);
} catch (e) { } catch (e) {
winston.warn('[' + 'missing'.red + '] ' + moduleName.bold + ' is a required dependency but could not be found\n'); winston.warn('[' + 'missing'.red + '] ' + moduleName.bold + ' is a required dependency but could not be found\n');
depsMissing = true; depsMissing = true;
return null; return null;
} }
return pkgData; return pkgData;
}; };
Meta.dependencies.doesSatisfy = function (moduleData, packageJSONVersion) { Dependencies.doesSatisfy = function (moduleData, packageJSONVersion) {
if (!moduleData) { if (!moduleData) {
return false; return false;
} }
var versionOk = !semver.validRange(packageJSONVersion) || semver.satisfies(moduleData.version, packageJSONVersion); var versionOk = !semver.validRange(packageJSONVersion) || semver.satisfies(moduleData.version, packageJSONVersion);
var githubRepo = moduleData._resolved && moduleData._resolved.indexOf('//github.com') !== -1; var githubRepo = moduleData._resolved && moduleData._resolved.indexOf('//github.com') !== -1;
var satisfies = versionOk || githubRepo; var satisfies = versionOk || githubRepo;
if (!satisfies) { if (!satisfies) {
winston.warn('[' + 'outdated'.yellow + '] ' + moduleData.name.bold + ' installed v' + moduleData.version + ', package.json requires ' + packageJSONVersion + '\n'); winston.warn('[' + 'outdated'.yellow + '] ' + moduleData.name.bold + ' installed v' + moduleData.version + ', package.json requires ' + packageJSONVersion + '\n');
depsOutdated = true; depsOutdated = true;
} }
return satisfies; return satisfies;
};
}; };

@ -8,61 +8,59 @@ var cronJob = require('cron').CronJob;
var db = require('../database'); var db = require('../database');
var analytics = require('../analytics'); var analytics = require('../analytics');
module.exports = function (Meta) { var Errors = module.exports;
Meta.errors = {};
var counters = {}; var counters = {};
new cronJob('0 * * * * *', function () { new cronJob('0 * * * * *', function () {
Meta.errors.writeData(); Errors.writeData();
}, null, true); }, null, true);
Meta.errors.writeData = function () { Errors.writeData = function () {
var dbQueue = []; var dbQueue = [];
if (Object.keys(counters).length > 0) { if (Object.keys(counters).length > 0) {
for (var key in counters) { for (var key in counters) {
if (counters.hasOwnProperty(key)) { if (counters.hasOwnProperty(key)) {
dbQueue.push(async.apply(db.sortedSetIncrBy, 'errors:404', counters[key], key)); dbQueue.push(async.apply(db.sortedSetIncrBy, 'errors:404', counters[key], key));
}
} }
counters = {};
async.series(dbQueue, function (err) {
if (err) {
winston.error(err);
}
});
} }
}; counters = {};
async.series(dbQueue, function (err) {
if (err) {
winston.error(err);
}
});
}
};
Meta.errors.log404 = function (route, callback) { Errors.log404 = function (route, callback) {
callback = callback || function () {}; callback = callback || function () {};
if (!route) { if (!route) {
return setImmediate(callback); return setImmediate(callback);
} }
route = route.replace(/\/$/, ''); // remove trailing slashes route = route.replace(/\/$/, ''); // remove trailing slashes
analytics.increment('errors:404'); analytics.increment('errors:404');
counters[route] = counters[route] || 0; counters[route] = counters[route] || 0;
counters[route] += 1; counters[route] += 1;
setImmediate(callback); setImmediate(callback);
}; };
Meta.errors.get = function (escape, callback) { Errors.get = function (escape, callback) {
async.waterfall([ async.waterfall([
function (next) { function (next) {
db.getSortedSetRevRangeWithScores('errors:404', 0, 199, next); db.getSortedSetRevRangeWithScores('errors:404', 0, 199, next);
}, },
function (data, next) { function (data, next) {
data = data.map(function (nfObject) { data = data.map(function (nfObject) {
nfObject.value = escape ? validator.escape(String(nfObject.value || '')) : nfObject.value; nfObject.value = escape ? validator.escape(String(nfObject.value || '')) : nfObject.value;
return nfObject; return nfObject;
}); });
next(null, data); next(null, data);
}, },
], callback); ], callback);
}; };
Meta.errors.clear = function (callback) { Errors.clear = function (callback) {
db.delete('errors:404', callback); db.delete('errors:404', callback);
};
}; };

@ -10,341 +10,339 @@ var file = require('../file');
var plugins = require('../plugins'); var plugins = require('../plugins');
var minifier = require('./minifier'); var minifier = require('./minifier');
module.exports = function (Meta) { var JS = module.exports;
Meta.js = {};
JS.scripts = {
Meta.js.scripts = { base: [
base: [ 'node_modules/jquery/dist/jquery.js',
'node_modules/jquery/dist/jquery.js', 'node_modules/socket.io-client/dist/socket.io.js',
'node_modules/socket.io-client/dist/socket.io.js', 'public/vendor/jquery/timeago/jquery.timeago.js',
'public/vendor/jquery/timeago/jquery.timeago.js', 'public/vendor/jquery/js/jquery.form.min.js',
'public/vendor/jquery/js/jquery.form.min.js', 'public/vendor/visibility/visibility.min.js',
'public/vendor/visibility/visibility.min.js', 'node_modules/bootstrap/dist/js/bootstrap.js',
'node_modules/bootstrap/dist/js/bootstrap.js', 'public/vendor/jquery/bootstrap-tagsinput/bootstrap-tagsinput.min.js',
'public/vendor/jquery/bootstrap-tagsinput/bootstrap-tagsinput.min.js', 'public/vendor/jquery/textcomplete/jquery.textcomplete.js',
'public/vendor/jquery/textcomplete/jquery.textcomplete.js', 'public/vendor/requirejs/require.js',
'public/vendor/requirejs/require.js', 'public/src/require-config.js',
'public/src/require-config.js', 'public/vendor/bootbox/bootbox.js',
'public/vendor/bootbox/bootbox.js', 'public/vendor/bootbox/wrapper.js',
'public/vendor/bootbox/wrapper.js', 'public/vendor/tinycon/tinycon.js',
'public/vendor/tinycon/tinycon.js', 'public/vendor/xregexp/xregexp.js',
'public/vendor/xregexp/xregexp.js', 'public/vendor/xregexp/unicode/unicode-base.js',
'public/vendor/xregexp/unicode/unicode-base.js', 'node_modules/templates.js/lib/templates.js',
'node_modules/templates.js/lib/templates.js', 'public/src/utils.js',
'public/src/utils.js', 'public/src/sockets.js',
'public/src/sockets.js', 'public/src/app.js',
'public/src/app.js', 'public/src/ajaxify.js',
'public/src/ajaxify.js', 'public/src/overrides.js',
'public/src/overrides.js', 'public/src/widgets.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
// files listed below are only available client-side, or are bundled in to reduce # of network requests on cold load rjs: [
rjs: [ 'public/src/client/footer.js',
'public/src/client/footer.js', 'public/src/client/chats.js',
'public/src/client/chats.js', 'public/src/client/infinitescroll.js',
'public/src/client/infinitescroll.js', 'public/src/client/pagination.js',
'public/src/client/pagination.js', 'public/src/client/recent.js',
'public/src/client/recent.js', 'public/src/client/unread.js',
'public/src/client/unread.js', 'public/src/client/topic.js',
'public/src/client/topic.js', 'public/src/client/topic/events.js',
'public/src/client/topic/events.js', 'public/src/client/topic/fork.js',
'public/src/client/topic/fork.js', 'public/src/client/topic/move.js',
'public/src/client/topic/move.js', 'public/src/client/topic/posts.js',
'public/src/client/topic/posts.js', 'public/src/client/topic/images.js',
'public/src/client/topic/images.js', 'public/src/client/topic/postTools.js',
'public/src/client/topic/postTools.js', 'public/src/client/topic/threadTools.js',
'public/src/client/topic/threadTools.js', 'public/src/client/categories.js',
'public/src/client/categories.js', 'public/src/client/category.js',
'public/src/client/category.js', 'public/src/client/category/tools.js',
'public/src/client/category/tools.js',
'public/src/modules/translator.js',
'public/src/modules/translator.js', 'public/src/modules/notifications.js',
'public/src/modules/notifications.js', 'public/src/modules/chat.js',
'public/src/modules/chat.js', 'public/src/modules/components.js',
'public/src/modules/components.js', 'public/src/modules/sort.js',
'public/src/modules/sort.js', 'public/src/modules/navigator.js',
'public/src/modules/navigator.js', 'public/src/modules/topicSelect.js',
'public/src/modules/topicSelect.js', 'public/src/modules/categorySelector.js',
'public/src/modules/categorySelector.js', 'public/src/modules/share.js',
'public/src/modules/share.js', 'public/src/modules/search.js',
'public/src/modules/search.js', 'public/src/modules/alerts.js',
'public/src/modules/alerts.js', 'public/src/modules/taskbar.js',
'public/src/modules/taskbar.js', 'public/src/modules/helpers.js',
'public/src/modules/helpers.js', 'public/src/modules/string.js',
'public/src/modules/string.js', 'public/src/modules/flags.js',
'public/src/modules/flags.js', 'public/src/modules/storage.js',
'public/src/modules/storage.js', ],
],
// modules listed below are built (/src/modules) so they can be defined anonymously
// modules listed below are built (/src/modules) so they can be defined anonymously modules: {
modules: { 'Chart.js': 'node_modules/chart.js/dist/Chart.min.js',
'Chart.js': 'node_modules/chart.js/dist/Chart.min.js', 'mousetrap.js': 'node_modules/mousetrap/mousetrap.min.js',
'mousetrap.js': 'node_modules/mousetrap/mousetrap.min.js', 'cropper.js': 'node_modules/cropperjs/dist/cropper.min.js',
'cropper.js': 'node_modules/cropperjs/dist/cropper.min.js', 'jqueryui.js': 'public/vendor/jquery/js/jquery-ui.js',
'jqueryui.js': 'public/vendor/jquery/js/jquery-ui.js', 'zxcvbn.js': 'node_modules/zxcvbn/dist/zxcvbn.js',
'zxcvbn.js': 'node_modules/zxcvbn/dist/zxcvbn.js', ace: 'node_modules/ace-builds/src-min',
ace: 'node_modules/ace-builds/src-min', },
}, };
};
var basePath = path.resolve(__dirname, '../..');
function minifyModules(modules, fork, callback) {
var moduleDirs = modules.reduce(function (prev, mod) {
var dir = path.resolve(path.dirname(mod.destPath));
if (prev.indexOf(dir) === -1) {
prev.push(dir);
}
return prev;
}, []);
async.eachLimit(moduleDirs, 1000, mkdirp, function (err) {
if (err) {
return callback(err);
}
var filtered = modules.reduce(function (prev, mod) {
if (mod.srcPath.endsWith('.min.js') || path.dirname(mod.srcPath).endsWith('min')) {
prev.skip.push(mod);
} else {
prev.minify.push(mod);
}
return prev;
}, { minify: [], skip: [] });
async.parallel([
function (cb) {
minifier.js.minifyBatch(filtered.minify, fork, cb);
},
function (cb) {
async.eachLimit(filtered.skip, 500, function (mod, next) {
file.link(mod.srcPath, mod.destPath, next);
}, cb);
},
], callback);
});
}
function linkModules(callback) { var basePath = path.resolve(__dirname, '../..');
var modules = Meta.js.scripts.modules;
async.eachLimit(Object.keys(modules), 1000, function (relPath, next) {
var srcPath = path.join(__dirname, '../../', modules[relPath]);
var destPath = path.join(__dirname, '../../build/public/src/modules', relPath);
async.parallel({
dir: function (cb) {
mkdirp(path.dirname(destPath), function (err) {
cb(err);
});
},
stats: function (cb) {
fs.stat(srcPath, cb);
},
}, function (err, res) {
if (err) {
return next(err);
}
if (res.stats.isDirectory()) {
return file.linkDirs(srcPath, destPath, next);
}
if (process.platform === 'win32') { function minifyModules(modules, fork, callback) {
fs.readFile(srcPath, function (err, file) { var moduleDirs = modules.reduce(function (prev, mod) {
if (err) { var dir = path.resolve(path.dirname(mod.destPath));
return next(err); if (prev.indexOf(dir) === -1) {
} prev.push(dir);
}
return prev;
}, []);
fs.writeFile(destPath, file, next); async.eachLimit(moduleDirs, 1000, mkdirp, function (err) {
}); if (err) {
} else { return callback(err);
file.link(srcPath, destPath, next); }
}
});
}, callback);
}
var moduleDirs = ['modules', 'admin', 'client']; var filtered = modules.reduce(function (prev, mod) {
if (mod.srcPath.endsWith('.min.js') || path.dirname(mod.srcPath).endsWith('min')) {
prev.skip.push(mod);
} else {
prev.minify.push(mod);
}
function getModuleList(callback) { return prev;
var modules = Object.keys(Meta.js.scripts.modules).map(function (relPath) { }, { minify: [], skip: [] });
return {
srcPath: path.join(__dirname, '../../', Meta.js.scripts.modules[relPath]),
destPath: path.join(__dirname, '../../build/public/src/modules', relPath),
};
});
var coreDirs = moduleDirs.map(function (dir) { async.parallel([
return { function (cb) {
srcPath: path.join(__dirname, '../../public/src', dir), minifier.js.minifyBatch(filtered.minify, fork, cb);
destPath: path.join(__dirname, '../../build/public/src', dir), },
}; function (cb) {
}); async.eachLimit(filtered.skip, 500, function (mod, next) {
file.link(mod.srcPath, mod.destPath, next);
}, cb);
},
], callback);
});
}
modules = modules.concat(coreDirs); function linkModules(callback) {
var modules = JS.scripts.modules;
var moduleFiles = []; async.eachLimit(Object.keys(modules), 1000, function (relPath, next) {
async.eachLimit(modules, 1000, function (module, next) { var srcPath = path.join(__dirname, '../../', modules[relPath]);
var srcPath = module.srcPath; var destPath = path.join(__dirname, '../../build/public/src/modules', relPath);
var destPath = module.destPath;
fs.stat(srcPath, function (err, stats) { async.parallel({
if (err) { dir: function (cb) {
return next(err); mkdirp(path.dirname(destPath), function (err) {
} cb(err);
if (!stats.isDirectory()) { });
moduleFiles.push(module); },
return next(); stats: function (cb) {
} fs.stat(srcPath, cb);
},
}, function (err, res) {
if (err) {
return next(err);
}
if (res.stats.isDirectory()) {
return file.linkDirs(srcPath, destPath, next);
}
file.walk(srcPath, function (err, files) { if (process.platform === 'win32') {
fs.readFile(srcPath, function (err, file) {
if (err) { if (err) {
return next(err); return next(err);
} }
var mods = files.filter(function (filePath) { fs.writeFile(destPath, file, next);
return path.extname(filePath) === '.js';
}).map(function (filePath) {
return {
srcPath: path.normalize(filePath),
destPath: path.join(destPath, path.relative(srcPath, filePath)),
};
});
moduleFiles = moduleFiles.concat(mods).map(function (mod) {
mod.filename = path.relative(basePath, mod.srcPath).replace(/\\/g, '/');
return mod;
});
next();
}); });
}); } else {
}, function (err) { file.link(srcPath, destPath, next);
callback(err, moduleFiles); }
}); });
} }, callback);
}
function clearModules(callback) { var moduleDirs = ['modules', 'admin', 'client'];
var builtPaths = moduleDirs.map(function (p) {
return path.join(__dirname, '../../build/public/src', p);
});
async.each(builtPaths, function (builtPath, next) {
rimraf(builtPath, next);
}, function (err) {
callback(err);
});
}
Meta.js.buildModules = function (fork, callback) { function getModuleList(callback) {
async.waterfall([ var modules = Object.keys(JS.scripts.modules).map(function (relPath) {
clearModules, return {
function (next) { srcPath: path.join(__dirname, '../../', JS.scripts.modules[relPath]),
if (global.env === 'development') { destPath: path.join(__dirname, '../../build/public/src/modules', relPath),
return linkModules(callback); };
} });
getModuleList(next); var coreDirs = moduleDirs.map(function (dir) {
}, return {
function (modules, next) { srcPath: path.join(__dirname, '../../public/src', dir),
minifyModules(modules, fork, next); destPath: path.join(__dirname, '../../build/public/src', dir),
}, };
], callback); });
};
modules = modules.concat(coreDirs);
var moduleFiles = [];
async.eachLimit(modules, 1000, function (module, next) {
var srcPath = module.srcPath;
var destPath = module.destPath;
Meta.js.linkStatics = function (callback) { fs.stat(srcPath, function (err, stats) {
rimraf(path.join(__dirname, '../../build/public/plugins'), function (err) {
if (err) { if (err) {
return callback(err); return next(err);
}
if (!stats.isDirectory()) {
moduleFiles.push(module);
return next();
} }
async.eachLimit(Object.keys(plugins.staticDirs), 1000, function (mappedPath, next) {
var sourceDir = plugins.staticDirs[mappedPath];
var destDir = path.join(__dirname, '../../build/public/plugins', mappedPath);
mkdirp(path.dirname(destDir), function (err) { file.walk(srcPath, function (err, files) {
if (err) { if (err) {
return next(err); return next(err);
} }
file.linkDirs(sourceDir, destDir, next); var mods = files.filter(function (filePath) {
return path.extname(filePath) === '.js';
}).map(function (filePath) {
return {
srcPath: path.normalize(filePath),
destPath: path.join(destPath, path.relative(srcPath, filePath)),
};
}); });
}, callback);
});
};
function getBundleScriptList(target, callback) { moduleFiles = moduleFiles.concat(mods).map(function (mod) {
var pluginDirectories = []; mod.filename = path.relative(basePath, mod.srcPath).replace(/\\/g, '/');
return mod;
});
if (target === 'admin') { next();
target = 'acp'; });
} });
var pluginScripts = plugins[target + 'Scripts'].filter(function (path) { }, function (err) {
if (path.endsWith('.js')) { callback(err, moduleFiles);
return true; });
}
function clearModules(callback) {
var builtPaths = moduleDirs.map(function (p) {
return path.join(__dirname, '../../build/public/src', p);
});
async.each(builtPaths, function (builtPath, next) {
rimraf(builtPath, next);
}, function (err) {
callback(err);
});
}
JS.buildModules = function (fork, callback) {
async.waterfall([
clearModules,
function (next) {
if (global.env === 'development') {
return linkModules(callback);
} }
pluginDirectories.push(path); getModuleList(next);
return false; },
}); function (modules, next) {
minifyModules(modules, fork, next);
},
], callback);
};
JS.linkStatics = function (callback) {
rimraf(path.join(__dirname, '../../build/public/plugins'), function (err) {
if (err) {
return callback(err);
}
async.eachLimit(Object.keys(plugins.staticDirs), 1000, function (mappedPath, next) {
var sourceDir = plugins.staticDirs[mappedPath];
var destDir = path.join(__dirname, '../../build/public/plugins', mappedPath);
async.each(pluginDirectories, function (directory, next) { mkdirp(path.dirname(destDir), function (err) {
file.walk(directory, function (err, scripts) {
if (err) { if (err) {
return next(err); return next(err);
} }
pluginScripts = pluginScripts.concat(scripts); file.linkDirs(sourceDir, destDir, next);
next();
}); });
}, function (err) { }, callback);
});
};
function getBundleScriptList(target, callback) {
var pluginDirectories = [];
if (target === 'admin') {
target = 'acp';
}
var pluginScripts = plugins[target + 'Scripts'].filter(function (path) {
if (path.endsWith('.js')) {
return true;
}
pluginDirectories.push(path);
return false;
});
async.each(pluginDirectories, function (directory, next) {
file.walk(directory, function (err, scripts) {
if (err) { if (err) {
return callback(err); return next(err);
} }
var scripts = Meta.js.scripts.base.concat(pluginScripts); pluginScripts = pluginScripts.concat(scripts);
next();
});
}, function (err) {
if (err) {
return callback(err);
}
if (target === 'client' && global.env !== 'development') { var scripts = JS.scripts.base.concat(pluginScripts);
scripts = scripts.concat(Meta.js.scripts.rjs);
}
scripts = scripts.map(function (script) { if (target === 'client' && global.env !== 'development') {
var srcPath = path.resolve(basePath, script).replace(/\\/g, '/'); scripts = scripts.concat(JS.scripts.rjs);
return { }
srcPath: srcPath,
filename: path.relative(basePath, srcPath).replace(/\\/g, '/'),
};
});
callback(null, scripts); scripts = scripts.map(function (script) {
var srcPath = path.resolve(basePath, script).replace(/\\/g, '/');
return {
srcPath: srcPath,
filename: path.relative(basePath, srcPath).replace(/\\/g, '/'),
};
}); });
}
Meta.js.buildBundle = function (target, fork, callback) { callback(null, scripts);
var fileNames = { });
client: 'nodebb.min.js', }
admin: 'acp.min.js',
};
async.waterfall([ JS.buildBundle = function (target, fork, callback) {
function (next) { var fileNames = {
getBundleScriptList(target, next); client: 'nodebb.min.js',
}, admin: 'acp.min.js',
function (files, next) {
var minify = global.env !== 'development';
var filePath = path.join(__dirname, '../../build/public', fileNames[target]);
minifier.js.bundle({
files: files,
filename: fileNames[target],
destPath: filePath,
}, minify, fork, next);
},
], callback);
}; };
Meta.js.killMinifier = function () { async.waterfall([
minifier.killAll(); function (next) {
}; getBundleScriptList(target, next);
},
function (files, next) {
var minify = global.env !== 'development';
var filePath = path.join(__dirname, '../../build/public', fileNames[target]);
minifier.js.bundle({
files: files,
filename: fileNames[target],
destPath: filePath,
}, minify, fork, next);
},
], callback);
};
JS.killMinifier = function () {
minifier.killAll();
}; };

@ -3,18 +3,16 @@
var path = require('path'); var path = require('path');
var fs = require('fs'); var fs = require('fs');
module.exports = function (Meta) { var Logs = module.exports;
Meta.logs = {
path: path.join(__dirname, '..', '..', 'logs', 'output.log'),
};
Meta.logs.get = function (callback) { Logs.path = path.join(__dirname, '..', '..', 'logs', 'output.log');
fs.readFile(Meta.logs.path, {
encoding: 'utf-8',
}, callback);
};
Meta.logs.clear = function (callback) { Logs.get = function (callback) {
fs.truncate(Meta.logs.path, 0, callback); fs.readFile(Logs.path, {
}; encoding: 'utf-8',
}, callback);
};
Logs.clear = function (callback) {
fs.truncate(Logs.path, 0, callback);
}; };

@ -4,61 +4,60 @@ var async = require('async');
var db = require('../database'); var db = require('../database');
var plugins = require('../plugins'); var plugins = require('../plugins');
var Meta = require('../meta');
module.exports = function (Meta) { var Settings = module.exports;
Meta.settings = {};
Meta.settings.get = function (hash, callback) { Settings.get = function (hash, callback) {
db.getObject('settings:' + hash, function (err, settings) { db.getObject('settings:' + hash, function (err, settings) {
callback(err, settings || {}); callback(err, settings || {});
}); });
}; };
Meta.settings.getOne = function (hash, field, callback) {
db.getObjectField('settings:' + hash, field, callback);
};
Meta.settings.set = function (hash, values, callback) {
async.waterfall([
function (next) {
db.setObject('settings:' + hash, values, next);
},
function (next) {
plugins.fireHook('action:settings.set', {
plugin: hash,
settings: values,
});
Meta.reloadRequired = true; Settings.getOne = function (hash, field, callback) {
next(); db.getObjectField('settings:' + hash, field, callback);
}, };
], callback);
};
Meta.settings.setOne = function (hash, field, value, callback) { Settings.set = function (hash, values, callback) {
db.setObjectField('settings:' + hash, field, value, callback); async.waterfall([
}; function (next) {
db.setObject('settings:' + hash, values, next);
},
function (next) {
plugins.fireHook('action:settings.set', {
plugin: hash,
settings: values,
});
Meta.reloadRequired = true;
next();
},
], callback);
};
Meta.settings.setOnEmpty = function (hash, values, callback) { Settings.setOne = function (hash, field, value, callback) {
async.waterfall([ db.setObjectField('settings:' + hash, field, value, callback);
function (next) { };
db.getObject('settings:' + hash, next);
},
function (settings, next) {
settings = settings || {};
var empty = {};
Object.keys(values).forEach(function (key) {
if (!settings.hasOwnProperty(key)) {
empty[key] = values[key];
}
});
if (Object.keys(empty).length) { Settings.setOnEmpty = function (hash, values, callback) {
db.setObject('settings:' + hash, empty, next); async.waterfall([
} else { function (next) {
next(); db.getObject('settings:' + hash, next);
},
function (settings, next) {
settings = settings || {};
var empty = {};
Object.keys(values).forEach(function (key) {
if (!settings.hasOwnProperty(key)) {
empty[key] = values[key];
} }
}, });
], callback);
}; if (Object.keys(empty).length) {
db.setObject('settings:' + hash, empty, next);
} else {
next();
}
},
], callback);
}; };

@ -9,125 +9,124 @@ var async = require('async');
var file = require('../file'); var file = require('../file');
var plugins = require('../plugins'); var plugins = require('../plugins');
var user = require('../user'); var user = require('../user');
var Meta = require('../meta');
var soundsPath = path.join(__dirname, '../../build/public/sounds'); var soundsPath = path.join(__dirname, '../../build/public/sounds');
var uploadsPath = path.join(__dirname, '../../public/uploads/sounds'); var uploadsPath = path.join(__dirname, '../../public/uploads/sounds');
module.exports = function (Meta) { var Sounds = module.exports;
Meta.sounds = {};
Meta.sounds.addUploads = function addUploads(callback) { Sounds.addUploads = function addUploads(callback) {
fs.readdir(uploadsPath, function (err, files) { fs.readdir(uploadsPath, function (err, files) {
if (err) { if (err) {
if (err.code !== 'ENOENT') { if (err.code !== 'ENOENT') {
return callback(err); return callback(err);
}
files = [];
} }
var uploadSounds = files.reduce(function (prev, fileName) { files = [];
var name = fileName.split('.'); }
if (!name.length || !name[0].length) {
return prev;
}
name = name[0];
name = name[0].toUpperCase() + name.slice(1);
prev[name] = fileName; var uploadSounds = files.reduce(function (prev, fileName) {
var name = fileName.split('.');
if (!name.length || !name[0].length) {
return prev; return prev;
}, {});
plugins.soundpacks = plugins.soundpacks.filter(function (pack) {
return pack.name !== 'Uploads';
});
if (Object.keys(uploadSounds).length) {
plugins.soundpacks.push({
name: 'Uploads',
id: 'uploads',
dir: uploadsPath,
sounds: uploadSounds,
});
} }
name = name[0];
name = name[0].toUpperCase() + name.slice(1);
prev[name] = fileName;
return prev;
}, {});
callback(); plugins.soundpacks = plugins.soundpacks.filter(function (pack) {
return pack.name !== 'Uploads';
}); });
}; if (Object.keys(uploadSounds).length) {
plugins.soundpacks.push({
name: 'Uploads',
id: 'uploads',
dir: uploadsPath,
sounds: uploadSounds,
});
}
Meta.sounds.build = function build(callback) { callback();
Meta.sounds.addUploads(function (err) { });
if (err) { };
return callback(err);
}
var map = plugins.soundpacks.map(function (pack) { Sounds.build = function build(callback) {
return Object.keys(pack.sounds).reduce(function (prev, soundName) { Sounds.addUploads(function (err) {
var soundPath = pack.sounds[soundName]; if (err) {
prev[pack.name + ' | ' + soundName] = pack.id + '/' + soundPath; return callback(err);
return prev; }
}, {});
});
map.unshift({});
map = Object.assign.apply(null, map);
async.series([
function (next) {
rimraf(soundsPath, next);
},
function (next) {
mkdirp(soundsPath, next);
},
function (cb) {
async.parallel([
function (next) {
fs.writeFile(path.join(soundsPath, 'fileMap.json'), JSON.stringify(map), next);
},
function (next) {
async.each(plugins.soundpacks, function (pack, next) {
file.linkDirs(pack.dir, path.join(soundsPath, pack.id), next);
}, next);
},
], cb);
},
], function (err) {
callback(err);
});
});
};
var keys = ['chat-incoming', 'chat-outgoing', 'notification']; var map = plugins.soundpacks.map(function (pack) {
return Object.keys(pack.sounds).reduce(function (prev, soundName) {
var soundPath = pack.sounds[soundName];
prev[pack.name + ' | ' + soundName] = pack.id + '/' + soundPath;
return prev;
}, {});
});
map.unshift({});
map = Object.assign.apply(null, map);
Meta.sounds.getUserSoundMap = function getUserSoundMap(uid, callback) { async.series([
async.parallel({ function (next) {
defaultMapping: function (next) { rimraf(soundsPath, next);
Meta.configs.getFields(keys, next);
}, },
userSettings: function (next) { function (next) {
user.getSettings(uid, next); mkdirp(soundsPath, next);
}, },
}, function (err, results) { function (cb) {
if (err) { async.parallel([
return callback(err); function (next) {
} fs.writeFile(path.join(soundsPath, 'fileMap.json'), JSON.stringify(map), next);
},
var userSettings = results.userSettings; function (next) {
userSettings = { async.each(plugins.soundpacks, function (pack, next) {
notification: userSettings.notificationSound, file.linkDirs(pack.dir, path.join(soundsPath, pack.id), next);
'chat-incoming': userSettings.incomingChatSound, }, next);
'chat-outgoing': userSettings.outgoingChatSound, },
}; ], cb);
var defaultMapping = results.defaultMapping || {}; },
var soundMapping = {}; ], function (err) {
callback(err);
keys.forEach(function (key) { });
if (userSettings[key] || userSettings[key] === '') { });
soundMapping[key] = userSettings[key] || ''; };
} else {
soundMapping[key] = defaultMapping[key] || '';
}
});
callback(null, soundMapping); var keys = ['chat-incoming', 'chat-outgoing', 'notification'];
Sounds.getUserSoundMap = function getUserSoundMap(uid, callback) {
async.parallel({
defaultMapping: function (next) {
Meta.configs.getFields(keys, next);
},
userSettings: function (next) {
user.getSettings(uid, next);
},
}, function (err, results) {
if (err) {
return callback(err);
}
var userSettings = results.userSettings;
userSettings = {
notification: userSettings.notificationSound,
'chat-incoming': userSettings.incomingChatSound,
'chat-outgoing': userSettings.outgoingChatSound,
};
var defaultMapping = results.defaultMapping || {};
var soundMapping = {};
keys.forEach(function (key) {
if (userSettings[key] || userSettings[key] === '') {
soundMapping[key] = userSettings[key] || '';
} else {
soundMapping[key] = defaultMapping[key] || '';
}
}); });
};
callback(null, soundMapping);
});
}; };

@ -4,163 +4,163 @@ var nconf = require('nconf');
var validator = require('validator'); var validator = require('validator');
var async = require('async'); var async = require('async');
var winston = require('winston'); var winston = require('winston');
var plugins = require('../plugins'); var plugins = require('../plugins');
var Meta = require('../meta');
var Tags = module.exports;
Tags.parse = function (req, meta, link, callback) {
async.parallel({
tags: function (next) {
var defaultTags = [{
name: 'viewport',
content: 'width=device-width, initial-scale=1.0',
}, {
name: 'content-type',
content: 'text/html; charset=UTF-8',
noEscape: true,
}, {
name: 'apple-mobile-web-app-capable',
content: 'yes',
}, {
name: 'mobile-web-app-capable',
content: 'yes',
}, {
property: 'og:site_name',
content: Meta.config.title || 'NodeBB',
}, {
name: 'msapplication-badge',
content: 'frequency=30; polling-uri=' + nconf.get('url') + '/sitemap.xml',
noEscape: true,
}];
if (Meta.config.keywords) {
defaultTags.push({
name: 'keywords',
content: Meta.config.keywords,
});
}
module.exports = function (Meta) { if (Meta.config['brand:logo']) {
Meta.tags = {}; defaultTags.push({
name: 'msapplication-square150x150logo',
content: Meta.config['brand:logo'],
noEscape: true,
});
}
Meta.tags.parse = function (req, meta, link, callback) { plugins.fireHook('filter:meta.getMetaTags', defaultTags, next);
async.parallel({ },
tags: function (next) { links: function (next) {
var defaultTags = [{ var defaultLinks = [{
name: 'viewport', rel: 'icon',
content: 'width=device-width, initial-scale=1.0', 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',
}];
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',
}, { }, {
name: 'content-type', rel: 'icon',
content: 'text/html; charset=UTF-8', sizes: '36x36',
noEscape: true, href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-36.png',
}, { }, {
name: 'apple-mobile-web-app-capable', rel: 'icon',
content: 'yes', sizes: '48x48',
href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-48.png',
}, { }, {
name: 'mobile-web-app-capable', rel: 'icon',
content: 'yes', sizes: '72x72',
href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-72.png',
}, { }, {
property: 'og:site_name', rel: 'icon',
content: Meta.config.title || 'NodeBB', sizes: '96x96',
href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-96.png',
}, { }, {
name: 'msapplication-badge',
content: 'frequency=30; polling-uri=' + nconf.get('url') + '/sitemap.xml',
noEscape: true,
}];
if (Meta.config.keywords) {
defaultTags.push({
name: 'keywords',
content: Meta.config.keywords,
});
}
if (Meta.config['brand:logo']) {
defaultTags.push({
name: 'msapplication-square150x150logo',
content: Meta.config['brand:logo'],
noEscape: true,
});
}
plugins.fireHook('filter:meta.getMetaTags', defaultTags, next);
},
links: function (next) {
var defaultLinks = [{
rel: 'icon', rel: 'icon',
type: 'image/x-icon', sizes: '144x144',
href: nconf.get('relative_path') + '/favicon.ico' + (Meta.config['cache-buster'] ? '?' + Meta.config['cache-buster'] : ''), href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-144.png',
}, { }, {
rel: 'manifest', rel: 'icon',
href: nconf.get('relative_path') + '/manifest.json', sizes: '192x192',
}]; href: nconf.get('relative_path') + '/assets/uploads/system/touchicon-192.png',
});
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',
}, {
rel: 'icon',
sizes: '36x36',
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',
}, {
rel: 'icon',
sizes: '72x72',
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',
}, {
rel: 'icon',
sizes: '144x144',
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',
});
}
plugins.fireHook('filter:meta.getLinkTags', defaultLinks, next);
},
}, function (err, results) {
if (err) {
return callback(err);
} }
plugins.fireHook('filter:meta.getLinkTags', defaultLinks, next);
},
}, function (err, results) {
if (err) {
return callback(err);
}
meta = results.tags.concat(meta || []).map(function (tag) { meta = results.tags.concat(meta || []).map(function (tag) {
if (!tag || typeof tag.content !== 'string') { if (!tag || typeof tag.content !== 'string') {
winston.warn('Invalid meta tag. ', tag); winston.warn('Invalid meta tag. ', tag);
return tag;
}
if (!tag.noEscape) {
tag.content = validator.escape(String(tag.content));
}
return tag; return tag;
}); }
addIfNotExists(meta, 'property', 'og:title', Meta.config.title || 'NodeBB'); if (!tag.noEscape) {
tag.content = validator.escape(String(tag.content));
}
var ogUrl = nconf.get('url') + req.path; return tag;
addIfNotExists(meta, 'property', 'og:url', ogUrl); });
addIfNotExists(meta, 'name', 'description', Meta.config.description); addIfNotExists(meta, 'property', 'og:title', Meta.config.title || 'NodeBB');
addIfNotExists(meta, 'property', 'og:description', Meta.config.description);
var ogImage = Meta.config['og:image'] || Meta.config['brand:logo'] || ''; var ogUrl = nconf.get('url') + req.path;
if (ogImage && !ogImage.startsWith('http')) { addIfNotExists(meta, 'property', 'og:url', ogUrl);
ogImage = nconf.get('url') + ogImage;
}
addIfNotExists(meta, 'property', 'og:image', ogImage);
if (ogImage) {
addIfNotExists(meta, 'property', 'og:image:width', 200);
addIfNotExists(meta, 'property', 'og:image:height', 200);
}
link = results.links.concat(link || []); addIfNotExists(meta, 'name', 'description', Meta.config.description);
addIfNotExists(meta, 'property', 'og:description', Meta.config.description);
callback(null, { var ogImage = Meta.config['og:image'] || Meta.config['brand:logo'] || '';
meta: meta, if (ogImage && !ogImage.startsWith('http')) {
link: link, ogImage = nconf.get('url') + ogImage;
}); }
}); addIfNotExists(meta, 'property', 'og:image', ogImage);
}; if (ogImage) {
addIfNotExists(meta, 'property', 'og:image:width', 200);
addIfNotExists(meta, 'property', 'og:image:height', 200);
}
function addIfNotExists(meta, keyName, tagName, value) { link = results.links.concat(link || []);
var exists = false;
meta.forEach(function (tag) { callback(null, {
if (tag[keyName] === tagName) { meta: meta,
exists = true; link: link,
}
}); });
});
};
if (!exists && value) { function addIfNotExists(meta, keyName, tagName, value) {
var data = { var exists = false;
content: validator.escape(String(value)), meta.forEach(function (tag) {
}; if (tag[keyName] === tagName) {
data[keyName] = tagName; exists = true;
meta.push(data);
} }
});
if (!exists && value) {
var data = {
content: validator.escape(String(value)),
};
data[keyName] = tagName;
meta.push(data);
} }
}; }

@ -9,168 +9,167 @@ var async = require('async');
var file = require('../file'); var file = require('../file');
var db = require('../database'); var db = require('../database');
var Meta = require('../meta');
module.exports = function (Meta) {
Meta.themes = {}; var Themes = module.exports;
Meta.themes.get = function (callback) { Themes.get = function (callback) {
var themePath = nconf.get('themes_path'); var themePath = nconf.get('themes_path');
if (typeof themePath !== 'string') { if (typeof themePath !== 'string') {
return callback(null, []); return callback(null, []);
} }
async.waterfall([ async.waterfall([
function (next) { function (next) {
fs.readdir(themePath, next); fs.readdir(themePath, next);
}, },
function (files, next) { function (files, next) {
async.filter(files, function (file, next) { async.filter(files, function (file, next) {
fs.stat(path.join(themePath, file), function (err, fileStat) { fs.stat(path.join(themePath, file), function (err, fileStat) {
if (err) { if (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
return next(null, false); return next(null, false);
}
return next(err);
}
next(null, (fileStat.isDirectory() && file.slice(0, 13) === 'nodebb-theme-'));
});
}, next);
},
function (themes, next) {
async.map(themes, function (theme, next) {
var config = path.join(themePath, theme, 'theme.json');
fs.readFile(config, function (err, file) {
if (err) {
if (err.code === 'ENOENT') {
return next(null, null);
}
return next(err);
} }
try { return next(err);
var configObj = JSON.parse(file.toString()); }
// Minor adjustments for API output next(null, (fileStat.isDirectory() && file.slice(0, 13) === 'nodebb-theme-'));
configObj.type = 'local'; });
if (configObj.screenshot) { }, next);
configObj.screenshot_url = nconf.get('relative_path') + '/css/previews/' + configObj.id; },
} else { function (themes, next) {
configObj.screenshot_url = nconf.get('relative_path') + '/assets/images/themes/default.png'; async.map(themes, function (theme, next) {
} var config = path.join(themePath, theme, 'theme.json');
next(null, configObj);
} catch (err) { fs.readFile(config, function (err, file) {
winston.error('[themes] Unable to parse theme.json ' + theme); if (err) {
next(null, null); if (err.code === 'ENOENT') {
return next(null, null);
} }
}); return next(err);
}, next); }
}, try {
function (themes, next) { var configObj = JSON.parse(file.toString());
themes = themes.filter(Boolean);
next(null, themes); // Minor adjustments for API output
}, configObj.type = 'local';
], callback); if (configObj.screenshot) {
}; configObj.screenshot_url = nconf.get('relative_path') + '/css/previews/' + configObj.id;
Meta.themes.set = function (data, callback) {
var themeData = {
'theme:type': data.type,
'theme:id': data.id,
'theme:staticDir': '',
'theme:templates': '',
'theme:src': '',
};
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),
], function (err) {
next(err);
});
},
function (next) {
fs.readFile(path.join(nconf.get('themes_path'), data.id, 'theme.json'), function (err, config) {
if (!err) {
config = JSON.parse(config.toString());
next(null, config);
} else { } else {
next(err); configObj.screenshot_url = nconf.get('relative_path') + '/assets/images/themes/default.png';
} }
}); next(null, configObj);
}, } catch (err) {
function (config, next) { winston.error('[themes] Unable to parse theme.json ' + theme);
themeData['theme:staticDir'] = config.staticDir ? config.staticDir : ''; next(null, null);
themeData['theme:templates'] = config.templates ? config.templates : ''; }
themeData['theme:src'] = ''; });
}, next);
Meta.configs.setMultiple(themeData, next); },
function (themes, next) {
themes = themes.filter(Boolean);
next(null, themes);
},
], callback);
};
// Re-set the themes path (for when NodeBB is reloaded) Themes.set = function (data, callback) {
Meta.themes.setPath(config); var themeData = {
}, 'theme:type': data.type,
], callback); 'theme:id': data.id,
'theme:staticDir': '',
Meta.reloadRequired = true; 'theme:templates': '',
break; 'theme:src': '',
case 'bootswatch':
Meta.configs.setMultiple({
'theme:src': data.src,
bootswatchSkin: data.id.toLowerCase(),
}, callback);
break;
}
}; };
Meta.themes.setupPaths = function (callback) { switch (data.type) {
case 'local':
async.waterfall([ 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),
], function (err) {
next(err);
});
},
function (next) { function (next) {
async.parallel({ fs.readFile(path.join(nconf.get('themes_path'), data.id, 'theme.json'), function (err, config) {
themesData: Meta.themes.get, if (!err) {
currentThemeId: function (next) { config = JSON.parse(config.toString());
db.getObjectField('config', 'theme:id', next); next(null, config);
}, } else {
}, next); next(err);
}
});
}, },
function (data, next) { function (config, next) {
var themeId = data.currentThemeId || 'nodebb-theme-persona'; themeData['theme:staticDir'] = config.staticDir ? config.staticDir : '';
themeData['theme:templates'] = config.templates ? config.templates : '';
var themeObj = data.themesData.filter(function (themeObj) { themeData['theme:src'] = '';
return themeObj.id === themeId;
})[0];
if (process.env.NODE_ENV === 'development') {
winston.info('[themes] Using theme ' + themeId);
}
if (!themeObj) { Meta.configs.setMultiple(themeData, next);
return callback(new Error('[[error:theme-not-found]]'));
}
Meta.themes.setPath(themeObj); // Re-set the themes path (for when NodeBB is reloaded)
next(); Themes.setPath(config);
}, },
], callback); ], callback);
};
Meta.themes.setPath = function (themeObj) { Meta.reloadRequired = true;
// Theme's templates path break;
var themePath = nconf.get('base_templates_path');
var fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
if (themeObj.templates) { case 'bootswatch':
themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates); Meta.configs.setMultiple({
} else if (file.existsSync(fallback)) { 'theme:src': data.src,
themePath = fallback; bootswatchSkin: data.id.toLowerCase(),
} }, callback);
break;
}
};
nconf.set('theme_templates_path', themePath); Themes.setupPaths = function (callback) {
nconf.set('theme_config', path.join(nconf.get('themes_path'), themeObj.id, 'theme.json')); async.waterfall([
}; function (next) {
async.parallel({
themesData: Themes.get,
currentThemeId: function (next) {
db.getObjectField('config', 'theme:id', next);
},
}, next);
},
function (data, next) {
var themeId = data.currentThemeId || 'nodebb-theme-persona';
var themeObj = data.themesData.filter(function (themeObj) {
return themeObj.id === themeId;
})[0];
if (process.env.NODE_ENV === 'development') {
winston.info('[themes] Using theme ' + themeId);
}
if (!themeObj) {
return callback(new Error('[[error:theme-not-found]]'));
}
Themes.setPath(themeObj);
next();
},
], callback);
};
Themes.setPath = function (themeObj) {
// Theme's templates path
var themePath = nconf.get('base_templates_path');
var fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
if (themeObj.templates) {
themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates);
} else if (file.existsSync(fallback)) {
themePath = fallback;
}
nconf.set('theme_templates_path', themePath);
nconf.set('theme_config', path.join(nconf.get('themes_path'), themeObj.id, 'theme.json'));
}; };

Loading…
Cancel
Save