Add rubocop to our build. (#5004)

This commit is contained in:
Guo Xiang Tan 2017-07-28 10:20:09 +09:00 committed by GitHub
parent ff4e295c4f
commit 5012d46cbd
871 changed files with 5480 additions and 6056 deletions

View File

@ -1,14 +1,104 @@
AllCops:
TargetRubyVersion: 2.3
TargetRubyVersion: 2.4
DisabledByDefault: true
Metrics/LineLength:
Max: 120
# Prefer &&/|| over and/or.
Style/AndOr:
Enabled: true
Metrics/MethodLength:
# Do not use braces for hash literals when they are the last argument of a
# method call.
Style/BracesAroundHashParameters:
Enabled: true
# Align `when` with `case`.
Layout/CaseIndentation:
Enabled: true
# Align comments with method definitions.
Layout/CommentIndentation:
Enabled: true
# No extra empty lines.
Layout/EmptyLines:
Enabled: true
# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }.
Style/HashSyntax:
Enabled: true
# Two spaces, no tabs (for indentation).
Layout/IndentationWidth:
Enabled: true
Layout/SpaceAfterColon:
Enabled: true
Layout/SpaceAfterComma:
Enabled: true
Layout/SpaceAroundEqualsInParameterDefault:
Enabled: true
Layout/SpaceAroundKeyword:
Enabled: true
Layout/SpaceAroundOperators:
Enabled: true
Layout/SpaceBeforeFirstArg:
Enabled: true
# Defining a method with parameters needs parentheses.
Style/MethodDefParentheses:
Enabled: true
# Use `foo {}` not `foo{}`.
Layout/SpaceBeforeBlockBraces:
Enabled: true
# Use `foo { bar }` not `foo {bar}`.
Layout/SpaceInsideBlockBraces:
Enabled: true
# Use `{ a: 1 }` not `{a:1}`.
Layout/SpaceInsideHashLiteralBraces:
Enabled: true
Layout/SpaceInsideParens:
Enabled: true
# Detect hard tabs, no hard tabs.
Layout/Tab:
Enabled: true
# Blank lines should not have any spaces.
Layout/TrailingBlankLines:
Enabled: true
# No trailing whitespace.
Layout/TrailingWhitespace:
Enabled: true
Lint/BlockAlignment:
Enabled: true
# Align `end` with the matching keyword or starting expression except for
# assignments, where it should be aligned with the LHS.
Lint/EndAlignment:
Enabled: true
EnforcedStyleAlignWith: variable
# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg.
Lint/RequireParentheses:
Enabled: true
Layout/MultilineMethodCallIndentation:
Enabled: true
EnforcedStyle: indented
Layout/AlignHash:
Enabled: true
Bundler/OrderedGems:
Enabled: false
Style/Documentation:
Enabled: false
Style/FrozenStringLiteralComment:
Enabled: False

View File

@ -36,7 +36,7 @@ cache:
- vendor/bundle
before_install:
- gem install bundler
- gem install bundler rubocop
- git clone --depth=1 https://github.com/discourse/discourse-backup-uploads-to-s3.git plugins/discourse-backup-uploads-to-s3
- git clone --depth=1 https://github.com/discourse/discourse-spoiler-alert.git plugins/discourse-spoiler-alert
- git clone --depth=1 https://github.com/discourse/discourse-cakeday.git plugins/discourse-cakeday
@ -48,6 +48,7 @@ before_install:
- eslint --ext .es6 test/javascripts
- eslint --ext .es6 plugins/**/assets/javascripts
- eslint test/javascripts
- rubocop --parallel
before_script:
- bundle exec rake db:create db:migrate

View File

@ -189,7 +189,6 @@ gem 'logster'
gem 'sassc', require: false
if ENV["IMPORT"] == "1"
gem 'mysql2'
gem 'redcarpet'

View File

@ -9,4 +9,3 @@ Discourse::Application.load_tasks
# this prevents crashes when migrating a database in production in certain
# PostgreSQL configuations when trying to create structure.sql
Rake::Task["db:structure:dump"].clear if Rails.env.production?

View File

@ -5,9 +5,9 @@ class Admin::BadgesController < Admin::AdminController
badge_types: BadgeType.all.order(:id).to_a,
badge_groupings: BadgeGrouping.all.order(:position).to_a,
badges: Badge.includes(:badge_grouping)
.includes(:badge_type)
.references(:badge_grouping)
.order('badge_groupings.position, badge_type_id, badges.name').to_a,
.includes(:badge_type)
.references(:badge_grouping)
.order('badge_groupings.position, badge_type_id, badges.name').to_a,
protected_system_fields: Badge.protected_system_fields,
triggers: Badge.trigger_hash
}
@ -43,9 +43,9 @@ class Admin::BadgesController < Admin::AdminController
badge_groupings = BadgeGrouping.all.order(:position).to_a
ids = params[:ids].map(&:to_i)
params[:names].each_with_index do |name,index|
params[:names].each_with_index do |name, index|
id = ids[index].to_i
group = badge_groupings.find{|b| b.id == id} || BadgeGrouping.new()
group = badge_groupings.find { |b| b.id == id } || BadgeGrouping.new()
group.name = name
group.position = index
group.save
@ -95,7 +95,7 @@ class Admin::BadgesController < Admin::AdminController
# Options:
# :new - reset the badge id to nil before saving
def update_badge_from_params(badge, opts={})
def update_badge_from_params(badge, opts = {})
errors = []
Badge.transaction do
allowed = Badge.column_names.map(&:to_sym)
@ -112,7 +112,7 @@ class Admin::BadgesController < Admin::AdminController
# Badge query contract checks
begin
if SiteSetting.enable_badge_sql
BadgeGranter.contract_checks!(badge.query, { target_posts: badge.target_posts, trigger: badge.trigger })
BadgeGranter.contract_checks!(badge.query, target_posts: badge.target_posts, trigger: badge.trigger)
end
rescue => e
errors << e.message

View File

@ -29,7 +29,6 @@ class Admin::ColorSchemesController < Admin::AdminController
render json: success_json
end
private
def fetch_color_scheme

View File

@ -2,13 +2,13 @@ require 'disk_space'
class Admin::DashboardController < Admin::AdminController
def index
dashboard_data = AdminDashboardData.fetch_cached_stats || Jobs::DashboardStats.new.execute({})
dashboard_data.merge!({version_check: DiscourseUpdates.check_version.as_json}) if SiteSetting.version_checks?
dashboard_data.merge!(version_check: DiscourseUpdates.check_version.as_json) if SiteSetting.version_checks?
dashboard_data[:disk_space] = DiskSpace.cached_stats
render json: dashboard_data
end
def problems
render_json_dump({problems: AdminDashboardData.fetch_problems})
render_json_dump(problems: AdminDashboardData.fetch_problems)
end
end

View File

@ -42,8 +42,8 @@ class Admin::DiagnosticsController < Admin::AdminController
GC.start(full_mark: true)
require 'objspace'
io = File.open("discourse-heap-#{SecureRandom.hex(3)}.json",'w')
ObjectSpace.dump_all(:output => io)
io = File.open("discourse-heap-#{SecureRandom.hex(3)}.json", 'w')
ObjectSpace.dump_all(output: io)
io.close
render plain: "HEAP DUMP:\n#{io.path}"

View File

@ -13,7 +13,7 @@ class Admin::EmailController < Admin::AdminController
Jobs::TestEmail.new.execute(to_address: params[:email_address])
render nothing: true
rescue => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -55,17 +55,17 @@ class Admin::EmailController < Admin::AdminController
params.require(:username)
params.require(:email)
user = User.find_by_username(params[:username])
message, skip_reason = UserNotifications.send(:digest, user, {since: params[:last_seen_at]})
message, skip_reason = UserNotifications.send(:digest, user, since: params[:last_seen_at])
if message
message.to = params[:email]
begin
Email::Sender.new(message, :digest).send
render json: success_json
rescue => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
else
render json: {errors: skip_reason}
render json: { errors: skip_reason }
end
end
@ -131,18 +131,18 @@ class Admin::EmailController < Admin::AdminController
serializer = IncomingEmailDetailsSerializer.new(incoming_email, root: false)
render_json_dump(serializer)
rescue => e
render json: {errors: [e.message]}, status: 404
render json: { errors: [e.message] }, status: 404
end
end
private
def filter_email_logs(email_logs, params)
email_logs = email_logs.includes(:user, { post: :topic })
.references(:user)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
email_logs = email_logs.includes(:user, post: :topic)
.references(:user)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
email_logs = email_logs.where("users.username ILIKE ?", "%#{params[:user]}%") if params[:user].present?
email_logs = email_logs.where("email_logs.to_address ILIKE ?", "%#{params[:address]}%") if params[:address].present?
@ -154,10 +154,10 @@ class Admin::EmailController < Admin::AdminController
end
def filter_incoming_emails(incoming_emails, params)
incoming_emails = incoming_emails.includes(:user, { post: :topic })
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
incoming_emails = incoming_emails.includes(:user, post: :topic)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
incoming_emails = incoming_emails.where("from_address ILIKE ?", "%#{params[:from]}%") if params[:from].present?
incoming_emails = incoming_emails.where("to_addresses ILIKE :to OR cc_addresses ILIKE :to", to: "%#{params[:to]}%") if params[:to].present?
@ -170,7 +170,7 @@ class Admin::EmailController < Admin::AdminController
def delivery_settings
action_mailer_settings
.reject { |k, _| k == :password }
.map { |k, v| { name: k, value: v }}
.map { |k, v| { name: k, value: v } }
end
def delivery_method

View File

@ -13,8 +13,8 @@ class Admin::EmojisController < Admin::AdminController
Scheduler::Defer.later("Upload Emoji") do
# fix the name
name = name.gsub(/[^a-z0-9]+/i, '_')
.gsub(/_{2,}/, '_')
.downcase
.gsub(/_{2,}/, '_')
.downcase
upload = UploadCreator.new(
file.tempfile,
@ -61,4 +61,3 @@ class Admin::EmojisController < Admin::AdminController
end
end

View File

@ -10,11 +10,11 @@ class Admin::FlagsController < Admin::AdminController
if posts.blank?
render json: { posts: [], topics: [], users: [] }
else
render json: MultiJson.dump({
render json: MultiJson.dump(
posts: posts,
topics: serialize_data(topics, FlaggedTopicSerializer),
users: serialize_data(users, FlaggedUserSerializer)
})
)
end
end

View File

@ -11,7 +11,7 @@ class Admin::GroupsController < Admin::AdminController
group = Group.find(params[:group_id].to_i)
users_added = 0
if group.present?
users = (params[:users] || []).map {|u| u.downcase}
users = (params[:users] || []).map { |u| u.downcase }
valid_emails = {}
valid_usernames = {}
@ -162,7 +162,7 @@ class Admin::GroupsController < Admin::AdminController
protected
def can_not_modify_automatic
render json: {errors: I18n.t('groups.errors.can_not_modify_automatic')}, status: 422
render json: { errors: I18n.t('groups.errors.can_not_modify_automatic') }, status: 422
end
private

View File

@ -46,7 +46,7 @@ class Admin::ScreenedIpAddressesController < Admin::AdminController
def roll_up
subnets = ScreenedIpAddress.roll_up(current_user)
render json: success_json.merge!({ subnets: subnets })
render json: success_json.merge!(subnets: subnets)
end
private

View File

@ -17,7 +17,7 @@ class Admin::SiteSettingsController < Admin::AdminController
SiteSetting.set_and_log(id, value, current_user)
render nothing: true
rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end

View File

@ -14,7 +14,7 @@ class Admin::SiteTextsController < Admin::AdminController
query = params[:q] || ""
if query.blank? && !overridden
extras[:recommended] = true
results = self.class.preferred_keys.map {|k| record_for(k) }
results = self.class.preferred_keys.map { |k| record_for(k) }
else
results = []
translations = I18n.search(query, overridden: overridden)
@ -69,14 +69,14 @@ class Admin::SiteTextsController < Admin::AdminController
protected
def record_for(k, value=nil)
def record_for(k, value = nil)
if k.ends_with?("_MF")
ovr = TranslationOverride.where(translation_key: k).pluck(:value)
value = ovr[0] if ovr.present?
end
value ||= I18n.t(k)
{id: k, value: value}
{ id: k, value: value }
end
def find_site_text

View File

@ -6,7 +6,7 @@ class Admin::StaffActionLogsController < Admin::AdminController
staff_action_logs = UserHistory.staff_action_records(current_user, filters).to_a
render json: StaffActionLogsSerializer.new({
staff_action_logs: staff_action_logs,
user_history_actions: UserHistory.staff_actions.sort.map{|name| {id: UserHistory.actions[name], name: name}}
user_history_actions: UserHistory.staff_actions.sort.map { |name| { id: UserHistory.actions[name], name: name } }
}, root: false)
end
@ -46,20 +46,18 @@ class Admin::StaffActionLogsController < Admin::AdminController
cur: child_themes(cur)
}
load_diff(diff_fields, :cur, cur)
load_diff(diff_fields, :prev, prev)
diff_fields.delete_if{|k,v| v[:cur] == v[:prev]}
diff_fields.delete_if { |k, v| v[:cur] == v[:prev] }
diff_fields.each do |k,v|
diff_fields.each do |k, v|
output << "<h3>#{k}</h3><p></p>"
diff = DiscourseDiff.new(v[:prev] || "", v[:cur] || "")
output << diff.side_by_side_markdown
end
render json: {side_by_side: output}
render json: { side_by_side: output }
end
protected
@ -67,11 +65,11 @@ class Admin::StaffActionLogsController < Admin::AdminController
def child_themes(theme)
return "" unless children = theme["child_themes"]
children.map{|row| row["name"]}.join(" ").to_s
children.map { |row| row["name"] }.join(" ").to_s
end
def load_diff(hash, key, val)
if f=val["theme_fields"]
if f = val["theme_fields"]
f.each do |row|
entry = hash[row["target"] + " " + row["name"]] ||= {}
entry[key] = row["value"]

View File

