From d714b5c592af56db12d25e858b9426bbe32ab8fd Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 12:54:03 -0400 Subject: [PATCH 01/12] editorconfig end_of_line --- .editorconfig | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.editorconfig b/.editorconfig index f2aa095e60..a259e2210b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,8 +1,4 @@ root = true -[*] -end_of_line = lf -insert_final_newline = true - [*.js, *.css, *.tpl] -indent_style = tab \ No newline at end of file +indent_style = tab From 6bab2523d50b258cf6c2173bdf2877a95c67d70e Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 12:55:20 -0400 Subject: [PATCH 02/12] fixes #276 popup alert appearing under admin content --- public/templates/admin/footer.tpl | 3 +++ public/templates/admin/header.tpl | 2 -- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/public/templates/admin/footer.tpl b/public/templates/admin/footer.tpl index 5721d11993..f5392a6499 100644 --- a/public/templates/admin/footer.tpl +++ b/public/templates/admin/footer.tpl @@ -1,6 +1,9 @@ + +
+ diff --git a/public/templates/admin/header.tpl b/public/templates/admin/header.tpl index 5847ae259d..ed5ff90413 100644 --- a/public/templates/admin/header.tpl +++ b/public/templates/admin/header.tpl @@ -63,8 +63,6 @@ -
-
From cf889cfe25007bb8637f7987491d45f03d00c626 Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 12:59:04 -0400 Subject: [PATCH 03/12] .jshintrc, massive dehinting adventure to follow --- .jshintrc | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 .jshintrc diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000000..5eaed9e374 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,86 @@ +{ + // JSHint Default Configuration File (as on JSHint website) + // See http://jshint.com/docs/ for more details + + "maxerr" : 50, // {int} Maximum error before stopping + + // Enforcing + "bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase" : false, // true: Identifiers must be in camelCase + "curly" : true, // true: Require {} for every new block or scope + "eqeqeq" : true, // true: Require triple equals (===) for comparison + "forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty() + "immed" : false, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "indent" : 4, // {int} Number of spaces to use for indentation + "latedef" : false, // true: Require variables/functions to be defined before being used + "newcap" : false, // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty" : true, // true: Prohibit use of empty blocks + "nonew" : false, // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus" : false, // true: Prohibit use of `++` & `--` + "quotmark" : false, // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) + "unused" : true, // true: Require all defined variables be used + "strict" : true, // true: Requires all functions run in ES5 Strict Mode + "trailing" : false, // true: Prohibit trailing whitespaces + "maxparams" : false, // {int} Max number of formal params allowed per function + "maxdepth" : false, // {int} Max depth of nested blocks (within functions) + "maxstatements" : false, // {int} Max number statements per function + "maxcomplexity" : false, // {int} Max cyclomatic complexity per function + "maxlen" : false, // {int} Max number of characters per line + + // Relaxing + "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss" : false, // true: Tolerate assignments where comparisons would be expected + "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // true: Tolerate use of `== null` + "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) + "esnext" : false, // true: Allow ES.next (ES6) syntax (ex: `const`) + "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "evil" : false, // true: Tolerate use of `eval` and `new Function()` + "expr" : false, // true: Tolerate `ExpressionStatement` as Programs + "funcscope" : false, // true: Tolerate defining variables inside control statements" + "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') + "iterator" : false, // true: Tolerate using the `__iterator__` property + "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak" : false, // true: Tolerate possibly unsafe line breakings + "laxcomma" : false, // true: Tolerate comma-first style coding + "loopfunc" : false, // true: Tolerate functions being defined in loops + "multistr" : false, // true: Tolerate multi-line strings + "proto" : false, // true: Tolerate using the `__proto__` property + "scripturl" : false, // true: Tolerate script-targeted URLs + "smarttabs" : false, // true: Tolerate mixed tabs/spaces when used for alignment + "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` + "validthis" : false, // true: Tolerate using this in a non-constructor function + + // Environments + "browser" : true, // Web Browser (window, document, etc) + "couch" : false, // CouchDB + "devel" : true, // Development/debugging (alert, confirm, etc) + "dojo" : false, // Dojo Toolkit + "jquery" : true, // jQuery + "mootools" : false, // MooTools + "node" : false, // Node.js + "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) + "prototypejs" : false, // Prototype and Scriptaculous + "rhino" : false, // Rhino + "worker" : false, // Web Workers + "wsh" : false, // Windows Scripting Host + "yui" : false, // Yahoo User Interface + + // Legacy + "nomen" : false, // true: Prohibit dangling `_` in variables + "onevar" : false, // true: Allow only one `var` statement per function + "passfail" : false, // true: Stop on first error + "white" : false, // true: Check against strict whitespace and indentation rules + + // Custom Globals + "globals" : {} // additional predefined global variables +} \ No newline at end of file From 828d937decff90c77eb7334edcec0ebb719b75d6 Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:03:53 -0400 Subject: [PATCH 04/12] .jsbeautify --- .jsbeautifyrc | 17 +++++++++++ public/src/app.js | 73 ++++++++++++++++++++++++----------------------- 2 files changed, 54 insertions(+), 36 deletions(-) create mode 100644 .jsbeautifyrc diff --git a/.jsbeautifyrc b/.jsbeautifyrc new file mode 100644 index 0000000000..2245d6adb6 --- /dev/null +++ b/.jsbeautifyrc @@ -0,0 +1,17 @@ +{ + "indent_size": 4, + "indent_char": " ", + "indent_level": 0, + "indent_with_tabs": false, + "preserve_newlines": true, + "max_preserve_newlines": 10, + "jslint_happy": false, + "brace_style": "collapse", + "keep_array_indentation": false, + "keep_function_indentation": false, + "space_before_conditional": true, + "break_chained_methods": false, + "eval_code": false, + "unescape_strings": false, + "wrap_line_length": 0 +} \ No newline at end of file diff --git a/public/src/app.js b/public/src/app.js index 3130e1cbe2..9782df78c4 100644 --- a/public/src/app.js +++ b/public/src/app.js @@ -30,9 +30,9 @@ var socket, app.alert(data); }); - socket.on('connect', function(data){ - if(reconnecting) { - setTimeout(function(){ + socket.on('connect', function(data) { + if (reconnecting) { + setTimeout(function() { app.alert({ alert_id: 'connection_alert', title: 'Connected', @@ -43,18 +43,20 @@ var socket, }, 1000); reconnecting = false; reconnectTries = 0; - socket.emit('api:updateHeader', { fields: ['username', 'picture', 'userslug'] }); + socket.emit('api:updateHeader', { + fields: ['username', 'picture', 'userslug'] + }); } }); socket.on('reconnecting', function(data) { function showDisconnectModal() { $('#disconnect-modal').modal({ - backdrop:'static', - show:true + backdrop: 'static', + show: true }); - $('#reload-button').on('click',function(){ + $('#reload-button').on('click', function() { $('#disconnect-modal').modal('hide'); window.location.reload(); }); @@ -63,7 +65,7 @@ var socket, reconnecting = true; reconnectTries++; - if(reconnectTries > 4) { + if (reconnectTries > 4) { showDisconnectModal(); return; } @@ -129,10 +131,10 @@ var socket, // Willingly stolen from: http://phpjs.org/functions/strip_tags/ app.strip_tags = function(input, allowed) { allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase () - var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, + var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /|<\?(?:php)?[\s\S]*?\?>/gi; - return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { + return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; }); } @@ -146,7 +148,7 @@ var socket, app.alert = function(params) { var alert_id = 'alert_button_' + ((params.alert_id) ? params.alert_id : new Date().getTime()); - var alert = $('#'+alert_id); + var alert = $('#' + alert_id); function startTimeout(div, timeout) { var timeoutId = setTimeout(function() { @@ -158,15 +160,14 @@ var socket, $(div).attr('timeoutId', timeoutId); } - if(alert.length > 0) { + if (alert.length > 0) { alert.find('strong').html(params.title); alert.find('p').html(params.message); alert.attr('class', "alert toaster-alert " + "alert-" + params.type); clearTimeout(alert.attr('timeoutId')); startTimeout(alert, params.timeout); - } - else { + } else { var div = document.createElement('div'), button = document.createElement('button'), strong = document.createElement('strong'), @@ -191,7 +192,7 @@ var socket, if (params.location == null) params.location = 'alert_window'; - jQuery('#'+params.location).prepend(jQuery(div).fadeIn('100')); + jQuery('#' + params.location).prepend(jQuery(div).fadeIn('100')); if (params.timeout) { startTimeout(div, params.timeout); @@ -209,7 +210,7 @@ var socket, } app.alertSuccess = function(message, timeout) { - if(!timeout) + if (!timeout) timeout = 2000; app.alert({ @@ -221,7 +222,7 @@ var socket, } app.alertError = function(message, timeout) { - if(!timeout) + if (!timeout) timeout = 2000; app.alert({ @@ -234,7 +235,7 @@ var socket, app.current_room = null; app.enter_room = function(room) { - if(socket) { + if (socket) { if (app.current_room === room) return; @@ -268,13 +269,13 @@ var socket, var url = window.location.href, parts = url.split('/'), - active = parts[parts.length-1]; + active = parts[parts.length - 1]; jQuery('#main-nav li').removeClass('active'); - if(active) { + if (active) { jQuery('#main-nav li a').each(function() { var href = this.getAttribute('href'); - if(active.match(/^users/)) + if (active.match(/^users/)) active = 'users'; if (href && href.match(active)) { jQuery(this.parentNode).addClass('active'); @@ -298,9 +299,9 @@ var socket, }); } - if(showWelcomeMessage) { + if (showWelcomeMessage) { showWelcomeMessage = false; - if(document.readyState !== 'complete') { + if (document.readyState !== 'complete') { $(document).ready(showAlert); } else { showAlert(); @@ -317,7 +318,7 @@ var socket, app.openChat = function(username, touid) { require(['chat'], function(chat) { var chatModal; - if(!chat.modalExists(touid)) { + if (!chat.modalExists(touid)) { chatModal = chat.createModal(username, touid); } else { chatModal = chat.getModal(touid); @@ -336,7 +337,7 @@ var socket, .append(html) .fadeIn('slow'); - for(var x=0,numPosts=data.posts.length;x Date: Tue, 17 Sep 2013 13:04:40 -0400 Subject: [PATCH 05/12] formatting - core client side --- public/src/ajaxify.js | 30 +++++++++++----------- public/src/templates.js | 40 +++++++++++++++-------------- public/src/utils.js | 56 +++++++++++++++++++++++++---------------- 3 files changed, 70 insertions(+), 56 deletions(-) diff --git a/public/src/ajaxify.js b/public/src/ajaxify.js index e25ceab420..5cf650703a 100644 --- a/public/src/ajaxify.js +++ b/public/src/ajaxify.js @@ -12,7 +12,7 @@ var ajaxify = {}; var events = []; ajaxify.register_events = function(new_page_events) { - for (var i = 0, ii = events.length; i/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase () - var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, + var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /|<\?(?:php)?[\s\S]*?\?>/gi; - return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { + return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; }); }, buildMetaTags: function(tagsArr) { - var tags = '', + var tags = '', tag; - for(var x=0,numTags=tagsArr.length;x 0) tags += "\n\t"; tag = ' 0 ? '(' + numNotifications + ') ' : '') + title; + document.title = (numNotifications > 0 ? '(' + numNotifications + ') ' : '') + title; notificationIcon = notificationIcon || document.querySelector('.notifications a i'); if (numNotifications > 0 && notificationIcon) notificationIcon.className = 'icon-circle active'; }); @@ -150,8 +151,7 @@ badge .removeClass('badge-inverse') .addClass('badge-important') - } - else { + } else { badge .removeClass('badge-important') .addClass('badge-inverse') @@ -160,26 +160,34 @@ }, isRelativeUrl: function(url) { - var firstChar = url.slice(0, 1); + var firstChar = url.slice(0, 1); return (firstChar === '.' || firstChar === '/'); } } if (!String.prototype.trim) { - String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');}; + String.prototype.trim = function() { + return this.replace(/^\s+|\s+$/g, ''); + }; } if (!String.prototype.ltrim) { - String.prototype.ltrim=function(){return this.replace(/^\s+/,'');}; + String.prototype.ltrim = function() { + return this.replace(/^\s+/, ''); + }; } if (!String.prototype.rtrim) { - String.prototype.rtrim=function(){return this.replace(/\s+$/,'');}; + String.prototype.rtrim = function() { + return this.replace(/\s+$/, ''); + }; } if (!String.prototype.fulltrim) { - String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');}; + String.prototype.fulltrim = function() { + return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '); + }; } @@ -187,4 +195,8 @@ window.utils = module.exports; } -})('undefined' === typeof module ? {module:{exports:{}}} : module) \ No newline at end of file +})('undefined' === typeof module ? { + module: { + exports: {} + } +} : module) \ No newline at end of file From 221b9bc149c5be456d8b82514358299752f35a2e Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:05:54 -0400 Subject: [PATCH 06/12] formatting - template associated js --- public/src/forum/account.js | 18 ++-- public/src/forum/accountedit.js | 81 ++++++++-------- public/src/forum/accountheader.js | 2 +- public/src/forum/accountsettings.js | 7 +- public/src/forum/category.js | 30 +++--- public/src/forum/favourites.js | 4 - public/src/forum/followers.js | 2 +- public/src/forum/following.js | 15 +-- public/src/forum/footer.js | 44 +++++---- public/src/forum/login.js | 18 ++-- public/src/forum/recent.js | 33 ++++--- public/src/forum/register.js | 33 ++++--- public/src/forum/reset.js | 16 +-- public/src/forum/reset_code.js | 13 ++- public/src/forum/search.js | 2 +- public/src/forum/topic.js | 145 ++++++++++++++++------------ public/src/forum/unread.js | 47 +++++---- public/src/forum/users.js | 71 +++++++------- 18 files changed, 320 insertions(+), 261 deletions(-) diff --git a/public/src/forum/account.js b/public/src/forum/account.js index 1bb4dc5325..6d8beaf79e 100644 --- a/public/src/forum/account.js +++ b/public/src/forum/account.js @@ -12,8 +12,8 @@ var followBtn = $('#follow-btn'); var unfollowBtn = $('#unfollow-btn'); - if(yourid !== theirid) { - if(isFollowing) { + if (yourid !== theirid) { + if (isFollowing) { followBtn.hide(); unfollowBtn.show(); } else { @@ -26,8 +26,10 @@ } followBtn.on('click', function() { - socket.emit('api:user.follow', {uid: theirid}, function(success) { - if(success) { + socket.emit('api:user.follow', { + uid: theirid + }, function(success) { + if (success) { followBtn.hide(); unfollowBtn.show(); app.alertSuccess('You are now following ' + username + '!'); @@ -39,8 +41,10 @@ }); unfollowBtn.on('click', function() { - socket.emit('api:user.unfollow', {uid: theirid}, function(success) { - if(success) { + socket.emit('api:user.unfollow', { + uid: theirid + }, function(success) { + if (success) { followBtn.show(); unfollowBtn.hide(); app.alertSuccess('You are no longer following ' + username + '!'); @@ -58,7 +62,7 @@ var onlineStatus = $('.account-online-status'); function handleUserOnline(data) { - if(data.online) { + if (data.online) { onlineStatus.find('span span').text('online'); onlineStatus.find('i').attr('class', 'icon-circle'); } else { diff --git a/public/src/forum/accountedit.js b/public/src/forum/accountedit.js index ab2c6cf16b..527eed2180 100644 --- a/public/src/forum/accountedit.js +++ b/public/src/forum/accountedit.js @@ -1,5 +1,3 @@ - - var gravatarPicture = templates.get('gravatarpicture'); var uploadedPicture = templates.get('uploadedpicture'); @@ -14,7 +12,7 @@ $(document).ready(function() { $('#upload-progress-box').show(); $('#upload-progress-box').removeClass('hide'); - if(!$('#userPhotoInput').val()) { + if (!$('#userPhotoInput').val()) { error('select an image to upload!'); return false; } @@ -28,13 +26,13 @@ $(document).ready(function() { error('Error: ' + xhr.status); }, - uploadProgress : function(event, position, total, percent) { - $('#upload-progress-bar').css('width', percent+'%'); + uploadProgress: function(event, position, total, percent) { + $('#upload-progress-bar').css('width', percent + '%'); }, success: function(response) { - if(response.error) { + if (response.error) { error(response.error); return; } @@ -51,7 +49,9 @@ $(document).ready(function() { $('#upload-picture-modal').modal('hide'); }, 750); - socket.emit('api:updateHeader', { fields: ['username', 'picture', 'userslug'] }); + socket.emit('api:updateHeader', { + fields: ['username', 'picture', 'userslug'] + }); success('File uploaded successfully!'); } }); @@ -87,7 +87,7 @@ $(document).ready(function() { }; socket.emit('api:user.changePicture', userData, function(success) { - if(!success) { + if (!success) { app.alertError('There was an error changing picture!'); } }); @@ -95,26 +95,26 @@ $(document).ready(function() { var selectedImageType = ''; - $('#submitBtn').on('click',function(){ + $('#submitBtn').on('click', function() { - var userData = { - uid:$('#inputUID').val(), - email:$('#inputEmail').val(), - fullname:$('#inputFullname').val(), - website:$('#inputWebsite').val(), - birthday:$('#inputBirthday').val(), - location:$('#inputLocation').val(), - signature:$('#inputSignature').val() + var userData = { + uid: $('#inputUID').val(), + email: $('#inputEmail').val(), + fullname: $('#inputFullname').val(), + website: $('#inputWebsite').val(), + birthday: $('#inputBirthday').val(), + location: $('#inputLocation').val(), + signature: $('#inputSignature').val() }; socket.emit('api:user.updateProfile', userData, function(err, data) { - if(data.success) { + if (data.success) { app.alertSuccess('Your profile has been updated successfully!'); - if(data.picture) { + if (data.picture) { $('#user-current-picture').attr('src', data.picture); $('#user_label img').attr('src', data.picture); } - if(data.gravatarpicture) { + if (data.gravatarpicture) { $('#user-gravatar-picture').attr('src', data.gravatarpicture); gravatarPicture = data.gravatarpicture; } @@ -128,27 +128,25 @@ $(document).ready(function() { function updateImages() { var currentPicture = $('#user-current-picture').attr('src'); - if(gravatarPicture) { + if (gravatarPicture) { $('#user-gravatar-picture').attr('src', gravatarPicture); $('#gravatar-box').show(); - } - else + } else $('#gravatar-box').hide(); - if(uploadedPicture) { + if (uploadedPicture) { $('#user-uploaded-picture').attr('src', uploadedPicture); $('#uploaded-box').show(); - } - else + } else $('#uploaded-box').hide(); - if(currentPicture == gravatarPicture) + if (currentPicture == gravatarPicture) $('#gravatar-box .icon-ok').show(); else $('#gravatar-box .icon-ok').hide(); - if(currentPicture == uploadedPicture) + if (currentPicture == uploadedPicture) $('#uploaded-box .icon-ok').show(); else $('#uploaded-box .icon-ok').hide(); @@ -165,13 +163,13 @@ $(document).ready(function() { return false; }); - $('#gravatar-box').on('click', function(){ + $('#gravatar-box').on('click', function() { $('#gravatar-box .icon-ok').show(); $('#uploaded-box .icon-ok').hide(); selectedImageType = 'gravatar'; }); - $('#uploaded-box').on('click', function(){ + $('#uploaded-box').on('click', function() { $('#gravatar-box .icon-ok').hide(); $('#uploaded-box .icon-ok').show(); selectedImageType = 'uploaded'; @@ -180,12 +178,12 @@ $(document).ready(function() { $('#savePictureChangesBtn').on('click', function() { $('#change-picture-modal').modal('hide'); - if(selectedImageType) { + if (selectedImageType) { changeUserPicture(selectedImageType); - if(selectedImageType == 'gravatar') + if (selectedImageType == 'gravatar') $('#user-current-picture').attr('src', gravatarPicture); - else if(selectedImageType == 'uploaded') + else if (selectedImageType == 'uploaded') $('#user-current-picture').attr('src', uploadedPicture); } @@ -195,7 +193,7 @@ $(document).ready(function() { $('#userPhotoInput').val(''); }); - $('#uploadPictureBtn').on('click', function(){ + $('#uploadPictureBtn').on('click', function() { $('#change-picture-modal').modal('hide'); $('#upload-picture-modal').modal('show'); @@ -226,7 +224,7 @@ $(document).ready(function() { password_notify.html('Password too short'); password_notify.attr('class', 'alert alert-danger'); password_notify.removeClass('hide'); - } else if(!passwordvalid) { + } else if (!passwordvalid) { password_notify.html('Invalid password'); password_notify.attr('class', 'alert alert-danger'); password_notify.removeClass('hide'); @@ -240,11 +238,11 @@ $(document).ready(function() { } function onPasswordConfirmChanged() { - if(password_notify.hasClass('alert-danger') || !password_confirm.val()) { + if (password_notify.hasClass('alert-danger') || !password_confirm.val()) { password_confirm_notify.addClass('hide'); return; } - if(password.val() !== password_confirm.val()) { + if (password.val() !== password_confirm.val()) { password_confirm_notify.html('Passwords must match!'); password_confirm_notify.attr('class', 'alert alert-danger'); password_confirm_notify.removeClass('hide'); @@ -262,8 +260,11 @@ $(document).ready(function() { $('#changePasswordBtn').on('click', function() { - if(passwordvalid && passwordsmatch && currentPassword.val()) { - socket.emit('api:user.changePassword', {'currentPassword': currentPassword.val(),'newPassword': password.val() }, function(err) { + if (passwordvalid && passwordsmatch && currentPassword.val()) { + socket.emit('api:user.changePassword', { + 'currentPassword': currentPassword.val(), + 'newPassword': password.val() + }, function(err) { currentPassword.val(''); password.val(''); @@ -273,7 +274,7 @@ $(document).ready(function() { passwordsmatch = false; passwordvalid = false; - if(err) { + if (err) { app.alertError(err.error); return; } diff --git a/public/src/forum/accountheader.js b/public/src/forum/accountheader.js index b6fccea441..0bd3d22300 100644 --- a/public/src/forum/accountheader.js +++ b/public/src/forum/accountheader.js @@ -24,7 +24,7 @@ var settingsLink = $('#settingsLink'); var favouritesLink = $('#favouritesLink'); - if(yourid === "0" || yourid !== theirid) { + if (yourid === "0" || yourid !== theirid) { editLink.hide(); settingsLink.hide(); favouritesLink.hide(); diff --git a/public/src/forum/accountsettings.js b/public/src/forum/accountsettings.js index 243f12dbeb..d121ecbe85 100644 --- a/public/src/forum/accountsettings.js +++ b/public/src/forum/accountsettings.js @@ -1,16 +1,13 @@ - - - $(document).ready(function() { $('#submitBtn').on('click', function() { var settings = { - showemail: $('#showemailCheckBox').is(':checked')?1:0 + showemail: $('#showemailCheckBox').is(':checked') ? 1 : 0 }; socket.emit('api:user.saveSettings', settings, function(success) { - if(success) { + if (success) { app.alertSuccess('Settings saved!'); } else { app.alertError('There was an error saving settings!'); diff --git a/public/src/forum/category.js b/public/src/forum/category.js index 70e8937701..03eea0ac47 100644 --- a/public/src/forum/category.js +++ b/public/src/forum/category.js @@ -36,7 +36,9 @@ ]); function onNewTopic(data) { - var html = templates.prepare(templates['category'].blocks['topics']).parse({ topics: [data] }), + var html = templates.prepare(templates['category'].blocks['topics']).parse({ + topics: [data] + }), topic = document.createElement('div'), container = document.getElementById('topics-container'), topics = document.querySelectorAll('#topics-container a'), @@ -50,7 +52,7 @@ topic = topic.querySelector('a'); if (numTopics > 0) { - for(x=0;x' + - '' + - '

' + - posts[i].content + - '

' + - '' + posts[i].username + ' - ' + utils.relativeTime(posts[i].timestamp) + ' ago' + - '
'; + li.innerHTML = '' + + '' + + '

' + + posts[i].content + + '

' + + '' + posts[i].username + ' - ' + utils.relativeTime(posts[i].timestamp) + ' ago' + + '
'; frag.appendChild(li.cloneNode(true)); recent_replies.appendChild(frag); @@ -98,7 +100,9 @@ function onTopicsLoaded(topics) { - var html = templates.prepare(templates['category'].blocks['topics']).parse({ topics: topics }), + var html = templates.prepare(templates['category'].blocks['topics']).parse({ + topics: topics + }), container = $('#topics-container'); jQuery('#topics-container, .category-sidebar').removeClass('hidden'); @@ -115,7 +119,7 @@ cid: cid, after: $('#topics-container').children().length }, function(data) { - if(data.topics.length) { + if (data.topics.length) { onTopicsLoaded(data.topics); } loadingMoreTopics = false; diff --git a/public/src/forum/favourites.js b/public/src/forum/favourites.js index e18876b19d..cff01ab271 100644 --- a/public/src/forum/favourites.js +++ b/public/src/forum/favourites.js @@ -1,11 +1,7 @@ (function() { - $(document).ready(function() { - $('.user-favourite-posts .topic-row').on('click', function() { ajaxify.go($(this).attr('topic-url')); }); - }); - }()); \ No newline at end of file diff --git a/public/src/forum/followers.js b/public/src/forum/followers.js index 9093dcbd1e..0fcb464f0b 100644 --- a/public/src/forum/followers.js +++ b/public/src/forum/followers.js @@ -6,7 +6,7 @@ $(document).ready(function() { - if(parseInt(followersCount, 10) === 0) { + if (parseInt(followersCount, 10) === 0) { $('#no-followers-notice').removeClass('hide'); } diff --git a/public/src/forum/following.js b/public/src/forum/following.js index 0353b72236..cd31d25466 100644 --- a/public/src/forum/following.js +++ b/public/src/forum/following.js @@ -6,22 +6,23 @@ $(document).ready(function() { - if(parseInt(followingCount, 10) === 0) { + if (parseInt(followingCount, 10) === 0) { $('#no-following-notice').removeClass('hide'); } - if(yourid !== theirid) { + if (yourid !== theirid) { $('.unfollow-btn').hide(); - } - else { - $('.unfollow-btn').on('click',function() { + } else { + $('.unfollow-btn').on('click', function() { var unfollowBtn = $(this); var followingUid = $(this).attr('followingUid'); - socket.emit('api:user.unfollow', {uid: followingUid}, function(success) { + socket.emit('api:user.unfollow', { + uid: followingUid + }, function(success) { var username = unfollowBtn.attr('data-username'); - if(success) { + if (success) { unfollowBtn.parent().remove(); app.alertSuccess('You are no longer following ' + username + '!'); } else { diff --git a/public/src/forum/footer.js b/public/src/forum/footer.js index f1d0c8da9c..f58633d898 100644 --- a/public/src/forum/footer.js +++ b/public/src/forum/footer.js @@ -22,7 +22,9 @@ stats_online.innerHTML = data.users; }); - socket.emit('api:updateHeader', { fields: ['username', 'picture', 'userslug'] }); + socket.emit('api:updateHeader', { + fields: ['username', 'picture', 'userslug'] + }); socket.on('api:updateHeader', function(data) { jQuery('#search-button').on('click', function() { @@ -49,18 +51,18 @@ jQuery('.nodebb-loggedout').hide(); var userLabel = rightMenu.find('#user_label'); - if(userLabel.length) { - if(data['userslug']) - userLabel.attr('href','/users/' + data['userslug']); - if(data['picture']) - userLabel.find('img').attr('src',data['picture']); - if(data['username']) + if (userLabel.length) { + if (data['userslug']) + userLabel.attr('href', '/users/' + data['userslug']); + if (data['picture']) + userLabel.find('img').attr('src', data['picture']); + if (data['username']) userLabel.find('span').html(data['username']); } else { var userli = $('
  • \ - \ - \ - '+data['username']+' \ + \ + \ + ' + data['username'] + ' \ \
  • '); rightMenu.append(userli); @@ -95,20 +97,20 @@ e.preventDefault(); if (notifContainer.className.indexOf('open') === -1) { socket.emit('api:notifications.get', null, function(data) { - var notifFrag = document.createDocumentFragment(), + var notifFrag = document.createDocumentFragment(), notifEl = document.createElement('li'), numRead = data.read.length, numUnread = data.unread.length, x; notifList.innerHTML = ''; if ((data.read.length + data.unread.length) > 0) { - for(x=0;x' + utils.relativeTime(data.unread[x].datetime, true) + '' + data.unread[x].text + ''; notifFrag.appendChild(notifEl.cloneNode(true)); } - for(x=0;x' + utils.relativeTime(data.read[x].datetime, true) + '' + data.read[x].text + ''; @@ -133,10 +135,16 @@ notifList.addEventListener('click', function(e) { var target; - switch(e.target.nodeName) { - case 'SPAN': target = e.target.parentNode.parentNode; break; - case 'A': target = e.target.parentNode; break; - case 'li': target = e.target; break; + switch (e.target.nodeName) { + case 'SPAN': + target = e.target.parentNode.parentNode; + break; + case 'A': + target = e.target.parentNode; + break; + case 'li': + target = e.target; + break; } if (target) { var nid = parseInt(target.getAttribute('data-nid')); @@ -161,7 +169,7 @@ require(['chat'], function(chat) { var modal = null; - if(chat.modalExists(data.fromuid)) { + if (chat.modalExists(data.fromuid)) { modal = chat.getModal(data.fromuid); chat.appendChatMessage(modal, data.message, data.timestamp); } else { diff --git a/public/src/forum/login.js b/public/src/forum/login.js index 7b475c566b..5ff7a2de58 100644 --- a/public/src/forum/login.js +++ b/public/src/forum/login.js @@ -1,13 +1,15 @@ - - (function() { // Alternate Logins var altLoginEl = document.querySelector('.alt-logins'); altLoginEl.addEventListener('click', function(e) { var target; - switch(e.target.nodeName) { - case 'LI': target = e.target; break; - case 'I': target = e.target.parentNode; break; + switch (e.target.nodeName) { + case 'LI': + target = e.target; + break; + case 'I': + target = e.target.parentNode; + break; } if (target) { document.location.href = target.getAttribute('data-url'); @@ -26,14 +28,14 @@ url: RELATIVE_PATH + '/login', data: loginData, success: function(data, textStatus, jqXHR) { - if(!data.success) { + if (!data.success) { $('#login-error-notify').show(); } else { $('#login-error-notify').hide(); window.location.replace(RELATIVE_PATH + "/?loggedin"); } }, - error : function(data, textStatus, jqXHR) { + error: function(data, textStatus, jqXHR) { $('#login-error-notify').show(); }, dataType: 'json', @@ -50,4 +52,4 @@ }); document.querySelector('#content input').focus(); -}()); +}()); \ No newline at end of file diff --git a/public/src/forum/recent.js b/public/src/forum/recent.js index 1cf2c25e98..f9b1fe228c 100644 --- a/public/src/forum/recent.js +++ b/public/src/forum/recent.js @@ -8,32 +8,33 @@ 'event:new_post' ]); - var newTopicCount = 0, newPostCount = 0; + var newTopicCount = 0, + newPostCount = 0; $('#new-topics-alert').on('click', function() { $(this).hide(); }); socket.on('event:new_topic', function(data) { - + ++newTopicCount; updateAlertText(); - + }); - + function updateAlertText() { var text = ''; - - if(newTopicCount > 1) + + if (newTopicCount > 1) text = 'There are ' + newTopicCount + ' new topics'; - else if(newTopicCount === 1) + else if (newTopicCount === 1) text = 'There is 1 new topic'; else text = 'There are no new topics'; - - if(newPostCount > 1) + + if (newPostCount > 1) text += ' and ' + newPostCount + ' new posts.'; - else if(newPostCount === 1) + else if (newPostCount === 1) text += ' and 1 new post.'; else text += ' and no new posts.'; @@ -42,7 +43,7 @@ $('#new-topics-alert').html(text).fadeIn('slow'); } - + socket.on('event:new_post', function(data) { ++newPostCount; updateAlertText(); @@ -50,7 +51,9 @@ function onTopicsLoaded(topics) { - var html = templates.prepare(templates['recent'].blocks['topics']).parse({ topics: topics }), + var html = templates.prepare(templates['recent'].blocks['topics']).parse({ + topics: topics + }), container = $('#topics-container'); $('#category-no-topics').remove(); @@ -60,8 +63,10 @@ function loadMoreTopics() { loadingMoreTopics = true; - socket.emit('api:topics.loadMoreRecentTopics', {after:$('#topics-container').children().length}, function(data) { - if(data.topics && data.topics.length) { + socket.emit('api:topics.loadMoreRecentTopics', { + after: $('#topics-container').children().length + }, function(data) { + if (data.topics && data.topics.length) { onTopicsLoaded(data.topics); } loadingMoreTopics = false; diff --git a/public/src/forum/register.js b/public/src/forum/register.js index 4af0af93a2..da83144674 100644 --- a/public/src/forum/register.js +++ b/public/src/forum/register.js @@ -29,16 +29,17 @@ } function validateEmail() { - if(!emailEl.val()) { + if (!emailEl.val()) { validationError = true; return; } - if(!utils.isEmailValid(emailEl.val())) { + if (!utils.isEmailValid(emailEl.val())) { showError(email_notify, 'Invalid email address.'); - } - else - socket.emit('user.email.exists', { email: emailEl.val() }); + } else + socket.emit('user.email.exists', { + email: emailEl.val() + }); } emailEl.on('blur', function() { @@ -46,19 +47,21 @@ }); function validateUsername() { - if(!username.val()) { + if (!username.val()) { validationError = true; return; } - if(username.val().length < config.minimumUsernameLength) { + if (username.val().length < config.minimumUsernameLength) { showError(username_notify, 'Username too short!'); - } else if(username.val().length > config.maximumUsernameLength) { + } else if (username.val().length > config.maximumUsernameLength) { showError(username_notify, 'Username too long!'); - } else if(!utils.isUserNameValid(username.val())) { + } else if (!utils.isUserNameValid(username.val())) { showError(username_notify, 'Invalid username!'); } else { - socket.emit('user.exists', {username: username.val()}); + socket.emit('user.exists', { + username: username.val() + }); } } @@ -70,20 +73,20 @@ }); function validatePassword() { - if(!password.val()){ + if (!password.val()) { validationError = true; return; } if (password.val().length < config.minimumPasswordLength) { showError(password_notify, 'Password too short!'); - } else if(!utils.isPasswordValid(password.val())) { + } else if (!utils.isPasswordValid(password.val())) { showError(password_notify, 'Invalid password!'); } else { showSuccess(password_notify, successIcon); } - if(password.val() !== password_confirm.val() && password_confirm.val() !== '') { + if (password.val() !== password_confirm.val() && password_confirm.val() !== '') { showError(password_confirm_notify, 'Passwords must match!'); } } @@ -93,11 +96,11 @@ }); function validatePasswordConfirm() { - if(!password.val() || password_notify.hasClass('alert-error')) { + if (!password.val() || password_notify.hasClass('alert-error')) { return; } - if(password.val() !== password_confirm.val()) { + if (password.val() !== password_confirm.val()) { showError(password_confirm_notify, 'Passwords must match!'); } else { showSuccess(password_confirm_notify, successIcon); diff --git a/public/src/forum/reset.js b/public/src/forum/reset.js index 053db42e43..366d382356 100644 --- a/public/src/forum/reset.js +++ b/public/src/forum/reset.js @@ -1,11 +1,13 @@ (function() { - var inputEl = document.getElementById('email'), + var inputEl = document.getElementById('email'), errorEl = document.getElementById('error'), errorTextEl = errorEl.querySelector('p'); document.getElementById('reset').onclick = function() { if (inputEl.value.length > 0 && inputEl.value.indexOf('@') !== -1) { - socket.emit('user:reset.send', { email: inputEl.value }); + socket.emit('user:reset.send', { + email: inputEl.value + }); } else { jQuery('#success').hide(); jQuery(errorEl).show(); @@ -14,9 +16,9 @@ }; ajaxify.register_events(['user.send_reset']); - + socket.on('user.send_reset', function(data) { - var submitEl = document.getElementById('reset'); + var submitEl = document.getElementById('reset'); if (data.status === 'ok') { jQuery('#error').hide(); @@ -26,13 +28,13 @@ } else { jQuery('#success').hide(); jQuery(errorEl).show(); - switch(data.message) { + switch (data.message) { case 'invalid-email': errorTextEl.innerHTML = 'The email you put in (' + data.email + ') is not registered with us. Please try again.'; - break; + break; case 'send-failed': errorTextEl.innerHTML = 'There was a problem sending the reset code. Please try again later.'; - break; + break; } } }); diff --git a/public/src/forum/reset_code.js b/public/src/forum/reset_code.js index 3bc8906777..527b0c7bf6 100644 --- a/public/src/forum/reset_code.js +++ b/public/src/forum/reset_code.js @@ -1,7 +1,7 @@ (function() { var reset_code = templates.get('reset_code'); - var resetEl = document.getElementById('reset'), + var resetEl = document.getElementById('reset'), password = document.getElementById('password'), repeat = document.getElementById('repeat'), noticeEl = document.getElementById('notice'); @@ -18,17 +18,22 @@ noticeEl.querySelector('p').innerHTML = 'The two passwords you\'ve entered do not match.'; noticeEl.style.display = 'block'; } else { - socket.emit('user:reset.commit', { code: reset_code, password: password.value }); + socket.emit('user:reset.commit', { + code: reset_code, + password: password.value + }); } }, false); // Enable the form if the code is valid - socket.emit('user:reset.valid', { code: reset_code }); + socket.emit('user:reset.valid', { + code: reset_code + }); ajaxify.register_events(['user:reset.valid', 'user:reset.commit']); socket.on('user:reset.valid', function(data) { - if (!!data.valid) resetEl.disabled = false; + if ( !! data.valid) resetEl.disabled = false; else { var formEl = document.getElementById('reset-form'); // Show error message diff --git a/public/src/forum/search.js b/public/src/forum/search.js index 4d53321ec8..5044a9be76 100644 --- a/public/src/forum/search.js +++ b/public/src/forum/search.js @@ -6,7 +6,7 @@ $('.search-result-text').each(function() { var text = $(this).html(); var regex = new RegExp(searchQuery, 'gi'); - text = text.replace(regex, ''+searchQuery+''); + text = text.replace(regex, '' + searchQuery + ''); $(this).html(text); }); diff --git a/public/src/forum/topic.js b/public/src/forum/topic.js index 3e6b572d3c..957083d92f 100644 --- a/public/src/forum/topic.js +++ b/public/src/forum/topic.js @@ -1,5 +1,5 @@ (function() { - var expose_tools = templates.get('expose_tools'), + var expose_tools = templates.get('expose_tools'), tid = templates.get('topic_id'), postListEl = document.getElementById('post-container'), editBtns = document.querySelectorAll('#post-container .post-buttons .edit, #post-container .post-buttons .edit i'), @@ -15,7 +15,7 @@ app.addCommasToNumbers(); - var room = 'topic_' + tid, + var room = 'topic_' + tid, adminTools = document.getElementById('thread-tools'); app.enter_room(room); @@ -34,11 +34,15 @@ $('#delete_thread').on('click', function(e) { if (thread_state.deleted !== '1') { bootbox.confirm('Are you sure you want to delete this thread?', function(confirm) { - if (confirm) socket.emit('api:topic.delete', { tid: tid }); + if (confirm) socket.emit('api:topic.delete', { + tid: tid + }); }); } else { bootbox.confirm('Are you sure you want to restore this thread?', function(confirm) { - if (confirm) socket.emit('api:topic.restore', { tid: tid }); + if (confirm) socket.emit('api:topic.restore', { + tid: tid + }); }); } return false; @@ -46,18 +50,26 @@ $('#lock_thread').on('click', function(e) { if (thread_state.locked !== '1') { - socket.emit('api:topic.lock', { tid: tid }); + socket.emit('api:topic.lock', { + tid: tid + }); } else { - socket.emit('api:topic.unlock', { tid: tid }); + socket.emit('api:topic.unlock', { + tid: tid + }); } return false; }); $('#pin_thread').on('click', function(e) { if (thread_state.pinned !== '1') { - socket.emit('api:topic.pin', { tid: tid }); + socket.emit('api:topic.pin', { + tid: tid + }); } else { - socket.emit('api:topic.unpin', { tid: tid }); + socket.emit('api:topic.unpin', { + tid: tid + }); } return false; }); @@ -73,7 +85,7 @@ if (loadingEl) { socket.once('api:categories.get', function(data) { // Render categories - var categoriesFrag = document.createDocumentFragment(), + var categoriesFrag = document.createDocumentFragment(), categoryEl = document.createElement('li'), numCategories = data.categories.length, modalBody = moveThreadModal.find('.modal-body'), @@ -85,7 +97,7 @@ x, info, targetCid, targetCatLabel; categoriesEl.className = 'category-list'; - for(x=0;x ' + info.name; @@ -132,7 +144,10 @@ }); } }); - socket.emit('api:topic.move', { tid: tid, cid: targetCid }); + socket.emit('api:topic.move', { + tid: tid, + cid: targetCid + }); } }); }); @@ -142,8 +157,8 @@ } // Fix delete state for this thread's posts - var postEls = document.querySelectorAll('#post-container li[data-deleted]'); - for(var x=0,numPosts=postEls.length;x 0) { - var snippet = selection.toString(); - if (snippet.length > 0) selectionText = '> ' + snippet.replace(/\n/g, '\n> '); - } + if ($(selection.baseNode).parents('.post-content').length > 0) { + var snippet = selection.toString(); + if (snippet.length > 0) selectionText = '> ' + snippet.replace(/\n/g, '\n> '); + } - if (thread_state.locked !== '1') { - require(['composer'], function(cmp) { - cmp.push(tid, null, null, selectionText.length > 0 ? selectionText + '\n\n' : ''); - }); - } - }; + if (thread_state.locked !== '1') { + require(['composer'], function(cmp) { + cmp.push(tid, null, null, selectionText.length > 0 ? selectionText + '\n\n' : ''); + }); + } + }; $('#post-container').on('click', '.post_reply', reply_fn); $('#post_reply').on('click', reply_fn); @@ -242,7 +257,9 @@ cmp.push(tid, null, null, quoted); }); }); - socket.emit('api:posts.getRawPost', { pid: pid }); + socket.emit('api:posts.getRawPost', { + pid: pid + }); } }); @@ -251,11 +268,16 @@ var uid = $(this).parents('li').attr('data-uid'); var element = $(this).find('i'); - if(element.attr('class') == 'icon-star-empty') { - socket.emit('api:posts.favourite', {pid: pid, room_id: app.current_room}); - } - else { - socket.emit('api:posts.unfavourite', {pid: pid, room_id: app.current_room}); + if (element.attr('class') == 'icon-star-empty') { + socket.emit('api:posts.favourite', { + pid: pid, + room_id: app.current_room + }); + } else { + socket.emit('api:posts.unfavourite', { + pid: pid, + room_id: app.current_room + }); } }); @@ -276,8 +298,12 @@ if (confirmDel) { deleteAction ? - socket.emit('api:posts.delete', { pid: pid }) : - socket.emit('api:posts.restore', { pid: pid }); + socket.emit('api:posts.delete', { + pid: pid + }) : + socket.emit('api:posts.restore', { + pid: pid + }); } }); @@ -285,7 +311,7 @@ var username = $(this).parents('li.row').attr('data-username'); var touid = $(this).parents('li.row').attr('data-uid'); - if(username === app.username || !app.username) + if (username === app.username || !app.username) return; app.openChat(username, touid); @@ -302,7 +328,7 @@ socket.on('api:get_users_in_room', function(data) { var activeEl = $('#thread_active_users'); - if(activeEl.length) + if (activeEl.length) activeEl.html(data); app.populate_online_users(); @@ -363,9 +389,9 @@ socket.on('event:post_edited', function(data) { var editedPostEl = document.getElementById('content_' + data.pid); - var editedPostTitle = $('#topic_title_'+data.pid); + var editedPostTitle = $('#topic_title_' + data.pid); - if(editedPostTitle.length > 0) { + if (editedPostTitle.length > 0) { editedPostTitle.fadeOut(250, function() { editedPostTitle.html(data.title); editedPostTitle.fadeIn(250); @@ -377,14 +403,14 @@ $(this).fadeIn(250); }); - if(data.uploadedImages && data.uploadedImages.length) { - $('#images_'+data.pid).html(''); - for(var i=0; i< data.uploadedImages.length; ++i) { - var img = $(' '+data.uploadedImages[i].name+'
    '); + if (data.uploadedImages && data.uploadedImages.length) { + $('#images_' + data.pid).html(''); + for (var i = 0; i < data.uploadedImages.length; ++i) { + var img = $(' ' + data.uploadedImages[i].name + '
    '); $('#images_' + data.pid).append(img); } } else { - $('#images_'+data.pid).html(''); + $('#images_' + data.pid).html(''); } console.log('time to recreate images', data); @@ -432,12 +458,12 @@ ptotal += value; utotal += value; - post_rep.html(ptotal+ ' '); - user_rep.html(utotal+ ' '); + post_rep.html(ptotal + ' '); + user_rep.html(utotal + ' '); } function set_locked_state(locked, alert) { - var threadReplyBtn = document.getElementById('post_reply'), + var threadReplyBtn = document.getElementById('post_reply'), postReplyBtns = document.querySelectorAll('#post-container .post_reply'), quoteBtns = document.querySelectorAll('#post-container .quote'), editBtns = document.querySelectorAll('#post-container .edit'), @@ -450,7 +476,7 @@ lockThreadEl.innerHTML = ' Unlock Thread'; threadReplyBtn.disabled = true; threadReplyBtn.innerHTML = 'Locked '; - for(x=0;x= scrollTop) && (elTop <= scrollBottom) - && (elBottom <= scrollBottom) && (elTop >= scrollTop)); + var inView = ((elBottom >= scrollTop) && (elTop <= scrollBottom) && (elBottom <= scrollBottom) && (elTop >= scrollTop)); - if (inView) { - pagination.innerHTML = this.postnumber + ' out of ' + postcount; + if (inView) { + pagination.innerHTML = this.postnumber + ' out of ' + postcount; postAuthorImage.src = (jQuery(this).find('.profile-image-block img').attr('src')); mobileAuthorOverlay.innerHTML = 'Posted by ' + jQuery(this).attr('data-username') + ', ' + jQuery(this).find('.relativeTimeAgo').html(); - } + } }); setTimeout(function() { - if(scrollTop + windowHeight == jQuery(document).height()) { + if (scrollTop + windowHeight == jQuery(document).height()) { pagination.innerHTML = postcount + ' out of ' + postcount; } }, 100); @@ -675,4 +700,4 @@ window.onscroll = updateHeader; window.onload = updateHeader; -})(); +})(); \ No newline at end of file diff --git a/public/src/forum/unread.js b/public/src/forum/unread.js index e3c3a19138..b4b78b67a1 100644 --- a/public/src/forum/unread.js +++ b/public/src/forum/unread.js @@ -8,32 +8,33 @@ 'event:new_post' ]); - var newTopicCount = 0, newPostCount = 0; + var newTopicCount = 0, + newPostCount = 0; $('#new-topics-alert').on('click', function() { $(this).hide(); }); socket.on('event:new_topic', function(data) { - + ++newTopicCount; updateAlertText(); - + }); - + function updateAlertText() { var text = ''; - - if(newTopicCount > 1) + + if (newTopicCount > 1) text = 'There are ' + newTopicCount + ' new topics'; - else if(newTopicCount === 1) + else if (newTopicCount === 1) text = 'There is 1 new topic'; else text = 'There are no new topics'; - - if(newPostCount > 1) + + if (newPostCount > 1) text += ' and ' + newPostCount + ' new posts.'; - else if(newPostCount === 1) + else if (newPostCount === 1) text += ' and 1 new post.'; else text += ' and no new posts.'; @@ -42,19 +43,19 @@ $('#new-topics-alert').html(text).fadeIn('slow'); } - + socket.on('event:new_post', function(data) { ++newPostCount; updateAlertText(); }); - + $('#mark-allread-btn').on('click', function() { var btn = $(this); - socket.emit('api:topics.markAllRead', {} , function(success) { - if(success) { + socket.emit('api:topics.markAllRead', {}, function(success) { + if (success) { btn.remove(); $('#topics-container').empty(); - $('#category-no-topics').removeClass('hidden'); + $('#category-no-topics').removeClass('hidden'); app.alertSuccess('All topics marked as read!'); $('#numUnreadBadge') .removeClass('badge-important') @@ -68,7 +69,9 @@ function onTopicsLoaded(topics) { - var html = templates.prepare(templates['unread'].blocks['topics']).parse({ topics: topics }), + var html = templates.prepare(templates['unread'].blocks['topics']).parse({ + topics: topics + }), container = $('#topics-container'); $('#category-no-topics').remove(); @@ -78,12 +81,14 @@ function loadMoreTopics() { loadingMoreTopics = true; - socket.emit('api:topics.loadMoreUnreadTopics', {after:parseInt($('#topics-container').attr('data-next-start'), 10)}, function(data) { - if(data.topics && data.topics.length) { + socket.emit('api:topics.loadMoreUnreadTopics', { + after: parseInt($('#topics-container').attr('data-next-start'), 10) + }, function(data) { + if (data.topics && data.topics.length) { onTopicsLoaded(data.topics); $('#topics-container').attr('data-next-start', data.nextStart); } else { - $('#load-more-btn').hide(); + $('#load-more-btn').hide(); } loadingMoreTopics = false; @@ -92,14 +97,14 @@ $(window).off('scroll').on('scroll', function() { var bottom = ($(document).height() - $(window).height()) * 0.9; - + if ($(window).scrollTop() > bottom && !loadingMoreTopics) { loadMoreTopics(); } }); - if($("body").height() <= $(window).height() && $('#topics-container').children().length >= 20) + if ($("body").height() <= $(window).height() && $('#topics-container').children().length >= 20) $('#load-more-btn').show(); $('#load-more-btn').on('click', function() { diff --git a/public/src/forum/users.js b/public/src/forum/users.js index 436a583100..255d1a1d52 100644 --- a/public/src/forum/users.js +++ b/public/src/forum/users.js @@ -1,12 +1,12 @@ (function() { - + $(document).ready(function() { var timeoutId = 0; var loadingMoreUsers = false; - + var url = window.location.href, parts = url.split('/'), - active = parts[parts.length-1]; + active = parts[parts.length - 1]; var lastSearch = null; @@ -19,86 +19,87 @@ return false; } }); - - jQuery('#search-user').on('keyup', function () { - if(timeoutId !== 0) { + + jQuery('#search-user').on('keyup', function() { + if (timeoutId !== 0) { clearTimeout(timeoutId); timeoutId = 0; } timeoutId = setTimeout(function() { var username = $('#search-user').val(); - + if (username == '') { jQuery('#user-notfound-notify').html(''); jQuery('#user-notfound-notify').parent().removeClass('btn-warning label-warning btn-success label-success'); return; } - + if (lastSearch === username) return; lastSearch = username; - + jQuery('#user-notfound-notify').html(''); setTimeout(function() { socket.emit('api:admin.user.search', username); }, 500); //replace this with global throttling function/constant - + }, 250); }); - + socket.removeAllListeners('api:admin.user.search'); - + socket.on('api:admin.user.search', function(data) { - if(data === null) { + if (data === null) { $('#user-notfound-notify').html('You need to be logged in to search!'); $('#user-notfound-notify').parent().addClass('btn-warning label-warning'); return; } - + var html = templates.prepare(templates['users'].blocks['users']).parse({ - users: data - }), + users: data + }), userListEl = document.querySelector('#users-container'); userListEl.innerHTML = html; - if(data && data.length === 0) { + if (data && data.length === 0) { $('#user-notfound-notify').html('User not found!'); $('#user-notfound-notify').parent().addClass('btn-warning label-warning'); - } - else { - $('#user-notfound-notify').html(data.length + ' user'+(data.length>1?'s':'') + ' found!'); + } else { + $('#user-notfound-notify').html(data.length + ' user' + (data.length > 1 ? 's' : '') + ' found!'); $('#user-notfound-notify').parent().addClass('btn-success label-success'); } }); - - - + + + function onUsersLoaded(users) { - var html = templates.prepare(templates['users'].blocks['users']).parse({ users: users }); + var html = templates.prepare(templates['users'].blocks['users']).parse({ + users: users + }); $('#users-container').append(html); } - + function loadMoreUsers() { var set = ''; - if(active === 'users-latest' || active === 'users') { + if (active === 'users-latest' || active === 'users') { set = 'users:joindate'; - } else if(active === 'users-sort-posts') { + } else if (active === 'users-sort-posts') { set = 'users:postcount'; - } else if(active === 'users-sort-reputation') { - set = 'users:reputation'; + } else if (active === 'users-sort-reputation') { + set = 'users:reputation'; } - if(set) { + if (set) { loadingMoreUsers = true; socket.emit('api:users.loadMore', { - set: set, - after: $('#users-container').children().length + set: set, + after: $('#users-container').children().length }, function(data) { - if(data.users.length) { + if (data.users.length) { onUsersLoaded(data.users); } else { $('#load-more-users-btn').addClass('disabled'); @@ -107,9 +108,9 @@ }); } } - + $('#load-more-users-btn').on('click', loadMoreUsers); - + $(window).off('scroll').on('scroll', function() { var bottom = ($(document).height() - $(window).height()) * 0.9; From c44461e33f9ffb4d60f4256f1fd45ad16cb126cb Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:07:30 -0400 Subject: [PATCH 07/12] formatting - template js admin side --- public/src/forum/admin/categories.js | 23 ++++----- public/src/forum/admin/footer.js | 29 ++++++----- public/src/forum/admin/groups.js | 44 ++++++++--------- public/src/forum/admin/index.js | 8 ++-- public/src/forum/admin/plugins.js | 52 ++++++++++---------- public/src/forum/admin/themes.js | 72 ++++++++++++++-------------- public/src/forum/admin/topics.js | 44 ++++++++++------- public/src/forum/admin/users.js | 62 ++++++++++++------------ 8 files changed, 173 insertions(+), 161 deletions(-) diff --git a/public/src/forum/admin/categories.js b/public/src/forum/admin/categories.js index 39efe81616..b9a4e2d5c5 100644 --- a/public/src/forum/admin/categories.js +++ b/public/src/forum/admin/categories.js @@ -1,4 +1,3 @@ - var modified_categories = {}; function modified(el) { @@ -16,7 +15,7 @@ function save() { function select_icon(el) { var selected = el.attr('class').replace(' icon-2x', ''); jQuery('#icons .selected').removeClass('selected'); - if(selected) + if (selected) jQuery('#icons .' + selected).parent().addClass('selected'); @@ -57,14 +56,14 @@ jQuery('.blockclass').each(function() { function createNewCategory() { var category = { - name:$('#inputName').val(), - description:$('#inputDescription').val(), - icon:$('#new-category-modal i').attr('value'), - blockclass:$('#inputBlockclass').val() + name: $('#inputName').val(), + description: $('#inputDescription').val(), + icon: $('#new-category-modal i').attr('value'), + blockclass: $('#inputBlockclass').val() }; socket.emit('api:admin.categories.create', category, function(err, data) { - if(!err) { + if (!err) { app.alert({ alert_id: 'category_created', title: 'Created', @@ -73,7 +72,9 @@ jQuery('.blockclass').each(function() { timeout: 2000 }); - var html = templates.prepare(templates['admin/categories'].blocks['categories']).parse({categories:[data]}); + var html = templates.prepare(templates['admin/categories'].blocks['categories']).parse({ + categories: [data] + }); $('#entry-container').append(html); $('#new-category-modal').modal('hide'); @@ -84,7 +85,7 @@ jQuery('.blockclass').each(function() { jQuery('document').ready(function() { var url = window.location.href, parts = url.split('/'), - active = parts[parts.length-1]; + active = parts[parts.length - 1]; jQuery('.nav-pills li').removeClass('active'); jQuery('.nav-pills li a').each(function() { @@ -112,7 +113,7 @@ jQuery('.blockclass').each(function() { jQuery('.entry-row button').each(function(index, element) { var disabled = $(element).attr('data-disabled'); - if(disabled == "0" || disabled == "") + if (disabled == "0" || disabled == "") $(element).html('Disable'); else $(element).html('Enable'); @@ -124,7 +125,7 @@ jQuery('.blockclass').each(function() { var categoryRow = btn.parents('li'); var cid = categoryRow.attr('data-cid'); - var disabled = btn.html() == "Disable" ? "1":"0"; + var disabled = btn.html() == "Disable" ? "1" : "0"; categoryRow.remove(); modified_categories[cid] = modified_categories[cid] || {}; modified_categories[cid]['disabled'] = disabled; diff --git a/public/src/forum/admin/footer.js b/public/src/forum/admin/footer.js index 9fc84c7325..9d1d3acd44 100644 --- a/public/src/forum/admin/footer.js +++ b/public/src/forum/admin/footer.js @@ -1,6 +1,3 @@ - - - var nodebb_admin = (function(nodebb_admin) { nodebb_admin.config = undefined; @@ -19,21 +16,21 @@ var nodebb_admin = (function(nodebb_admin) { numFields = fields.length, saveBtn = document.getElementById('save'), x, key, inputType; - for(x=0;x 0) { - for(x=0;x 0) { - var numResults = results.length, + var numResults = results.length, resultsSlug = document.createDocumentFragment(), x; if (numResults > 4) numResults = 4; - for(x=0;x" + room + " " + count + " active user" + (count > 1 ? "s" : "") + "
    "; + active_users.innerHTML = active_users.innerHTML + "
    " + room + " " + count + " active user" + (count > 1 ? "s" : "") + "
    "; } } diff --git a/public/src/forum/admin/plugins.js b/public/src/forum/admin/plugins.js index a913cc9fe9..297fc6eb3c 100644 --- a/public/src/forum/admin/plugins.js +++ b/public/src/forum/admin/plugins.js @@ -1,35 +1,35 @@ -var nodebb_admin = nodebb_admin || {}; +var nodebb_admin = nodebb_admin || {}; (function() { - var plugins = { - init: function() { - var pluginsList = $('.plugins'), - numPlugins = pluginsList[0].querySelectorAll('li').length, - pluginID, pluginTgl; + var plugins = { + init: function() { + var pluginsList = $('.plugins'), + numPlugins = pluginsList[0].querySelectorAll('li').length, + pluginID, pluginTgl; - if (numPlugins > 0) { - pluginsList.on('click', 'button[data-action="toggleActive"]', function() { - pluginID = $(this).parents('li').attr('data-plugin-id'); - socket.emit('api:admin.plugins.toggle', pluginID); - }); + if (numPlugins > 0) { + pluginsList.on('click', 'button[data-action="toggleActive"]', function() { + pluginID = $(this).parents('li').attr('data-plugin-id'); + socket.emit('api:admin.plugins.toggle', pluginID); + }); - socket.on('api:admin.plugins.toggle', function(status) { - pluginTgl = document.querySelector('.plugins li[data-plugin-id="' + status.id + '"] button'); - pluginTgl.innerHTML = ' ' + (status.active ? 'Dea' : 'A') + 'ctivate'; + socket.on('api:admin.plugins.toggle', function(status) { + pluginTgl = document.querySelector('.plugins li[data-plugin-id="' + status.id + '"] button'); + pluginTgl.innerHTML = ' ' + (status.active ? 'Dea' : 'A') + 'ctivate'; - app.alert({ - alert_id: 'plugin_toggled_' + status.id, - title: 'Plugin Enabled', - message: 'You may need to restart NodeBB in order for these changes to be reflected.', - type: 'warning', - timeout: 5000 - }) - }); - } else { - pluginsList.append('
  • No plugins found.

  • '); - } + app.alert({ + alert_id: 'plugin_toggled_' + status.id, + title: 'Plugin Enabled', + message: 'You may need to restart NodeBB in order for these changes to be reflected.', + type: 'warning', + timeout: 5000 + }) + }); + } else { + pluginsList.append('
  • No plugins found.

  • '); } - }; + } + }; jQuery(document).ready(function() { nodebb_admin.plugins = plugins; diff --git a/public/src/forum/admin/themes.js b/public/src/forum/admin/themes.js index de6396715b..05440189cb 100644 --- a/public/src/forum/admin/themes.js +++ b/public/src/forum/admin/themes.js @@ -1,5 +1,3 @@ - - var nodebb_admin = (function(nodebb_admin) { var themes = {}; @@ -10,20 +8,20 @@ var nodebb_admin = (function(nodebb_admin) { themeContainer = document.querySelector('#bootstrap_themes'), numThemes = bootswatch.themes.length; - for(var x=0;x' + - '
    ' + - '
    ' + - ' ' + - '' + - '
    ' + - '

    ' + theme.name + '

    ' + - '

    ' + theme.description + '

    ' + - '
    ' + - '
    '; + themeEl.innerHTML = '' + + '
    ' + + '
    ' + + ' ' + + '' + + '
    ' + + '

    ' + theme.name + '

    ' + + '

    ' + theme.description + '

    ' + + '
    ' + + '
    '; themeFrag.appendChild(themeEl.cloneNode(true)); } themeContainer.innerHTML = ''; @@ -42,28 +40,30 @@ var nodebb_admin = (function(nodebb_admin) { scriptEl.src = 'http://api.bootswatch.com/3/?callback=nodebb_admin.themes.render'; document.body.appendChild(scriptEl); - var bootstrapThemeContainer = document.querySelector('#bootstrap_themes'), + var bootstrapThemeContainer = document.querySelector('#bootstrap_themes'), installedThemeContainer = document.querySelector('#installed_themes'), themeEvent = function(e) { if (e.target.hasAttribute('data-action')) { - switch(e.target.getAttribute('data-action')) { + switch (e.target.getAttribute('data-action')) { case 'preview': - var cssSrc = $(e.target).parents('li').attr('data-css'), + var cssSrc = $(e.target).parents('li').attr('data-css'), cssEl = document.getElementById('base-theme'); cssEl.href = cssSrc; - break; + break; case 'use': - var parentEl = $(e.target).parents('li'), + var parentEl = $(e.target).parents('li'), cssSrc = parentEl.attr('data-css'), cssName = parentEl.attr('data-theme'); socket.emit('api:config.set', { - key: 'theme:id', value: 'bootswatch:' + cssName + key: 'theme:id', + value: 'bootswatch:' + cssName }); socket.emit('api:config.set', { - key: 'theme:src', value: cssSrc + key: 'theme:src', + value: cssSrc }); - break; + break; } } }; @@ -82,27 +82,27 @@ var nodebb_admin = (function(nodebb_admin) { // Installed Themes socket.emit('api:admin.themes.getInstalled', function(themes) { - var instListEl = document.getElementById('installed_themes'), + var instListEl = document.getElementById('installed_themes'), themeFrag = document.createDocumentFragment(), liEl = document.createElement('li'); if (themes.length > 0) { - for(var x=0,numThemes=themes.length;x' + - '
    ' + - '
    ' + - ' ' + - '' + - '
    ' + - '

    ' + themes[x].name + '

    ' + - '

    ' + - themes[x].description + - (themes[x].url ? ' (Homepage)' : '') + - '

    ' + - '
    ' + - '
    '; + liEl.innerHTML = '' + + '
    ' + + '
    ' + + ' ' + + '' + + '
    ' + + '

    ' + themes[x].name + '

    ' + + '

    ' + + themes[x].description + + (themes[x].url ? ' (Homepage)' : '') + + '

    ' + + '
    ' + + '
    '; themeFrag.appendChild(liEl.cloneNode(true)); } } else { diff --git a/public/src/forum/admin/topics.js b/public/src/forum/admin/topics.js index d0c6608fef..040197df82 100644 --- a/public/src/forum/admin/topics.js +++ b/public/src/forum/admin/topics.js @@ -7,25 +7,37 @@ $(document).ready(function() { action = this.getAttribute('data-action'), tid = $this.parents('[data-tid]').attr('data-tid'); - switch(action) { + switch (action) { case 'pin': - if (!$this.hasClass('active')) socket.emit('api:topic.pin', { tid: tid }); - else socket.emit('api:topic.unpin', { tid: tid }); - break; + if (!$this.hasClass('active')) socket.emit('api:topic.pin', { + tid: tid + }); + else socket.emit('api:topic.unpin', { + tid: tid + }); + break; case 'lock': - if (!$this.hasClass('active')) socket.emit('api:topic.lock', { tid: tid }); - else socket.emit('api:topic.unlock', { tid: tid }); - break; + if (!$this.hasClass('active')) socket.emit('api:topic.lock', { + tid: tid + }); + else socket.emit('api:topic.unlock', { + tid: tid + }); + break; case 'delete': - if (!$this.hasClass('active')) socket.emit('api:topic.delete', { tid: tid }); - else socket.emit('api:topic.restore', { tid: tid }); - break; + if (!$this.hasClass('active')) socket.emit('api:topic.delete', { + tid: tid + }); + else socket.emit('api:topic.restore', { + tid: tid + }); + break; } }); loadMoreEl.addEventListener('click', function() { if (this.className.indexOf('disabled') === -1) { - var topics = document.querySelectorAll('.topics li[data-tid]'), + var topics = document.querySelectorAll('.topics li[data-tid]'), lastTid = parseInt(topics[topics.length - 1].getAttribute('data-tid')); this.innerHTML = ' Retrieving topics'; @@ -37,9 +49,9 @@ $(document).ready(function() { topics = JSON.parse(topics); if (topics.length > 0) { - var html = templates.prepare(templates['admin/topics'].blocks['topics']).parse({ - topics: topics - }), + var html = templates.prepare(templates['admin/topics'].blocks['topics']).parse({ + topics: topics + }), topicsListEl = document.querySelector('.topics'); topicsListEl.innerHTML += html; @@ -54,9 +66,9 @@ $(document).ready(function() { }, false); // Resolve proper button state for all topics - var topicEls = topicsListEl.querySelectorAll('li'), + var topicEls = topicsListEl.querySelectorAll('li'), numTopics = topicEls.length; - for(var x=0;x1?'s':'') + ' found!') + } else { + $('#user-notfound-notify').html(data.length + ' user' + (data.length > 1 ? 's' : '') + ' found!') .show() .addClass('label-success') .removeClass('label-danger'); @@ -191,28 +189,30 @@ }); function onUsersLoaded(users) { - var html = templates.prepare(templates['admin/users'].blocks['users']).parse({ users: users }); + var html = templates.prepare(templates['admin/users'].blocks['users']).parse({ + users: users + }); $('#users-container').append(html); updateUserButtons(); } function loadMoreUsers() { var set = ''; - if(active === 'latest') { + if (active === 'latest') { set = 'users:joindate'; - } else if(active === 'sort-posts') { + } else if (active === 'sort-posts') { set = 'users:postcount'; - } else if(active === 'sort-reputation') { + } else if (active === 'sort-reputation') { set = 'users:reputation'; } - if(set) { + if (set) { loadingMoreUsers = true; socket.emit('api:users.loadMore', { set: set, after: $('#users-container').children().length }, function(data) { - if(data.users.length) { + if (data.users.length) { onUsersLoaded(data.users); } loadingMoreUsers = false; From aea3181d2742f10126458593c11add832dd7a050 Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:09:37 -0400 Subject: [PATCH 08/12] formatting - server side core --- src/categories.js | 72 +++++++------ src/favourites.js | 16 ++- src/feed.js | 40 ++++---- src/groups.js | 8 +- src/imgur.js | 26 ++--- src/install.js | 165 ++++++++++++++--------------- src/login.js | 20 ++-- src/messaging.js | 13 ++- src/meta.js | 19 ++-- src/notifications.js | 14 +-- src/plugins.js | 56 +++++----- src/postTools.js | 65 ++++++------ src/posts.js | 93 +++++++++-------- src/redis.js | 15 ++- src/sitemap.js | 24 +++-- src/threadTools.js | 38 ++++--- src/topics.js | 153 ++++++++++++++------------- src/upgrade.js | 45 ++++---- src/user.js | 240 +++++++++++++++++++++++++------------------ src/webserver.js | 192 ++++++++++++++++++++++------------ src/websockets.js | 201 ++++++++++++++++++++---------------- 21 files changed, 839 insertions(+), 676 deletions(-) diff --git a/src/categories.js b/src/categories.js index 2912bf40c3..985f2a3df8 100644 --- a/src/categories.js +++ b/src/categories.js @@ -1,4 +1,4 @@ -var RDB = require('./redis.js'), +var RDB = require('./redis.js'), posts = require('./posts.js'), utils = require('./../public/src/utils.js'), user = require('./user.js'), @@ -10,7 +10,7 @@ var RDB = require('./redis.js'), Categories.create = function(data, callback) { RDB.incr('global:next_category_id', function(err, cid) { - if(err) + if (err) return callback(err, null); var slug = cid + '/' + utils.slugify(data.name); @@ -57,16 +57,16 @@ var RDB = require('./redis.js'), active_users = results[1]; var categoryData = { - 'category_name' : category_name, + 'category_name': category_name, 'category_description': category_description, 'disabled': disabled, - 'show_sidebar' : 'show', + 'show_sidebar': 'show', 'show_topic_button': 'inline-block', 'no_topics_message': 'hidden', 'topic_row_size': 'col-md-9', 'category_id': category_id, 'active_users': [], - 'topics' : [], + 'topics': [], 'twitter-intent-url': 'https://twitter.com/intent/tweet?url=' + encodeURIComponent(nconf.get('url') + 'category/' + category_slug) + '&text=' + encodeURIComponent(category_name), 'facebook-share-url': 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(nconf.get('url') + 'category/' + category_slug), 'google-share-url': 'https://plus.google.com/share?url=' + encodeURIComponent(nconf.get('url') + 'category/' + category_slug) @@ -102,7 +102,7 @@ var RDB = require('./redis.js'), categoryData.moderator_block_class = results[1].length > 0 ? '' : 'none'; categoryData.moderators = results[1]; categoryData.active_users = results[2]; - categoryData.show_sidebar = categoryData.topics.length > 0 ? 'show':'hidden'; + categoryData.show_sidebar = categoryData.topics.length > 0 ? 'show' : 'hidden'; callback(null, categoryData); }); } @@ -136,8 +136,8 @@ var RDB = require('./redis.js'), Categories.getModerators = function(cid, callback) { RDB.smembers('cid:' + cid + ':moderators', function(err, mods) { - if(!err) { - if(mods && mods.length) { + if (!err) { + if (mods && mods.length) { user.getMultipleUserFields(mods, ['username'], function(err, moderators) { callback(err, moderators); }); @@ -155,14 +155,14 @@ var RDB = require('./redis.js'), Categories.privileges = function(cid, uid, callback) { function isModerator(next) { user.isModerator(uid, cid, function(isMod) { - next(null, isMod); - }); + next(null, isMod); + }); } function isAdministrator(next) { user.isAdministrator(uid, function(isAdmin) { - next(null, isAdmin); - }); + next(null, isAdmin); + }); } async.parallel([isModerator, isAdministrator], function(err, results) { @@ -179,8 +179,8 @@ var RDB = require('./redis.js'), topics.hasReadTopics(tids, uid, function(hasRead) { var allread = true; - for (var i=0, ii=tids.length; i count) { + if (postData.length > count) { postData = postData.slice(0, count); } callback(postData); @@ -246,9 +246,9 @@ var RDB = require('./redis.js'), } topics.getPids(tid, function(err, pids) { - if(!err) { + if (!err) { async.each(pids, movePost, function(err) { - if(!err) { + if (!err) { callback(null, 1); } else { winston.err(err); @@ -267,15 +267,15 @@ var RDB = require('./redis.js'), Categories.addActiveUser(cid, uid); Categories.isUserActiveIn(oldCid, uid, function(err, active) { - if(!err && !active) { + if (!err && !active) { Categories.removeActiveUser(oldCid, uid); } }); } topics.getUids(tid, function(err, uids) { - if(!err && uids) { - for(var i=0; i 0) { - var photoUrl = photos[0].value; + var photoUrl = photos[0].value; photoUrl = path.dirname(photoUrl) + '/' + path.basename(photoUrl, path.extname(photoUrl)).slice(0, -6) + 'bigger' + path.extname(photoUrl); user.setUserField(uid, 'uploadedpicture', photoUrl); user.setUserField(uid, 'picture', photoUrl); @@ -157,5 +160,4 @@ var user = require('./user.js'), }); } -}(exports)); - +}(exports)); \ No newline at end of file diff --git a/src/messaging.js b/src/messaging.js index cb6bd0b66c..27b9b6d8b2 100644 --- a/src/messaging.js +++ b/src/messaging.js @@ -1,4 +1,3 @@ - var RDB = require('./redis'), async = require('async'); @@ -15,7 +14,7 @@ var RDB = require('./redis'), var uids = sortUids(fromuid, touid); RDB.incr('global:next_message_id', function(err, mid) { - if(err) + if (err) return callback(err, null); var message = { @@ -36,10 +35,10 @@ var RDB = require('./redis'), var uids = sortUids(fromuid, touid); RDB.lrange('messages:' + uids[0] + ':' + uids[1], 0, -1, function(err, mids) { - if(err) + if (err) return callback(err, null); - if(!mids || !mids.length) { + if (!mids || !mids.length) { return callback(null, []); } @@ -50,10 +49,10 @@ var RDB = require('./redis'), function getMessage(mid, next) { RDB.hgetall('message:' + mid, function(err, message) { - if(err) + if (err) return next(err); - if(message.fromuid === fromuid) + if (message.fromuid === fromuid) message.content = 'You : ' + message.content; else message.content = tousername + ' : ' + message.content; @@ -64,7 +63,7 @@ var RDB = require('./redis'), } async.eachSeries(mids, getMessage, function(err) { - if(err) + if (err) return callback(err, null); callback(null, messages); diff --git a/src/meta.js b/src/meta.js index 25c8d49f4b..73a938a914 100644 --- a/src/meta.js +++ b/src/meta.js @@ -35,7 +35,7 @@ var utils = require('./../public/src/utils.js'), }, set: function(field, value, callback) { RDB.hset('config', field, value, function(err, res) { - if(callback) + if (callback) callback(err, res); }); }, @@ -52,7 +52,7 @@ var utils = require('./../public/src/utils.js'), Meta.themes = { get: function(callback) { - var themePath = path.join(__dirname, '../node_modules'); + var themePath = path.join(__dirname, '../node_modules'); fs.readdir(themePath, function(err, files) { async.filter(files, function(file, next) { fs.stat(path.join(themePath, file), function(err, fileStat) { @@ -62,11 +62,11 @@ var utils = require('./../public/src/utils.js'), }); }, function(themes) { async.map(themes, function(theme, next) { - var config = path.join(themePath, theme, 'theme.json'); + var config = path.join(themePath, theme, 'theme.json'); if (fs.existsSync(config)) { fs.readFile(config, function(err, file) { - var configObj = JSON.parse(file.toString()); + var configObj = JSON.parse(file.toString()); if (!configObj.screenshot) configObj.screenshot = nconf.get('relative_path') + '/images/themes/default.png'; next(err, configObj); }); @@ -84,7 +84,7 @@ var utils = require('./../public/src/utils.js'), Meta.title = { build: function(urlFragment, current_user, callback) { - var self = this, + var self = this, user = require('./user'); async.parallel({ @@ -95,7 +95,7 @@ var utils = require('./../public/src/utils.js'), user.notifications.getUnreadCount(current_user, next); } }, function(err, values) { - var title; + var title; if (err) title = Meta.config.title || 'NodeBB'; else title = (values.title ? values.title + ' | ' : '') + (Meta.config.title || 'NodeBB'); @@ -113,13 +113,13 @@ var utils = require('./../public/src/utils.js'), } else if (urlFragment === 'users') { callback(null, 'Registered Users'); } else if (/^category\/\d+\/?/.test(urlFragment)) { - var cid = urlFragment.match(/category\/(\d+)/)[1]; + var cid = urlFragment.match(/category\/(\d+)/)[1]; require('./categories').getCategoryField(cid, 'name', function(err, name) { callback(null, name); }); } else if (/^topic\/\d+\/?/.test(urlFragment)) { - var tid = urlFragment.match(/topic\/(\d+)/)[1]; + var tid = urlFragment.match(/topic\/(\d+)/)[1]; require('./topics').getTopicField(tid, 'title', function(err, title) { callback(null, title); @@ -129,5 +129,4 @@ var utils = require('./../public/src/utils.js'), } -}(exports)); - +}(exports)); \ No newline at end of file diff --git a/src/notifications.js b/src/notifications.js index 3e251628f5..b3fdd4eafa 100644 --- a/src/notifications.js +++ b/src/notifications.js @@ -1,4 +1,4 @@ -var RDB = require('./redis.js'), +var RDB = require('./redis.js'), async = require('async'), utils = require('../public/src/utils.js'), @@ -35,25 +35,25 @@ var RDB = require('./redis.js'), 'path', path || null, 'datetime', Date.now(), 'uniqueId', uniqueId || utils.generateUUID(), - function(err, status) { - if (status === 'OK') callback(nid); - }); + function(err, status) { + if (status === 'OK') callback(nid); + }); }); }, push: function(nid, uids, callback) { if (!Array.isArray(uids)) uids = [uids]; - var numUids = uids.length, + var numUids = uids.length, x; notifications.get(nid, function(notif_data) { - for(x=0;x 0) { (function(uid) { notifications.remove_by_uniqueId(notif_data.uniqueId, uid, function() { RDB.zadd('uid:' + uid + ':notifications:unread', notif_data.score, nid); RDB.set('uid:' + uid + ':notifications:flag', 1); - global.io.sockets.in('uid_' + uid).emit('event:new_notification'); + global.io.sockets. in ('uid_' + uid).emit('event:new_notification'); if (callback) callback(true); }); })(uids[x]); diff --git a/src/plugins.js b/src/plugins.js index 900292c622..1afdc3b211 100644 --- a/src/plugins.js +++ b/src/plugins.js @@ -1,4 +1,4 @@ -var fs = require('fs'), +var fs = require('fs'), path = require('path'), RDB = require('./redis.js'), async = require('async'), @@ -16,7 +16,7 @@ var fs = require('fs'), if (this.initialized) return; if (global.env === 'development') winston.info('[plugins] Initializing plugins system'); - var _self = this; + var _self = this; // Read the list of activated plugins and require their libraries async.waterfall([ @@ -27,13 +27,13 @@ var fs = require('fs'), if (plugins && Array.isArray(plugins) && plugins.length > 0) { async.each(plugins, function(plugin, next) { // TODO: Update this check to also check node_modules - var pluginPath = path.join(__dirname, '../plugins/', plugin), + var pluginPath = path.join(__dirname, '../plugins/', plugin), modulePath = path.join(__dirname, '../node_modules/', plugin); if (fs.existsSync(pluginPath)) _self.loadPlugin(pluginPath, next); else if (fs.existsSync(modulePath)) _self.loadPlugin(modulePath, next); else { if (global.env === 'development') winston.warn('[plugins] Plugin \'' + plugin + '\' not found'); - next(); // Ignore this plugin silently + next(); // Ignore this plugin silently } }, next); } else next(); @@ -41,7 +41,7 @@ var fs = require('fs'), function(next) { if (global.env === 'development') winston.info('[plugins] Sorting hooks to fire in priority sequence'); Object.keys(_self.loadedHooks).forEach(function(hook) { - var hooks = _self.loadedHooks[hook]; + var hooks = _self.loadedHooks[hook]; hooks = hooks.sort(function(a, b) { return a[3] - b[3]; }); @@ -65,12 +65,12 @@ var fs = require('fs'), }, initialized: false, loadPlugin: function(pluginPath, callback) { - var _self = this; + var _self = this; fs.readFile(path.join(pluginPath, 'plugin.json'), function(err, data) { if (err) return callback(err); - var pluginData = JSON.parse(data), + var pluginData = JSON.parse(data), libraryPath, staticDir; async.parallel([ @@ -119,30 +119,30 @@ var fs = require('fs'), `data.callbacked`, whether or not the hook expects a callback (true), or a return (false). Only used for filters. (Default: false) `data.priority`, the relative priority of the method when it is eventually called (default: 10) */ - var _self = this; + var _self = this; if (data.hook && data.method) { // Assign default priority of 10 if none is passed-in if (!data.priority) data.priority = 10; _self.loadedHooks[data.hook] = _self.loadedHooks[data.hook] || []; - _self.loadedHooks[data.hook].push([id, data.method, !!data.callbacked, data.priority]); + _self.loadedHooks[data.hook].push([id, data.method, !! data.callbacked, data.priority]); if (global.env === 'development') winston.info('[plugins] Hook registered: ' + data.hook + ' will call ' + id); callback(); } else return; }, fireHook: function(hook, args, callback) { - var _self = this - hookList = this.loadedHooks[hook]; + var _self = this + hookList = this.loadedHooks[hook]; if (hookList && Array.isArray(hookList)) { if (global.env === 'development') winston.info('[plugins] Firing hook: \'' + hook + '\''); - var hookType = hook.split(':')[0]; - switch(hookType) { + var hookType = hook.split(':')[0]; + switch (hookType) { case 'filter': // Filters only take one argument, so only args[0] will be passed in - var returnVal = (Array.isArray(args) ? args[0] : args); + var returnVal = (Array.isArray(args) ? args[0] : args); async.eachSeries(hookList, function(hookObj, next) { if (hookObj[2]) { @@ -163,7 +163,7 @@ var fs = require('fs'), callback(returnVal); }); - break; + break; case 'action': async.each(hookList, function(hookObj) { if ( @@ -176,14 +176,14 @@ var fs = require('fs'), if (global.env === 'development') winston.info('[plugins] Expected method \'' + hookObj[1] + '\' in plugin \'' + hookObj[0] + '\' not found, skipping.'); } }); - break; + break; default: // Do nothing... - break; + break; } } else { // Otherwise, this hook contains no methods - var returnVal = (Array.isArray(args) ? args[0] : args); + var returnVal = (Array.isArray(args) ? args[0] : args); if (callback) callback(returnVal); } }, @@ -214,9 +214,9 @@ var fs = require('fs'), }, showInstalled: function(callback) { // TODO: Also check /node_modules - var _self = this; - localPluginPath = path.join(__dirname, '../plugins'), - npmPluginPath = path.join(__dirname, '../node_modules'); + var _self = this; + localPluginPath = path.join(__dirname, '../plugins'), + npmPluginPath = path.join(__dirname, '../node_modules'); async.waterfall([ function(next) { @@ -233,7 +233,7 @@ var fs = require('fs'), dirs[0] = dirs[0].map(function(file) { return path.join(localPluginPath, file); }).filter(function(file) { - var stats = fs.statSync(file); + var stats = fs.statSync(file); if (stats.isDirectory()) return true; else return false; }); @@ -241,8 +241,8 @@ var fs = require('fs'), dirs[1] = dirs[1].map(function(file) { return path.join(npmPluginPath, file); }).filter(function(file) { - var stats = fs.statSync(file); - if (stats.isDirectory() && file.substr(npmPluginPath.length+1, 14) === 'nodebb-plugin-') return true; + var stats = fs.statSync(file); + if (stats.isDirectory() && file.substr(npmPluginPath.length + 1, 14) === 'nodebb-plugin-') return true; else return false; }); @@ -250,17 +250,17 @@ var fs = require('fs'), }); }, function(files, next) { - var plugins = []; + var plugins = []; async.each(files, function(file, next) { - var configPath; + var configPath; async.waterfall([ function(next) { fs.readFile(path.join(file, 'plugin.json'), next); }, function(configJSON, next) { - var config = JSON.parse(configJSON); + var config = JSON.parse(configJSON); _self.isActive(config.id, function(err, active) { if (err) next(new Error('no-active-state')); @@ -272,7 +272,7 @@ var fs = require('fs'), }); } ], function(err, config) { - if (err) return next(); // Silently fail + if (err) return next(); // Silently fail plugins.push(config); next(); diff --git a/src/postTools.js b/src/postTools.js index 2006abc0c2..78e64621fd 100644 --- a/src/postTools.js +++ b/src/postTools.js @@ -1,4 +1,4 @@ -var RDB = require('./redis.js'), +var RDB = require('./redis.js'), posts = require('./posts.js'), topics = require('./topics'), threadTools = require('./threadTools.js'), @@ -57,7 +57,7 @@ var RDB = require('./redis.js'), } PostTools.edit = function(uid, pid, title, content, images) { - var success = function() { + var success = function() { posts.setPostField(pid, 'content', content); posts.setPostField(pid, 'edited', Date.now()); posts.setPostField(pid, 'editor', uid); @@ -82,7 +82,10 @@ var RDB = require('./redis.js'), }); } - next(null, {tid:tid, isMainPost:isMainPost}); + next(null, { + tid: tid, + isMainPost: isMainPost + }); }); }); }, @@ -90,12 +93,12 @@ var RDB = require('./redis.js'), PostTools.toHTML(content, next); } ], function(err, results) { - io.sockets.in('topic_' + results[1].tid).emit('event:post_edited', { + io.sockets. in ('topic_' + results[1].tid).emit('event:post_edited', { pid: pid, title: title, isMainPost: results[1].isMainPost, content: results[2], - uploadedImages:results[0] + uploadedImages: results[0] }); }); }; @@ -117,13 +120,13 @@ var RDB = require('./redis.js'), postSearch.remove(pid); posts.getPostFields(pid, ['tid', 'uid'], function(postData) { - RDB.hincrby('topic:'+postData.tid, 'postcount', -1); + RDB.hincrby('topic:' + postData.tid, 'postcount', -1); user.decrementUserFieldBy(postData.uid, 'postcount', 1, function(err, postcount) { RDB.zadd('users:postcount', postcount, postData.uid); }); - io.sockets.in('topic_' + postData.tid).emit('event:post_deleted', { + io.sockets. in ('topic_' + postData.tid).emit('event:post_deleted', { pid: pid }); @@ -153,35 +156,35 @@ var RDB = require('./redis.js'), PostTools.restore = function(uid, pid) { var success = function() { - posts.setPostField(pid, 'deleted', 0); + posts.setPostField(pid, 'deleted', 0); - posts.getPostFields(pid, ['tid', 'uid', 'content'], function(postData) { - RDB.hincrby('topic:'+postData.tid, 'postcount', 1); + posts.getPostFields(pid, ['tid', 'uid', 'content'], function(postData) { + RDB.hincrby('topic:' + postData.tid, 'postcount', 1); - user.incrementUserFieldBy(postData.uid, 'postcount', 1); + user.incrementUserFieldBy(postData.uid, 'postcount', 1); - io.sockets.in('topic_' + postData.tid).emit('event:post_restored', { - pid: pid - }); + io.sockets. in ('topic_' + postData.tid).emit('event:post_restored', { + pid: pid + }); - threadTools.get_latest_undeleted_pid(postData.tid, function(err, pid) { - posts.getPostField(pid, 'timestamp', function(timestamp) { - topics.updateTimestamp(postData.tid, timestamp); - }); + threadTools.get_latest_undeleted_pid(postData.tid, function(err, pid) { + posts.getPostField(pid, 'timestamp', function(timestamp) { + topics.updateTimestamp(postData.tid, timestamp); }); + }); - // Restore topic if it is the only post - topics.getTopicField(postData.tid, 'postcount', function(err, count) { - if (count === '1') { - threadTools.restore(postData.tid, uid); - } - }); + // Restore topic if it is the only post + topics.getTopicField(postData.tid, 'postcount', function(err, count) { + if (count === '1') { + threadTools.restore(postData.tid, uid); + } + }); - Feed.updateTopic(postData.tid); + Feed.updateTopic(postData.tid); - postSearch.index(postData.content, pid); - }); - }; + postSearch.index(postData.content, pid); + }); + }; PostTools.privileges(pid, uid, function(privileges) { if (privileges.editable) { @@ -193,11 +196,11 @@ var RDB = require('./redis.js'), PostTools.toHTML = function(raw, callback) { raw = raw || ''; plugins.fireHook('filter:post.parse', raw, function(parsed) { - var cheerio = require('cheerio'); + var cheerio = require('cheerio'); if (parsed && parsed.length > 0) { - var parsedContentDOM = cheerio.load(parsed); - var domain = nconf.get('url'); + var parsedContentDOM = cheerio.load(parsed); + var domain = nconf.get('url'); parsedContentDOM('a').each(function() { this.attr('rel', 'nofollow'); diff --git a/src/posts.js b/src/posts.js index ca56201021..84e9c655a0 100644 --- a/src/posts.js +++ b/src/posts.js @@ -1,4 +1,4 @@ -var RDB = require('./redis.js'), +var RDB = require('./redis.js'), utils = require('./../public/src/utils.js'), schema = require('./schema.js'), user = require('./user.js'), @@ -34,7 +34,7 @@ var RDB = require('./redis.js'), Posts.addUserInfoToPost = function(post, callback) { user.getUserFields(post.uid, ['username', 'userslug', 'reputation', 'postcount', 'picture', 'signature', 'banned'], function(err, userData) { - if(err) return callback(); + if (err) return callback(); postTools.toHTML(userData.signature, function(err, signature) { post.username = userData.username || 'anonymous'; @@ -42,12 +42,12 @@ var RDB = require('./redis.js'), post.user_rep = userData.reputation || 0; post.user_postcount = userData.postcount || 0; post.user_banned = userData.banned || '0'; - post.picture = userData.picture || require('gravatar').url('', {}, https=nconf.get('https')); + post.picture = userData.picture || require('gravatar').url('', {}, https = nconf.get('https')); post.signature = signature; - if(post.editor !== '') { + if (post.editor !== '') { user.getUserFields(post.editor, ['username', 'userslug'], function(err, editorData) { - if(err) return callback(); + if (err) return callback(); post.editorname = editorData.username; post.editorslug = editorData.userslug; @@ -104,7 +104,7 @@ var RDB = require('./redis.js'), } async.eachSeries(pids, getPostSummary, function(err) { - if(!err) { + if (!err) { callback(null, posts); } else { callback(err, null); @@ -120,22 +120,20 @@ var RDB = require('./redis.js'), Posts.getPostData = function(pid, callback) { RDB.hgetall('post:' + pid, function(err, data) { - if(err === null) { + if (err === null) { plugins.fireHook('filter:post.get', data, function(data) { callback(data); }); - } - else + } else console.log(err); }); } Posts.getPostFields = function(pid, fields, callback) { RDB.hmgetObject('post:' + pid, fields, function(err, data) { - if(err === null) { + if (err === null) { callback(data); - } - else { + } else { console.log(err); } }); @@ -143,7 +141,7 @@ var RDB = require('./redis.js'), Posts.getPostField = function(pid, field, callback) { RDB.hget('post:' + pid, field, function(err, data) { - if(err === null) + if (err === null) callback(data); else console.log(err); @@ -158,18 +156,18 @@ var RDB = require('./redis.js'), Posts.getPostsByPids = function(pids, callback) { var posts = []; - async.eachSeries(pids, function (pid, callback) { + async.eachSeries(pids, function(pid, callback) { Posts.getPostData(pid, function(postData) { - if(postData) { + if (postData) { postData.relativeTime = utils.relativeTime(postData.timestamp); postData.post_rep = postData.reputation; postData['edited-class'] = postData.editor !== '' ? '' : 'none'; postData['relativeEditTime'] = postData.edited !== '0' ? utils.relativeTime(postData.edited) : ''; - if(postData.uploadedImages) { + if (postData.uploadedImages) { try { postData.uploadedImages = JSON.parse(postData.uploadedImages); - } catch(err) { + } catch (err) { postData.uploadedImages = []; winston.err(err); } @@ -185,7 +183,7 @@ var RDB = require('./redis.js'), } }); }, function(err) { - if(!err) { + if (!err) { callback(null, posts); } else { callback(err, null); @@ -220,14 +218,14 @@ var RDB = require('./redis.js'), Posts.emitTooManyPostsAlert = function(socket) { socket.emit('event:alert', { title: 'Too many posts!', - message: 'You can only post every '+ meta.config.postDelay/1000 + ' seconds.', + message: 'You can only post every ' + meta.config.postDelay / 1000 + ' seconds.', type: 'danger', timeout: 2000 }); } Posts.reply = function(tid, uid, content, images, callback) { - if(content) { + if (content) { content = content.trim(); } @@ -237,7 +235,7 @@ var RDB = require('./redis.js'), } user.getUserField(uid, 'lastposttime', function(lastposttime) { - if(Date.now() - lastposttime < meta.config.postDelay) { + if (Date.now() - lastposttime < meta.config.postDelay) { callback(new Error('too-many-posts'), null); return; } @@ -256,10 +254,12 @@ var RDB = require('./redis.js'), threadTools.notify_followers(tid, uid); Posts.addUserInfoToPost(postData, function() { - var socketData = { posts: [postData] }; - io.sockets.in('topic_' + tid).emit('event:new_post', socketData); - io.sockets.in('recent_posts').emit('event:new_post', socketData); - io.sockets.in('users/' + uid).emit('event:new_post', socketData); + var socketData = { + posts: [postData] + }; + io.sockets. in ('topic_' + tid).emit('event:new_post', socketData); + io.sockets. in ('recent_posts').emit('event:new_post', socketData); + io.sockets. in ('users/' + uid).emit('event:new_post', socketData); }); callback(null, 'Reply successful'); @@ -333,7 +333,7 @@ var RDB = require('./redis.js'), async.parallel({ uploadedImages: function(next) { Posts.uploadPostImages(postData.pid, images, function(err, uploadedImages) { - if(err) { + if (err) { winston.error('Uploading images failed!', err.stack); next(null, []); } else { @@ -369,21 +369,26 @@ var RDB = require('./redis.js'), var imgur = require('./imgur'); imgur.setClientID(meta.config.imgurClientID); - if(!images) + if (!images) return callback(null, []); - var uploadedImages = images.filter(function(image) { return !!image.url; }); + var uploadedImages = images.filter(function(image) { + return !!image.url; + }); function uploadImage(image, next) { - if(!image.data) + if (!image.data) return next(null); imgur.upload(image.data, 'base64', function(err, data) { - if(err) { + if (err) { next(err); } else { - if(data.success) { - var img= {url:data.data.link, name:image.name}; + if (data.success) { + var img = { + url: data.data.link, + name: image.name + }; uploadedImages.push(img); next(null); } else { @@ -395,7 +400,7 @@ var RDB = require('./redis.js'), } async.each(images, uploadImage, function(err) { - if(!err) { + if (!err) { Posts.setPostField(pid, 'uploadedImages', JSON.stringify(uploadedImages)); callback(null, uploadedImages); } else { @@ -409,28 +414,26 @@ var RDB = require('./redis.js'), user.getPostIds(uid, start, end, function(pids) { - if(pids && pids.length) { + if (pids && pids.length) { Posts.getPostsByPids(pids, function(err, posts) { callback(posts); }); - } - else + } else callback([]); }); } Posts.getTopicPostStats = function(socket) { RDB.mget(['totaltopiccount', 'totalpostcount'], function(err, data) { - if(err === null) { + if (err === null) { var stats = { - topics: data[0]?data[0]:0, - posts: data[1]?data[1]:0 + topics: data[0] ? data[0] : 0, + posts: data[1] ? data[1] : 0 }; socket.emit('post.stats', stats); - } - else + } else console.log(err); }); } @@ -442,7 +445,7 @@ var RDB = require('./redis.js'), Posts.getPostField(pid, 'content', function(content) { postSearch.remove(pid, function() { - if(content && content.length) { + if (content && content.length) { postSearch.index(content, pid); } callback(null); @@ -451,7 +454,7 @@ var RDB = require('./redis.js'), } async.each(pids, reIndex, function(err) { - if(err) { + if (err) { callback(err, null); } else { callback(null, 'Posts reindexed'); @@ -461,11 +464,11 @@ var RDB = require('./redis.js'), Posts.getFavourites = function(uid, callback) { RDB.zrevrange('uid:' + uid + ':favourites', 0, -1, function(err, pids) { - if(err) + if (err) return callback(err, null); Posts.getPostSummaryByPids(pids, function(err, posts) { - if(err) + if (err) return callback(err, null); callback(null, posts); diff --git a/src/redis.js b/src/redis.js index 6f80a2c5c7..d8e1c750ba 100644 --- a/src/redis.js +++ b/src/redis.js @@ -5,7 +5,7 @@ RedisDB.exports = redis.createClient(nconf.get('redis:port'), nconf.get('redis:host')); - if(nconf.get('redis:password')) { + if (nconf.get('redis:password')) { RedisDB.exports.auth(nconf.get('redis:password')); } @@ -20,8 +20,8 @@ /* - * A possibly more efficient way of doing multiple sismember calls - */ + * A possibly more efficient way of doing multiple sismember calls + */ RedisDB.exports.sismembers = function(key, needles, callback) { var tempkey = key + ':temp:' + utils.generateUUID(); RedisDB.exports.sadd(tempkey, needles, function() { @@ -35,18 +35,17 @@ /* * gets fields of a hash as an object instead of an array */ - RedisDB.exports.hmgetObject = function (key, fields, callback) { + RedisDB.exports.hmgetObject = function(key, fields, callback) { RedisDB.exports.hmget(key, fields, function(err, data) { - if(err === null) { + if (err === null) { var returnData = {}; - for(var i=0, ii=fields.length; i= after) { tids = tids.slice(0, x); break; @@ -457,7 +464,9 @@ var RDB = require('./redis.js') } // Sort into descending order - tids.sort(function(a, b) { return b - a; }); + tids.sort(function(a, b) { + return b - a; + }); async.each(tids, function(tid, next) { Topics.getTopicDataWithUsername(tid, function(topicData) { @@ -472,14 +481,14 @@ var RDB = require('./redis.js') Topics.markAllRead = function(uid, callback) { RDB.smembers('topics:tid', function(err, tids) { - if(err) { + if (err) { console.log(err); callback(err, null); return; } - if(tids && tids.length) { - for(var i=0; i 150) { - next({error:'Signature can\'t be longer than 150 characters!'}, false); + if (data['signature'] !== undefined && data['signature'].length > 150) { + next({ + error: 'Signature can\'t be longer than 150 characters!' + }, false); } else { next(null, true); } } function isEmailAvailable(next) { - if(!data['email']) { + if (!data['email']) { return next(null, true); } User.getUserField(uid, 'email', function(err, email) { - if(email !== data['email']) { + if (email !== data['email']) { User.isEmailAvailable(data['email'], function(err, available) { - if(err) + if (err) return next(err, null); - if(!available) { - next({error:'Email not available!'}, false); + if (!available) { + next({ + error: 'Email not available!' + }, false); } else { next(null, true); } @@ -228,11 +239,11 @@ var utils = require('./../public/src/utils.js'), } async.series([isSignatureValid, isEmailAvailable], function(err, results) { - if(err) { + if (err) { callback(err, returnData); } else { async.each(fields, updateField, function(err) { - if(err) { + if (err) { callback(err, returnData); } else { returnData.success = true; @@ -243,18 +254,18 @@ var utils = require('./../public/src/utils.js'), }); function updateField(field, next) { - if(data[field] !== undefined) { - if(field === 'email') { + if (data[field] !== undefined) { + if (field === 'email') { var gravatarpicture = User.createGravatarURLFromEmail(data[field]); User.setUserField(uid, 'gravatarpicture', gravatarpicture); User.getUserFields(uid, ['email', 'picture', 'uploadedpicture'], function(err, userData) { - if(err) + if (err) return next(err); RDB.hdel('email:uid', userData['email']); RDB.hset('email:uid', data['email'], uid); User.setUserField(uid, field, data[field]); - if(userData.picture !== userData.uploadedpicture) { + if (userData.picture !== userData.uploadedpicture) { returnData.picture = gravatarpicture; User.setUserField(uid, 'picture', gravatarpicture); } @@ -262,7 +273,7 @@ var utils = require('./../public/src/utils.js'), next(null); }); return; - } else if(field === 'signature') { + } else if (field === 'signature') { data[field] = utils.strip_tags(data[field]); } @@ -282,13 +293,15 @@ var utils = require('./../public/src/utils.js'), } User.changePassword = function(uid, data, callback) { - if(!utils.isPasswordValid(data.newPassword)) { - return callback({error:'Invalid password!'}); + if (!utils.isPasswordValid(data.newPassword)) { + return callback({ + error: 'Invalid password!' + }); } User.getUserField(uid, 'password', function(err, user_password) { bcrypt.compare(data.currentPassword, user_password, function(err, res) { - if(err) { + if (err) { return callback(err); } @@ -299,7 +312,9 @@ var utils = require('./../public/src/utils.js'), callback(null); }); } else { - callback({error:'Your current password is not correct!'}); + callback({ + error: 'Your current password is not correct!' + }); } }); }); @@ -325,13 +340,13 @@ var utils = require('./../public/src/utils.js'), var data = []; RDB.zrevrange(set, start, stop, function(err, uids) { - if(err) { + if (err) { return callback(err, null); } function iterator(uid, callback) { User.getUserData(uid, function(err, userData) { - if(userData) { + if (userData) { data.push(userData); } callback(null); @@ -356,11 +371,11 @@ var utils = require('./../public/src/utils.js'), options.forcedefault = 'y'; } - return require('gravatar').url(email, options, https=nconf.get('https')); + return require('gravatar').url(email, options, https = nconf.get('https')); } User.hashPassword = function(password, callback) { - if(!password) { + if (!password) { callback(password); return; } @@ -372,17 +387,17 @@ var utils = require('./../public/src/utils.js'), User.reIndexAll = function(callback) { User.getUsers('users:joindate', 0, -1, function(err, usersData) { - if(err) { + if (err) { return callback(err, null); } function reIndexUser(uid, username) { - userSearch.remove(uid, function(){ + userSearch.remove(uid, function() { userSearch.index(username, uid); }) } - for(var i=0; i made a new post'; - notifications.create(message, 5, nconf.get('relative_path') + '/topic/' + slug + '#' + pid, 'topic:'+ tid, function(nid) { - notifications.push(nid, followers); + notifications.create(message, 5, nconf.get('relative_path') + '/topic/' + slug + '#' + pid, 'topic:' + tid, function(nid) { + notifications.push(nid, followers); }); }); }); @@ -594,7 +611,7 @@ var utils = require('./../public/src/utils.js'), User.isFollowing = function(uid, theirid, callback) { RDB.sismember('following:' + uid, theirid, function(err, data) { - if(!err) { + if (!err) { callback(data === 1); } else { console.log(err); @@ -604,7 +621,7 @@ var utils = require('./../public/src/utils.js'), User.exists = function(userslug, callback) { User.get_uid_by_userslug(userslug, function(err, exists) { - callback(!!exists); + callback( !! exists); }); }; @@ -612,7 +629,9 @@ var utils = require('./../public/src/utils.js'), RDB.get('usercount', function(err, count) { RDB.handle(err); - socket.emit('user.count', { count: count ? count : 0 }); + socket.emit('user.count', { + count: count ? count : 0 + }); }); }; @@ -621,8 +640,11 @@ var utils = require('./../public/src/utils.js'), RDB.handle(err); User.getUserFields(uid, ['username', 'userslug'], function(err, userData) { - if(!err && userData) - socket.emit('user.latest', {userslug: userData.userslug, username: userData.username}); + if (!err && userData) + socket.emit('user.latest', { + userslug: userData.userslug, + username: userData.username + }); }); }); } @@ -725,7 +747,7 @@ var utils = require('./../public/src/utils.js'), RDB.handle(err); } - var expiry = 60*60*24*14, // Login valid for two weeks + var expiry = 60 * 60 * 24 * 14, // Login valid for two weeks sess_key = 'sess:' + sessionID + ':uid', uid_key = 'uid:' + uid + ':session'; @@ -739,14 +761,14 @@ var utils = require('./../public/src/utils.js'), User.isModerator = function(uid, cid, callback) { RDB.sismember('cid:' + cid + ':moderators', uid, function(err, exists) { RDB.handle(err); - callback(!!exists); + callback( !! exists); }); } User.isAdministrator = function(uid, callback) { Groups.getGidFromName('Administrators', function(err, gid) { Groups.isMember(uid, gid, function(err, isAdmin) { - callback(!!isAdmin); + callback( !! isAdmin); }); }); } @@ -769,9 +791,11 @@ var utils = require('./../public/src/utils.js'), RDB.handle(err); } - if (expiry >= +Date.now()/1000|0) { + if (expiry >= +Date.now() / 1000 | 0) { if (!callback) { - socket.emit('user:reset.valid', { valid: true }); + socket.emit('user:reset.valid', { + valid: true + }); } else { callback(true); } @@ -780,7 +804,9 @@ var utils = require('./../public/src/utils.js'), RDB.del('reset:' + code + ':uid'); RDB.del('reset:' + code + ':expiry'); if (!callback) { - socket.emit('user:reset.valid', { valid: false }); + socket.emit('user:reset.valid', { + valid: false + }); } else { callback(false); } @@ -788,7 +814,9 @@ var utils = require('./../public/src/utils.js'), }); } else { if (!callback) { - socket.emit('user:reset.valid', { valid: false }); + socket.emit('user:reset.valid', { + valid: false + }); } else { callback(false); } @@ -801,23 +829,25 @@ var utils = require('./../public/src/utils.js'), // Generate a new reset code var reset_code = utils.generateUUID(); RDB.set('reset:' + reset_code + ':uid', uid); - RDB.set('reset:' + reset_code + ':expiry', (60*60)+new Date()/1000|0); // Active for one hour + RDB.set('reset:' + reset_code + ':expiry', (60 * 60) + new Date() / 1000 | 0); // Active for one hour var reset_link = nconf.get('url') + 'reset/' + reset_code, - reset_email = global.templates['emails/reset'].parse({'RESET_LINK': reset_link}), - reset_email_plaintext = global.templates['emails/reset_plaintext'].parse({ 'RESET_LINK': reset_link }); + reset_email = global.templates['emails/reset'].parse({ + 'RESET_LINK': reset_link + }), + reset_email_plaintext = global.templates['emails/reset_plaintext'].parse({ + 'RESET_LINK': reset_link + }); var message = emailjs.message.create({ text: reset_email_plaintext, - from: meta.config.mailer?meta.config.mailer.from:'localhost@example.org', + from: meta.config.mailer ? meta.config.mailer.from : 'localhost@example.org', to: email, subject: 'Password Reset Requested', - attachment: [ - { - data: reset_email, - alternative: true - } - ] + attachment: [{ + data: reset_email, + alternative: true + }] }); emailjsServer.send(message, function(err, success) { @@ -860,7 +890,9 @@ var utils = require('./../public/src/utils.js'), RDB.del('reset:' + code + ':uid'); RDB.del('reset:' + code + ':expiry'); - socket.emit('user:reset.commit', { status: 'ok' }); + socket.emit('user:reset.commit', { + status: 'ok' + }); }); } }); @@ -870,9 +902,11 @@ var utils = require('./../public/src/utils.js'), User.email = { exists: function(socket, email, callback) { User.get_uid_by_email(email, function(exists) { - exists = !!exists; + exists = !! exists; if (typeof callback !== 'function') { - socket.emit('user.email.exists', { exists: exists }); + socket.emit('user.email.exists', { + exists: exists + }); } else { callback(exists); } @@ -887,9 +921,13 @@ var utils = require('./../public/src/utils.js'), if (email !== null) { RDB.set('email:' + email + ':confirm', true); RDB.del('confirm:' + code + ':email'); - callback({ status: 'ok' }); + callback({ + status: 'ok' + }); } else { - callback({ status: 'not_ok' }); + callback({ + status: 'not_ok' + }); } }); } @@ -897,7 +935,7 @@ var utils = require('./../public/src/utils.js'), User.notifications = { get: function(uid, callback) { - var maxNotifs = 15; + var maxNotifs = 15; async.parallel({ unread: function(next) { @@ -946,7 +984,7 @@ var utils = require('./../public/src/utils.js'), } }, function(err, notifications) { // While maintaining score sorting, sort by time - var readCount = notifications.read.length, + var readCount = notifications.read.length, unreadCount = notifications.unread.length; notifications.read.sort(function(a, b) { @@ -985,4 +1023,4 @@ var utils = require('./../public/src/utils.js'), }); } } -}(exports)); +}(exports)); \ No newline at end of file diff --git a/src/webserver.js b/src/webserver.js index ca1c9c8f4d..7dff3c792b 100644 --- a/src/webserver.js +++ b/src/webserver.js @@ -31,12 +31,19 @@ var express = require('express'), * accepts: metaTags */ app.build_header = function(options, callback) { - var defaultMetaTags = [ - { name: 'viewport', content: 'width=device-width, initial-scale=1.0' }, - { 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' }, - ], + var defaultMetaTags = [{ + name: 'viewport', + content: 'width=device-width, initial-scale=1.0' + }, { + 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' + }, ], metaString = utils.buildMetaTags(defaultMetaTags.concat(options.metaTags || [])), templateValues = { cssSrc: meta.config['theme:src'] || nconf.get('relative_path') + '/vendor/bootstrap/css/bootstrap.min.css', @@ -58,21 +65,24 @@ var express = require('express'), // Middlewares app.use(express.favicon(path.join(__dirname, '../', 'public', 'favicon.ico'))); - app.use(require('less-middleware')({ src: path.join(__dirname, '../', 'public'), prefix:nconf.get('relative_path') })); + app.use(require('less-middleware')({ + src: path.join(__dirname, '../', 'public'), + prefix: nconf.get('relative_path') + })); app.use(nconf.get('relative_path'), express.static(path.join(__dirname, '../', 'public'))); - app.use(express.bodyParser()); // Puts POST vars in request.body + app.use(express.bodyParser()); // Puts POST vars in request.body - app.use(express.cookieParser()); // If you want to parse cookies (res.cookies) + app.use(express.cookieParser()); // If you want to parse cookies (res.cookies) app.use(express.compress()); app.use(express.session({ store: new RedisStore({ client: RDB, - ttl: 60*60*24*30 + ttl: 60 * 60 * 24 * 30 }), secret: nconf.get('secret'), key: 'express.sid', cookie: { - maxAge: 60*60*24*30*1000 // 30 days + maxAge: 60 * 60 * 24 * 30 * 1000 // 30 days } })); app.use(express.csrf()); @@ -83,7 +93,7 @@ var express = require('express'), // Static Directories for NodeBB Plugins app.configure(function() { - var tailMiddlewares = []; + var tailMiddlewares = []; plugins.ready(function() { // Remove some middlewares until the router is gone @@ -92,7 +102,7 @@ var express = require('express'), tailMiddlewares.push(app.stack.pop()); tailMiddlewares.push(app.stack.pop()); tailMiddlewares.push(app.stack.pop()); - for(d in plugins.staticDirs) { + for (d in plugins.staticDirs) { app.use(nconf.get('relative_path') + '/plugins/' + d, express.static(plugins.staticDirs[d])); } @@ -138,7 +148,9 @@ var express = require('express'), // respond with json if (req.accepts('json')) { - res.send({ error: 'Not found' }); + res.send({ + error: 'Not found' + }); return; } @@ -155,7 +167,9 @@ var express = require('express'), res.status(err.status || 500); - res.json('500', { error: err.message }); + res.json('500', { + error: err.message + }); }); @@ -177,19 +191,22 @@ var express = require('express'), (function() { var routes = ['login', 'register', 'account', 'recent', 'unread', 'popular', 'active', '403', '404']; - for (var i=0, ii=routes.length; i 0)) { + if ((route === 'login' || route === 'register') && (req.user && req.user.uid > 0)) { user.getUserField(req.user.uid, 'userslug', function(err, userslug) { - res.redirect('/users/'+userslug); + res.redirect('/users/' + userslug); }); return; } - app.build_header({ req: req, res: res }, function(err, header) { + app.build_header({ + req: req, + res: res + }, function(err, header) { res.send(header + app.create_route(route) + templates['footer']); }); }); @@ -204,12 +221,19 @@ var express = require('express'), 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' } - ] + 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) { @@ -233,9 +257,9 @@ var express = require('express'), if (tid.match(/^\d+\.rss$/)) { tid = tid.slice(0, -4); - var rssPath = path.join(__dirname, '../', 'feeds/topics', tid + '.rss'), + var rssPath = path.join(__dirname, '../', 'feeds/topics', tid + '.rss'), loadFeed = function() { - fs.readFile(rssPath, function (err, data) { + fs.readFile(rssPath, function(err, data) { if (err) res.type('text').send(404, "Unable to locate an rss feed at this location."); else res.type('xml').set('Content-Length', data.length).send(data); }); @@ -255,8 +279,8 @@ var express = require('express'), async.waterfall([ function(next) { topics.getTopicWithPosts(tid, ((req.user) ? req.user.uid : 0), 0, -1, function(err, topicData) { - if(topicData) { - if(topicData.deleted === '1' && topicData.expose_tools === 0) + if (topicData) { + if (topicData.deleted === '1' && topicData.expose_tools === 0) return next(new Error('Topic deleted'), null); } @@ -267,7 +291,7 @@ var express = require('express'), var lastMod = 0, timestamp; - for(var x=0,numPosts=topicData.posts.length;x lastMod) lastMod = timestamp; } @@ -275,16 +299,31 @@ var express = require('express'), app.build_header({ req: req, res: res, - metaTags: [ - { name: "title", content: topicData.topic_name }, - { property: 'og:title', content: topicData.topic_name + ' | ' + (meta.config.title || 'NodeBB') }, - { property: "og:type", content: 'article' }, - { property: "og:url", content: nconf.get('url') + 'topic/' + topicData.slug }, - { property: 'og:image', content: topicData.main_posts[0].picture }, - { property: "article:published_time", content: new Date(parseInt(topicData.main_posts[0].timestamp, 10)).toISOString() }, - { property: 'article:modified_time', content: new Date(lastMod).toISOString() }, - { property: 'article:section', content: topicData.category_name } - ] + metaTags: [{ + name: "title", + content: topicData.topic_name + }, { + property: 'og:title', + content: topicData.topic_name + ' | ' + (meta.config.title || 'NodeBB') + }, { + property: "og:type", + content: 'article' + }, { + property: "og:url", + content: nconf.get('url') + 'topic/' + topicData.slug + }, { + property: 'og:image', + content: topicData.main_posts[0].picture + }, { + property: "article:published_time", + content: new Date(parseInt(topicData.main_posts[0].timestamp, 10)).toISOString() + }, { + property: 'article:modified_time', + content: new Date(lastMod).toISOString() + }, { + property: 'article:section', + content: topicData.category_name + }] }, function(err, header) { next(err, { header: header, @@ -310,9 +349,9 @@ var express = require('express'), if (cid.match(/^\d+\.rss$/)) { cid = cid.slice(0, -4); - var rssPath = path.join(__dirname, '../', 'feeds/categories', cid + '.rss'), + var rssPath = path.join(__dirname, '../', 'feeds/categories', cid + '.rss'), loadFeed = function() { - fs.readFile(rssPath, function (err, data) { + fs.readFile(rssPath, function(err, data) { if (err) res.type('text').send(404, "Unable to locate an rss feed at this location."); else res.type('xml').set('Content-Length', data.length).send(data); }); @@ -333,8 +372,8 @@ var express = require('express'), function(next) { categories.getCategoryById(cid, 0, function(err, categoryData) { - if(categoryData) { - if(categoryData.disabled === '1') + if (categoryData) { + if (categoryData.disabled === '1') return next(new Error('Category disabled'), null); } next(err, categoryData); @@ -344,11 +383,16 @@ var express = require('express'), app.build_header({ req: req, res: res, - metaTags: [ - { name: 'title', content: categoryData.category_name }, - { name: 'description', content: categoryData.category_description }, - { property: "og:type", content: 'website' } - ] + metaTags: [{ + name: 'title', + content: categoryData.category_name + }, { + name: 'description', + content: categoryData.category_description + }, { + property: "og:type", + content: 'website' + }] }, function(err, header) { next(err, { header: header, @@ -357,7 +401,7 @@ var express = require('express'), }); } ], function(err, data) { - if(err) return res.redirect('404'); + if (err) return res.redirect('404'); var category_url = cid + (req.params.slug ? '/' + req.params.slug : ''); res.send( @@ -370,13 +414,16 @@ var express = require('express'), }); app.get('/confirm/:code', function(req, res) { - app.build_header({ req: req, res: res }, function(err, header) { + app.build_header({ + req: req, + res: res + }, function(err, header) { res.send(header + '' + templates['footer']); }); }); app.get('/sitemap.xml', function(req, res) { - var sitemap = require('./sitemap.js'); + var sitemap = require('./sitemap.js'); sitemap.render(function(xml) { res.type('xml').set('Content-Length', xml.length).send(xml); @@ -385,15 +432,15 @@ var express = require('express'), app.get('/robots.txt', function(req, res) { res.set('Content-Type', 'text/plain'); - res.send( "User-agent: *\n" + - "Disallow: \n" + - "Disallow: /admin/\n" + - "Sitemap: " + nconf.get('url') + "sitemap.xml"); + res.send("User-agent: *\n" + + "Disallow: \n" + + "Disallow: /admin/\n" + + "Sitemap: " + nconf.get('url') + "sitemap.xml"); }); app.get('/cid/:cid', function(req, res) { categories.getCategoryData(req.params.cid, function(err, data) { - if(data) + if (data) res.send(data); else res.send(404, "Category doesn't exist!"); @@ -401,8 +448,8 @@ var express = require('express'), }); app.get('/tid/:tid', function(req, res) { - topics.getTopicData(req.params.tid, function(data){ - if(data) + topics.getTopicData(req.params.tid, function(data) { + if (data) res.send(data); else res.send(404, "Topic doesn't exist!"); @@ -410,8 +457,8 @@ var express = require('express'), }); app.get('/pid/:pid', function(req, res) { - posts.getPostData(req.params.pid, function(data){ - if(data) + posts.getPostData(req.params.pid, function(data) { + if (data) res.send(data); else res.send(404, "Post doesn't exist!"); @@ -421,7 +468,10 @@ var express = require('express'), app.get('/outgoing', function(req, res) { if (!req.query.url) return res.redirect('/404'); - app.build_header({ req: req, res: res }, function(err, header) { + app.build_header({ + req: req, + res: res + }, function(err, header) { res.send( header + '\n\t' + @@ -431,25 +481,31 @@ var express = require('express'), }); app.get('/search', function(req, res) { - app.build_header({ req: req, res: res }, function(err, header) { + app.build_header({ + req: req, + res: res + }, function(err, header) { res.send(header + app.create_route("search", null, "search") + templates['footer']); }); }); app.get('/search/:term', function(req, res) { - app.build_header({ req: req, res: res }, function(err, header) { - res.send(header + app.create_route("search/"+req.params.term, null, "search") + templates['footer']); + app.build_header({ + req: req, + res: res + }, function(err, header) { + res.send(header + app.create_route("search/" + req.params.term, null, "search") + templates['footer']); }); }); app.get('/reindex', function(req, res) { topics.reIndexAll(function(err) { - if(err) { + if (err) { return res.json(err); } user.reIndexAll(function(err) { - if(err) { + if (err) { return res.json(err); } else { res.send('Topics and users reindexed'); @@ -462,4 +518,4 @@ var express = require('express'), }(WebServer)); server.listen(nconf.get('PORT') || nconf.get('port')); -global.server = server; +global.server = server; \ No newline at end of file diff --git a/src/websockets.js b/src/websockets.js index ea18ef15bc..c67046cb28 100644 --- a/src/websockets.js +++ b/src/websockets.js @@ -1,8 +1,7 @@ - var SocketIO = require('socket.io').listen(global.server, { - log: false, - transports: ['websocket', 'xhr-polling', 'jsonp-polling', 'flashsocket'] - }), + log: false, + transports: ['websocket', 'xhr-polling', 'jsonp-polling', 'flashsocket'] +}), cookie = require('cookie'), express = require('express'), user = require('./user.js'), @@ -22,7 +21,7 @@ var SocketIO = require('socket.io').listen(global.server, { RDB = require('./redis'), RedisStore = new RedisStoreLib({ client: RDB, - ttl: 60*60*24*14 + ttl: 60 * 60 * 24 * 14 }), socketCookieParser = express.cookieParser(nconf.get('secret')), admin = { @@ -40,7 +39,7 @@ var SocketIO = require('socket.io').listen(global.server, { global.io = io; io.sockets.on('connection', function(socket) { - var hs = socket.handshake, + var hs = socket.handshake, sessionID, uid; // Validate the session, if present @@ -53,12 +52,16 @@ var SocketIO = require('socket.io').listen(global.server, { userSockets[uid] = userSockets[uid] || []; userSockets[uid].push(socket); - if(uid) { + if (uid) { socket.join('uid_' + uid); - io.sockets.in('global').emit('api:user.isOnline', isUserOnline(uid)); + io.sockets. in ('global').emit('api:user.isOnline', isUserOnline(uid)); user.getUserField(uid, 'username', function(err, username) { - socket.emit('event:connect', {status: 1, username:username, uid:uid}); + socket.emit('event:connect', { + status: 1, + username: username, + uid: uid + }); }); } }); @@ -69,25 +72,25 @@ var SocketIO = require('socket.io').listen(global.server, { socket.on('disconnect', function() { var index = userSockets[uid].indexOf(socket); - if(index !== -1) { + if (index !== -1) { userSockets[uid].splice(index, 1); } - if(userSockets[uid].length === 0) { + if (userSockets[uid].length === 0) { delete users[sessionID]; delete userSockets[uid]; - if(uid) { - io.sockets.in('global').emit('api:user.isOnline', isUserOnline(uid)); + if (uid) { + io.sockets. in ('global').emit('api:user.isOnline', isUserOnline(uid)); } } emitOnlineUserCount(); - for(var roomName in rooms) { + for (var roomName in rooms) { socket.leave(roomName); - if(rooms[roomName][socket.id]) { + if (rooms[roomName][socket.id]) { delete rooms[roomName][socket.id]; } @@ -103,8 +106,8 @@ var SocketIO = require('socket.io').listen(global.server, { function getUidsInRoom(room) { var uids = []; - for(var socketId in room) { - if(uids.indexOf(room[socketId]) === -1) + for (var socketId in room) { + if (uids.indexOf(room[socketId]) === -1) uids.push(room[socketId]); } return uids; @@ -114,10 +117,10 @@ var SocketIO = require('socket.io').listen(global.server, { var clients = io.sockets.clients(roomName); var anonCount = 0; - for(var i=0; i' + users[i].username + ''; + for (var i = 0, ii = users.length; i < ii; ++i) { + usernames[i] = '' + '' + users[i].username + ''; } var joiner = anonymousCount + userCount == 1 ? 'is' : 'are', - userList = anonymousCount > 0 ? usernames.concat(util.format('%d guest%s', anonymousCount, anonymousCount > 1 ? 's' : '')) : usernames, - lastUser = userList.length > 1 ? ' and ' + userList.pop() : ''; + userList = anonymousCount > 0 ? usernames.concat(util.format('%d guest%s', anonymousCount, anonymousCount > 1 ? 's' : '')) : usernames, + lastUser = userList.length > 1 ? ' and ' + userList.pop() : ''; return util.format('%s%s %s browsing this thread', userList.join(', '), lastUser, joiner); } if (uids.length === 0) { - io.sockets.in(roomName).emit('api:get_users_in_room', userList([], anonymousCount, 0)); + io.sockets. in (roomName).emit('api:get_users_in_room', userList([], anonymousCount, 0)); } else { user.getMultipleUserFields(uids, ['username', 'userslug'], function(err, users) { - if(!err) - io.sockets.in(roomName).emit('api:get_users_in_room', userList(users, anonymousCount, users.length)); + if (!err) + io.sockets. in (roomName).emit('api:get_users_in_room', userList(users, anonymousCount, users.length)); }); } } @@ -171,42 +174,45 @@ var SocketIO = require('socket.io').listen(global.server, { } } - if(data.leave) + if (data.leave) updateRoomBrowsingText(data.leave); updateRoomBrowsingText(data.enter); if (data.enter != 'admin') - io.sockets.in('admin').emit('api:get_all_rooms', io.sockets.manager.rooms); + io.sockets. in ('admin').emit('api:get_all_rooms', io.sockets.manager.rooms); }); // BEGIN: API calls (todo: organize) socket.on('api:updateHeader', function(data) { - if(uid) { + if (uid) { user.getUserFields(uid, data.fields, function(err, fields) { - if(!err && fields) { + if (!err && fields) { fields.uid = uid; socket.emit('api:updateHeader', fields); } }); - } - else { + } else { socket.emit('api:updateHeader', { - uid:0, + uid: 0, username: "Anonymous User", email: '', - picture: require('gravatar').url('', {s:'24'}, https=nconf.get('https')) + picture: require('gravatar').url('', { + s: '24' + }, https = nconf.get('https')) }); } }); socket.on('user.exists', function(data) { - if(data.username) { - user.exists(utils.slugify(data.username), function(exists){ - socket.emit('user.exists', {exists: exists}); + if (data.username) { + user.exists(utils.slugify(data.username), function(exists) { + socket.emit('user.exists', { + exists: exists + }); }); } }); @@ -246,9 +252,9 @@ var SocketIO = require('socket.io').listen(global.server, { socket.on('api:user.get_online_users', function(data) { var returnData = []; - for(var i=0; i'; - if(!isUserOnline(touid)) { - notifications.create(notifText, 5, 'javascript:app.openChat(''+username+'', '+uid+');', 'notification_' + uid + '_' + touid, function(nid) { + if (!isUserOnline(touid)) { + notifications.create(notifText, 5, 'javascript:app.openChat('' + username + '', ' + uid + ');', 'notification_' + uid + '_' + touid, function(nid) { notifications.push(nid, [touid], function(success) { }); @@ -558,20 +569,30 @@ var SocketIO = require('socket.io').listen(global.server, { require('./messaging').addMessage(uid, touid, msg, function(err, message) { var numSockets = 0; - if(userSockets[touid]) { + if (userSockets[touid]) { numSockets = userSockets[touid].length; - for(var x=0; x 0) { user.getUserFields(uid, ['username', 'picture'], function(err, userData) { - if(!err && userData) { + if (!err && userData) { socket.emit('api:composer.push', { tid: 0, cid: data.cid, @@ -626,7 +649,7 @@ var SocketIO = require('socket.io').listen(global.server, { posts.getPostFields(data.pid, ['content', 'uploadedImages'], function(raw) { try { raw.uploadedImages = JSON.parse(raw.uploadedImages); - } catch(e) { + } catch (e) { winston.err(e); raw.uploadedImages = []; } @@ -696,7 +719,9 @@ var SocketIO = require('socket.io').listen(global.server, { end = start + 9; topics.getTopicPosts(data.tid, start, end, uid, function(posts) { - callback({posts:posts}); + callback({ + posts: posts + }); }); }); @@ -705,7 +730,9 @@ var SocketIO = require('socket.io').listen(global.server, { end = start + 9; categories.getCategoryTopics(data.cid, start, end, uid, function(topics) { - callback({topics:topics}); + callback({ + topics: topics + }); }); }); @@ -732,10 +759,12 @@ var SocketIO = require('socket.io').listen(global.server, { end = start + 19; user.getUsers(data.set, start, end, function(err, data) { - if(err) { + if (err) { winston.err(err); } else { - callback({users:data}); + callback({ + users: data + }); } }); }); @@ -757,37 +786,37 @@ var SocketIO = require('socket.io').listen(global.server, { }); socket.on('api:admin.user.makeAdmin', function(theirid) { - if(uid && uid > 0) { + if (uid && uid > 0) { admin.user.makeAdmin(uid, theirid, socket); } }); socket.on('api:admin.user.removeAdmin', function(theirid) { - if(uid && uid > 0) { + if (uid && uid > 0) { admin.user.removeAdmin(uid, theirid, socket); } }); socket.on('api:admin.user.deleteUser', function(theirid) { - if(uid && uid > 0) { + if (uid && uid > 0) { admin.user.deleteUser(uid, theirid, socket); } }); socket.on('api:admin.user.banUser', function(theirid) { - if(uid && uid > 0) { + if (uid && uid > 0) { admin.user.banUser(uid, theirid, socket); } }); socket.on('api:admin.user.unbanUser', function(theirid) { - if(uid && uid > 0) { + if (uid && uid > 0) { admin.user.unbanUser(uid, theirid, socket); } }); socket.on('api:admin.user.search', function(username, callback) { - if(uid && uid > 0) { + if (uid && uid > 0) { user.search(username, function(data) { if (!callback) socket.emit('api:admin.user.search', data); else callback(null, data); @@ -855,4 +884,4 @@ var SocketIO = require('socket.io').listen(global.server, { }); }); -}(SocketIO)); +}(SocketIO)); \ No newline at end of file From 1780b343b4b59912d90bd5aebc8d874188321644 Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:10:14 -0400 Subject: [PATCH 09/12] formatting - routes --- src/routes/admin.js | 78 ++++++++---- src/routes/api.js | 42 ++++--- src/routes/authentication.js | 49 ++++++-- src/routes/testbed.js | 44 ++++--- src/routes/user.js | 235 +++++++++++++++++++++++------------ 5 files changed, 285 insertions(+), 163 deletions(-) diff --git a/src/routes/admin.js b/src/routes/admin.js index f3b72d4d3d..f74aad3b2d 100644 --- a/src/routes/admin.js +++ b/src/routes/admin.js @@ -1,4 +1,3 @@ - var user = require('./../user.js'), Groups = require('../groups'), topics = require('./../topics.js'), @@ -18,7 +17,7 @@ var user = require('./../user.js'), Admin.build_header = function(res) { return templates['admin/header'].parse({ - csrf:res.locals.csrf_token, + csrf: res.locals.csrf_token, relative_path: nconf.get('relative_path') }); } @@ -26,14 +25,14 @@ var user = require('./../user.js'), Admin.create_routes = function(app) { (function() { - var routes = [ - 'categories/active', 'categories/disabled', 'users', 'topics', 'settings', 'themes', - 'twitter', 'facebook', 'gplus', 'redis', 'motd', 'groups', - 'users/latest', 'users/sort-posts', 'users/sort-reputation', - 'users/search', 'plugins' - ]; - - for (var i=0, ii=routes.length; i2 ? 2 : posts.length; + category["post_count"] = posts.length > 2 ? 2 : posts.length; callback(null); }); } @@ -70,7 +70,7 @@ var user = require('./../user.js'), 'login_window:spansize': 'col-md-6', 'alternate_logins:display': 'block' } - for (var i=0, ii=num_strategies; i 262144) { + if (req.files.userPhoto.size > 262144) { res.send({ error: 'Images must be smaller than 256kb!' }); @@ -118,7 +144,7 @@ var user = require('./../user.js'), var allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif']; - if(allowedTypes.indexOf(req.files.userPhoto.type) === -1) { + if (allowedTypes.indexOf(req.files.userPhoto.type) === -1) { res.send({ error: 'Allowed image types are png, jpg and gif!' }); @@ -126,7 +152,7 @@ var user = require('./../user.js'), } user.getUserField(req.user.uid, 'uploadedpicture', function(err, oldpicture) { - if(!oldpicture) { + if (!oldpicture) { uploadUserPicture(req.user.uid, path.extname(req.files.userPhoto.name), req.files.userPhoto.path, res); return; } @@ -134,7 +160,7 @@ var user = require('./../user.js'), var absolutePath = path.join(process.cwd(), global.nconf.get('upload_path'), path.basename(oldpicture)); fs.unlink(absolutePath, function(err) { - if(err) { + if (err) { winston.err(err); } @@ -144,7 +170,7 @@ var user = require('./../user.js'), }); function uploadUserPicture(uid, extension, tempPath, res) { - if(!extension) { + if (!extension) { res.send({ error: 'Error uploading file! Error : Invalid extension!' }); @@ -154,7 +180,7 @@ var user = require('./../user.js'), var filename = uid + '-profileimg' + extension; var uploadPath = path.join(process.cwd(), global.nconf.get('upload_path'), filename); - winston.info('Attempting upload to: '+ uploadPath); + winston.info('Attempting upload to: ' + uploadPath); var is = fs.createReadStream(tempPath); var os = fs.createWriteStream(uploadPath); @@ -169,15 +195,17 @@ var user = require('./../user.js'), require('node-imagemagick').crop({ srcPath: uploadPath, - dstPath: uploadPath, + dstPath: uploadPath, width: 128, height: 128 - }, function(err, stdout, stderr){ + }, function(err, stdout, stderr) { if (err) { winston.err(err); } - res.json({ path: imageUrl }); + res.json({ + path: imageUrl + }); }); }); @@ -191,49 +219,58 @@ var user = require('./../user.js'), app.get('/users/:userslug/following', function(req, res) { - if(!req.user) + if (!req.user) return res.redirect('/403'); user.get_uid_by_userslug(req.params.userslug, function(err, uid) { - if(!uid) { + if (!uid) { res.redirect('/404'); return; } - app.build_header({ req: req, res: res }, function(err, header) { - res.send(header + app.create_route('users/'+req.params.userslug+'/following','following') + templates['footer']); + app.build_header({ + req: req, + res: res + }, function(err, header) { + res.send(header + app.create_route('users/' + req.params.userslug + '/following', 'following') + templates['footer']); }); }); }); app.get('/users/:userslug/followers', function(req, res) { - if(!req.user) + if (!req.user) return res.redirect('/403'); user.get_uid_by_userslug(req.params.userslug, function(err, uid) { - if(!uid) { + if (!uid) { res.redirect('/404'); return; } - app.build_header({ req: req, res: res }, function(err, header) { - res.send(header + app.create_route('users/'+req.params.userslug+'/followers','followers') + templates['footer']); + app.build_header({ + req: req, + res: res + }, function(err, header) { + res.send(header + app.create_route('users/' + req.params.userslug + '/followers', 'followers') + templates['footer']); }); }); }); app.get('/users/:userslug/favourites', function(req, res) { - if(!req.user) + if (!req.user) return res.redirect('/403'); user.get_uid_by_userslug(req.params.userslug, function(err, uid) { - if(!uid) { + if (!uid) { res.redirect('/404'); return; } - app.build_header({ req: req, res: res }, function(err, header) { - res.send(header + app.create_route('users/'+req.params.userslug+'/favourites','favourites') + templates['footer']); + app.build_header({ + req: req, + res: res + }, function(err, header) { + res.send(header + app.create_route('users/' + req.params.userslug + '/favourites', 'favourites') + templates['footer']); }); }); }); @@ -242,7 +279,7 @@ var user = require('./../user.js'), var callerUID = req.user ? req.user.uid : 0; getUserDataByUserSlug(req.params.userslug, callerUID, function(userData) { - if(userData) { + if (userData) { user.getFollowing(userData.uid, function(followingData) { userData.following = followingData; userData.followingCount = followingData.length; @@ -250,7 +287,9 @@ var user = require('./../user.js'), }); } else { - res.json(404, { error: 'User not found!' }) ; + res.json(404, { + error: 'User not found!' + }); } }); }); @@ -259,14 +298,16 @@ var user = require('./../user.js'), var callerUID = req.user ? req.user.uid : 0; getUserDataByUserSlug(req.params.userslug, callerUID, function(userData) { - if(userData) { + if (userData) { user.getFollowers(userData.uid, function(followersData) { userData.followers = followersData; userData.followersCount = followersData.length; res.json(userData); }); } else { - res.json(404, { error: 'User not found!' }) ; + res.json(404, { + error: 'User not found!' + }); } }); }); @@ -283,27 +324,33 @@ var user = require('./../user.js'), var callerUID = req.user ? req.user.uid : 0; user.get_uid_by_userslug(req.params.userslug, function(err, uid) { - if(!uid) { - res.json(404, { error: 'User not found!' }) ; + if (!uid) { + res.json(404, { + error: 'User not found!' + }); return; } - if(uid !== callerUID || callerUID === "0") { - res.json(403, { error: 'Not allowed!' }); + if (uid !== callerUID || callerUID === "0") { + res.json(403, { + error: 'Not allowed!' + }); return; } - user.getUserFields(uid, ['username','userslug','showemail'], function(err, userData) { - if(err) + user.getUserFields(uid, ['username', 'userslug', 'showemail'], function(err, userData) { + if (err) return next(err); - if(userData) { - if(userData.showemail && userData.showemail === "1") + if (userData) { + if (userData.showemail && userData.showemail === "1") userData.showemail = "checked"; else userData.showemail = ""; res.json(userData); } else { - res.json(404, { error: 'User not found!' }) ; + res.json(404, { + error: 'User not found!' + }); } }); }); @@ -313,30 +360,36 @@ var user = require('./../user.js'), var callerUID = req.user ? req.user.uid : 0; user.get_uid_by_userslug(req.params.userslug, function(err, uid) { - if(!uid) { - res.json(404, { error: 'User not found!' }) ; + if (!uid) { + res.json(404, { + error: 'User not found!' + }); return; } - if(uid !== callerUID || callerUID === "0") { - res.json(403, { error: 'Not allowed!' }); + if (uid !== callerUID || callerUID === "0") { + res.json(403, { + error: 'Not allowed!' + }); return; } - user.getUserFields(uid, ['username','userslug'], function(err, userData) { - if(err) + user.getUserFields(uid, ['username', 'userslug'], function(err, userData) { + if (err) return next(err); - if(userData) { + if (userData) { posts.getFavourites(uid, function(err, posts) { - if(err) + if (err) return next(err); userData.posts = posts; - userData.show_nofavourites = posts.length?'hide':'show'; + userData.show_nofavourites = posts.length ? 'hide' : 'show'; res.json(userData); }); } else { - res.json(404, { error: 'User not found!' }) ; + res.json(404, { + error: 'User not found!' + }); } }); }); @@ -346,15 +399,17 @@ var user = require('./../user.js'), var callerUID = req.user ? req.user.uid : 0; getUserDataByUserSlug(req.params.userslug, callerUID, function(userData) { - if(userData) { + if (userData) { user.isFollowing(callerUID, userData.theirid, function(isFollowing) { posts.getPostsByUid(userData.theirid, 0, 9, function(posts) { - userData.posts = posts.filter(function(p) {return p.deleted !== "1";}); + userData.posts = posts.filter(function(p) { + return p.deleted !== "1"; + }); userData.isFollowing = isFollowing; - if(!userData.profileviews) + if (!userData.profileviews) userData.profileviews = 1; - if(callerUID !== userData.uid) + if (callerUID !== userData.uid) user.incrementUserFieldBy(userData.uid, 'profileviews', 1); postTools.toHTML(userData.signature, function(err, signature) { @@ -364,7 +419,9 @@ var user = require('./../user.js'), }); }); } else { - res.json(404, { error: 'User not found!' }) ; + res.json(404, { + error: 'User not found!' + }); } }); }); @@ -378,39 +435,55 @@ var user = require('./../user.js'), function getUsersSortedByJoinDate(req, res) { user.getUsers('users:joindate', 0, 49, function(err, data) { - res.json({ search_display: 'none', loadmore_display:'block', users:data }); + res.json({ + search_display: 'none', + loadmore_display: 'block', + users: data + }); }); } function getUsersSortedByPosts(req, res) { user.getUsers('users:postcount', 0, 49, function(err, data) { - res.json({ search_display: 'none', loadmore_display:'block', users:data }); + res.json({ + search_display: 'none', + loadmore_display: 'block', + users: data + }); }); } function getUsersSortedByReputation(req, res) { user.getUsers('users:reputation', 0, 49, function(err, data) { - res.json({ search_display: 'none', loadmore_display:'block', users:data }); + res.json({ + search_display: 'none', + loadmore_display: 'block', + users: data + }); }); } function getUsersForSearch(req, res) { - res.json({ search_display: 'block', loadmore_display:'none', users: [] }); + res.json({ + search_display: 'block', + loadmore_display: 'none', + users: [] + }); } function getUserDataByUserSlug(userslug, callerUID, callback) { user.get_uid_by_userslug(userslug, function(err, uid) { - if(uid === null) { + if (uid === null) { callback(null); return; } user.getUserData(uid, function(err, data) { - if(data) { + if (data) { data.joindate = utils.relativeTime(data.joindate); - if(!data.birthday) { + if (!data.birthday) { data.age = ''; } else { data.age = new Date().getFullYear() - new Date(data.birthday).getFullYear(); @@ -420,15 +493,15 @@ var user = require('./../user.js'), return callerUID === uid || (data.email && (data.showemail && data.showemail === "1")); } - if(!canSeeEmail()) + if (!canSeeEmail()) data.email = ""; - if(callerUID === uid && (!data.showemail || data.showemail === "0")) + if (callerUID === uid && (!data.showemail || data.showemail === "0")) data.emailClass = ""; else data.emailClass = "hide"; - data.show_banned = data.banned === '1'?'':'hide'; + data.show_banned = data.banned === '1' ? '' : 'hide'; data.uid = uid; data.yourid = callerUID; @@ -451,4 +524,4 @@ var user = require('./../user.js'), }; -}(exports)); +}(exports)); \ No newline at end of file From 1b9e451a6f682bff1da3b53c71a0c50dfedf3e7b Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:10:58 -0400 Subject: [PATCH 10/12] formatting - server side admin --- src/admin/categories.js | 2 +- src/admin/user.js | 19 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/admin/categories.js b/src/admin/categories.js index a8dc20b8ea..4f4dc682a7 100644 --- a/src/admin/categories.js +++ b/src/admin/categories.js @@ -1,4 +1,4 @@ -var RDB = require('./../redis.js'), +var RDB = require('./../redis.js'), utils = require('./../../public/src/utils.js'), categories = require('./../categories.js'); diff --git a/src/admin/user.js b/src/admin/user.js index 4da5a06360..8933018828 100644 --- a/src/admin/user.js +++ b/src/admin/user.js @@ -1,4 +1,4 @@ -var RDB = require('../redis'), +var RDB = require('../redis'), utils = require('../../public/src/utils'), user = require('../user'), Groups = require('../groups'); @@ -7,7 +7,7 @@ var RDB = require('../redis'), UserAdmin.makeAdmin = function(uid, theirid, socket) { user.isAdministrator(uid, function(isAdmin) { - if(isAdmin) { + if (isAdmin) { Groups.getGidFromName('Administrators', function(err, gid) { Groups.join(gid, theirid, function(err) { if (!err) { @@ -28,14 +28,14 @@ var RDB = require('../redis'), message: 'You need to be an administrator to make someone else an administrator!', type: 'warning', timeout: 2000 - }); + }); } }); }; UserAdmin.removeAdmin = function(uid, theirid, socket) { user.isAdministrator(uid, function(isAdmin) { - if(isAdmin) { + if (isAdmin) { Groups.getGidFromName('Administrators', function(err, gid) { Groups.leave(gid, theirid, function(err) { if (!err) { @@ -57,7 +57,7 @@ var RDB = require('../redis'), UserAdmin.deleteUser = function(uid, theirid, socket) { user.isAdministrator(uid, function(amIAdmin) { user.isAdministrator(theirid, function(areTheyAdmin) { - if(amIAdmin && !areTheyAdmin) { + if (amIAdmin && !areTheyAdmin) { user.delete(theirid, function(data) { socket.emit('event:alert', { @@ -75,7 +75,7 @@ var RDB = require('../redis'), UserAdmin.banUser = function(uid, theirid, socket) { user.isAdministrator(uid, function(amIAdmin) { user.isAdministrator(theirid, function(areTheyAdmin) { - if(amIAdmin && !areTheyAdmin) { + if (amIAdmin && !areTheyAdmin) { user.ban(theirid, function(err, result) { socket.emit('event:alert', { @@ -86,13 +86,13 @@ var RDB = require('../redis'), }); }); } - }); + }); }); }; UserAdmin.unbanUser = function(uid, theirid, socket) { user.isAdministrator(uid, function(amIAdmin) { - if(amIAdmin) { + if (amIAdmin) { user.unban(theirid, function(err, result) { socket.emit('event:alert', { title: 'User Unbanned', @@ -105,5 +105,4 @@ var RDB = require('../redis'), }); }; -}(exports)); - +}(exports)); \ No newline at end of file From c789f4230de8e99e439aa79643282672f1fb4fbf Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:15:36 -0400 Subject: [PATCH 11/12] formatted app.js, updated jshintrc to include node --- .jshintrc | 2 +- app.js | 24 ++++++++++++++---------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/.jshintrc b/.jshintrc index 5eaed9e374..1981c254c5 100644 --- a/.jshintrc +++ b/.jshintrc @@ -67,7 +67,7 @@ "dojo" : false, // Dojo Toolkit "jquery" : true, // jQuery "mootools" : false, // MooTools - "node" : false, // Node.js + "node" : true, // Node.js "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) "prototypejs" : false, // Prototype and Scriptaculous "rhino" : false, // Rhino diff --git a/app.js b/app.js index b7385c424e..546ea1c8a2 100644 --- a/app.js +++ b/app.js @@ -32,12 +32,12 @@ global.env = process.env.NODE_ENV || 'production'; winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { - colorize:true + colorize: true }); winston.add(winston.transports.File, { - filename:'error.log', - level:'error' + filename: 'error.log', + level: 'error' }); // TODO: remove once https://github.com/flatiron/winston/issues/280 is fixed @@ -53,9 +53,11 @@ winston.info(''); if (fs.existsSync(__dirname + '/config.json') && (!nconf.get('setup') && !nconf.get('upgrade'))) { // Load server-side config - nconf.file({ file: __dirname + '/config.json'}); + nconf.file({ + file: __dirname + '/config.json' + }); - var meta = require('./src/meta.js'); + var meta = require('./src/meta.js'); nconf.set('url', nconf.get('base_url') + (nconf.get('use_port') ? ':' + nconf.get('port') : '') + nconf.get('relative_path') + '/'); nconf.set('upload_url', nconf.get('url') + 'uploads/'); @@ -65,7 +67,7 @@ if (fs.existsSync(__dirname + '/config.json') && (!nconf.get('setup') && !nconf. meta.configs.init(function() { // Initial setup for Redis & Reds - var reds = require('reds'); + var reds = require('reds'); RDB = require('./src/redis.js'); reds.createClient = function() { return reds.client || (reds.client = RDB); @@ -75,7 +77,7 @@ if (fs.existsSync(__dirname + '/config.json') && (!nconf.get('setup') && !nconf. templates = require('./public/src/templates.js'), webserver = require('./src/webserver.js'), websockets = require('./src/websockets.js'), - plugins = require('./src/plugins'), // Don't remove this - plugins initializes itself + plugins = require('./src/plugins'), // Don't remove this - plugins initializes itself admin = { 'categories': require('./src/admin/categories.js') }; @@ -93,8 +95,10 @@ if (fs.existsSync(__dirname + '/config.json') && (!nconf.get('setup') && !nconf. }); } else if (nconf.get('upgrade')) { - nconf.file({ file: __dirname + '/config.json'}); - var meta = require('./src/meta.js'); + nconf.file({ + file: __dirname + '/config.json' + }); + var meta = require('./src/meta.js'); meta.configs.init(function() { require('./src/upgrade').upgrade(); @@ -104,7 +108,7 @@ if (fs.existsSync(__dirname + '/config.json') && (!nconf.get('setup') && !nconf. if (nconf.get('setup')) winston.info('NodeBB Setup Triggered via Command Line'); else winston.warn('Configuration not found, starting NodeBB setup'); - var install = require('./src/install'), + var install = require('./src/install'), meta = { config: {} }; From 678db837fd269f8afb6dd0cf73f43fb3ade46cc5 Mon Sep 17 00:00:00 2001 From: psychobunny Date: Tue, 17 Sep 2013 13:29:45 -0400 Subject: [PATCH 12/12] refactored post-block --- public/templates/topic.tpl | 4 ++-- public/themes/cerulean/topic.less | 17 +++++++++-------- public/themes/vanilla/topic.less | 6 ++++-- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/public/templates/topic.tpl b/public/templates/topic.tpl index 624c233416..a39d1967f2 100644 --- a/public/templates/topic.tpl +++ b/public/templates/topic.tpl @@ -62,7 +62,7 @@
    {main_posts.signature}
    -
    +
    {posts.signature}
    -
    +