Skip to content

Node.js based forum software built for the modern web

Merge remote-tracking branch 'origin/master' into webserver.js-refactor

psychobunny1ef95bd09ee3
diff --cc app.js
index 3f7d3aaf7b,c38b06e262..097734cd25
--- a/app.js
+++ b/app.js
@@@ -130,27 -131,25 +130,28 @@@ function start()
upgrade.check(function(schema_ok) {
if (schema_ok || nconf.get('check-schema') === false) {
-
sockets.init(webserver.server);
-
plugins.init();
-
translator.loadServer();
- var customTemplates = meta.config['theme:templates'] ? path.join(nconf.get('themes_path'), meta.config['theme:id'], meta.config['theme:templates']) : false;
-
- utils.walk(path.join(__dirname, 'public/templates'), function (err, tplsToLoad) {
- templates.init(tplsToLoad, customTemplates);
- });
+ nconf.set('base_templates_path', path.join(nconf.get('themes_path'), 'nodebb-theme-vanilla/templates'));
+ nconf.set('theme_templates_path', meta.config['theme:templates'] ? path.join(nconf.get('themes_path'), meta.config['theme:id'], meta.config['theme:templates']) : nconf.get('base_templates_path'));
plugins.ready(function() {
- templates.ready(webserver.init);
+ webserver.init();
});
- notifications.init();
+ // Temporarily removed until ncb000gt/node-cron/issues/81 and ncb000gt/node-cron/issues/83 are fixed
+ // notifications.init();
+
+ process.on('SIGTERM', shutdown);
+ process.on('SIGINT', shutdown);
+ process.on('SIGHUP', restart);
+ process.on('uncaughtException', function(err) {
+ winston.error('[app] Encountered Uncaught Exception: ' + err.message);
+ console.log(err.stack);
+ restart();
+ });
} else {
winston.warn('Your NodeBB schema is out-of-date. Please run the following command to bring your dataset up to spec:');
winston.warn(' node app --upgrade');
diff --cc public/templates/category.tpl
index 0000000000,03a40c51b7..d4d9bca105
mode 000000,100644..100644
--- a/public/templates/category.tpl
+++ b/public/templates/category.tpl
@@@ -1,0 -1,117 +1,117 @@@
-
-<input type="hidden" template-variable="category_id" value="{cid}" />
-<input type="hidden" template-variable="category_name" value="{name}" />
-<input type="hidden" template-variable="currentPage" value="{currentPage}" />
-<input type="hidden" template-variable="pageCount" value="{pageCount}" />
-
-<ol class="breadcrumb">
- <li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb">
- <a href="{relative_path}/" itemprop="url"><span itemprop="title">[[global:home]]</span></a>
- </li>
- <li class="active" itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb">
- <span itemprop="title">{name} <a target="_blank" href="../{cid}.rss"><i class="fa fa-rss-square"></i></a></span>
- </li>
-</ol>
-
-<div>
- <!-- IF privileges.write -->
- <button id="new_post" class="btn btn-primary">[[category:new_topic_button]]</button>
- <!-- ENDIF privileges.write -->
- <!-- IF !config.disableSocialButtons -->
- <div class="inline-block pull-right">
- <a href="#" id="facebook-share"><i class="fa fa-facebook-square fa-2x"></i></a>&nbsp;
- <a href="#" id="twitter-share"><i class="fa fa-twitter-square fa-2x"></i></a>&nbsp;
- <a href="#" id="google-share"><i class="fa fa-google-plus-square fa-2x"></i></a>&nbsp;
- </div>
- <!-- ENDIF !config.disableSocialButtons -->
-</div>
-
-<hr/>
-
-<!-- IF !topics.length -->
-<div class="alert alert-warning" id="category-no-topics">
- [[category:no_topics]]
-</div>
-<!-- ENDIF !topics.length -->
-
-<div class="category row">
- <div class="{topic_row_size}" no-widget-class="col-lg-12 col-sm-12">
- <ul id="topics-container" itemscope itemtype="http://www.schema.org/ItemList" data-nextstart="{nextStart}">
- <meta itemprop="itemListOrder" content="descending">
- <!-- BEGIN topics -->
- <li class="category-item <!-- IF topics.deleted -->deleted<!-- ENDIF topics.deleted --><!-- IF topics.unread -->unread<!-- ENDIF topics.unread -->" itemprop="itemListElement" data-tid="{topics.tid}" data-index="{topics.index}">
-
- <div class="col-md-12 col-xs-12 panel panel-default topic-row">
-
- <!--
- todo: tidy this up, not sure what to do with the topic thumbs
- todo: fix this nesting if issue#1065 is a win
- todo: add a check for config.allowTopicsThumbnail if issue#1066 is a win
- -->
- <a href="../../user/{topics.user.userslug}" class="pull-left">
- <img src="<!-- IF topics.thumb -->{topics.thumb}<!-- ELSE -->{topics.user.picture}<!-- ENDIF topics.thumb -->" class="img-rounded user-img" title="{topics.user.username}"/>
- </a>
-
- <h3>
- <a href="../../topic/{topics.slug}" itemprop="url">
- <meta itemprop="name" content="{topics.title}">
-
- <strong><!-- IF topics.pinned --><i class="fa fa-thumb-tack"></i><!-- ENDIF topics.pinned --> <!-- IF topics.locked --><i class="fa fa-lock"></i><!-- ENDIF topics.locked --></strong>
- <span class="topic-title">{topics.title}</span>
- </a>
- </h3>
-
- <small>
- <span class="topic-stats">
- [[category:posts]]
- <strong class="human-readable-number" title="{topics.postcount}">{topics.postcount}</strong>
- </span>
- |
- <span class="topic-stats">
- [[category:views]]
- <strong class="human-readable-number" title="{topics.viewcount}">{topics.viewcount}</strong>
- </span>
- |
- <span>
- [[category:posted]] <span class="timeago" title="{topics.relativeTime}"></span>
- </span>
-
- <span class="pull-right">
- <!-- IF topics.unreplied -->
- [[category:no_replies]]
- <!-- ELSE -->
- <a href="../../user/{topics.teaser.userslug}">
- <img class="teaser-pic" src="{topics.teaser.picture}" title="{topics.teaser.username}"/>
- </a>
- <a href="../../topic/{topics.slug}#{topics.teaser.pid}">
- [[category:replied]]
- </a>
- <span class="timeago" title="{topics.teaser.timestamp}"></span>
- <!-- ENDIF topics.unreplied -->
- </span>
- </small>
-
- </div>
-
- </li>
- <!-- END topics -->
- </ul>
- <!-- IF config.usePagination -->
- <div class="text-center">
- <ul class="pagination">
- <li class="previous pull-left"><a href="#"><i class="fa fa-chevron-left"></i> [[global:previouspage]]</a></li>
- <li class="next pull-right"><a href="#">[[global:nextpage]] <i class="fa fa-chevron-right"></i></a></li>
- </ul>
- </div>
- <!-- ENDIF config.usePagination -->
- </div>
-
- <!-- IF topics.length -->
- <div widget-area="sidebar" class="col-md-3 col-xs-12 category-sidebar">
- <!-- BEGIN widgets -->
- {widgets.html}
- <!-- END widgets -->
- </div>
- <!-- ENDIF topics.length -->
-</div>
-
++
++<input type="hidden" template-variable="category_id" value="{cid}" />
++<input type="hidden" template-variable="category_name" value="{name}" />
++<input type="hidden" template-variable="currentPage" value="{currentPage}" />
++<input type="hidden" template-variable="pageCount" value="{pageCount}" />
++
++<ol class="breadcrumb">
++ <li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb">
++ <a href="{relative_path}/" itemprop="url"><span itemprop="title">[[global:home]]</span></a>
++ </li>
++ <li class="active" itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb">
++ <span itemprop="title">{name} <a target="_blank" href="../{cid}.rss"><i class="fa fa-rss-square"></i></a></span>
++ </li>
++</ol>
++
++<div>
++ <!-- IF privileges.write -->
++ <button id="new_post" class="btn btn-primary">[[category:new_topic_button]]</button>
++ <!-- ENDIF privileges.write -->
++ <!-- IF !config.disableSocialButtons -->
++ <div class="inline-block pull-right">
++ <a href="#" id="facebook-share"><i class="fa fa-facebook-square fa-2x"></i></a>&nbsp;
++ <a href="#" id="twitter-share"><i class="fa fa-twitter-square fa-2x"></i></a>&nbsp;
++ <a href="#" id="google-share"><i class="fa fa-google-plus-square fa-2x"></i></a>&nbsp;
++ </div>
++ <!-- ENDIF !config.disableSocialButtons -->
++</div>
++
++<hr/>
++
++<!-- IF !topics.length -->
++<div class="alert alert-warning" id="category-no-topics">
++ [[category:no_topics]]
++</div>
++<!-- ENDIF !topics.length -->
++
++<div class="category row">
++ <div class="{topic_row_size}" no-widget-class="col-lg-12 col-sm-12">
++ <ul id="topics-container" itemscope itemtype="http://www.schema.org/ItemList" data-nextstart="{nextStart}">
++ <meta itemprop="itemListOrder" content="descending">
++ <!-- BEGIN topics -->
++ <li class="category-item <!-- IF topics.deleted -->deleted<!-- ENDIF topics.deleted --><!-- IF topics.unread -->unread<!-- ENDIF topics.unread -->" itemprop="itemListElement" data-tid="{topics.tid}" data-index="{topics.index}">
++
++ <div class="col-md-12 col-xs-12 panel panel-default topic-row">
++
++ <!--
++ todo: tidy this up, not sure what to do with the topic thumbs
++ todo: fix this nesting if issue#1065 is a win
++ todo: add a check for config.allowTopicsThumbnail if issue#1066 is a win
++ -->
++ <a href="../../user/{topics.user.userslug}" class="pull-left">
++ <img src="<!-- IF topics.thumb -->{topics.thumb}<!-- ELSE -->{topics.user.picture}<!-- ENDIF topics.thumb -->" class="img-rounded user-img" title="{topics.user.username}"/>
++ </a>
++
++ <h3>
++ <a href="../../topic/{topics.slug}" itemprop="url">
++ <meta itemprop="name" content="{topics.title}">
++
++ <strong><!-- IF topics.pinned --><i class="fa fa-thumb-tack"></i><!-- ENDIF topics.pinned --> <!-- IF topics.locked --><i class="fa fa-lock"></i><!-- ENDIF topics.locked --></strong>
++ <span class="topic-title">{topics.title}</span>
++ </a>
++ </h3>
++
++ <small>
++ <span class="topic-stats">
++ [[category:posts]]
++ <strong class="human-readable-number" title="{topics.postcount}">{topics.postcount}</strong>
++ </span>
++ |
++ <span class="topic-stats">
++ [[category:views]]
++ <strong class="human-readable-number" title="{topics.viewcount}">{topics.viewcount}</strong>
++ </span>
++ |
++ <span>
++ [[category:posted]] <span class="timeago" title="{topics.relativeTime}"></span>
++ </span>
++
++ <span class="pull-right">
++ <!-- IF topics.unreplied -->
++ [[category:no_replies]]
++ <!-- ELSE -->
++ <a href="../../user/{topics.teaser.userslug}">
++ <img class="teaser-pic" src="{topics.teaser.picture}" title="{topics.teaser.username}"/>
++ </a>
++ <a href="../../topic/{topics.slug}#{topics.teaser.pid}">
++ [[category:replied]]
++ </a>
++ <span class="timeago" title="{topics.teaser.timestamp}"></span>
++ <!-- ENDIF topics.unreplied -->
++ </span>
++ </small>
++
++ </div>
++
++ </li>
++ <!-- END topics -->
++ </ul>
++ <!-- IF config.usePagination -->
++ <div class="text-center">
++ <ul class="pagination">
++ <li class="previous pull-left"><a href="#"><i class="fa fa-chevron-left"></i> [[global:previouspage]]</a></li>
++ <li class="next pull-right"><a href="#">[[global:nextpage]] <i class="fa fa-chevron-right"></i></a></li>
++ </ul>
++ </div>
++ <!-- ENDIF config.usePagination -->
++ </div>
++
++ <!-- IF topics.length -->
++ <div widget-area="sidebar" class="col-md-3 col-xs-12 category-sidebar">
++ <!-- BEGIN widgets -->
++ {widgets.html}
++ <!-- END widgets -->
++ </div>
++ <!-- ENDIF topics.length -->
++</div>
++
diff --cc src/middleware/index.js
index a15092ab6f,0000000000..b2e428f7c1
mode 100644,000000..100644
--- a/src/middleware/index.js
+++ b/src/middleware/index.js
@@@ -1,240 -1,0 +1,231 @@@
+"use strict";
+
+var templates = require('./../../public/src/templates'),
+ translator = require('./../../public/src/translator'),
+ utils = require('./../../public/src/utils'),
+ meta = require('./../meta'),
+ plugins = require('./../plugins'),
+ db = require('./../database'),
+ auth = require('./../routes/authentication'),
+ async = require('async'),
+ path = require('path'),
+ fs = require('fs'),
+ nconf = require('nconf'),
+ express = require('express'),
+ winston = require('winston');
+
+
+var middleware = {};
+
+
+function routeThemeScreenshots(app, themes) {
+ var screenshotPath;
+
+ async.each(themes, function(themeObj, next) {
+ if (themeObj.screenshot) {
+ screenshotPath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.screenshot);
+ (function(id, path) {
+ fs.exists(path, function(exists) {
+ if (exists) {
+ app.get('/css/previews/' + id, function(req, res) {
+ res.sendfile(path);
+ });
+ }
+ });
+ })(themeObj.id, screenshotPath);
+ } else {
+ next(false);
+ }
+ });
+}
+
+function routeCurrentTheme(app, themeData) {
+ var themeId = (themeData['theme:id'] || 'nodebb-theme-vanilla');
+
+ // Detect if a theme has been selected, and handle appropriately
+ if (!themeData['theme:type'] || themeData['theme:type'] === 'local') {
+ // Local theme
+ if (process.env.NODE_ENV === 'development') {
+ winston.info('[themes] Using theme ' + themeId);
+ }
+
+ // Theme's static directory
+ if (themeData['theme:staticDir']) {
- app.use('/css/assets', express.static(path.join(nconf.get('themes_path'), themeData['theme:id'], themeData['theme:staticDir']), {
++ app.use(nconf.get('relative_path') + '/css/assets', express.static(path.join(nconf.get('themes_path'), themeData['theme:id'], themeData['theme:staticDir']), {
+ maxAge: app.enabled('cache') ? 5184000000 : 0
+ }));
+ if (process.env.NODE_ENV === 'development') {
+ winston.info('Static directory routed for theme: ' + themeData['theme:id']);
+ }
+ }
-
- if (themeData['theme:templates']) {
- app.use('/templates', express.static(path.join(nconf.get('themes_path'), themeData['theme:id'], themeData['theme:templates']), {
- maxAge: app.enabled('cache') ? 5184000000 : 0
- }));
- if (process.env.NODE_ENV === 'development') {
- winston.info('Custom templates directory routed for theme: ' + themeData['theme:id']);
- }
- }
+ } else {
+ // If not using a local theme (bootswatch, etc), drop back to vanilla
+ if (process.env.NODE_ENV === 'development') {
+ winston.info('[themes] Using theme ' + themeId);
+ }
+
+ app.use(require('less-middleware')({
+ src: path.join(nconf.get('themes_path'), '/nodebb-theme-vanilla'),
+ dest: path.join(__dirname, '../../public/css'),
+ prefix: nconf.get('relative_path') + '/css',
+ yuicompress: app.enabled('minification') ? true : false
+ }));
+ }
+}
+
+function compileTemplates(pluginTemplates) {
+ var mkdirp = require('mkdirp'),
+ rimraf = require('rimraf');
+
+ winston.info('[themes] Compiling templates');
+ rimraf.sync(nconf.get('views_dir'));
+ mkdirp.sync(nconf.get('views_dir'));
+
+ utils.walk(nconf.get('base_templates_path'), function(err, baseTpls) {
+ utils.walk(nconf.get('theme_templates_path'), function (err, themeTpls) {
+ var paths = pluginTemplates;
+
+ baseTpls = baseTpls.map(function(tpl) { return tpl.replace(nconf.get('base_templates_path'), ''); });
+ themeTpls = themeTpls.map(function(tpl) { return tpl.replace(nconf.get('theme_templates_path'), ''); });
+
+ baseTpls.forEach(function(el, i) {
+ var relative_path = (themeTpls.indexOf(el) !== -1 ? themeTpls[themeTpls.indexOf(el)] : baseTpls[i]),
+ full_path = path.join(themeTpls.indexOf(el) !== -1 ? nconf.get('theme_templates_path') : nconf.get('base_templates_path'), relative_path);
+
+ paths[themeTpls.indexOf(el) !== -1 ? themeTpls[themeTpls.indexOf(el)] : baseTpls[i]] = full_path;
+ });
+
+ async.each(Object.keys(paths), function(relative_path, next) {
+ var file = fs.readFileSync(paths[relative_path]).toString(),
+ matches = null,
+ regex = /[ \t]*<!-- IMPORT ([\s\S]*?)? -->[ \t]*/;
+
+ while (matches = file.match(regex)) {
+ if (paths["/" + matches[1]]) {
+ file = file.replace(regex, fs.readFileSync(paths["/" + matches[1]]).toString());
+ } else {
+ winston.warn('[themes] Partial not found: ' + matches[1]);
+ file = file.replace(regex, "");
+ }
+ }
+
+ mkdirp.sync(path.join(nconf.get('views_dir'), relative_path.split('/').slice(0, -1).join('/')));
+ fs.writeFile(path.join(nconf.get('views_dir'), relative_path), file, next);
+ }, function(err) {
+ if (err) {
+ winston.error(err);
+ } else {
+ winston.info('[themes] Successfully compiled templates.');
+ }
+ });
+ });
+ });
+}
+
+function handleErrors(err, req, res, next) {
+ // we may use properties of the error object
+ // here and next(err) appropriately, or if
+ // we possibly recovered from the error, simply next().
+ console.error(err.stack);
+ var status = err.status || 500;
+ res.status(status);
+
+ res.json(status, {
+ error: err.message
+ });
+}
+
+function catch404(req, res, next) {
+ var isLanguage = new RegExp('^' + nconf.get('relative_path') + '/language/[\\w]{2,}/.*.json'),
+ isClientScript = new RegExp('^' + nconf.get('relative_path') + '\\/src\\/forum(\\/admin)?\\/[\\w]+\\.js');
+
+ res.status(404);
+
+ if (isClientScript.test(req.url)) {
+ res.type('text/javascript').send(200, '');
+ } else if (isLanguage.test(req.url)) {
+ res.json(200, {});
+ } else if (req.accepts('html')) {
+ if (process.env.NODE_ENV === 'development') {
+ winston.warn('Route requested but not found: ' + req.url);
+ }
+
+ res.redirect(nconf.get('relative_path') + '/404');
+ } else if (req.accepts('json')) {
+ if (process.env.NODE_ENV === 'development') {
+ winston.warn('Route requested but not found: ' + req.url);
+ }
+
+ res.json({
+ error: 'Not found'
+ });
+ } else {
+ res.type('txt').send('Not found');
+ }
+}
+
+
+
+
+module.exports = function(app, data) {
+ middleware = require('./middleware')(app);
+
+ app.configure(function() {
+ app.engine('tpl', templates.__express);
+ app.set('view engine', 'tpl');
+ app.set('views', nconf.get('views_dir'));
+
+ app.use(express.compress());
+
+ app.use(express.favicon(path.join(__dirname, '../../', 'public', meta.config['brand:favicon'] ? meta.config['brand:favicon'] : 'favicon.ico')));
+ app.use('/apple-touch-icon', middleware.routeTouchIcon);
+
+ app.use(require('less-middleware')({
+ src: path.join(__dirname, '../../', 'public'),
+ prefix: nconf.get('relative_path'),
+ yuicompress: app.enabled('minification') ? true : false
+ }));
+
+ app.use(express.bodyParser());
+ app.use(express.cookieParser());
+
+ app.use(express.session({
+ store: db.sessionStore,
+ secret: nconf.get('secret'),
+ key: 'express.sid',
+ cookie: {
+ maxAge: 1000 * 60 * 60 * 24 * parseInt(meta.configs.loginDays || 14, 10)
+ }
+ }));
+
+ app.use(express.csrf()); // todo, make this a conditional middleware
+
+ app.use(function (req, res, next) {
+ res.locals.csrf_token = req.session._csrf;
+ res.setHeader('X-Frame-Options', 'SAMEORIGIN');
+ next();
+ });
+
+ app.use(middleware.processRender);
+
+ auth.initialize(app);
+
+ routeCurrentTheme(app, data.currentThemeData);
+ routeThemeScreenshots(app, data.themesData);
+
+ plugins.getTemplates(function(err, pluginTemplates) {
+ compileTemplates(pluginTemplates);
+ });
+
+ app.use(app.router);
+
+ app.use(nconf.get('relative_path'), express.static(path.join(__dirname, '../../', 'public'), {
+ maxAge: app.enabled('cache') ? 5184000000 : 0
+ }));
+
+ app.use(catch404);
+ app.use(handleErrors);
+ });
+
+ return middleware;
+};
diff --cc src/middleware/middleware.js
index 4407adc595,0000000000..2944e6f0e0
mode 100644,000000..100644
--- a/src/middleware/middleware.js
+++ b/src/middleware/middleware.js
@@@ -1,334 -1,0 +1,334 @@@
+"use strict";
+
+var app,
+ clientScripts,
+ middleware = {},
+ async = require('async'),
+ path = require('path'),
+ winston = require('winston'),
+ validator = require('validator'),
+ fs = require('fs'),
+ nconf = require('nconf'),
+ plugins = require('./../plugins'),
+ meta = require('./../meta'),
+ translator = require('./../../public/src/translator'),
+ user = require('./../user'),
+ db = require('./../database'),
+
+ controllers = {
+ api: require('./../controllers/api')
+ };
+
+middleware.authenticate = function(req, res, next) {
+ if(!req.user) {
+ if (res.locals.isAPI) {
+ return res.json(403, 'not-allowed');
+ } else {
+ return res.redirect('403');
+ }
+ } else {
+ next();
+ }
+};
+
+middleware.updateLastOnlineTime = function(req, res, next) {
+ if(req.user) {
+ user.updateLastOnlineTime(req.user.uid);
+ }
+
+ db.sortedSetAdd('ip:recent', Date.now(), req.ip || 'Unknown');
+
+ next();
+};
+
+middleware.prepareAPI = function(req, res, next) {
+ res.locals.isAPI = true;
+ next();
+};
+
+middleware.guestSearchingAllowed = function(req, res, next) {
+ if (!req.user && meta.config.allowGuestSearching !== '1') {
+ return res.redirect('/403');
+ }
+};
+
+middleware.checkGlobalPrivacySettings = function(req, res, next) {
+ var callerUID = req.user ? parseInt(req.user.uid, 10) : 0;
+
+ if (!callerUID && !!parseInt(meta.config.privateUserInfo, 10)) {
+ if (res.locals.isAPI) {
+ return res.json(403, 'not-allowed');
+ } else {
+ return res.redirect('403');
+ }
+ }
+
+ next();
+};
+
+middleware.checkAccountPermissions = function(req, res, next) {
+ var callerUID = req.user ? parseInt(req.user.uid, 10) : 0;
+
+ // this function requires userslug to be passed in. todo: /user/uploadpicture should pass in userslug I think
+ user.getUidByUserslug(req.params.userslug, function (err, uid) {
+ if (err) {
+ return next(err);
+ }
+
+ // not sure if this check really should belong here. also make sure we're not doing this check again in the actual method
+ if (!uid) {
+ if (res.locals.isAPI) {
+ return res.json(404);
+ } else {
+ return res.redirect('404');
+ }
+ }
+
+ if (parseInt(uid, 10) === callerUID) {
+ return next();
+ }
+
+ user.isAdministrator(callerUID, function(err, isAdmin) {
+ if(err) {
+ return next(err);
+ }
+
+ if(isAdmin) {
+ next();
+ }
+
+ if (res.locals.isAPI) {
+ return res.json(403, 'not-allowed');
+ } else {
+ return res.redirect('403');
+ }
+ });
+ });
+};
+
+middleware.buildHeader = function(req, res, next) {
+ async.parallel([
+ function(next) {
+ res.locals.renderHeader = true;
+ next();
+ },
+ function(next) {
+ controllers.api.getConfig(req, res, function(err, config) {
+ res.locals.config = config;
+ next();
+ });
+ },
+ function(next) {
+ // this is slower than the original implementation because the rendered template is not cached
+ // but I didn't bother to fix this because we will deprecate [filter:footer.build] in favour of the widgets system by 0.4x
+ plugins.fireHook('filter:footer.build', '', function(err, appendHTML) {
+ app.render('footer', {footerHTML: appendHTML}, function(err, template) {
+ translator.translate(template, function(parsedTemplate) {
+ res.locals.footer = template;
+ next(err);
+ });
+ });
+ });
+ }
+ ], function(err) {
+ next(err);
+ });
+};
+
+middleware.renderHeader = function(req, res, callback) {
+ var custom_header = {
+ 'navigation': []
+ };
+
+ plugins.fireHook('filter:header.build', custom_header, function(err, custom_header) {
+ var defaultMetaTags = [{
+ name: 'viewport',
+ content: 'width=device-width, initial-scale=1.0, user-scalable=no'
+ }, {
+ name: 'content-type',
+ content: 'text/html; charset=UTF-8'
+ }, {
+ name: 'apple-mobile-web-app-capable',
+ content: 'yes'
+ }, {
+ property: 'og:site_name',
+ content: meta.config.title || 'NodeBB'
+ }, {
+ property: 'keywords',
+ content: meta.config.keywords || ''
+ }],
+ defaultLinkTags = [{
+ rel: 'apple-touch-icon',
+ href: '/apple-touch-icon'
+ }],
+ templateValues = {
+ bootswatchCSS: meta.config['theme:src'],
+ title: meta.config.title || '',
+ description: meta.config.description || '',
+ 'brand:logo': meta.config['brand:logo'] || '',
+ 'brand:logo:display': meta.config['brand:logo']?'':'hide',
+ csrf: res.locals.csrf_token,
+ relative_path: nconf.get('relative_path'),
+ clientScripts: clientScripts,
+ navigation: custom_header.navigation,
+ 'cache-buster': meta.config['cache-buster'] ? 'v=' + meta.config['cache-buster'] : '',
+ allowRegistration: meta.config.allowRegistration === undefined || parseInt(meta.config.allowRegistration, 10) === 1,
+ searchEnabled: plugins.hasListeners('filter:search.query') ? true : false
+ },
+ escapeList = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ "'": '&apos;',
+ '"': '&quot;'
+ };
+
+ for (var key in res.locals.config) {
+ if (res.locals.config.hasOwnProperty(key)) {
+ templateValues[key] = res.locals.config[key];
+ }
+ }
+
+ var uid = '0';
+
+ templateValues.metaTags = defaultMetaTags.concat(res.locals.metaTags || []).map(function(tag) {
+ if(!tag || typeof tag.content !== 'string') {
+ winston.warn('Invalid meta tag. ', tag);
+ return tag;
+ }
+
+ tag.content = tag.content.replace(/[&<>'"]/g, function(tag) {
+ return escapeList[tag] || tag;
+ });
+ return tag;
+ });
+
+ templateValues.linkTags = defaultLinkTags.concat(res.locals.linkTags || []);
+ templateValues.linkTags.push({
+ rel: "icon",
+ type: "image/x-icon",
+ href: nconf.get('relative_path') + '/favicon.ico'
+ });
+
+ if(req.user && req.user.uid) {
+ uid = req.user.uid;
+ }
+
+ templateValues.useCustomCSS = false;
+ if (meta.config.useCustomCSS === '1') {
+ templateValues.useCustomCSS = true;
+ templateValues.customCSS = meta.config.customCSS;
+ }
+
+ async.parallel([
+ function(next) {
+ translator.get('pages:' + path.basename(req.url), function(translated) {
+ var metaTitle = templateValues.metaTags.filter(function(tag) {
+ return tag.name === 'title';
+ });
+
+ if (translated) {
+ templateValues.browserTitle = translated;
+ } else if (metaTitle.length > 0 && metaTitle[0].content) {
+ templateValues.browserTitle = metaTitle[0].content;
+ } else {
+ templateValues.browserTitle = meta.config.browserTitle || 'NodeBB';
+ }
+
+ next();
+ });
+ },
+ function(next) {
+ user.isAdministrator(uid, function(err, isAdmin) {
+ templateValues.isAdmin = isAdmin || false;
+ next();
+ });
+ }
+ ], function() {
+ app.render('header', templateValues, function(err, template) {
+ callback(null, template);
+ });
+ });
+ });
+};
+
+middleware.processRender = function(req, res, next) {
+ // res.render post-processing, modified from here: https://gist.github.com/mrlannigan/5051687
+ var render = res.render;
+ res.render = function(template, options, fn) {
+ var self = this,
+ options = options || {},
+ req = this.req,
+ app = req.app,
+ defaultFn = function(err, str){
+ if (err) {
+ return req.next(err);
+ }
+
+ self.send(str);
+ };
+
+ if ('function' === typeof options) {
+ fn = options, options = {};
+ }
+
+ if ('function' !== typeof fn) {
+ fn = defaultFn;
+ }
+
+ render.call(self, template, options, function(err, str) {
+ if (res.locals.footer) {
+ str = str + res.locals.footer;
+ } else if (res.locals.adminFooter) {
+ str = str + res.locals.adminFooter;
+ }
+
+ if (res.locals.renderHeader) {
+ middleware.renderHeader(req, res, function(err, template) {
+ str = template + str;
+
+ translator.translate(str, function(translated) {
+ fn(err, translated);
+ });
+ });
+ } else if (res.locals.adminHeader) {
+ str = res.locals.adminHeader + str;
+ fn(err, str);
+ } else {
+ fn(err, str);
+ }
+ });
+ };
+
+ next();
+};
+
+middleware.routeTouchIcon = function(req, res) {
+ if (meta.config['brand:logo'] && validator.isURL(meta.config['brand:logo'])) {
+ return res.redirect(meta.config['brand:logo']);
+ } else {
- return res.sendfile(path.join(__dirname, '../../public', meta.config['brand:logo'] || nconf.get('relative_path') + '/logo.png'), {
++ return res.sendfile(path.join(__dirname, '../public', meta.config['brand:logo'] || '/logo.png'), {
+ maxAge: app.enabled('cache') ? 5184000000 : 0
+ });
+ }
+};
+
+module.exports = function(webserver) {
+ app = webserver;
+ middleware.admin = require('./admin')(webserver);
+
+ plugins.ready(function() {
+ // Minify client-side libraries
+ meta.js.get(function (err, scripts) {
+ clientScripts = scripts.map(function (script) {
+ script = {
+ script: script
+ };
+
+ return script;
+ });
+ });
+ });
+
+ return middleware;
+};
diff --cc src/routes/plugins.js
index 86f78bfda6,1d6d9684cb..9764c5479d
--- a/src/routes/plugins.js
+++ b/src/routes/plugins.js
@@@ -5,196 -4,71 +5,195 @@@ var _ = require('underscore')
path = require('path'),
fs = require('fs'),
validator = require('validator'),
- _ = require('underscore'),
async = require('async'),
- plugins = require('../plugins');
-
-(function(Plugins) {
- Plugins.createRoutes = function(app) {
- app.get('/plugins/fireHook', function(req, res) {
- // GET = filter
- plugins.fireHook('filter:' + req.query.hook, req.query.args, function(err, returnData) {
- if (typeof returnData === 'object') {
- res.json(200, returnData);
- } else {
- res.send(200, validator.escape(returnData));
+ winston = require('winston'),
+
+ plugins = require('../plugins'),
-
+ pluginRoutes = [];
+
+/*
+* TO BE DEPRECATED post 0.4x
+*/
+function setupPluginRoutes(app) {
+ var custom_routes = {
+ 'routes': [],
+ 'api': [],
+ 'templates': []
+ };
+
+ plugins.ready(function() {
+ plugins.fireHook('filter:server.create_routes', custom_routes, function(err, custom_routes) {
+ winston.warn('[plugins] filter:server.create_routes is deprecated and will maintain limited functionality until 0.4x');
+ var route,
+ routes = custom_routes.routes;
+
+ pluginRoutes = custom_routes;
+
+ for (route in routes) {
+ if (routes.hasOwnProperty(route)) {
+ (function(route) {
+ app[routes[route].method || 'get'](routes[route].route, function(req, res) {
+ routes[route].options(req, res, function(options) {
+ async.parallel([
+ function(next) {
+ app.render('header', {}, next);
+ },
+ function(next) {
+ app.render('footer', {}, next);
+ }
+ ], function(err, data) {
+ res.send(data[0] + options.content + data[1]);
+ });
+ });
+ });
+ }(route));
}
- });
+ }
+
+ var apiRoutes = custom_routes.api;
+ for (route in apiRoutes) {
+ if (apiRoutes.hasOwnProperty(route)) {
+ (function(route) {
+ app[apiRoutes[route].method || 'get']('/api' + apiRoutes[route].route, function(req, res) {
+ apiRoutes[route].callback(req, res, function(data) {
+ res.json(data);
+ });
+ });
+ }(route));
+ }
+ }
+
+ var templateRoutes = custom_routes.templates;
+ for (route in templateRoutes) {
+ if (templateRoutes.hasOwnProperty(route)) {
+ (function(route) {
+ app.get('/templates/' + templateRoutes[route].template, function(req, res) {
+ res.send(templateRoutes[route].content);
+ });
+ }(route));
+ }
+ }
});
+ });
+}
+
+/*
+* TO BE DEPRECATED post 0.4x
+*/
+function setupPluginAdminRoutes(app) {
+ var custom_routes = {
+ 'routes': [],
+ 'api': []
+ };
- app.put('/plugins/fireHook', function(req, res) {
- // PUT = action
- var hook = 'action:' + req.body.hook;
- if (plugins.hasListeners(hook)) {
- // Hook executes
- plugins.fireHook(hook, req.body.args);
+ plugins.ready(function() {
+ plugins.fireHook('filter:admin.create_routes', custom_routes, function(err, custom_routes) {
+ winston.warn('[plugins] filter:admin.create_routes is deprecated and will maintain limited functionality until 0.4x');
+ var route, routes = custom_routes.routes;
+
+ for (route in routes) {
+ if (routes.hasOwnProperty(route)) {
+ (function(route) {
+ app[routes[route].method || 'get']('/admin' + routes[route].route, function(req, res) {
+ routes[route].options(req, res, function(options) {
+ async.parallel([
+ function(next) {
+ app.render('admin/header', {}, next);
+ },
+ function(next) {
+ app.render('admin/footer', {}, next);
+ }
+ ], function(err, data) {
+ res.send(data[0] + options.content + data[1]);
+ });
+ });
+ });
+ }(route));
+ }
}
- res.send(200);
+ var apiRoutes = custom_routes.api;
+ for (route in apiRoutes) {
+ if (apiRoutes.hasOwnProperty(route)) {
+ (function(route) {
+ app[apiRoutes[route].method || 'get']('/api/admin' + apiRoutes[route].route, function(req, res) {
+ apiRoutes[route].callback(req, res, function(data) {
+ res.json(data);
+ });
+ });
+ }(route));
+ }
+ }
});
+ });
+}
- // Static Assets
- app.get('/plugins/:id/*', function(req, res) {
- var relPath = req._parsedUrl.pathname.replace(nconf.get('relative_path') + '/plugins/', ''),
- matches = _.map(plugins.staticDirs, function(realPath, mappedPath) {
- if (relPath.match(mappedPath)) {
- return mappedPath;
- } else {
- return null;
- }
- }).filter(function(a) { return a; });
-
- if (matches) {
- async.map(matches, function(mappedPath, next) {
- var filePath = path.join(plugins.staticDirs[mappedPath], decodeURIComponent(relPath.slice(mappedPath.length)));
-
- fs.exists(filePath, function(exists) {
- if (exists) {
- next(null, filePath);
- } else {
- next();
- }
- });
- }, function(err, matches) {
- // Filter out the nulls
- matches = matches.filter(function(a) {
- return a;
- });
-
- if (matches.length) {
- res.sendfile(matches[0]);
- } else {
- res.redirect('/404');
- }
- });
+module.exports = function(app, middleware, controllers) {
+ /**
+ * GET/PUT /plugins/fireHook to be deprecated after 0.4.x
+ *
+ */
+ app.get('/plugins/fireHook', function(req, res) {
+ // GET = filter
+ plugins.fireHook('filter:' + req.query.hook, req.query.args, function(err, returnData) {
+ if (typeof returnData === 'object') {
+ res.json(200, returnData);
} else {
- res.redirect('/404');
+ res.send(200, validator.escape(returnData));
}
});
- };
-})(exports);
+ });
+
+ app.put('/plugins/fireHook', function(req, res) {
+ // PUT = action
+ var hook = 'action:' + req.body.hook;
+ if (plugins.hasListeners(hook)) {
+ // Hook executes
+ plugins.fireHook(hook, req.body.args);
+ }
+
+ res.send(200);
+ });
+
+ // Static Assets
+ app.get('/plugins/:id/*', function(req, res) {
+ var relPath = req._parsedUrl.pathname.replace(nconf.get('relative_path') + '/plugins/', ''),
+ matches = _.map(plugins.staticDirs, function(realPath, mappedPath) {
+ if (relPath.match(mappedPath)) {
+ return mappedPath;
+ } else {
+ return null;
+ }
+ }).filter(function(a) { return a; });
+
+ if (matches) {
+ async.map(matches, function(mappedPath, next) {
+ var filePath = path.join(plugins.staticDirs[mappedPath], decodeURIComponent(relPath.slice(mappedPath.length)));
+
+ fs.exists(filePath, function(exists) {
+ if (exists) {
+ next(null, filePath);
+ } else {
+ next();
+ }
+ });
+ }, function(err, matches) {
+ // Filter out the nulls
+ matches = matches.filter(function(a) {
+ return a;
+ });
+
+ if (matches.length) {
+ res.sendfile(matches[0]);
+ } else {
+ res.redirect('/404');
+ }
+ });
+ } else {
+ res.redirect('/404');
+ }
+ });
+
+ setupPluginRoutes(app);
+ setupPluginAdminRoutes(app);
+};
diff --cc src/webserver.js
index 0653cdedb3,d7d7158684..b3db354389
--- a/src/webserver.js
+++ b/src/webserver.js
@@@ -95,4 -477,534 +95,5 @@@ if(nconf.get('ssl'))
winston.info('NodeBB Ready');
});
};
+
- app.create_route = function (url, tpl) { // to remove
- var routerScript = '<script> \
- ajaxify.initialLoad = true; \
- templates.ready(function(){ajaxify.go("' + url + '", null, true);}); \
- </script>';
-
- return routerScript;
- };
-
- app.namespace(nconf.get('relative_path'), function () {
- auth.registerApp(app);
- metaRoute.createRoutes(app);
- admin.createRoutes(app);
- userRoute.createRoutes(app);
- apiRoute.createRoutes(app);
- feedsRoute.createRoutes(app);
- pluginsRoute.createRoutes(app);
-
- // Basic Routes (entirely client-side parsed, goal is to move the rest of the crap in this file into this one section)
- (function () {
- var routes = ['login', 'register', 'account', 'recent', 'popular', '403', '404', '500'],
- loginRequired = ['unread', 'notifications'];
-
- async.each(routes.concat(loginRequired), function(route, next) {
- app.get('/' + route, function (req, res) {
-
- if ((route === 'register' || route === 'login') && (req.user && req.user.uid > 0)) {
- user.getUserField(req.user.uid, 'userslug', function (err, userslug) {
- res.redirect('/user/' + userslug);
- });
- return;
- } else if(route === 'register' && meta.config.allowRegistration !== undefined && parseInt(meta.config.allowRegistration, 10) === 0) {
- return res.redirect('/403');
- } else if (loginRequired.indexOf(route) !== -1 && !req.user) {
- return res.redirect('/403');
- }
-
- app.build_header({
- req: req,
- res: res
- }, function (err, header) {
- res.send((isNaN(parseInt(route, 10)) ? 200 : parseInt(route, 10)), header + app.create_route(route) + templates.footer);
- });
- });
- });
- }());
-
-
- app.get('/', function (req, res) {
- async.parallel({
- "header": function (next) {
- app.build_header({
- req: req,
- res: res,
- metaTags: [{
- name: "title",
- content: meta.config.title || 'NodeBB'
- }, {
- name: "description",
- content: meta.config.description || ''
- }, {
- property: 'og:title',
- content: 'Index | ' + (meta.config.title || 'NodeBB')
- }, {
- property: "og:type",
- content: 'website'
- }]
- }, next);
- },
- "categories": function (next) {
- function canSee(category, next) {
- CategoryTools.privileges(category.cid, ((req.user) ? req.user.uid || 0 : 0), function(err, privileges) {
- next(!err && privileges.read);
- });
- }
-
- categories.getAllCategories(0, function (err, returnData) {
- returnData.categories = returnData.categories.filter(function (category) {
- return !category.disabled;
- });
-
- async.filter(returnData.categories, canSee, function(visibleCategories) {
- returnData.categories = visibleCategories;
- next(null, returnData);
- });
- });
- }
- }, function (err, data) {
- res.send(
- data.header +
- '\n\t<noscript>\n' + templates['noscript/header'] + templates['noscript/home'].parse(data.categories) + '\n\t</noscript>' +
- app.create_route('') +
- templates.footer
- );
- });
- });
-
- app.get('/topic/:topic_id/:slug?', function (req, res, next) {
- var tid = req.params.topic_id,
- page = req.query.page || 1,
- uid = req.user ? req.user.uid : 0;
-
- async.waterfall([
- function(next) {
- ThreadTools.privileges(tid, ((req.user) ? req.user.uid || 0 : 0), function(err, privileges) {
- if (!err) {
- if (!privileges.read) {
- next(new Error('not-enough-privileges'));
- } else {
- next();
- }
- } else {
- next(err);
- }
- });
- },
- function (next) {
- user.getSettings(uid, function(err, settings) {
- if (err) {
- return next(err);
- }
-
- var start = (page - 1) * settings.topicsPerPage,
- end = start + settings.topicsPerPage - 1;
-
- topics.getTopicWithPosts(tid, uid, start, end, function (err, topicData) {
- if (topicData) {
- if (parseInt(topicData.deleted, 10) === 1 && parseInt(topicData.expose_tools, 10) === 0) {
- return next(new Error('Topic deleted'), null);
- }
- }
-
- next(err, topicData);
- });
- });
- },
- function (topicData, next) {
-
- var lastMod = topicData.timestamp,
- description = (function() {
- var content = '';
- if(topicData.posts.length) {
- content = S(topicData.posts[0].content).stripTags().s;
- }
-
- if (content.length > 255) {
- content = content.substr(0, 255) + '...';
- }
-
- return validator.escape(content);
- })(),
- timestamp;
-
- for (var x = 0, numPosts = topicData.posts.length; x < numPosts; x++) {
- timestamp = parseInt(topicData.posts[x].timestamp, 10);
- if (timestamp > lastMod) {
- lastMod = timestamp;
- }
- }
-
- var ogImageUrl = meta.config['brand:logo'];
- if(ogImageUrl && ogImageUrl.indexOf('http') === -1) {
- ogImageUrl = nconf.get('url') + ogImageUrl;
- }
-
- app.build_header({
- req: req,
- res: res,
- metaTags: [
- {
- name: "title",
- content: topicData.title
- },
- {
- name: "description",
- content: description
- },
- {
- property: 'og:title',
- content: topicData.title
- },
- {
- property: 'og:description',
- content: description
- },
- {
- property: "og:type",
- content: 'article'
- },
- {
- property: "og:url",
- content: nconf.get('url') + '/topic/' + topicData.slug
- },
- {
- property: "og:image:url",
- content: ogImageUrl
- },
- {
- property: 'og:image',
- content: topicData.posts.length?topicData.posts[0].picture:''
- },
- {
- property: "article:published_time",
- content: utils.toISOString(topicData.timestamp)
- },
- {
- property: 'article:modified_time',
- content: utils.toISOString(lastMod)
- },
- {
- property: 'article:section',
- content: topicData.category.name
- }
- ],
- linkTags: [
- {
- rel: 'alternate',
- type: 'application/rss+xml',
- href: nconf.get('url') + '/topic/' + tid + '.rss'
- },
- {
- rel: 'up',
- href: nconf.get('url') + '/category/' + topicData.category.slug
- }
- ]
- }, function (err, header) {
- next(err, {
- header: header,
- posts: topicData
- });
- });
- }
- ], function (err, data) {
- if (err) {
- if (err.message === 'not-enough-privileges') {
- return res.redirect('403');
- } else {
- return res.redirect('404');
- }
- }
-
- var topic_url = tid + (req.params.slug ? '/' + req.params.slug : '');
- var queryString = qs.stringify(req.query);
- if(queryString.length) {
- topic_url += '?' + queryString;
- }
-
- // Paginator for noscript
- data.posts.pages = [];
- for(var x=1;x<=data.posts.pageCount;x++) {
- data.posts.pages.push({
- page: x,
- active: x === parseInt(page, 10)
- });
- }
-
- translator.translate(templates['noscript/topic'].parse(data.posts), function(translatedHTML) {
- res.send(
- data.header +
- '\n\t<noscript>\n' + templates['noscript/header'] + translatedHTML + '\n\t</noscript>' +
- '\n\t' + app.create_route('topic/' + topic_url) + templates.footer
- );
- });
- });
- });
-
- app.get('/category/:category_id/:slug?', function (req, res, next) {
- var cid = req.params.category_id,
- page = req.query.page || 1,
- uid = req.user ? req.user.uid : 0;
-
- async.waterfall([
- function(next) {
- CategoryTools.privileges(cid, uid, function(err, privileges) {
- if (!err) {
- if (!privileges.read) {
- next(new Error('not-enough-privileges'));
- } else {
- next();
- }
- } else {
- next(err);
- }
- });
- },
- function (next) {
- user.getSettings(uid, function(err, settings) {
- if (err) {
- return next(err);
- }
-
- var start = (page - 1) * settings.topicsPerPage,
- end = start + settings.topicsPerPage - 1;
-
- categories.getCategoryById(cid, start, end, 0, function (err, categoryData) {
- if (categoryData) {
- if (parseInt(categoryData.disabled, 10) === 1) {
- return next(new Error('Category disabled'), null);
- }
- }
-
- next(err, categoryData);
- });
- });
- },
- function (categoryData, next) {
- app.build_header({
- req: req,
- res: res,
- metaTags: [
- {
- name: 'title',
- content: categoryData.name
- },
- {
- property: 'og:title',
- content: categoryData.name
- },
- {
- name: 'description',
- content: categoryData.description
- },
- {
- property: "og:type",
- content: 'website'
- }
- ],
- linkTags: [
- {
- rel: 'alternate',
- type: 'application/rss+xml',
- href: nconf.get('url') + '/category/' + cid + '.rss'
- },
- {
- rel: 'up',
- href: nconf.get('url')
- }
- ]
- }, function (err, header) {
- next(err, {
- header: header,
- topics: categoryData
- });
- });
- }
- ], function (err, data) {
- if (err) {
- if (err.message === 'not-enough-privileges') {
- return res.redirect('403');
- } else {
- return res.redirect('404');
- }
- }
-
- if(data.topics.link) {
- return res.redirect(data.topics.link);
- }
-
- var category_url = cid + (req.params.slug ? '/' + req.params.slug : '');
- var queryString = qs.stringify(req.query);
- if(queryString.length) {
- category_url += '?' + queryString;
- }
-
- // Paginator for noscript
- data.topics.pages = [];
- for(var x=1;x<=data.topics.pageCount;x++) {
- data.topics.pages.push({
- page: x,
- active: x === parseInt(page, 10)
- });
- }
-
- translator.translate(templates['noscript/category'].parse(data.topics), function(translatedHTML) {
- res.send(
- data.header +
- '\n\t<noscript>\n' + templates['noscript/header'] + translatedHTML + '\n\t</noscript>' +
- '\n\t' + app.create_route('category/' + category_url) + templates.footer
- );
- });
- });
- });
-
- app.get('/confirm/:code', function (req, res) {
- app.build_header({
- req: req,
- res: res
- }, function (err, header) {
- res.send(header + app.create_route('confirm/' + req.params.code) + templates.footer);
- });
- });
-
- app.get('/sitemap.xml', function (req, res) {
- var sitemap = require('./sitemap.js');
-
- sitemap.render(function (xml) {
- res.header('Content-Type', 'application/xml');
- res.send( xml );
- });
- });
-
- app.get('/robots.txt', function (req, res) {
- res.set('Content-Type', 'text/plain');
-
- if (meta.config["robots.txt"]) {
- res.send(meta.config["robots.txt"])
- } else {
- res.send("User-agent: *\n" +
- "Disallow: /admin/\n" +
- "Sitemap: " + nconf.get('url') + "/sitemap.xml");
- }
- });
-
- app.get('/recent/:term?', function (req, res) {
- // TODO consolidate with /recent route as well -> that can be combined into this area. See "Basic Routes" near top.
- app.build_header({
- req: req,
- res: res
- }, function (err, header) {
- res.send(header + app.create_route('recent/' + req.params.term, null, 'recent') + templates.footer);
- });
-
- });
-
- app.get('/popular/:term?', function (req, res) {
- app.build_header({
- req: req,
- res: res
- }, function (err, header) {
- res.send(header + app.create_route('popular/' + req.params.term, null, 'popular') + templates.footer);
- });
-
- });
-
- app.get('/outgoing', function (req, res) {
- if (!req.query.url) {
- return res.redirect('/404');
- }
-
- app.build_header({
- req: req,
- res: res
- }, function (err, header) {
- res.send(header + app.create_route('outgoing?url=' + encodeURIComponent(req.query.url)) + templates.footer);
- });
- });
-
- app.get('/search/:term?', function (req, res) {
-
- if (!req.user && meta.config.allowGuestSearching !== '1') {
- return res.redirect('/403');
- }
- if(!req.params.term) {
- req.params.term = '';
- }
- app.build_header({
- req: req,
- res: res
- }, function (err, header) {
- res.send(header + app.create_route('search/' + req.params.term, null, 'search') + templates.footer);
- });
- });
-
- // Debug routes
- if (process.env.NODE_ENV === 'development') {
- require('./routes/debug')(app);
- }
-
- var custom_routes = {
- 'routes': [],
- 'api': [],
- 'templates': []
- };
-
- app.get_custom_templates = function() {
- return custom_routes.templates.map(function(tpl) {
- return tpl.template.split('.tpl')[0];
- });
- };
-
- plugins.ready(function() {
- plugins.fireHook('filter:server.create_routes', custom_routes, function(err, custom_routes) {
- var routes = custom_routes.routes;
- for (var route in routes) {
- if (routes.hasOwnProperty(route)) {
- (function(route) {
- app[routes[route].method || 'get'](routes[route].route, function(req, res) {
- routes[route].options(req, res, function(options) {
- app.build_header({
- req: options.req || req,
- res: options.res || res
- }, function (err, header) {
- res.send(header + options.content + templates.footer);
- });
- });
- });
- }(route));
- }
- }
-
- var apiRoutes = custom_routes.api;
- for (var route in apiRoutes) {
- if (apiRoutes.hasOwnProperty(route)) {
- (function(route) {
- app[apiRoutes[route].method || 'get']('/api' + apiRoutes[route].route, function(req, res) {
- apiRoutes[route].callback(req, res, function(data) {
- res.json(data);
- });
- });
- }(route));
- }
- }
-
- var templateRoutes = custom_routes.templates;
- for (var route in templateRoutes) {
- if (templateRoutes.hasOwnProperty(route)) {
- (function(route) {
- app.get('/templates/' + templateRoutes[route].template, function(req, res) {
- res.send(templateRoutes[route].content);
- });
- }(route));
- }
- }
-
- });
- });
-
-
- });
}(WebServer));