@ -62,7 +62,7 @@ class Admin::ThemesController < Admin::AdminController
}
respond_to do |format|
format.json { render json: payload}
format.json { render json: payload }
end
end
@ -77,7 +77,7 @@ class Admin::ThemesController < Admin::AdminController
if @theme.save
update_default_theme
log_theme_change(nil, @theme)
format.json { render json: @theme, status: :created}
format.json { render json: @theme, status: :created }
else
format.json { render json: @theme.errors, status: :unprocessable_entity }
end
@ -100,7 +100,7 @@ class Admin::ThemesController < Admin::AdminController
@theme.child_theme_relation.to_a.each do |child|
if expected.include?(child.child_theme_id)
expected.reject!{|id| id == child.child_theme_id}
expected.reject! { |id| id == child.child_theme_id }
else
child.destroy
end
@ -133,12 +133,12 @@ class Admin::ThemesController < Admin::AdminController
update_default_theme
log_theme_change(original_json, @theme)
format.json { render json: @theme, status: :created}
format.json { render json: @theme, status: :created }
else
format.json {
error = @theme.errors[:color_scheme] ? I18n.t("themes.bad_color_scheme") : I18n.t("themes.other_error")
render json: {errors: [ error ]}, status: :unprocessable_entity
render json: { errors: [ error ] }, status: :unprocessable_entity
}
end
end
@ -192,13 +192,14 @@ class Admin::ThemesController < Admin::AdminController
begin
# deep munge is a train wreck, work around it for now
params[:theme][:child_theme_ids] ||= [] if params[:theme].key?(:child_theme_ids)
params.require(:theme)
.permit(:name,
:color_scheme_id,
:default,
:user_selectable,
theme_fields: [:name, :target, :value, :upload_id, :type_id],
child_theme_ids: [])
params.require(:theme).permit(
:name,
:color_scheme_id,
:default,
:user_selectable,
theme_fields: [:name, :target, :value, :upload_id, :type_id],
child_theme_ids: []
)
end
end

View File

@ -51,8 +51,7 @@ class Admin::UserFieldsController < Admin::AdminController
options = params[:user_field][:options]
if options.present?
UserFieldOption.where(user_field_id: field.id).delete_all
field.user_field_options_attributes = options.map {|o| {value: o} }.uniq
field.user_field_options_attributes = options.map { |o| { value: o } }.uniq
end
end
end

View File

@ -77,7 +77,7 @@ class Admin::UsersController < Admin::AdminController
@user.logged_out
render json: success_json
else
render json: {error: I18n.t('admin_js.admin.users.id_not_found')}, status: 404
render json: { error: I18n.t('admin_js.admin.users.id_not_found') }, status: 404
end
end
@ -154,8 +154,7 @@ class Admin::UsersController < Admin::AdminController
guardian.ensure_can_change_trust_level!(@user)
level = params[:level].to_i
if !@user.trust_level_locked && [0,1,2].include?(level) && Promotion.send("tl#{level+1}_met?", @user)
if !@user.trust_level_locked && [0, 1, 2].include?(level) && Promotion.send("tl#{level + 1}_met?", @user)
@user.trust_level_locked = true
@user.save
end
@ -187,7 +186,7 @@ class Admin::UsersController < Admin::AdminController
unless @user.trust_level_locked
p = Promotion.new(@user)
2.times{ p.review }
2.times { p.review }
p.review_tl2
if @user.trust_level == 3 && Promotion.tl3_lost?(@user)
@user.change_trust_level!(2, log_action_for: current_user)
@ -242,7 +241,7 @@ class Admin::UsersController < Admin::AdminController
d = UserDestroyer.new(current_user)
User.where(id: params[:users]).each do |u|
success_count += 1 if guardian.can_delete_user?(u) and d.destroy(u, params.slice(:context)) rescue UserDestroyer::PostsExistError
success_count += 1 if guardian.can_delete_user?(u) && d.destroy(u, params.slice(:context)) rescue UserDestroyer::PostsExistError
end
render json: {
@ -339,12 +338,12 @@ class Admin::UsersController < Admin::AdminController
user.save!
user.grant_admin!
user.change_trust_level!(4)
user.email_tokens.update_all confirmed: true
user.email_tokens.update_all confirmed: true
email_token = user.email_tokens.create(email: user.email)
unless params[:send_email] == '0' || params[:send_email] == 'false'
Jobs.enqueue( :critical_user_email,
Jobs.enqueue(:critical_user_email,
type: :account_created,
user_id: user.id,
email_token: email_token.token)

View File

@ -28,7 +28,7 @@ class Admin::WatchedWordsController < Admin::AdminController
File.open(file.tempfile, encoding: "ISO-8859-1").each_line do |line|
WatchedWord.create_or_update_word(word: line, action_key: action_key) unless line.empty?
end
data = {url: '/ok'}
data = { url: '/ok' }
rescue => e
data = failed_json.merge(errors: [e.message])
end

View File

@ -6,10 +6,10 @@ class Admin::WebHooksController < Admin::AdminController
offset = params[:offset].to_i
web_hooks = WebHook.limit(limit)
.offset(offset)
.includes(:web_hook_event_types)
.includes(:categories)
.includes(:groups)
.offset(offset)
.includes(:web_hook_event_types)
.includes(:categories)
.includes(:groups)
json = {
web_hooks: serialize_data(web_hooks, AdminWebHookSerializer),

View File

@ -147,7 +147,7 @@ class ApplicationController < ActionController::Base
render_json_error I18n.t('read_only_mode_enabled'), type: :read_only, status: 503
end
def rescue_discourse_actions(type, status_code, include_ember=false)
def rescue_discourse_actions(type, status_code, include_ember = false)
show_json_errors = (request.format && request.format.json?) ||
(request.xhr?) ||
@ -175,7 +175,7 @@ class ApplicationController < ActionController::Base
def set_current_user_for_logs
if current_user
Logster.add_to_env(request.env,"username",current_user.username)
Logster.add_to_env(request.env, "username", current_user.username)
response.headers["X-Discourse-Username"] = current_user.username
end
response.headers["X-Discourse-Route"] = "#{controller_name}/#{action_name}"
@ -298,9 +298,9 @@ class ApplicationController < ActionController::Base
current_user ? SiteSetting.homepage : SiteSetting.anonymous_homepage
end
def serialize_data(obj, serializer, opts=nil)
def serialize_data(obj, serializer, opts = nil)
# If it's an array, apply the serializer as an each_serializer to the elements
serializer_opts = {scope: guardian}.merge!(opts || {})
serializer_opts = { scope: guardian }.merge!(opts || {})
if obj.respond_to?(:to_ary)
serializer_opts[:each_serializer] = serializer
ActiveModel::ArraySerializer.new(obj.to_ary, serializer_opts).as_json
@ -313,11 +313,11 @@ class ApplicationController < ActionController::Base
# 20% slower than calling MultiJSON.dump ourselves. I'm not sure why
# Rails doesn't call MultiJson.dump when you pass it json: obj but
# it seems we don't need whatever Rails is doing.
def render_serialized(obj, serializer, opts=nil)
def render_serialized(obj, serializer, opts = nil)
render_json_dump(serialize_data(obj, serializer, opts), opts)
end
def render_json_dump(obj, opts=nil)
def render_json_dump(obj, opts = nil)
opts ||= {}
if opts[:rest_serializer]
obj['__rest_serializer'] = "1"
@ -341,7 +341,7 @@ class ApplicationController < ActionController::Base
Middleware::AnonymousCache.anon_cache(request.env, time_length)
end
def fetch_user_from_params(opts=nil, eager_load = [])
def fetch_user_from_params(opts = nil, eager_load = [])
opts ||= {}
user = if params[:username]
username_lower = params[:username].downcase.chomp('.json')
@ -361,9 +361,9 @@ class ApplicationController < ActionController::Base
end
def post_ids_including_replies
post_ids = params[:post_ids].map {|p| p.to_i}
post_ids = params[:post_ids].map { |p| p.to_i }
if params[:reply_post_ids]
post_ids |= PostReply.where(post_id: params[:reply_post_ids].map {|p| p.to_i}).pluck(:reply_id)
post_ids |= PostReply.where(post_id: params[:reply_post_ids].map { |p| p.to_i }).pluck(:reply_id)
end
post_ids
end
@ -394,7 +394,6 @@ class ApplicationController < ActionController::Base
end
end
def secure_session
SecureSession.new(session["secure_session_id"] ||= SecureRandom.hex)
end
@ -433,14 +432,16 @@ class ApplicationController < ActionController::Base
def custom_html_json
target = view_context.mobile_view? ? :mobile : :desktop
data = if @theme_key
{
top: Theme.lookup_field(@theme_key, target, "after_header"),
footer: Theme.lookup_field(@theme_key, target, "footer")
}
else
{}
end
data =
if @theme_key
{
top: Theme.lookup_field(@theme_key, target, "after_header"),
footer: Theme.lookup_field(@theme_key, target, "footer")
}
else
{}
end
if DiscoursePluginRegistry.custom_html
data.merge! DiscoursePluginRegistry.custom_html
@ -480,7 +481,7 @@ class ApplicationController < ActionController::Base
# opts:
# type - a machine-readable description of the error
# status - HTTP status code to return
def render_json_error(obj, opts={})
def render_json_error(obj, opts = {})
opts = { status: opts } if opts.is_a?(Integer)
render json: MultiJson.dump(create_errors_json(obj, opts[:type])), status: opts[:status] || 422
end
@ -493,7 +494,7 @@ class ApplicationController < ActionController::Base
{ failed: 'FAILED' }
end
def json_result(obj, opts={})
def json_result(obj, opts = {})
if yield(obj)
json = success_json
@ -574,21 +575,20 @@ class ApplicationController < ActionController::Base
raise Discourse::ReadOnly.new if !(request.get? || request.head?) && Discourse.readonly_mode?
end
def build_not_found_page(status=404, layout=false)
def build_not_found_page(status = 404, layout = false)
category_topic_ids = Category.pluck(:topic_id).compact
@container_class = "wrap not-found-container"
@top_viewed = TopicQuery.new(nil, {except_topic_ids: category_topic_ids}).list_top_for("monthly").topics.first(10)
@top_viewed = TopicQuery.new(nil, except_topic_ids: category_topic_ids).list_top_for("monthly").topics.first(10)
@recent = Topic.where.not(id: category_topic_ids).recent(10)
@slug = params[:slug].class == String ? params[:slug] : ''
@slug = (params[:id].class == String ? params[:id] : '') if @slug.blank?
@slug.tr!('-',' ')
@slug.tr!('-', ' ')
render_to_string status: status, layout: layout, formats: [:html], template: '/exceptions/not_found'
end
protected
def render_post_json(post, add_raw=true)
def render_post_json(post, add_raw = true)
post_serializer = PostSerializer.new(post, scope: guardian, root: false)
post_serializer.add_raw = add_raw

View File

@ -14,7 +14,7 @@ class BadgesController < ApplicationController
if (params[:only_listable] == "true") || !request.xhr?
# NOTE: this is sorted client side if needed
badges = badges.includes(:badge_grouping)
.where(enabled: true, listable: true)
.where(enabled: true, listable: true)
end

View File

@ -218,7 +218,7 @@ class CategoriesController < ApplicationController
end
if p = params[:permissions]
p.each do |k,v|
p.each do |k, v|
p[k] = v.to_i
end
end
@ -250,10 +250,10 @@ class CategoriesController < ApplicationController
:default_view,
:subcategory_list_style,
:default_top_period,
:custom_fields => [params[:custom_fields].try(:keys)],
:permissions => [*p.try(:keys)],
:allowed_tags => [],
:allowed_tag_groups => [])
custom_fields: [params[:custom_fields].try(:keys)],
permissions: [*p.try(:keys)],
allowed_tags: [],
allowed_tag_groups: [])
end
end
@ -265,7 +265,7 @@ class CategoriesController < ApplicationController
@staff_action_logger = StaffActionLogger.new(current_user)
end
def include_topics(parent_category=nil)
def include_topics(parent_category = nil)
view_context.mobile_view? ||
params[:include_topics] ||
(parent_category && parent_category.subcategory_list_includes_topics?) ||

View File

@ -8,7 +8,7 @@ class ClicksController < ApplicationController
params = track_params.merge(ip: request.remote_ip)
if params[:topic_id].present? || params[:post_id].present?
params.merge!({ user_id: current_user.id }) if current_user.present?
params.merge!(user_id: current_user.id) if current_user.present?
@redirect_url = TopicLinkClick.create_from(params)
end

View File

@ -11,7 +11,7 @@ class ComposerMessagesController < ApplicationController
if params[:topic_id].present?
topic = Topic.where(id: params[:topic_id]).first
if guardian.can_see?(topic)
json[:extras] = {duplicate_lookup: TopicLink.duplicate_lookup(topic)}
json[:extras] = { duplicate_lookup: TopicLink.duplicate_lookup(topic) }
end
end

View File

@ -53,7 +53,7 @@ class DirectoryItemsController < ApplicationController
# Put yourself at the top of the first page
if result.present? && current_user.present? && page == 0
position = result.index {|r| r.user_id == current_user.id }
position = result.index { |r| r.user_id == current_user.id }
# Don't show the record unless you're not in the top positions already
if (position || 10) >= 10

View File

@ -5,7 +5,7 @@ class DraftController < ApplicationController
def show
seq = params[:sequence] || DraftSequence.current(current_user, params[:draft_key])
render json: {draft: Draft.get(current_user, params[:draft_key], seq), draft_sequence: seq}
render json: { draft: Draft.get(current_user, params[:draft_key], seq), draft_sequence: seq }
end
def update

View File

@ -31,8 +31,8 @@ class EmailController < ApplicationController
if @topic.category_id
if CategoryUser.exists?(user_id: @user.id, notification_level: CategoryUser.watching_levels, category_id: @topic.category_id)
@watched_count = TopicUser.joins(:topic)
.where(user: @user, notification_level: watching, "topics.category_id" => @topic.category_id)
.count
.where(user: @user, notification_level: watching, "topics.category_id" => @topic.category_id)
.count
end
end
end
@ -52,28 +52,28 @@ class EmailController < ApplicationController
if topic
if params["unwatch_topic"]
TopicUser.where(topic_id: topic.id, user_id: user.id)
.update_all(notification_level: TopicUser.notification_levels[:tracking])
.update_all(notification_level: TopicUser.notification_levels[:tracking])
updated = true
end
if params["unwatch_category"] && topic.category_id
TopicUser.joins(:topic)
.where(:user => user,
:notification_level => TopicUser.notification_levels[:watching],
"topics.category_id" => topic.category_id)
.update_all(notification_level: TopicUser.notification_levels[:tracking])
.where(:user => user,
:notification_level => TopicUser.notification_levels[:watching],
"topics.category_id" => topic.category_id)
.update_all(notification_level: TopicUser.notification_levels[:tracking])
CategoryUser.where(user_id: user.id,
category_id: topic.category_id,
notification_level: CategoryUser.watching_levels
category_id: topic.category_id,
notification_level: CategoryUser.watching_levels
)
.destroy_all
.destroy_all
updated = true
end
if params["mute_topic"]
TopicUser.where(topic_id: topic.id, user_id: user.id)
.update_all(notification_level: TopicUser.notification_levels[:muted])
.update_all(notification_level: TopicUser.notification_levels[:muted])
updated = true
end
end
@ -90,9 +90,9 @@ class EmailController < ApplicationController
if params["unsubscribe_all"]
user.user_option.update_columns(email_always: false,
email_digests: false,
email_direct: false,
email_private_messages: false)
email_digests: false,
email_direct: false,
email_private_messages: false)
updated = true
end

View File

@ -74,7 +74,7 @@ class EmbedController < ApplicationController
by_url = {}
if embed_urls.present?
urls = embed_urls.map {|u| u.sub(/#discourse-comments$/, '').sub(/\/$/, '') }
urls = embed_urls.map { |u| u.sub(/#discourse-comments$/, '').sub(/\/$/, '') }
topic_embeds = TopicEmbed.where(embed_url: urls).includes(:topic).references(:topic)
topic_embeds.each do |te|
@ -88,7 +88,7 @@ class EmbedController < ApplicationController
end
end
render json: {counts: by_url}, callback: params[:callback]
render json: { counts: by_url }, callback: params[:callback]
end
private
@ -96,7 +96,7 @@ class EmbedController < ApplicationController
def get_embeddable_css_class
@embeddable_css_class = ""
embeddable_host = EmbeddableHost.record_for_url(request.referer)
@embeddable_css_class = " class=\"#{embeddable_host.class_name}\"" if embeddable_host.present? and embeddable_host.class_name.present?
@embeddable_css_class = " class=\"#{embeddable_host.class_name}\"" if embeddable_host.present? && embeddable_host.class_name.present?
end
def ensure_api_request
@ -114,5 +114,4 @@ class EmbedController < ApplicationController
raise Discourse::InvalidAccess.new('invalid referer host')
end
end

View File

@ -124,13 +124,13 @@ class GroupsController < ApplicationController
members = group.users
.order('NOT group_users.owner')
.order(order)
.order(:username_lower => dir)
.order(username_lower: dir)
.limit(limit)
.offset(offset)
owners = group.users
.order(order)
.order(:username_lower => dir)
.order(username_lower: dir)
.where('group_users.owner')
render json: {
@ -274,8 +274,8 @@ class GroupsController < ApplicationController
end
GroupUser.where(group_id: group.id)
.where(user_id: user_id)
.update_all(notification_level: notification_level)
.where(user_id: user_id)
.update_all(notification_level: notification_level)
render json: success_json
end

View File

@ -26,4 +26,3 @@ class HighlightJsController < ApplicationController
end
end
end

View File

@ -16,11 +16,12 @@ class InvitesController < ApplicationController
invite = Invite.find_by(invite_key: params[:id])
if invite.present?
store_preloaded("invite_info", MultiJson.dump({
store_preloaded("invite_info", MultiJson.dump(
invited_by: UserNameSerializer.new(invite.invited_by, scope: guardian, root: false),
email: invite.email,
username: UserNameSuggester.suggest(invite.email)
}))
username: UserNameSuggester.suggest(invite.email))
)
render layout: 'application'
else
flash.now[:error] = I18n.t('invite.not_found')
@ -81,7 +82,7 @@ class InvitesController < ApplicationController
render json: failed_json, status: 422
end
rescue Invite::UserExists, ActiveRecord::RecordInvalid => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -110,7 +111,7 @@ class InvitesController < ApplicationController
render json: failed_json, status: 422
end
rescue => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -163,7 +164,7 @@ class InvitesController < ApplicationController
data = if extension.downcase == ".csv"
path = Invite.create_csv(file, name)
Jobs.enqueue(:bulk_invite, filename: "#{name}#{extension}", current_user_id: current_user.id)
{url: path}
{ url: path }
else
failed_json.merge(errors: [I18n.t("bulk_invite.file_should_be_csv")])
end

View File

@ -205,7 +205,7 @@ class ListController < ApplicationController
render 'list', formats: [:rss]
end
def top(options=nil)
def top(options = nil)
options ||= {}
period = ListController.best_period_for(current_user.try(:previous_visit_at), options[:category])
send("top_#{period}", options)
@ -308,7 +308,7 @@ class ListController < ApplicationController
parent_category_id = nil
if parent_slug_or_id.present?
parent_category_id = Category.query_parent_category(parent_slug_or_id)
permalink_redirect_or_not_found and return if parent_category_id.blank? && !id
permalink_redirect_or_not_found && (return) if parent_category_id.blank? && !id
end
@category = Category.query_category(slug_or_id, parent_category_id)
@ -319,7 +319,7 @@ class ListController < ApplicationController
(redirect_to category.url, status: 301) && return if category
end
permalink_redirect_or_not_found and return if !@category
permalink_redirect_or_not_found && (return) if !@category
@description_meta = @category.description_text
raise Discourse::NotFound unless guardian.can_see?(@category)
@ -362,23 +362,23 @@ class ListController < ApplicationController
else # :next
public_send(method, opts.merge(next_page_params(opts)))
end
url.sub('.json?','?')
url.sub('.json?', '?')
end
def get_excluded_category_ids(current_category=nil)
def get_excluded_category_ids(current_category = nil)
exclude_category_ids = Category.where(suppress_from_homepage: true)
exclude_category_ids = exclude_category_ids.where.not(id: current_category) if current_category
exclude_category_ids.pluck(:id)
end
def self.best_period_for(previous_visit_at, category_id=nil)
def self.best_period_for(previous_visit_at, category_id = nil)
default_period = ((category_id && Category.where(id: category_id).pluck(:default_top_period).first) ||
SiteSetting.top_page_default_timeframe).to_sym
best_period_with_topics_for(previous_visit_at, category_id, default_period) || default_period
end
def self.best_period_with_topics_for(previous_visit_at, category_id=nil, default_period=SiteSetting.top_page_default_timeframe)
def self.best_period_with_topics_for(previous_visit_at, category_id = nil, default_period = SiteSetting.top_page_default_timeframe)
best_periods_for(previous_visit_at, default_period.to_sym).each do |period|
top_topics = TopTopic.where("#{period}_score > 0")
top_topics = top_topics.joins(:topic).where("topics.category_id = ?", category_id) if category_id
@ -389,12 +389,12 @@ class ListController < ApplicationController
false
end
def self.best_periods_for(date, default_period=:all)
def self.best_periods_for(date, default_period = :all)
date ||= 1.year.ago
periods = []
periods << default_period if :all != default_period
periods << :daily if :daily != default_period && date > 8.days.ago
periods << :weekly if :weekly != default_period && date > 35.days.ago
periods << :daily if :daily != default_period && date > 8.days.ago
periods << :weekly if :weekly != default_period && date > 35.days.ago
periods << :monthly if :monthly != default_period && date > 180.days.ago
periods << :yearly if :yearly != default_period
periods

View File

@ -31,7 +31,7 @@ class MetadataController < ApplicationController
}
if SiteSetting.native_app_install_banner
manifest = manifest.merge({
manifest = manifest.merge(
prefer_related_applications: true,
related_applications: [
{
@ -39,7 +39,7 @@ class MetadataController < ApplicationController
id: "com.discourse"
}
]
})
)
end
manifest

View File

@ -37,9 +37,9 @@ class NotificationsController < ApplicationController
offset = params[:offset].to_i
notifications = Notification.where(user_id: user.id)
.visible
.includes(:topic)
.order(created_at: :desc)
.visible
.includes(:topic)
.order(created_at: :desc)
total_rows = notifications.dup.count
notifications = notifications.offset(offset).limit(60)

View File

@ -12,10 +12,9 @@ class PostActionUsersController < ApplicationController
post = finder.first
guardian.ensure_can_see!(post)
post_actions = post.post_actions.where(post_action_type_id: post_action_type_id)
.includes(:user)
.order('post_actions.created_at asc')
.includes(:user)
.order('post_actions.created_at asc')
if !guardian.can_see_post_actors?(post.topic, post_action_type_id)
if !current_user

View File

@ -41,23 +41,23 @@ class PostsController < ApplicationController
if params[:id] == "private_posts"
raise Discourse::NotFound if current_user.nil?
posts = Post.private_posts
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
rss_description = I18n.t("rss_description.private_posts")
else
posts = Post.public_posts
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
rss_description = I18n.t("rss_description.posts")
end
@ -92,12 +92,12 @@ class PostsController < ApplicationController
user = fetch_user_from_params
posts = Post.public_posts
.where(user_id: user.id)
.where(post_type: Post.types[:regular])
.order(created_at: :desc)
.includes(:user)
.includes(topic: :category)
.limit(50)
.where(user_id: user.id)
.where(post_type: Post.types[:regular])
.order(created_at: :desc)
.includes(:user)
.includes(topic: :category)
.limit(50)
posts = posts.reject { |post| !guardian.can_see?(post) || post.topic.blank? }
@ -230,20 +230,20 @@ class PostsController < ApplicationController
RateLimiter.new(current_user, "delete_post", 3, 1.minute).performed! unless current_user.staff?
if too_late_to(:delete_post, post)
render json: {errors: [I18n.t('too_late_to_edit')]}, status: 422
render json: { errors: [I18n.t('too_late_to_edit')] }, status: 422
return
end
guardian.ensure_can_delete!(post)
destroyer = PostDestroyer.new(current_user, post, { context: params[:context] })
destroyer = PostDestroyer.new(current_user, post, context: params[:context])
destroyer.destroy
render nothing: true
end
def expand_embed
render json: {cooked: TopicEmbed.expanded_for(find_post_from_params) }
render json: { cooked: TopicEmbed.expanded_for(find_post_from_params) }
rescue
render_json_error I18n.t('errors.embed.load_from_remote')
end
@ -266,10 +266,10 @@ class PostsController < ApplicationController
raise Discourse::InvalidParameters.new(:post_ids) if posts.blank?
# Make sure we can delete the posts
posts.each {|p| guardian.ensure_can_delete!(p) }
posts.each { |p| guardian.ensure_can_delete!(p) }
Post.transaction do
posts.each {|p| PostDestroyer.new(current_user, p).destroy }
posts.each { |p| PostDestroyer.new(current_user, p).destroy }
end
render nothing: true
@ -399,7 +399,7 @@ class PostsController < ApplicationController
post = find_post_from_params
guardian.ensure_can_wiki!(post)
post.revise(current_user, { wiki: params[:wiki] })
post.revise(current_user, wiki: params[:wiki])
render nothing: true
end
@ -408,7 +408,7 @@ class PostsController < ApplicationController
guardian.ensure_can_change_post_type!
post = find_post_from_params
post.revise(current_user, { post_type: params[:post_type].to_i })
post.revise(current_user, post_type: params[:post_type].to_i)
render nothing: true
end
@ -441,7 +441,7 @@ class PostsController < ApplicationController
limit = [(params[:limit] || 60).to_i, 100].min
posts = user_posts(guardian, user.id, offset: offset, limit: limit)
.where(id: PostAction.where(post_action_type_id: PostActionType.notify_flag_type_ids)
.where(id: PostAction.where(post_action_type_id: PostActionType.notify_flag_type_ids)
.where(disagreed_at: nil)
.select(:post_id))
@ -479,7 +479,6 @@ class PostsController < ApplicationController
render json: json_obj, status: (!!success) ? 200 : 422
end
def find_post_revision_from_params
post_id = params[:id] || params[:post_id]
revision = params[:revision].to_i
@ -529,9 +528,9 @@ class PostsController < ApplicationController
def user_posts(guardian, user_id, opts)
posts = Post.includes(:user, :topic, :deleted_by, :user_actions)
.where(user_id: user_id)
.with_deleted
.order(created_at: :desc)
.where(user_id: user_id)
.with_deleted
.order(created_at: :desc)
if guardian.user.moderator?
@ -545,7 +544,7 @@ class PostsController < ApplicationController
end
posts.offset(opts[:offset])
.limit(opts[:limit])
.limit(opts[:limit])
end
def create_params
@ -622,7 +621,7 @@ class PostsController < ApplicationController
"post##" << Digest::SHA1.hexdigest(args
.to_a
.concat([["user", current_user.id]])
.sort{|x,y| x[0] <=> y[0]}.join do |x,y|
.sort { |x, y| x[0] <=> y[0] }.join do |x, y|
"#{x}:#{y}"
end)
end

View File

@ -41,18 +41,17 @@ class QueuedPostsController < ApplicationController
render_serialized(qp, QueuedPostSerializer, root: :queued_posts)
end
private
def user_deletion_opts
base = {
context: I18n.t('queue.delete_reason', {performed_by: current_user.username}),
context: I18n.t('queue.delete_reason', performed_by: current_user.username),
delete_posts: true,
delete_as_spammer: true
}
if Rails.env.production? && ENV["Staging"].nil?
base.merge!({block_email: true, block_ip: true})
base.merge!(block_email: true, block_ip: true)
end
base

View File

@ -98,7 +98,7 @@ class SearchController < ApplicationController
search_context = params[:search_context]
unless search_context
if (context = params[:context]) && (id = params[:context_id])
search_context = {type: context, id: id}
search_context = { type: context, id: id }
end
end
@ -108,7 +108,7 @@ class SearchController < ApplicationController
# A user is found by username
context_obj = nil
if ['user','private_messages'].include? search_context[:type]
if ['user', 'private_messages'].include? search_context[:type]
context_obj = User.find_by(username_lower: search_context[:id].downcase)
elsif 'category' == search_context[:type]
context_obj = Category.find_by(id: search_context[:id].to_i)

View File

@ -9,7 +9,7 @@ class SessionController < ApplicationController
ACTIVATE_USER_KEY = "activate_user"
def csrf
render json: {csrf: form_authenticity_token }
render json: { csrf: form_authenticity_token }
end
def sso
@ -35,7 +35,7 @@ class SessionController < ApplicationController
end
end
def sso_provider(payload=nil)
def sso_provider(payload = nil)
payload ||= request.query_string
if SiteSetting.enable_sso_provider
sso = SingleSignOn.parse(payload, SiteSetting.sso_secret)
@ -112,7 +112,7 @@ class SessionController < ApplicationController
activation = UserActivator.new(user, request, session, cookies)
activation.finish
session["user_created_message"] = activation.message
redirect_to users_account_created_path and return
redirect_to(users_account_created_path) && (return)
else
if SiteSetting.verbose_sso_logging
Rails.logger.warn("Verbose SSO log: User was logged on #{user.username}\n\n#{sso.diagnostics}")
@ -292,11 +292,11 @@ class SessionController < ApplicationController
end
def invalid_credentials
render json: {error: I18n.t("login.incorrect_username_email_or_password")}
render json: { error: I18n.t("login.incorrect_username_email_or_password") }
end
def login_not_approved
render json: {error: I18n.t("login.not_approved")}
render json: { error: I18n.t("login.not_approved") }
end
def not_activated(user)
@ -310,19 +310,19 @@ class SessionController < ApplicationController
end
def not_allowed_from_ip_address(user)
render json: {error: I18n.t("login.not_allowed_from_ip_address", username: user.username)}
render json: { error: I18n.t("login.not_allowed_from_ip_address", username: user.username) }
end
def admin_not_allowed_from_ip_address(user)
render json: {error: I18n.t("login.admin_not_allowed_from_ip_address", username: user.username)}
render json: { error: I18n.t("login.admin_not_allowed_from_ip_address", username: user.username) }
end
def failed_to_login(user)
message = user.suspend_reason ? "login.suspended_with_reason" : "login.suspended"
render json: {
error: I18n.t(message, { date: I18n.l(user.suspended_till, format: :date_only),
reason: Rack::Utils.escape_html(user.suspend_reason) }),
error: I18n.t(message, date: I18n.l(user.suspended_till, format: :date_only),
reason: Rack::Utils.escape_html(user.suspend_reason)),
reason: 'suspended'
}
end
@ -337,7 +337,6 @@ class SessionController < ApplicationController
render_serialized(user, UserSerializer)
end
def render_sso_error(status:, text:)
@sso_error = text
render status: status, layout: 'no_ember'

View File

@ -26,7 +26,7 @@ class SimilarTopicsController < ApplicationController
return render json: [] if invalid_length || !Topic.count_exceeds_minimum?
topics = Topic.similar_to(title, raw, current_user).to_a
topics.map! {|t| SimilarTopic.new(t) }
topics.map! { |t| SimilarTopic.new(t) }
render_serialized(topics, SimilarTopicSerializer, root: :similar_topics, rest_serializer: true)
end

View File

@ -13,9 +13,9 @@ class StaticController < ApplicationController
return redirect_to path('/login') if SiteSetting.login_required? && current_user.nil? && (params[:id] == 'faq' || params[:id] == 'guidelines')
map = {
"faq" => {redirect: "faq_url", topic_id: "guidelines_topic_id"},
"tos" => {redirect: "tos_url", topic_id: "tos_topic_id"},
"privacy" => {redirect: "privacy_policy_url", topic_id: "privacy_topic_id"}
"faq" => { redirect: "faq_url", topic_id: "guidelines_topic_id" },
"tos" => { redirect: "tos_url", topic_id: "tos_topic_id" },
"privacy" => { redirect: "privacy_policy_url", topic_id: "privacy_topic_id" }
}
@page = params[:id]
@ -100,7 +100,7 @@ class StaticController < ApplicationController
# a huge expiry, we also cache these assets in nginx so it bypassed if needed
def favicon
data = DistributedMemoizer.memoize('favicon' + SiteSetting.favicon_url, 60*30) do
data = DistributedMemoizer.memoize('favicon' + SiteSetting.favicon_url, 60 * 30) do
begin
file = FileHelper.download(
SiteSetting.favicon_url,
@ -137,21 +137,19 @@ class StaticController < ApplicationController
end
end
def cdn_asset
serve_asset
end
protected
def serve_asset(suffix=nil)
def serve_asset(suffix = nil)
path = File.expand_path(Rails.root + "public/assets/#{params[:path]}#{suffix}")
# SECURITY what if path has /../
raise Discourse::NotFound unless path.start_with?(Rails.root.to_s + "/public/assets")
response.headers["Expires"] = 1.year.from_now.httpdate
response.headers["Access-Control-Allow-Origin"] = params[:origin] if params[:origin]

View File

@ -20,7 +20,7 @@ class StepsController < ApplicationController
else
errors = []
updater.errors.messages.each do |field, msg|
errors << {field: field, description: msg.join }
errors << { field: field, description: msg.join }
end
render json: { errors: errors }, status: 422
end

View File

@ -19,17 +19,17 @@ class StylesheetsController < ApplicationController
no_cookies
target,digest = params[:name].split(/_([a-f0-9]{40})/)
target, digest = params[:name].split(/_([a-f0-9]{40})/)
if !Rails.env.production?
# TODO add theme
# calling this method ensures we have a cache for said target
# we hold of re-compilation till someone asks for asset
if target.include?("theme")
split_target,theme_id = target.split(/_(-?[0-9]+)/)
split_target, theme_id = target.split(/_(-?[0-9]+)/)
theme = Theme.find(theme_id) if theme_id
else
split_target,color_scheme_id = target.split(/_(-?[0-9]+)/)
split_target, color_scheme_id = target.split(/_(-?[0-9]+)/)
theme = Theme.find_by(color_scheme_id: color_scheme_id)
end
Stylesheet::Manager.stylesheet_link_tag(split_target, nil, theme&.key)
@ -59,7 +59,6 @@ class StylesheetsController < ApplicationController
return render nothing: true, status: 304
end
unless File.exist?(location)
if current = query.limit(1).pluck(source_map ? :source_map : :content).first
File.write(location, current)

View File

@ -69,7 +69,7 @@ class TagGroupsController < ApplicationController
end
def tag_groups_params
result = params.permit(:id, :name, :one_per_topic, :tag_names => [], :parent_tag_name => [])
result = params.permit(:id, :name, :one_per_topic, tag_names: [], parent_tag_name: [])
result[:tag_names] ||= []
result[:parent_tag_name] ||= []
result[:one_per_topic] = (params[:one_per_topic] == "true")

View File

@ -14,18 +14,18 @@ class TagsController < ::ApplicationController
:tag_feed,
:search,
:check_hashtag,
Discourse.anonymous_filters.map { |f| :"show_#{f}"}
Discourse.anonymous_filters.map { |f| :"show_#{f}" }
].flatten
before_filter :set_category_from_params, except: [:index, :update, :destroy, :tag_feed, :search, :notifications, :update_notifications]
def index
categories = Category.where("id in (select category_id from category_tags)")
.where("id in (?)", guardian.allowed_category_ids)
.preload(:tags)
.where("id in (?)", guardian.allowed_category_ids)
.preload(:tags)
category_tag_counts = categories.map do |c|
h = Tag.category_tags_by_count_query(c, limit: 300).count(Tag::COUNT_ARG)
h.merge!(c.tags.where.not(name: h.keys).inject({}) { |sum,t| sum[t.name] = 0; sum }) # unused tags
{id: c.id, tags: self.class.tag_counts_json(h)}
h.merge!(c.tags.where.not(name: h.keys).inject({}) { |sum, t| sum[t.name] = 0; sum }) # unused tags
{ id: c.id, tags: self.class.tag_counts_json(h) }
end
tag_counts = self.class.tags_by_count(guardian, limit: 300).count(Tag::COUNT_ARG)
@ -91,7 +91,7 @@ class TagsController < ::ApplicationController
tag.name = new_tag_name
if tag.save
StaffActionLogger.new(current_user).log_custom('renamed_tag', previous_value: params[:tag_id], new_value: new_tag_name)
render json: { tag: { id: new_tag_name }}
render json: { tag: { id: new_tag_name } }
else
render_json_error tag.errors.full_messages
end
@ -116,7 +116,7 @@ class TagsController < ::ApplicationController
@title = "#{SiteSetting.title} - #{@description}"
@atom_link = "#{Discourse.base_url}/tags/#{tag_id}.rss"
query = TopicQuery.new(current_user, {tags: [tag_id]})
query = TopicQuery.new(current_user, tags: [tag_id])
latest_results = query.latest_results
@topic_list = query.create_list(:by_tag, {}, latest_results)
@ -129,15 +129,13 @@ class TagsController < ::ApplicationController
tags_with_counts = DiscourseTagging.filter_allowed_tags(
Tag.tags_by_count_query(params.slice(:limit)),
guardian,
{
for_input: params[:filterForInput],
term: params[:q],
category: category,
selected_tags: params[:selected_tags]
}
for_input: params[:filterForInput],
term: params[:q],
category: category,
selected_tags: params[:selected_tags]
)
tags = tags_with_counts.count(Tag::COUNT_ARG).map {|t, c| { id: t, text: t, count: c } }
tags = tags_with_counts.count(Tag::COUNT_ARG).map { |t, c| { id: t, text: t, count: c } }
json_response = { results: tags }
@ -161,7 +159,7 @@ class TagsController < ::ApplicationController
raise Discourse::NotFound unless tag
level = params[:tag_notification][:notification_level].to_i
TagUser.change(current_user.id, tag.id, level)
render json: {notification_level: level}
render json: { notification_level: level }
end
def check_hashtag
@ -180,12 +178,12 @@ class TagsController < ::ApplicationController
raise Discourse::NotFound unless SiteSetting.tagging_enabled?
end
def self.tags_by_count(guardian, opts={})
def self.tags_by_count(guardian, opts = {})
guardian.filter_allowed_categories(Tag.tags_by_count_query(opts))
end
def self.tag_counts_json(tag_counts)
tag_counts.map {|t, c| { id: t, text: t, count: c } }
tag_counts.map { |t, c| { id: t, text: t, count: c } }
end
def set_category_from_params
@ -201,13 +199,13 @@ class TagsController < ::ApplicationController
parent_category_id = nil
if parent_slug_or_id.present?
parent_category_id = Category.query_parent_category(parent_slug_or_id)
category_redirect_or_not_found and return if parent_category_id.blank?
category_redirect_or_not_found && (return) if parent_category_id.blank?
end
@filter_on_category = Category.query_category(slug_or_id, parent_category_id)
end
category_redirect_or_not_found and return if !@filter_on_category
category_redirect_or_not_found && (return) if !@filter_on_category
guardian.ensure_can_see!(@filter_on_category)
end
@ -236,7 +234,7 @@ class TagsController < ::ApplicationController
end
end
def url_method(opts={})
def url_method(opts = {})
if opts[:parent_category] && opts[:category]
"tag_parent_category_category_#{action_name}_path"
elsif opts[:category]
@ -254,7 +252,7 @@ class TagsController < ::ApplicationController
else # :next
public_send(method, opts.merge(next_page_params(opts)))
end
url.sub('.json?','?')
url.sub('.json?', '?')
end
def build_topic_list_options

View File

@ -40,7 +40,7 @@ class TopicsController < ApplicationController
topic = Topic.find_by(slug: params[:slug].downcase)
guardian.ensure_can_see!(topic)
raise Discourse::NotFound unless topic
render json: {slug: topic.slug, topic_id: topic.id, url: topic.url}
render json: { slug: topic.slug, topic_id: topic.id, url: topic.url }
end
def show
@ -155,7 +155,6 @@ class TopicsController < ApplicationController
TopicUser.change(current_user.id, params[:topic_id].to_i, notification_level: TopicUser.notification_levels[:muted])
end
perform_show_response
end
@ -164,7 +163,8 @@ class TopicsController < ApplicationController
params.require(:topic_id)
params.permit(:min_trust_level, :min_score, :min_replies, :bypass_trust_level_score, :only_moderator_liked)
opts = { best: params[:best].to_i,
opts = {
best: params[:best].to_i,
min_trust_level: params[:min_trust_level] ? params[:min_trust_level].to_i : 1,
min_score: params[:min_score].to_i,
min_replies: params[:min_replies].to_i,
@ -206,17 +206,16 @@ class TopicsController < ApplicationController
guardian.ensure_can_see!(@topic)
@posts = Post.where(hidden: false, deleted_at: nil, topic_id: @topic.id)
.where('posts.id in (?)', post_ids)
.joins("LEFT JOIN users u on u.id = posts.user_id")
.pluck(:id, :cooked, :username)
.map do |post_id, cooked, username|
{
post_id: post_id,
username: username,
excerpt: PrettyText.excerpt(cooked, 800, keep_emoji_images: true)
}
end
.where('posts.id in (?)', post_ids)
.joins("LEFT JOIN users u on u.id = posts.user_id")
.pluck(:id, :cooked, :username)
.map do |post_id, cooked, username|
{
post_id: post_id,
username: username,
excerpt: PrettyText.excerpt(cooked, 800, keep_emoji_images: true)
}
end
render json: @posts.to_json
end
@ -266,7 +265,7 @@ class TopicsController < ApplicationController
params.require(:enabled)
params.permit(:until)
status = params[:status]
status = params[:status]
topic_id = params[:topic_id].to_i
enabled = params[:enabled] == 'true'
@ -319,13 +318,13 @@ class TopicsController < ApplicationController
)
if topic.save
render json: success_json.merge!({
render json: success_json.merge!(
execute_at: topic_status_update&.execute_at,
duration: topic_status_update&.duration,
based_on_last_post: topic_status_update&.based_on_last_post,
closed: topic.closed,
category_id: topic_status_update&.category_id
})
)
else
render_json_error(topic)
end
@ -353,8 +352,8 @@ class TopicsController < ApplicationController
topic = Topic.find(params[:topic_id].to_i)
PostAction.joins(:post)
.where(user_id: current_user.id)
.where('topic_id = ?', topic.id).each do |pa|
.where(user_id: current_user.id)
.where('topic_id = ?', topic.id).each do |pa|
PostAction.remove_act(current_user, pa.post, PostActionType.types[:bookmark])
end
@ -378,7 +377,7 @@ class TopicsController < ApplicationController
group_ids = current_user.groups.pluck(:id)
if group_ids.present?
allowed_groups = topic.allowed_groups
.where('topic_allowed_groups.group_id IN (?)', group_ids).pluck(:id)
.where('topic_allowed_groups.group_id IN (?)', group_ids).pluck(:id)
allowed_groups.each do |id|
if archive
GroupArchivedMessage.archive!(id, topic.id)
@ -421,7 +420,7 @@ class TopicsController < ApplicationController
guardian.ensure_can_delete!(topic)
first_post = topic.ordered_posts.first
PostDestroyer.new(current_user, first_post, { context: params[:context] }).destroy
PostDestroyer.new(current_user, first_post, context: params[:context]).destroy
render nothing: true
end
@ -484,7 +483,6 @@ class TopicsController < ApplicationController
topic = Topic.find_by(id: params[:topic_id])
groups = Group.lookup_groups(
group_ids: params[:group_ids],
group_names: params[:group_names]
@ -505,7 +503,7 @@ class TopicsController < ApplicationController
render json: failed_json, status: 422
end
rescue Topic::UserExists => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@ -547,10 +545,10 @@ class TopicsController < ApplicationController
guardian.ensure_can_change_post_owner!
begin
PostOwnerChanger.new( post_ids: params[:post_ids].to_a,
topic_id: params[:topic_id].to_i,
new_owner: User.find_by(username: params[:username]),
acting_user: current_user ).change_owner!
PostOwnerChanger.new(post_ids: params[:post_ids].to_a,
topic_id: params[:topic_id].to_i,
new_owner: User.find_by(username: params[:username]),
acting_user: current_user).change_owner!
render json: success_json
rescue ArgumentError
render json: failed_json, status: 422
@ -594,8 +592,8 @@ class TopicsController < ApplicationController
current_user,
params[:topic_id].to_i,
params[:topic_time].to_i,
(params[:timings] || []).map{|post_number, t| [post_number.to_i, t.to_i]},
{mobile: view_context.mobile_view?}
(params[:timings] || []).map { |post_number, t| [post_number.to_i, t.to_i] },
mobile: view_context.mobile_view?
)
render nothing: true
end
@ -608,7 +606,7 @@ class TopicsController < ApplicationController
def bulk
if params[:topic_ids].present?
topic_ids = params[:topic_ids].map {|t| t.to_i}
topic_ids = params[:topic_ids].map { |t| t.to_i }
elsif params[:filter] == 'unread'
tq = TopicQuery.new(current_user)
topics = TopicQuery.unread_filter(tq.joined_topic_user, current_user.id, staff: guardian.is_staff?).listable_topics
@ -664,7 +662,7 @@ class TopicsController < ApplicationController
params[:slug] && @topic_view.topic.slug != params[:slug]
end
def redirect_to_correct_topic(topic, post_number=nil)
def redirect_to_correct_topic(topic, post_number = nil)
url = topic.relative_url
url << "/#{post_number}" if post_number.to_i > 0
url << ".json" if request.format.json?
@ -728,9 +726,9 @@ class TopicsController < ApplicationController
def render_topic_changes(dest_topic)
if dest_topic.present?
render json: {success: true, url: dest_topic.relative_url}
render json: { success: true, url: dest_topic.relative_url }
else
render json: {success: false}
render json: { success: false }
end
end

View File

@ -40,7 +40,7 @@ class UserApiKeysController < ApplicationController
@client_id = params[:client_id]
@auth_redirect = params[:auth_redirect]
@push_url = params[:push_url]
@localized_scopes = params[:scopes].split(",").map{|s| I18n.t("user_api_key.scopes.#{s}")}
@localized_scopes = params[:scopes].split(",").map { |s| I18n.t("user_api_key.scopes.#{s}") }
@scopes = params[:scopes]
rescue Discourse::InvalidAccess
@ -52,10 +52,10 @@ class UserApiKeysController < ApplicationController
require_params
unless SiteSetting.allowed_user_api_auth_redirects
.split('|')
.any?{|u| params[:auth_redirect] == u}
.split('|')
.any? { |u| params[:auth_redirect] == u }
raise Discourse::InvalidAccess
raise Discourse::InvalidAccess
end
raise Discourse::InvalidAccess unless meets_tl?
@ -126,7 +126,7 @@ class UserApiKeysController < ApplicationController
:client_id,
:auth_redirect,
:application_name
].each{|p| params.require(p)}
].each { |p| params.require(p) }
end
def validate_params

View File

@ -89,7 +89,7 @@ class UserAvatarsController < ApplicationController
return render_blank if size < 8 || size > 1000
if !Discourse.avatar_sizes.include?(size) && Discourse.store.external?
closest = Discourse.avatar_sizes.to_a.min { |a,b| (size-a).abs <=> (size-b).abs }
closest = Discourse.avatar_sizes.to_a.min { |a, b| (size - a).abs <=> (size - b).abs }
avatar_url = UserAvatar.local_avatar_url(hostname, user.username_lower, upload_id, closest)
return redirect_to cdn_path(avatar_url)
end

View File

@ -33,12 +33,12 @@ class UserBadgesController < ApplicationController
if params[:grouped]
user_badges = user_badges.group(:badge_id)
.select(UserBadge.attribute_names.map {|x| "MAX(#{x}) AS #{x}" }, 'COUNT(*) AS "count"')
.select(UserBadge.attribute_names.map { |x| "MAX(#{x}) AS #{x}" }, 'COUNT(*) AS "count"')
end
user_badges = user_badges.includes(badge: [:badge_grouping, :badge_type])
.includes(post: :topic)
.includes(:granted_by)
.includes(post: :topic)
.includes(:granted_by)
render_serialized(user_badges, DetailedUserBadgeSerializer, root: :user_badges)
end
@ -104,6 +104,6 @@ class UserBadgesController < ApplicationController
def can_assign_badge_to_user?(user)
master_api_call = current_user.nil? && is_api?
master_api_call or guardian.can_grant_badges?(user)
master_api_call || guardian.can_grant_badges?(user)
end
end

View File

@ -36,7 +36,7 @@ class Users::OmniauthCallbacksController < ApplicationController
auth[:session] = session
authenticator = self.class.find_authenticator(params[:provider])
provider = Discourse.auth_providers && Discourse.auth_providers.find{|p| p.name == params[:provider]}
provider = Discourse.auth_providers && Discourse.auth_providers.find { |p| p.name == params[:provider] }
@auth_result = authenticator.after_authenticate(auth)
@ -83,7 +83,6 @@ class Users::OmniauthCallbacksController < ApplicationController
render layout: 'no_ember'
end
def self.find_authenticator(name)
BUILTIN_AUTH.each do |authenticator|
if authenticator.name == name

View File

@ -50,7 +50,7 @@ class UsersController < ApplicationController
topic_id = params[:include_post_count_for].to_i
if topic_id != 0
user_serializer.topic_post_count = {topic_id => Post.where(topic_id: topic_id, user_id: @user.id).count }
user_serializer.topic_post_count = { topic_id => Post.where(topic_id: topic_id, user_id: @user.id).count }
end
if !params[:skip_track_visit] && (@user != current_user)
@ -59,7 +59,7 @@ class UsersController < ApplicationController
# This is a hack to get around a Rails issue where values with periods aren't handled correctly
# when used as part of a route.
if params[:external_id] and params[:external_id].ends_with? '.json'
if params[:external_id] && params[:external_id].ends_with?('.json')
return render_json_dump(user_serializer)
end
@ -224,8 +224,8 @@ class UsersController < ApplicationController
pending_count = Invite.find_pending_invites_count(inviter)
redeemed_count = Invite.find_redeemed_invites_count(inviter)
render json: {counts: { pending: pending_count, redeemed: redeemed_count,
total: (pending_count.to_i + redeemed_count.to_i) } }
render json: { counts: { pending: pending_count, redeemed: redeemed_count,
total: (pending_count.to_i + redeemed_count.to_i) } }
end
def is_local_username
@ -238,7 +238,7 @@ class UsersController < ApplicationController
Group.mentionable(current_user)
.where(name: usernames)
.pluck(:name, :user_count)
.map{ |name,user_count| {name: name, user_count: user_count} }
.map { |name, user_count| { name: name, user_count: user_count } }
end
usernames -= groups
@ -250,14 +250,14 @@ class UsersController < ApplicationController
topic_id = params[:topic_id]
unless topic_id.blank?
topic = Topic.find_by(id: topic_id)
usernames.each{ |username| cannot_see.push(username) unless Guardian.new(User.find_by_username(username)).can_see?(topic) }
usernames.each { |username| cannot_see.push(username) unless Guardian.new(User.find_by_username(username)).can_see?(topic) }
end
result = User.where(staged: false)
.where(username_lower: usernames)
.pluck(:username_lower)
.where(username_lower: usernames)
.pluck(:username_lower)
render json: {valid: result, valid_groups: groups, mentionable_groups: mentionable_groups, cannot_see: cannot_see}
render json: { valid: result, valid_groups: groups, mentionable_groups: mentionable_groups, cannot_see: cannot_see }
end
def render_available_true
@ -265,7 +265,7 @@ class UsersController < ApplicationController
end
def changing_case_of_own_username(target_user, username)
target_user and username.downcase == target_user.username.downcase
target_user && username.downcase == (target_user.username.downcase)
end
# Used for checking availability of a username and will return suggestions
@ -385,7 +385,7 @@ class UsersController < ApplicationController
end
def get_honeypot_value
render json: {value: honeypot_value, challenge: challenge_value}
render json: { value: honeypot_value, challenge: challenge_value }
end
def password_reset
@ -433,7 +433,7 @@ class UsersController < ApplicationController
if @error
render layout: 'no_ember'
else
store_preloaded("password_reset", MultiJson.dump({ is_developer: UsernameCheckerService.is_developer?(@user.email) }))
store_preloaded("password_reset", MultiJson.dump(is_developer: UsernameCheckerService.is_developer?(@user.email)))
end
return redirect_to(wizard_path) if request.put? && Wizard.user_requires_completion?(@user)
end
@ -456,7 +456,7 @@ class UsersController < ApplicationController
}
end
else
render json: {is_developer: UsernameCheckerService.is_developer?(@user.email)}
render json: { is_developer: UsernameCheckerService.is_developer?(@user.email) }
end
end
end
@ -469,14 +469,15 @@ class UsersController < ApplicationController
end
def logon_after_password_reset
message = if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
'password_reset.success'
else
@requires_approval = true
'password_reset.success_unapproved'
end
message =
if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
'password_reset.success'
else
@requires_approval = true
'password_reset.success_unapproved'
end
@success = I18n.t(message)
end
@ -606,7 +607,7 @@ class UsersController < ApplicationController
User.transaction do
@user.email = params[:email]
if @user.save
@user.email_tokens.create(email: @user.email)
enqueue_activation_email
@ -662,7 +663,6 @@ class UsersController < ApplicationController
@group = Group.find_by(name: params[:group])
end
results = UserSearch.new(term,
topic_id: topic_id,
topic_allowed_users: topic_allowed_users,
@ -683,8 +683,8 @@ class UsersController < ApplicationController
if params[:include_mentionable_groups] == "true" && current_user
to_render[:groups] = Group.mentionable(current_user)
.where("name ILIKE :term_like", term_like: "#{term}%")
.map do |m|
.where("name ILIKE :term_like", term_like: "#{term}%")
.map do |m|
{ name: m.name, full_name: m.full_name }
end
end
@ -752,7 +752,7 @@ class UsersController < ApplicationController
@user = fetch_user_from_params
guardian.ensure_can_delete_user!(@user)
UserDestroyer.new(current_user).destroy(@user, { delete_posts: true, context: params[:context] })
UserDestroyer.new(current_user).destroy(@user, delete_posts: true, context: params[:context])
render json: success_json
end
@ -797,14 +797,14 @@ class UsersController < ApplicationController
private
def honeypot_value
Digest::SHA1::hexdigest("#{Discourse.current_hostname}:#{GlobalSetting.safe_secret_key_base}")[0,15]
Digest::SHA1::hexdigest("#{Discourse.current_hostname}:#{GlobalSetting.safe_secret_key_base}")[0, 15]
end
def challenge_value
challenge = $redis.get('SECRET_CHALLENGE')
unless challenge && challenge.length == 16*2
unless challenge && challenge.length == 16 * 2
challenge = SecureRandom.hex(16)
$redis.set('SECRET_CHALLENGE',challenge)
$redis.set('SECRET_CHALLENGE', challenge)
end
challenge
@ -833,9 +833,9 @@ class UsersController < ApplicationController
def user_params
result = params.permit(:name, :email, :password, :username, :date_of_birth)
.merge(ip_address: request.remote_ip,
registration_ip_address: request.remote_ip,
locale: user_locale)
.merge(ip_address: request.remote_ip,
registration_ip_address: request.remote_ip,
locale: user_locale)
if !UsernameCheckerService.is_developer?(result['email']) &&
is_api? &&
@ -845,7 +845,6 @@ class UsersController < ApplicationController
result.merge!(params.permit(:active, :staged))
end
result
end

View File

@ -15,7 +15,7 @@ module ApplicationHelper
include ConfigurableUrls
include GlobalPath
def google_universal_analytics_json(ua_domain_name=nil)
def google_universal_analytics_json(ua_domain_name = nil)
result = {}
if ua_domain_name
result[:cookieDomain] = ua_domain_name.gsub(/^http(s)?:\/\//, '')
@ -55,7 +55,7 @@ module ApplicationHelper
GlobalSetting.cdn_url.start_with?("https") &&
ENV["COMPRESS_BROTLI"] == "1" &&
request.env["HTTP_ACCEPT_ENCODING"] =~ /br/
path.gsub!("#{GlobalSetting.cdn_url}/assets/", "#{GlobalSetting.cdn_url}/brotli_asset/")
path.gsub!("#{GlobalSetting.cdn_url}/assets/", "#{GlobalSetting.cdn_url}/brotli_asset/")
end
"<link rel='preload' href='#{path}' as='script'/>
<script src='#{path}'></script>".html_safe
@ -158,7 +158,7 @@ module ApplicationHelper
end
# Creates open graph and twitter card meta data
def crawlable_meta_data(opts=nil)
def crawlable_meta_data(opts = nil)
opts ||= {}
opts[:url] ||= "#{Discourse.base_url_no_prefix}#{request.fullpath}"
@ -242,7 +242,7 @@ module ApplicationHelper
end
def mobile_view?
MobileDetection.resolve_mobile_view!(request.user_agent,params,session)
MobileDetection.resolve_mobile_view!(request.user_agent, params, session)
end
def crawler_layout?
@ -283,7 +283,7 @@ module ApplicationHelper
controller.class.name.split("::").first == "Admin"
end
def category_badge(category, opts=nil)
def category_badge(category, opts = nil)
CategoryBadge.html_for(category, opts).html_safe
end
@ -297,11 +297,11 @@ module ApplicationHelper
return "" if Rails.env.test?
matcher = Regexp.new("/connectors/#{name}/.*\.html\.erb$")
erbs = ApplicationHelper.all_connectors.select {|c| c =~ matcher }
erbs = ApplicationHelper.all_connectors.select { |c| c =~ matcher }
return "" if erbs.blank?
result = ""
erbs.each {|erb| result << render(file: erb) }
erbs.each { |erb| result << render(file: erb) }
result.html_safe
end
@ -335,7 +335,7 @@ module ApplicationHelper
lookup.html_safe if lookup
end
def discourse_stylesheet_link_tag(name, opts={})
def discourse_stylesheet_link_tag(name, opts = {})
if opts.key?(:theme_key)
key = opts[:theme_key] unless customization_disabled?
else

View File

@ -6,7 +6,7 @@ module ListHelper
return if total_pages < 2
page = [total_pages - (max_pages+1), 2].max
page = [total_pages - (max_pages + 1), 2].max
result = "("
while page <= total_pages

View File

@ -2,7 +2,7 @@ module TopicsHelper
include ApplicationHelper
def render_topic_title(topic)
link_to(Emoji.gsub_emoji_to_unicode(topic.title),topic.relative_url)
link_to(Emoji.gsub_emoji_to_unicode(topic.title), topic.relative_url)
end
def categories_breadcrumb(topic)

View File

@ -1,6 +1,6 @@
module UserNotificationsHelper
def indent(text, by=2)
def indent(text, by = 2)
spacer = " " * by
result = ""
text.each_line do |line|
@ -48,9 +48,9 @@ module UserNotificationsHelper
doc.css('div').first
end
def email_excerpt(html_arg, posts_count=nil)
def email_excerpt(html_arg, posts_count = nil)
# only include 1st paragraph when more than 1 posts
html = (posts_count.nil? || posts_count > 1) ? (first_paragraph_from(html_arg)||html_arg).to_s : html_arg
html = (posts_count.nil? || posts_count > 1) ? (first_paragraph_from(html_arg) || html_arg).to_s : html_arg
PrettyText.format_for_email(html).html_safe
end

View File

@ -71,11 +71,11 @@ module Jobs
ctx
end
def self.delayed_perform(opts={})
def self.delayed_perform(opts = {})
self.new.perform(opts)
end
def execute(opts={})
def execute(opts = {})
raise "Overwrite me!"
end
@ -114,7 +114,6 @@ module Jobs
end
end
dbs =
if opts[:current_site_id]
[opts[:current_site_id]]
@ -203,7 +202,7 @@ module Jobs
end
end
def self.enqueue(job_name, opts={})
def self.enqueue(job_name, opts = {})
klass = "Jobs::#{job_name.to_s.camelcase}".constantize
# Unless we want to work on all sites
@ -227,20 +226,20 @@ module Jobs
end
def self.enqueue_in(secs, job_name, opts={})
def self.enqueue_in(secs, job_name, opts = {})
enqueue(job_name, opts.merge!(delay_for: secs))
end
def self.enqueue_at(datetime, job_name, opts={})
def self.enqueue_at(datetime, job_name, opts = {})
secs = [(datetime - Time.zone.now).to_i, 0].max
enqueue_in(secs, job_name, opts)
end
def self.cancel_scheduled_job(job_name, opts={})
def self.cancel_scheduled_job(job_name, opts = {})
scheduled_for(job_name, opts).each(&:delete)
end
def self.scheduled_for(job_name, opts={})
def self.scheduled_for(job_name, opts = {})
opts = opts.with_indifferent_access
unless opts.delete(:all_sites)
opts[:current_site_id] ||= RailsMultisite::ConnectionManagement.current_db
@ -265,6 +264,6 @@ module Jobs
end
end
Dir["#{Rails.root}/app/jobs/onceoff/*.rb"].each {|file| require_dependency file }
Dir["#{Rails.root}/app/jobs/regular/*.rb"].each {|file| require_dependency file }
Dir["#{Rails.root}/app/jobs/scheduled/*.rb"].each {|file| require_dependency file }
Dir["#{Rails.root}/app/jobs/onceoff/*.rb"].each { |file| require_dependency file }
Dir["#{Rails.root}/app/jobs/regular/*.rb"].each { |file| require_dependency file }
Dir["#{Rails.root}/app/jobs/scheduled/*.rb"].each { |file| require_dependency file }

View File

@ -6,11 +6,11 @@ module Jobs
to_award = {}
Post.secured(Guardian.new)
.select(:id, :created_at, :cooked, :user_id)
.visible
.public_posts
.where("cooked LIKE '%emoji%'")
.find_in_batches do |group|
.select(:id, :created_at, :cooked, :user_id)
.visible
.public_posts
.where("cooked LIKE '%emoji%'")
.find_in_batches do |group|
group.each do |p|
doc = Nokogiri::HTML::fragment(p.cooked)
if (doc.css("img.emoji") - doc.css(".quote img")).size > 0

View File

@ -7,12 +7,12 @@ module Jobs
to_award = {}
Post.select(:id, :created_at, :user_id)
.secured(Guardian.new)
.visible
.public_posts
.where(via_email: true)
.where("post_number > 1")
.find_in_batches do |group|
.secured(Guardian.new)
.visible
.public_posts
.where(via_email: true)
.where("post_number > 1")
.find_in_batches do |group|
group.each do |p|
to_award[p.user_id] ||= { post_id: p.id, created_at: p.created_at }
end

View File

@ -8,11 +8,11 @@ module Jobs
to_award = {}
Post.secured(Guardian.new)
.select(:id, :created_at, :raw, :user_id)
.visible
.public_posts
.where("raw LIKE '%http%'")
.find_in_batches do |group|
.select(:id, :created_at, :raw, :user_id)
.visible
.public_posts
.where("raw LIKE '%http%'")
.find_in_batches do |group|
group.each do |p|
begin
# Note we can't use `p.cooked` here because oneboxes have been cooked out

View File

@ -4,7 +4,7 @@ module Jobs
def execute_onceoff(args)
all_tags = TopicCustomField.where(name: "tags").select('DISTINCT value').all.map(&:value)
tag_id_lookup = Tag.create(all_tags.map { |tag_name| {name: tag_name} }).inject({}) { |h,v| h[v.name] = v.id; h }
tag_id_lookup = Tag.create(all_tags.map { |tag_name| { name: tag_name } }).inject({}) { |h, v| h[v.name] = v.id; h }
TopicCustomField.where(name: "tags").find_each do |tcf|
TopicTag.create(topic_id: tcf.topic_id, tag_id: tag_id_lookup[tcf.value] || Tag.find_by_name(tcf.value).try(:id))

View File

@ -14,4 +14,3 @@ module Jobs
end
end

View File

@ -14,11 +14,11 @@ module Jobs
domains = group.automatic_membership_email_domains.gsub('.', '\.')
User.joins(:user_emails)
.where("user_emails.email ~* '@(#{domains})$'")
.where("users.id NOT IN (SELECT user_id FROM group_users WHERE group_users.group_id = ?)", group_id)
.activated
.where(staged: false)
.find_each do |user|
.where("user_emails.email ~* '@(#{domains})$'")
.where("users.id NOT IN (SELECT user_id FROM group_users WHERE group_users.group_id = ?)", group_id)
.activated
.where(staged: false)
.find_each do |user|
next unless user.email_confirmed?
group.add(user)
GroupActionLogger.new(Discourse.system_user, group).log_add_user_to_group(user)

View File

@ -12,7 +12,7 @@ module Jobs
if Guardian.new(topic_timer.user).can_delete?(topic)
first_post = topic.ordered_posts.first
PostDestroyer.new(topic_timer.user, first_post, { context: I18n.t("topic_statuses.auto_deleted_by_timer") }).destroy
PostDestroyer.new(topic_timer.user, first_post, context: I18n.t("topic_statuses.auto_deleted_by_timer")).destroy
topic_timer.trash!(Discourse.system_user)
end
end

View File

@ -83,12 +83,13 @@ module Jobs
web_hook_event = WebHookEvent.create!(web_hook_id: web_hook.id)
begin
content_type = case web_hook.content_type
when WebHook.content_types['application/x-www-form-urlencoded']
'application/x-www-form-urlencoded'
else
'application/json'
end
content_type =
case web_hook.content_type
when WebHook.content_types['application/x-www-form-urlencoded']
'application/x-www-form-urlencoded'
else
'application/json'
end
headers = {
'Accept' => '*/*',

View File

@ -8,18 +8,18 @@ module Jobs
sidekiq_options retry: false
HEADER_ATTRS_FOR ||= HashWithIndifferentAccess.new({
user_archive: ['topic_title','category','sub_category','is_pm','post','like_count','reply_count','url','created_at'],
user_list: ['id','name','username','email','title','created_at','last_seen_at','last_posted_at','last_emailed_at','trust_level','approved','suspended_at','suspended_till','blocked','active','admin','moderator','ip_address'],
user_stats: ['topics_entered','posts_read_count','time_read','topic_count','post_count','likes_given','likes_received'],
user_profile: ['location','website','views'],
user_sso: ['external_id','external_email', 'external_username', 'external_name', 'external_avatar_url'],
staff_action: ['staff_user','action','subject','created_at','details', 'context'],
screened_email: ['email','action','match_count','last_match_at','created_at','ip_address'],
screened_ip: ['ip_address','action','match_count','last_match_at','created_at'],
screened_url: ['domain','action','match_count','last_match_at','created_at'],
report: ['date', 'value'],
})
HEADER_ATTRS_FOR ||= HashWithIndifferentAccess.new(
user_archive: ['topic_title', 'category', 'sub_category', 'is_pm', 'post', 'like_count', 'reply_count', 'url', 'created_at'],
user_list: ['id', 'name', 'username', 'email', 'title', 'created_at', 'last_seen_at', 'last_posted_at', 'last_emailed_at', 'trust_level', 'approved', 'suspended_at', 'suspended_till', 'blocked', 'active', 'admin', 'moderator', 'ip_address'],
user_stats: ['topics_entered', 'posts_read_count', 'time_read', 'topic_count', 'post_count', 'likes_given', 'likes_received'],
user_profile: ['location', 'website', 'views'],
user_sso: ['external_id', 'external_email', 'external_username', 'external_name', 'external_avatar_url'],
staff_action: ['staff_user', 'action', 'subject', 'created_at', 'details', 'context'],
screened_email: ['email', 'action', 'match_count', 'last_match_at', 'created_at', 'ip_address'],
screened_ip: ['ip_address', 'action', 'match_count', 'last_match_at', 'created_at'],
screened_url: ['domain', 'action', 'match_count', 'last_match_at', 'created_at'],
report: ['date', 'value']
)
def execute(args)
@entity = args[:entity]
@ -58,11 +58,11 @@ module Jobs
return enum_for(:user_archive_export) unless block_given?
Post.includes(topic: :category)
.where(user_id: @current_user.id)
.select(:topic_id, :post_number, :raw, :like_count, :reply_count, :created_at)
.order(:created_at)
.with_deleted
.each do |user_archive|
.where(user_id: @current_user.id)
.select(:topic_id, :post_number, :raw, :like_count, :reply_count, :created_at)
.order(:created_at)
.with_deleted
.each do |user_archive|
yield get_user_archive_fields(user_archive)
end
end
@ -132,9 +132,9 @@ module Jobs
return enum_for(:screened_url_export) unless block_given?
ScreenedUrl.select("domain, sum(match_count) as match_count, max(last_match_at) as last_match_at, min(created_at) as created_at")
.group(:domain)
.order('last_match_at DESC')
.each do |screened_url|
.group(:domain)
.order('last_match_at DESC')
.each do |screened_url|
yield get_screened_url_fields(screened_url)
end
end
@ -181,14 +181,14 @@ module Jobs
def get_base_user_array(user)
user_array = []
user_array.push(user.id,escape_comma(user.name),user.username,user.email,escape_comma(user.title),user.created_at,user.last_seen_at,user.last_posted_at,user.last_emailed_at,user.trust_level,user.approved,user.suspended_at,user.suspended_till,user.blocked,user.active,user.admin,user.moderator,user.ip_address,user.user_stat.topics_entered,user.user_stat.posts_read_count,user.user_stat.time_read,user.user_stat.topic_count,user.user_stat.post_count,user.user_stat.likes_given,user.user_stat.likes_received,escape_comma(user.user_profile.location),user.user_profile.website,user.user_profile.views)
user_array.push(user.id, escape_comma(user.name), user.username, user.email, escape_comma(user.title), user.created_at, user.last_seen_at, user.last_posted_at, user.last_emailed_at, user.trust_level, user.approved, user.suspended_at, user.suspended_till, user.blocked, user.active, user.admin, user.moderator, user.ip_address, user.user_stat.topics_entered, user.user_stat.posts_read_count, user.user_stat.time_read, user.user_stat.topic_count, user.user_stat.post_count, user.user_stat.likes_given, user.user_stat.likes_received, escape_comma(user.user_profile.location), user.user_profile.website, user.user_profile.views)
end
def add_single_sign_on(user, user_info_array)
if user.single_sign_on_record
user_info_array.push(user.single_sign_on_record.external_id,user.single_sign_on_record.external_email,user.single_sign_on_record.external_username,escape_comma(user.single_sign_on_record.external_name),user.single_sign_on_record.external_avatar_url)
user_info_array.push(user.single_sign_on_record.external_id, user.single_sign_on_record.external_email, user.single_sign_on_record.external_username, escape_comma(user.single_sign_on_record.external_name), user.single_sign_on_record.external_avatar_url)
else
user_info_array.push(nil,nil,nil,nil,nil)
user_info_array.push(nil, nil, nil, nil, nil)
end
user_info_array
end
@ -233,7 +233,7 @@ module Jobs
is_pm = topic_data.archetype == "private_message" ? I18n.t("csv_export.boolean_yes") : I18n.t("csv_export.boolean_no")
url = "#{Discourse.base_url}/t/#{topic_data.slug}/#{topic_data.id}/#{user_archive['post_number']}"
topic_hash = {"post" => user_archive['raw'], "topic_title" => topic_data.title, "category" => category_name, "sub_category" => sub_category, "is_pm" => is_pm, "url" => url}
topic_hash = { "post" => user_archive['raw'], "topic_title" => topic_data.title, "category" => category_name, "sub_category" => sub_category, "is_pm" => is_pm, "url" => url }
user_archive.merge!(topic_hash)
HEADER_ATTRS_FOR['user_archive'].each do |attr|

View File

@ -14,19 +14,19 @@ module Jobs
users =
User.activated.not_blocked.not_suspended.real
.joins(:user_option)
.where('user_options.mailing_list_mode AND user_options.mailing_list_mode_frequency > 0')
.where('NOT EXISTS (
.joins(:user_option)
.where('user_options.mailing_list_mode AND user_options.mailing_list_mode_frequency > 0')
.where('NOT EXISTS (
SELECT 1
FROM muted_users mu
WHERE mu.muted_user_id = ? AND mu.user_id = users.id
)', post.user_id)
.where('NOT EXISTS (
.where('NOT EXISTS (
SELECT 1
FROM topic_users tu
WHERE tu.topic_id = ? AND tu.user_id = users.id AND tu.notification_level = ?
)', post.topic_id, TopicUser.notification_levels[:muted])
.where('NOT EXISTS (
.where('NOT EXISTS (
SELECT 1
FROM category_users cu
WHERE cu.category_id = ? AND cu.user_id = users.id AND cu.notification_level = ?
@ -57,7 +57,7 @@ module Jobs
end
end
rescue => e
Discourse.handle_job_exception(e, error_context(args, "Sending post to mailing list subscribers", { user_id: user.id, user_email: user.email }))
Discourse.handle_job_exception(e, error_context(args, "Sending post to mailing list subscribers", user_id: user.id, user_email: user.email))
end
end
end

View File

@ -17,8 +17,8 @@ module Jobs
p.user.notifications.create(notification_type: Notification.types[:moved_post],
topic_id: p.topic_id,
post_number: p.post_number,
data: {topic_title: p.topic.title,
display_username: moved_by.username}.to_json)
data: { topic_title: p.topic.title,
display_username: moved_by.username }.to_json)
users_notified << p.user_id
end
end

View File

@ -13,11 +13,9 @@ module Jobs
}
clients = args["clients"]
clients.group_by{|r| r[1]}.each do |push_url, group|
clients.group_by { |r| r[1] }.each do |push_url, group|
notifications = group.map do |client_id, _|
notification.merge({
client_id: client_id
})
notification.merge(client_id: client_id)
end
result = Excon.post(push_url,

View File

@ -19,5 +19,3 @@ module Jobs
end
end

View File

@ -56,7 +56,7 @@ module Jobs
quoted
}
def message_for_email(user, post, type, notification, notification_type=nil, notification_data_hash=nil, email_token=nil, to_address=nil)
def message_for_email(user, post, type, notification, notification_type = nil, notification_data_hash = nil, email_token = nil, to_address = nil)
set_skip_context(type, user.id, to_address || user.email, post.try(:id))
return skip_message(I18n.t("email_log.anonymous_user")) if user.anonymous?
@ -90,8 +90,8 @@ module Jobs
user.user_option.mailing_list_mode_frequency > 0 && # don't catch notifications for users on daily mailing list mode
(!post.try(:topic).try(:private_message?)) &&
NOTIFICATIONS_SENT_BY_MAILING_LIST.include?(email_args[:notification_type])
# no need to log a reason when the mail was already sent via the mailing list job
return [nil, nil]
# no need to log a reason when the mail was already sent via the mailing list job
return [nil, nil]
end
unless user.user_option.email_always?
@ -141,7 +141,7 @@ module Jobs
# extracted from sidekiq
def self.seconds_to_delay(count)
(count ** 4) + 15 + (rand(30) * (count + 1))
(count**4) + 15 + (rand(30) * (count + 1))
end
private

View File

@ -15,7 +15,7 @@ module Jobs
BadgeGranter.backfill(b)
rescue => ex
# TODO - expose errors in UI
Discourse.handle_job_exception(ex, error_context({}, code_desc: 'Exception granting badges', extra: {badge_id: b.id}))
Discourse.handle_job_exception(ex, error_context({}, code_desc: 'Exception granting badges', extra: { badge_id: b.id }))
end
end

View File

@ -9,8 +9,8 @@ module Jobs
threshold = SiteSetting.delete_email_logs_after_days.days.ago
EmailLog.where(reply_key: nil)
.where("created_at < ?", threshold)
.delete_all
.where("created_at < ?", threshold)
.delete_all
end
end

View File

@ -7,8 +7,8 @@ module Jobs
last_match_threshold = SiteSetting.max_age_unmatched_emails.days.ago
ScreenedEmail.where(action_type: ScreenedEmail.actions[:block])
.where("last_match_at < ?", last_match_threshold)
.destroy_all
.where("last_match_at < ?", last_match_threshold)
.destroy_all
end
end

View File

@ -11,8 +11,8 @@ module Jobs
# remove old unmatched IP addresses
ScreenedIpAddress.where(action_type: ScreenedIpAddress.actions[:block])
.where("last_match_at < ? OR (last_match_at IS NULL AND created_at < ?)", last_match_threshold, last_match_threshold)
.destroy_all
.where("last_match_at < ? OR (last_match_at IS NULL AND created_at < ?)", last_match_threshold, last_match_threshold)
.destroy_all
end
end

View File

@ -10,4 +10,3 @@ module Jobs
end
end

View File

@ -5,11 +5,11 @@ module Jobs
def execute(args)
# backfill in batches of 5000 an hour
UserAvatar.includes(:user)
.joins(:user)
.where(last_gravatar_download_attempt: nil)
.order("users.last_posted_at DESC")
.limit(5000)
.each do |u|
.joins(:user)
.where(last_gravatar_download_attempt: nil)
.order("users.last_posted_at DESC")
.limit(5000)
.each do |u|
u.user.refresh_avatar
end
end

View File

@ -7,7 +7,7 @@ module Jobs
if problems_started_at && problems_started_at < 2.days.ago
# If there have been problems reported on the dashboard for a while,
# send a message to admins no more often than once per week.
GroupMessage.create(Group[:admins].name, :dashboard_problems, {limit_once_per: 7.days.to_i})
GroupMessage.create(Group[:admins].name, :dashboard_problems, limit_once_per: 7.days.to_i)
end
AdminDashboardData.refresh_stats

View File

@ -4,7 +4,7 @@ module Jobs
def execute(args)
periods = DirectoryItem.period_types.keys - [:daily]
periods.each {|p| DirectoryItem.refresh_period!(p)}
periods.each { |p| DirectoryItem.refresh_period!(p) }
end
end
end

View File

@ -14,15 +14,15 @@ module Jobs
def target_user_ids
# Users who want to receive digest email within their chosen digest email frequency
query = User.real
.not_suspended
.activated
.where(staged: false)
.joins(:user_option, :user_stat)
.where("user_options.email_digests")
.where("user_stats.bounce_score < #{SiteSetting.bounce_score_threshold}")
.where("COALESCE(last_emailed_at, '2010-01-01') <= CURRENT_TIMESTAMP - ('1 MINUTE'::INTERVAL * user_options.digest_after_minutes)")
.where("COALESCE(last_seen_at, '2010-01-01') <= CURRENT_TIMESTAMP - ('1 MINUTE'::INTERVAL * user_options.digest_after_minutes)")
.where("COALESCE(last_seen_at, '2010-01-01') >= CURRENT_TIMESTAMP - ('1 DAY'::INTERVAL * #{SiteSetting.suppress_digest_email_after_days})")
.not_suspended
.activated
.where(staged: false)
.joins(:user_option, :user_stat)
.where("user_options.email_digests")
.where("user_stats.bounce_score < #{SiteSetting.bounce_score_threshold}")
.where("COALESCE(last_emailed_at, '2010-01-01') <= CURRENT_TIMESTAMP - ('1 MINUTE'::INTERVAL * user_options.digest_after_minutes)")
.where("COALESCE(last_seen_at, '2010-01-01') <= CURRENT_TIMESTAMP - ('1 MINUTE'::INTERVAL * user_options.digest_after_minutes)")
.where("COALESCE(last_seen_at, '2010-01-01') >= CURRENT_TIMESTAMP - ('1 DAY'::INTERVAL * #{SiteSetting.suppress_digest_email_after_days})")
# If the site requires approval, make sure the user is approved
query = query.where("approved OR moderator OR admin") if SiteSetting.must_approve_users?

View File

@ -8,7 +8,7 @@ module Jobs
def execute(args)
badge = Badge.find(Badge::NewUserOfTheMonth)
return unless SiteSetting.enable_badges? and badge.enabled?
return unless SiteSetting.enable_badges? && badge.enabled?
# Don't award it if a month hasn't gone by
return if UserBadge.where("badge_id = ? AND granted_at >= ?",
@ -22,9 +22,7 @@ module Jobs
user = User.find(user_id)
if user.badges.where(id: Badge::NewUserOfTheMonth).blank?
BadgeGranter.grant(badge, user)
SystemMessage.new(user).create('new_user_of_the_month', {
month_year: Time.now.strftime("%B %Y")
})
SystemMessage.new(user).create('new_user_of_the_month', month_year: Time.now.strftime("%B %Y"))
end
end
end
@ -75,10 +73,8 @@ module Jobs
LIMIT :max_awarded
SQL
User.exec_sql(sql, {
like: PostActionType.types[:like],
max_awarded: MAX_AWARDED
}).each do |row|
User.exec_sql(sql, like: PostActionType.types[:like],
max_awarded: MAX_AWARDED).each do |row|
scores[row['id'].to_i] = row['score'].to_f
end
scores

View File

@ -9,8 +9,8 @@ module Jobs
# clean up failed uploads
Upload.where("created_at < ?", 1.hour.ago)
.where("LENGTH(COALESCE(url, '')) = 0")
.destroy_all
.where("LENGTH(COALESCE(url, '')) = 0")
.destroy_all
# migrate uploads to new scheme
problems = Upload.migrate_to_new_scheme(50)

View File

@ -25,8 +25,8 @@ module Jobs
target_group_names: Group[:moderators].name,
archetype: Archetype.private_message,
subtype: TopicSubtype.system_message,
title: I18n.t('flags_reminder.subject_template', { count: flagged_posts_count }),
raw: mentions + I18n.t('flags_reminder.flags_were_submitted', { count: SiteSetting.notify_about_flags_after })
title: I18n.t('flags_reminder.subject_template', count: flagged_posts_count),
raw: mentions + I18n.t('flags_reminder.flags_were_submitted', count: SiteSetting.notify_about_flags_after)
)
self.last_notified_id = flag_ids.max
@ -54,10 +54,10 @@ module Jobs
def active_moderator_usernames
User.where(moderator: true)
.human_users
.order('last_seen_at DESC')
.limit(3)
.pluck(:username)
.human_users
.order('last_seen_at DESC')
.limit(3)
.pluck(:username)
end
end

View File

@ -7,7 +7,7 @@ module Jobs
def execute(args)
if SiteSetting.must_approve_users && SiteSetting.pending_users_reminder_delay >= 0
query = AdminUserIndexQuery.new({query: 'pending', stats: false}).find_users_query # default order is: users.created_at DESC
query = AdminUserIndexQuery.new(query: 'pending', stats: false).find_users_query # default order is: users.created_at DESC
if SiteSetting.pending_users_reminder_delay > 0
query = query.where('users.created_at < ?', SiteSetting.pending_users_reminder_delay.hours.ago)
end
@ -21,10 +21,10 @@ module Jobs
if count > 0
target_usernames = Group[:moderators].users.map do |u|
u.id > 0 && u.notifications.joins(:topic)
.where("notifications.id > ?", u.seen_notification_id)
.where("notifications.read = false")
.where("topics.subtype = '#{TopicSubtype.pending_users_reminder}'")
.count == 0 ? u.username : nil
.where("notifications.id > ?", u.seen_notification_id)
.where("notifications.read = false")
.where("topics.subtype = '#{TopicSubtype.pending_users_reminder}'")
.count == 0 ? u.username : nil
end.compact
unless target_usernames.empty?
@ -33,8 +33,8 @@ module Jobs
target_usernames: target_usernames,
archetype: Archetype.private_message,
subtype: TopicSubtype.pending_users_reminder,
title: I18n.t("system_messages.pending_users_reminder.subject_template", {count: count}),
raw: I18n.t("system_messages.pending_users_reminder.text_body_template", {count: count, base_url: Discourse.base_url})
title: I18n.t("system_messages.pending_users_reminder.subject_template", count: count),
raw: I18n.t("system_messages.pending_users_reminder.text_body_template", count: count, base_url: Discourse.base_url)
)
self.previous_newest_username = newest_username

View File

@ -20,7 +20,7 @@ module Jobs
CategoryFeaturedTopic.feature_topics
# Update the scores of posts
args = {min_topic_age: 1.day.ago}
args = { min_topic_age: 1.day.ago }
args[:max_topic_length] = 500 unless self.class.should_update_long_topics?
ScoreCalculator.new.calculate(args)

View File

@ -7,4 +7,3 @@ module Jobs
end
end
end

View File

@ -19,7 +19,7 @@ module Jobs
# Promotions
User.real.where(trust_level: TrustLevel[2],
trust_level_locked: false)
.where.not(id: demoted_user_ids).find_each do |u|
.where.not(id: demoted_user_ids).find_each do |u|
Promotion.new(u).review_tl2
end
end

View File

@ -6,7 +6,7 @@ module Jobs
every 1.day
def execute(args)
if SiteSetting.version_checks? and (DiscourseUpdates.updated_at.nil? or DiscourseUpdates.updated_at < 1.minute.ago)
if SiteSetting.version_checks? && (DiscourseUpdates.updated_at.nil? || DiscourseUpdates.updated_at < (1.minute.ago))
begin
prev_missing_versions_count = DiscourseUpdates.missing_versions_count || 0
@ -18,10 +18,10 @@ module Jobs
DiscourseUpdates.updated_at = Time.zone.now
DiscourseUpdates.missing_versions = json['versions']
if GlobalSetting.new_version_emails and
SiteSetting.new_version_emails and
json['missingVersionsCount'] > 0 and
prev_missing_versions_count < json['missingVersionsCount'].to_i
if GlobalSetting.new_version_emails &&
SiteSetting.new_version_emails &&
json['missingVersionsCount'] > (0) &&
prev_missing_versions_count < (json['missingVersionsCount'].to_i)
message = VersionMailer.send_notice
Email::Sender.new(message, :new_version).send

View File

@ -12,4 +12,3 @@ class AdminConfirmationMailer < ActionMailer::Base
)
end
end

View File

@ -23,14 +23,14 @@ class PendingFlagsMailer < ActionMailer::Base
@hours = SiteSetting.notify_about_flags_after
subject = "[#{SiteSetting.title}] " + I18n.t('flags_reminder.subject_template', { count: PostAction.flagged_posts_count })
subject = "[#{SiteSetting.title}] " + I18n.t('flags_reminder.subject_template', count: PostAction.flagged_posts_count)
build_email(SiteSetting.contact_email, subject: subject)
end
private
def flag_reason_counts(post)
post[:post_actions].inject({}) do |h,v|
post[:post_actions].inject({}) do |h, v|
h[v[:name_key]] ||= 0
h[v[:name_key]] += 1
h

View File

@ -3,7 +3,7 @@ require_dependency 'email/message_builder'
class PendingQueuedPostsMailer < ActionMailer::Base
include Email::BuildEmailHelper
def notify(opts={})
def notify(opts = {})
return unless SiteSetting.contact_email
build_email(SiteSetting.contact_email, template: 'queued_posts_reminder', count: opts[:count])
end

View File

@ -3,7 +3,7 @@ require_dependency 'email/message_builder'
class SubscriptionMailer < ActionMailer::Base
include Email::BuildEmailHelper
def confirm_unsubscribe(user, opts={})
def confirm_unsubscribe(user, opts = {})
unsubscribe_key = UnsubscribeKey.create_key_for(user, "all")
build_email user.email,
template: "unsubscribe_mailer",

View File

@ -11,14 +11,14 @@ class UserNotifications < ActionMailer::Base
include Email::BuildEmailHelper
def signup(user, opts={})
def signup(user, opts = {})
build_email(user.email,
template: "user_notifications.signup",
locale: user_locale(user),
email_token: opts[:email_token])
end
def signup_after_approval(user, opts={})
def signup_after_approval(user, opts = {})
build_email(user.email,
template: 'user_notifications.signup_after_approval',
locale: user_locale(user),
@ -26,42 +26,42 @@ class UserNotifications < ActionMailer::Base
new_user_tips: I18n.t('system_messages.usage_tips.text_body_template', base_url: Discourse.base_url, locale: locale))
end
def notify_old_email(user, opts={})
def notify_old_email(user, opts = {})
build_email(user.email,
template: "user_notifications.notify_old_email",
locale: user_locale(user),
new_email: opts[:new_email])
end
def confirm_old_email(user, opts={})
def confirm_old_email(user, opts = {})
build_email(user.email,
template: "user_notifications.confirm_old_email",
locale: user_locale(user),
email_token: opts[:email_token])
end
def confirm_new_email(user, opts={})
def confirm_new_email(user, opts = {})
build_email(user.email,
template: "user_notifications.confirm_new_email",
locale: user_locale(user),
email_token: opts[:email_token])
end
def forgot_password(user, opts={})
def forgot_password(user, opts = {})
build_email(user.email,
template: user.has_password? ? "user_notifications.forgot_password" : "user_notifications.set_password",
locale: user_locale(user),
email_token: opts[:email_token])
end
def admin_login(user, opts={})
def admin_login(user, opts = {})
build_email(user.email,
template: "user_notifications.admin_login",
locale: user_locale(user),
email_token: opts[:email_token])
end
def account_created(user, opts={})
def account_created(user, opts = {})
build_email(user.email,
template: "user_notifications.account_created",
locale: user_locale(user),
@ -76,30 +76,30 @@ class UserNotifications < ActionMailer::Base
end
end
def digest(user, opts={})
def digest(user, opts = {})
build_summary_for(user)
min_date = opts[:since] || user.last_emailed_at || user.last_seen_at || 1.month.ago
# Fetch some topics and posts to show
digest_opts = {limit: SiteSetting.digest_topics + SiteSetting.digest_other_topics, top_order: true}
digest_opts = { limit: SiteSetting.digest_topics + SiteSetting.digest_other_topics, top_order: true }
topics_for_digest = Topic.for_digest(user, min_date, digest_opts).to_a
if topics_for_digest.empty? && !user.user_option.try(:include_tl0_in_digests)
# Find some topics from new users that are at least 24 hours old
topics_for_digest = Topic.for_digest(user, min_date, digest_opts.merge(include_tl0: true)).where('topics.created_at < ?', 24.hours.ago).to_a
end
@popular_topics = topics_for_digest[0,SiteSetting.digest_topics]
@popular_topics = topics_for_digest[0, SiteSetting.digest_topics]
if @popular_topics.present?
@other_new_for_you = topics_for_digest.size > SiteSetting.digest_topics ? topics_for_digest[SiteSetting.digest_topics..-1] : []
@popular_posts = if SiteSetting.digest_posts > 0
Post.order("posts.score DESC")
.for_mailing_list(user, min_date)
.where('posts.post_type = ?', Post.types[:regular])
.where('posts.deleted_at IS NULL AND posts.hidden = false AND posts.user_deleted = false')
.where("posts.post_number > ? AND posts.score > ?", 1, ScoreCalculator.default_score_weights[:like_score] * 5.0)
.limit(SiteSetting.digest_posts)
.for_mailing_list(user, min_date)
.where('posts.post_type = ?', Post.types[:regular])
.where('posts.deleted_at IS NULL AND posts.hidden = false AND posts.user_deleted = false')
.where("posts.post_number > ? AND posts.score > ?", 1, ScoreCalculator.default_score_weights[:like_score] * 5.0)
.limit(SiteSetting.digest_posts)
else
[]
end
@ -117,19 +117,19 @@ class UserNotifications < ActionMailer::Base
# We used topics from new users instead, so count should match
new_topics_count = topics_for_digest.size
end
@counts = [{label_key: 'user_notifications.digest.new_topics',
value: new_topics_count,
href: "#{Discourse.base_url}/new"}]
@counts = [{ label_key: 'user_notifications.digest.new_topics',
value: new_topics_count,
href: "#{Discourse.base_url}/new" }]
value = user.unread_notifications
@counts << {label_key: 'user_notifications.digest.unread_notifications', value: value, href: "#{Discourse.base_url}/my/notifications"} if value > 0
@counts << { label_key: 'user_notifications.digest.unread_notifications', value: value, href: "#{Discourse.base_url}/my/notifications" } if value > 0
value = user.unread_private_messages
@counts << {label_key: 'user_notifications.digest.unread_messages', value: value, href: "#{Discourse.base_url}/my/messages"} if value > 0
@counts << { label_key: 'user_notifications.digest.unread_messages', value: value, href: "#{Discourse.base_url}/my/messages" } if value > 0
if @counts.size < 3
value = user.unread_notifications_of_type(Notification.types[:liked])
@counts << {label_key: 'user_notifications.digest.liked_received', value: value, href: "#{Discourse.base_url}/my/notifications"} if value > 0
@counts << { label_key: 'user_notifications.digest.liked_received', value: value, href: "#{Discourse.base_url}/my/notifications" } if value > 0
end
if @counts.size < 3
@ -157,7 +157,6 @@ class UserNotifications < ActionMailer::Base
end
end
def user_replied(user, opts)
opts[:allow_reply_by_email] = true
opts[:use_site_subject] = true
@ -252,7 +251,7 @@ class UserNotifications < ActionMailer::Base
(user.locale.present? && I18n.available_locales.include?(user.locale.to_sym)) ? user.locale : nil
end
def email_post_markdown(post, add_posted_by=false)
def email_post_markdown(post, add_posted_by = false)
result = "#{post.raw}\n\n"
if add_posted_by
result << "#{I18n.t('user_notifications.posted_by', username: post.username, post_date: post.created_at.strftime("%m/%d/%Y"))}\n\n"
@ -275,12 +274,12 @@ class UserNotifications < ActionMailer::Base
allowed_post_types << Post.types[:whisper] if topic_user.try(:user).try(:staff?)
context_posts = Post.where(topic_id: post.topic_id)
.where("post_number < ?", post.post_number)
.where(user_deleted: false)
.where(hidden: false)
.where(post_type: allowed_post_types)
.order('created_at desc')
.limit(SiteSetting.email_posts_context)
.where("post_number < ?", post.post_number)
.where(user_deleted: false)
.where(hidden: false)
.where(post_type: allowed_post_types)
.order('created_at desc')
.limit(SiteSetting.email_posts_context)
if topic_user && topic_user.last_emailed_post_number && user.user_option.email_previous_replies == UserOption.previous_replies_type[:unless_emailed]
context_posts = context_posts.where("post_number > ?", topic_user.last_emailed_post_number)
@ -429,7 +428,7 @@ class UserNotifications < ActionMailer::Base
reached_limit = SiteSetting.max_emails_per_day_per_user > 0
reached_limit &&= (EmailLog.where(user_id: user.id, skipped: false)
.where('created_at > ?', 1.day.ago)
.count) >= (SiteSetting.max_emails_per_day_per_user-1)
.count) >= (SiteSetting.max_emails_per_day_per_user - 1)
in_reply_to_post = post.reply_to_post if user.user_option.email_in_reply_to
if SiteSetting.private_email?
@ -438,7 +437,6 @@ class UserNotifications < ActionMailer::Base
message = email_post_markdown(post) + (reached_limit ? "\n\n#{I18n.t "user_notifications.reached_limit", count: SiteSetting.max_emails_per_day_per_user}" : "");
end
unless translation_override_exists
html = UserNotificationRenderer.new(Rails.configuration.paths["app/views"]).render(
template: 'email/notification',

View File

@ -6,17 +6,17 @@ class VersionMailer < ActionMailer::Base
def send_notice
if SiteSetting.contact_email.present?
missing_versions = DiscourseUpdates.missing_versions
if missing_versions.present? and missing_versions.first['notes'].present?
build_email( SiteSetting.contact_email,
if missing_versions.present? && missing_versions.first['notes'].present?
build_email(SiteSetting.contact_email,
template: 'new_version_mailer_with_notes',
notes: missing_versions.first['notes'],
new_version: DiscourseUpdates.latest_version,
installed_version: Discourse::VERSION::STRING )
installed_version: Discourse::VERSION::STRING)
else
build_email( SiteSetting.contact_email,
build_email(SiteSetting.contact_email,
template: 'new_version_mailer',
new_version: DiscourseUpdates.latest_version,
installed_version: Discourse::VERSION::STRING )
installed_version: Discourse::VERSION::STRING)
end
end
end

View File

@ -35,8 +35,8 @@ class About
def moderators
@moderators ||= User.where(moderator: true, admin: false)
.human_users
.order(:username_lower)
.human_users
.order(:username_lower)
end
def admins

View File

@ -31,7 +31,7 @@ class AdminDashboardData
USER_REPORTS ||= ['users_by_trust_level']
MOBILE_REPORTS ||= ['mobile_visits'] + ApplicationRequest.req_types.keys.select {|r| r =~ /mobile/}.map { |r| r + "_reqs" }
MOBILE_REPORTS ||= ['mobile_visits'] + ApplicationRequest.req_types.keys.select { |r| r =~ /mobile/ }.map { |r| r + "_reqs" }
def self.add_problem_check(*syms, &blk)
@problem_syms.push(*syms) if syms
@ -120,7 +120,7 @@ class AdminDashboardData
$redis.get(problem_message_key(i18n_key)) ? I18n.t(i18n_key) : nil
end
def self.add_problem_message(i18n_key, expire_seconds=nil)
def self.add_problem_message(i18n_key, expire_seconds = nil)
if expire_seconds.to_i > 0
$redis.setex problem_message_key(i18n_key), expire_seconds.to_i, 1
else

View File

@ -19,7 +19,7 @@ class ApplicationRequest < ActiveRecord::Base
self.autoflush_seconds = 5.minutes
self.last_flush = Time.now.utc
def self.increment!(type, opts=nil)
def self.increment!(type, opts = nil)
key = redis_key(type)
val = $redis.incr(key).to_i
# 3.days, see: https://github.com/rails/rails/issues/21296
@ -36,7 +36,7 @@ class ApplicationRequest < ActiveRecord::Base
end
end
def self.write_cache!(date=nil)
def self.write_cache!(date = nil)
if date.nil?
write_cache!(Time.now.utc)
write_cache!(Time.now.utc.yesterday)
@ -49,8 +49,8 @@ class ApplicationRequest < ActiveRecord::Base
# this may seem a bit fancy but in so it allows
# for concurrent calls without double counting
req_types.each do |req_type,_|
key = redis_key(req_type,date)
req_types.each do |req_type, _|
key = redis_key(req_type, date)
val = $redis.get(key).to_i
next if val == 0
@ -63,28 +63,28 @@ class ApplicationRequest < ActiveRecord::Base
next
end
id = req_id(date,req_type)
id = req_id(date, req_type)
where(id: id).update_all(["count = count + ?", val])
end
end
def self.clear_cache!(date=nil)
def self.clear_cache!(date = nil)
if date.nil?
clear_cache!(Time.now.utc)
clear_cache!(Time.now.utc.yesterday)
return
end
req_types.each do |req_type,_|
key = redis_key(req_type,date)
req_types.each do |req_type, _|
key = redis_key(req_type, date)
$redis.del key
end
end
protected
def self.req_id(date,req_type,retries=0)
def self.req_id(date, req_type, retries = 0)
req_type_id = req_types[req_type]
@ -94,13 +94,13 @@ class ApplicationRequest < ActiveRecord::Base
rescue # primary key violation
if retries == 0
req_id(date,req_type,1)
req_id(date, req_type, 1)
else
raise
end
end
def self.redis_key(req_type, time=Time.now.utc)
def self.redis_key(req_type, time = Time.now.utc)
"app_req_#{req_type}#{time.strftime('%Y%m%d')}"
end

View File

@ -10,9 +10,9 @@ class Backup
def self.all
Dir.glob(File.join(Backup.base_directory, "*.{gz,tgz}"))
.sort_by { |file| File.mtime(file) }
.reverse
.map { |backup| Backup.create_from_filename(File.basename(backup)) }
.sort_by { |file| File.mtime(file) }
.reverse
.map { |backup| Backup.create_from_filename(File.basename(backup)) }
end
def self.[](filename)

View File

@ -63,7 +63,7 @@ class Badge < ActiveRecord::Base
def self.trigger_hash
Hash[*(
Badge::Trigger.constants.map{|k|
Badge::Trigger.constants.map { |k|
[k.to_s.underscore, Badge::Trigger.const_get(k)]
}.flatten
)]
@ -100,7 +100,7 @@ class Badge < ActiveRecord::Base
validates :allow_title, inclusion: [true, false]
validates :multiple_grant, inclusion: [true, false]
scope :enabled, ->{ where(enabled: true) }
scope :enabled, -> { where(enabled: true) }
before_create :ensure_not_system
@ -208,7 +208,6 @@ class Badge < ActiveRecord::Base
val
end
def slug
Slug.for(self.display_name, '-')
end

Some files were not shown because too many files have changed in this diff Show More