Kill trailing whitespace in ruby files

This commit is contained in:
小太
2013-03-19 23:10:10 +11:00
parent c107f96cec
commit cba839ba76
319 changed files with 2710 additions and 2710 deletions

View File

@@ -1,10 +1,10 @@
module Admin module Admin
class AliasAndImplicationImportsController < ApplicationController class AliasAndImplicationImportsController < ApplicationController
before_filter :admin_only before_filter :admin_only
def new def new
end end
def create def create
@importer = AliasAndImplicationImporter.new(params[:batch][:text], params[:batch][:forum_id]) @importer = AliasAndImplicationImporter.new(params[:batch][:text], params[:batch][:forum_id])
@importer.process! @importer.process!

View File

@@ -1,11 +1,11 @@
module Admin module Admin
class UsersController < ApplicationController class UsersController < ApplicationController
before_filter :moderator_only before_filter :moderator_only
def edit def edit
@user = User.find(params[:id]) @user = User.find(params[:id])
end end
def update def update
@user = User.find(params[:id]) @user = User.find(params[:id])
@user.level = params[:user][:level] @user.level = params[:user][:level]

View File

@@ -8,5 +8,5 @@ class AdvertisementHitsController < ApplicationController
protected protected
def set_title def set_title
@page_title = Danbooru.config.app_name + "/advertisements" @page_title = Danbooru.config.app_name + "/advertisements"
end end
end end

View File

@@ -1,27 +1,27 @@
class AdvertisementsController < ApplicationController class AdvertisementsController < ApplicationController
before_filter :advertiser_only before_filter :advertiser_only
def new def new
@advertisement = Advertisement.new( @advertisement = Advertisement.new(
:ad_type => "vertical", :ad_type => "vertical",
:status => "active" :status => "active"
) )
end end
def edit def edit
@advertisement = Advertisement.find(params[:id]) @advertisement = Advertisement.find(params[:id])
end end
def index def index
@advertisements = Advertisement.order("id desc").all @advertisements = Advertisement.order("id desc").all
@start_date = 1.month.ago.to_date @start_date = 1.month.ago.to_date
@end_date = Date.today @end_date = Date.today
end end
def show def show
@advertisement = Advertisement.find(params[:id]) @advertisement = Advertisement.find(params[:id])
end end
def create def create
@advertisement = Advertisement.new(params[:advertisement]) @advertisement = Advertisement.new(params[:advertisement])
if @advertisement.save if @advertisement.save
@@ -31,7 +31,7 @@ class AdvertisementsController < ApplicationController
render :action => "new" render :action => "new"
end end
end end
def update def update
@advertisement = Advertisement.find(params[:id]) @advertisement = Advertisement.find(params[:id])
if @advertisement.update_attributes(params[:advertisement]) if @advertisement.update_attributes(params[:advertisement])
@@ -41,13 +41,13 @@ class AdvertisementsController < ApplicationController
render :action => "edit" render :action => "edit"
end end
end end
def destroy def destroy
@advertisement = Advertisement.find(params[:id]) @advertisement = Advertisement.find(params[:id])
@advertisement.destroy @advertisement.destroy
redirect_to advertisements_path, :notice => "Advertisement destroyed" redirect_to advertisements_path, :notice => "Advertisement destroyed"
end end
private private
def advertiser_only def advertiser_only
if !Danbooru.config.is_user_advertiser?(CurrentUser.user) if !Danbooru.config.is_user_advertiser?(CurrentUser.user)

View File

@@ -6,14 +6,14 @@ class ApplicationController < ActionController::Base
before_filter :set_title before_filter :set_title
before_filter :set_started_at_session before_filter :set_started_at_session
layout "default" layout "default"
rescue_from User::PrivilegeError, :with => :access_denied rescue_from User::PrivilegeError, :with => :access_denied
rescue_from Danbooru::Paginator::PaginationError, :with => :render_pagination_limit rescue_from Danbooru::Paginator::PaginationError, :with => :render_pagination_limit
protected protected
def rescue_exception(exception) def rescue_exception(exception)
@exception = exception @exception = exception
if exception.is_a?(::ActiveRecord::StatementInvalid) && exception.to_s =~ /statement timeout/ if exception.is_a?(::ActiveRecord::StatementInvalid) && exception.to_s =~ /statement timeout/
@exception = nil @exception = nil
@error_message = "The database timed out running your query." @error_message = "The database timed out running your query."
@@ -26,17 +26,17 @@ protected
render :template => "static/error", :status => 500 render :template => "static/error", :status => 500
end end
end end
def render_pagination_limit def render_pagination_limit
@error_message = "You can only view up to #{Danbooru.config.max_numbered_pages} pages. Please narrow your search terms." @error_message = "You can only view up to #{Danbooru.config.max_numbered_pages} pages. Please narrow your search terms."
render :template => "static/error", :status => 410 render :template => "static/error", :status => 410
end end
def access_denied def access_denied
previous_url = params[:url] || request.fullpath previous_url = params[:url] || request.fullpath
respond_to do |fmt| respond_to do |fmt|
fmt.html do fmt.html do
if request.get? if request.get?
redirect_to new_session_path(:url => previous_url), :notice => "Access denied" redirect_to new_session_path(:url => previous_url), :notice => "Access denied"
else else
@@ -56,18 +56,18 @@ protected
session_loader = SessionLoader.new(session, cookies, request) session_loader = SessionLoader.new(session, cookies, request)
session_loader.load session_loader.load
end end
def reset_current_user def reset_current_user
CurrentUser.user = nil CurrentUser.user = nil
CurrentUser.ip_addr = nil CurrentUser.ip_addr = nil
end end
def set_started_at_session def set_started_at_session
if session[:started_at].blank? if session[:started_at].blank?
session[:started_at] = Time.now session[:started_at] = Time.now
end end
end end
%w(member banned privileged platinum contributor janitor moderator admin).each do |level| %w(member banned privileged platinum contributor janitor moderator admin).each do |level|
define_method("#{level}_only") do define_method("#{level}_only") do
if CurrentUser.user.__send__("is_#{level}?") if CurrentUser.user.__send__("is_#{level}?")
@@ -78,7 +78,7 @@ protected
end end
end end
end end
def set_title def set_title
@page_title = Danbooru.config.app_name + "/#{params[:controller]}" @page_title = Danbooru.config.app_name + "/#{params[:controller]}"
end end

View File

@@ -2,28 +2,28 @@ class ArtistsController < ApplicationController
respond_to :html, :xml, :json respond_to :html, :xml, :json
before_filter :member_only, :except => [:index, :show, :banned] before_filter :member_only, :except => [:index, :show, :banned]
before_filter :admin_only, :only => [:ban] before_filter :admin_only, :only => [:ban]
def new def new
@artist = Artist.new_with_defaults(params) @artist = Artist.new_with_defaults(params)
respond_with(@artist) respond_with(@artist)
end end
def edit def edit
@artist = Artist.find(params[:id]) @artist = Artist.find(params[:id])
respond_with(@artist) respond_with(@artist)
end end
def banned def banned
@artists = Artist.where("is_banned = ?", true).order("name") @artists = Artist.where("is_banned = ?", true).order("name")
respond_with(@artists) respond_with(@artists)
end end
def ban def ban
@artist = Artist.find(params[:id]) @artist = Artist.find(params[:id])
@artist.ban! @artist.ban!
redirect_to(artist_path(@artist), :notice => "Artist was banned") redirect_to(artist_path(@artist), :notice => "Artist was banned")
end end
def index def index
@artists = Artist.search(params[:search] || params).order("id desc").paginate(params[:page]) @artists = Artist.search(params[:search] || params).order("id desc").paginate(params[:page])
respond_with(@artists) do |format| respond_with(@artists) do |format|
@@ -35,34 +35,34 @@ class ArtistsController < ApplicationController
end end
end end
end end
def search def search
end end
def show def show
@artist = Artist.find(params[:id]) @artist = Artist.find(params[:id])
@post_set = PostSets::Artist.new(@artist) @post_set = PostSets::Artist.new(@artist)
respond_with(@artist) respond_with(@artist)
end end
def create def create
@artist = Artist.create(params[:artist], :as => CurrentUser.role) @artist = Artist.create(params[:artist], :as => CurrentUser.role)
respond_with(@artist) respond_with(@artist)
end end
def update def update
@artist = Artist.find(params[:id]) @artist = Artist.find(params[:id])
@artist.update_attributes(params[:artist], :as => CurrentUser.role) @artist.update_attributes(params[:artist], :as => CurrentUser.role)
respond_with(@artist) respond_with(@artist)
end end
def revert def revert
@artist = Artist.find(params[:id]) @artist = Artist.find(params[:id])
@version = ArtistVersion.find(params[:version_id]) @version = ArtistVersion.find(params[:version_id])
@artist.revert_to!(@version) @artist.revert_to!(@version)
respond_with(@artist) respond_with(@artist)
end end
def show_or_new def show_or_new
@artist = Artist.find_by_name(params[:name]) @artist = Artist.find_by_name(params[:name])
if @artist if @artist

View File

@@ -1,33 +1,33 @@
class BansController < ApplicationController class BansController < ApplicationController
before_filter :moderator_only, :except => [:show, :index] before_filter :moderator_only, :except => [:show, :index]
def new def new
@ban = Ban.new @ban = Ban.new
end end
def edit def edit
@ban = Ban.find(params[:id]) @ban = Ban.find(params[:id])
end end
def index def index
@search = Ban.search(params[:search]).order("id desc") @search = Ban.search(params[:search]).order("id desc")
@bans = @search.paginate(params[:page]) @bans = @search.paginate(params[:page])
end end
def show def show
@ban = Ban.find(params[:id]) @ban = Ban.find(params[:id])
end end
def create def create
@ban = Ban.create(params[:ban]) @ban = Ban.create(params[:ban])
if @ban.errors.any? if @ban.errors.any?
render :action => "new" render :action => "new"
else else
redirect_to ban_path(@ban), :notice => "Ban created" redirect_to ban_path(@ban), :notice => "Ban created"
end end
end end
def update def update
@ban = Ban.find(params[:id]) @ban = Ban.find(params[:id])
if @ban.update_attributes(params[:ban]) if @ban.update_attributes(params[:ban])
@@ -35,8 +35,8 @@ class BansController < ApplicationController
else else
render :action => "edit" render :action => "edit"
end end
end end
def destroy def destroy
@ban = Ban.find(params[:id]) @ban = Ban.find(params[:id])
@ban.destroy @ban.destroy

View File

@@ -1,7 +1,7 @@
class CommentVotesController < ApplicationController class CommentVotesController < ApplicationController
respond_to :js respond_to :js
before_filter :member_only before_filter :member_only
def create def create
@comment = Comment.find(params[:comment_id]) @comment = Comment.find(params[:comment_id])
@comment_vote = @comment.vote!(params[:score]) @comment_vote = @comment.vote!(params[:score])

View File

@@ -3,7 +3,7 @@ class CommentsController < ApplicationController
before_filter :member_only, :only => [:update, :create, :edit, :destroy] before_filter :member_only, :only => [:update, :create, :edit, :destroy]
rescue_from User::PrivilegeError, :with => "static/access_denied" rescue_from User::PrivilegeError, :with => "static/access_denied"
rescue_from ActiveRecord::StatementInvalid, :with => :search_error rescue_from ActiveRecord::StatementInvalid, :with => :search_error
def index def index
if params[:group_by] == "comment" if params[:group_by] == "comment"
index_by_comment index_by_comment
@@ -13,21 +13,21 @@ class CommentsController < ApplicationController
index_by_post index_by_post
end end
end end
def search def search
end end
def new def new
redirect_to comments_path redirect_to comments_path
end end
def update def update
@comment = Comment.find(params[:id]) @comment = Comment.find(params[:id])
check_privilege(@comment) check_privilege(@comment)
@comment.update_attributes(params[:comment]) @comment.update_attributes(params[:comment])
respond_with(@comment, :location => post_path(@comment.post_id)) respond_with(@comment, :location => post_path(@comment.post_id))
end end
def create def create
@comment = Comment.create(params[:comment]) @comment = Comment.create(params[:comment])
respond_with(@comment) do |format| respond_with(@comment) do |format|
@@ -40,20 +40,20 @@ class CommentsController < ApplicationController
end end
end end
end end
def edit def edit
@comment = Comment.find(params[:id]) @comment = Comment.find(params[:id])
check_privilege(@comment) check_privilege(@comment)
respond_with(@comment) respond_with(@comment)
end end
def show def show
@comment = Comment.find(params[:id]) @comment = Comment.find(params[:id])
respond_with(@comment) do |format| respond_with(@comment) do |format|
format.json {render :json => @comment.to_json(:methods => [:creator_name])} format.json {render :json => @comment.to_json(:methods => [:creator_name])}
end end
end end
def destroy def destroy
@comment = Comment.find(params[:id]) @comment = Comment.find(params[:id])
check_privilege(@comment) check_privilege(@comment)
@@ -62,7 +62,7 @@ class CommentsController < ApplicationController
format.js format.js
end end
end end
private private
def index_for_post def index_for_post
@post = Post.find(params[:post_id]) @post = Post.find(params[:post_id])
@@ -78,14 +78,14 @@ private
format.html {render :action => "index_by_post"} format.html {render :action => "index_by_post"}
end end
end end
def index_by_comment def index_by_comment
@comments = Comment.search(params[:search]).order("comments.id DESC").paginate(params[:page], :search_count => params[:search]) @comments = Comment.search(params[:search]).order("comments.id DESC").paginate(params[:page], :search_count => params[:search])
respond_with(@comments) do |format| respond_with(@comments) do |format|
format.html {render :action => "index_by_comment"} format.html {render :action => "index_by_comment"}
end end
end end
def check_privilege(comment) def check_privilege(comment)
if !comment.editable_by?(CurrentUser.user) if !comment.editable_by?(CurrentUser.user)
raise User::PrivilegeError raise User::PrivilegeError
@@ -93,7 +93,7 @@ private
end end
protected protected
def search_error(e) def search_error(e)
if e.message =~ /syntax error in tsquery/ if e.message =~ /syntax error in tsquery/
@error_message = "Meta-tags are not supported in comment searches by tag" @error_message = "Meta-tags are not supported in comment searches by tag"

View File

@@ -9,19 +9,19 @@ class DmailsController < ApplicationController
else else
@dmail = Dmail.new(params[:dmail]) @dmail = Dmail.new(params[:dmail])
end end
respond_with(@dmail) respond_with(@dmail)
end end
def index def index
@search = Dmail.visible.search(params[:search]) @search = Dmail.visible.search(params[:search])
@dmails = @search.order("dmails.created_at desc").paginate(params[:page]) @dmails = @search.order("dmails.created_at desc").paginate(params[:page])
respond_with(@dmails) respond_with(@dmails)
end end
def search def search
end end
def show def show
@dmail = Dmail.find(params[:id]) @dmail = Dmail.find(params[:id])
check_privilege(@dmail) check_privilege(@dmail)
@@ -33,20 +33,20 @@ class DmailsController < ApplicationController
@dmail = Dmail.create_split(params[:dmail]) @dmail = Dmail.create_split(params[:dmail])
respond_with(@dmail) respond_with(@dmail)
end end
def destroy def destroy
@dmail = Dmail.find(params[:id]) @dmail = Dmail.find(params[:id])
check_privilege(@dmail) check_privilege(@dmail)
@dmail.destroy @dmail.destroy
redirect_to dmails_path, :notice => "Message destroyed" redirect_to dmails_path, :notice => "Message destroyed"
end end
def mark_all_as_read def mark_all_as_read
Dmail.visible.unread.each do |x| Dmail.visible.unread.each do |x|
x.update_column(:is_read, true) x.update_column(:is_read, true)
end end
end end
private private
def check_privilege(dmail) def check_privilege(dmail)
if !dmail.visible_to?(CurrentUser.user) if !dmail.visible_to?(CurrentUser.user)

View File

@@ -1,7 +1,7 @@
module Explore module Explore
class PostsController < ApplicationController class PostsController < ApplicationController
respond_to :html, :xml, :json respond_to :html, :xml, :json
def popular def popular
@post_set = PostSets::Popular.new(params[:date], params[:scale]) @post_set = PostSets::Popular.new(params[:date], params[:scale])
@posts = @post_set.posts @posts = @post_set.posts

View File

@@ -1,6 +1,6 @@
class FavoritesController < ApplicationController class FavoritesController < ApplicationController
before_filter :member_only before_filter :member_only
def index def index
if params[:tags] if params[:tags]
redirect_to(posts_path(:tags => params[:tags])) redirect_to(posts_path(:tags => params[:tags]))
@@ -8,7 +8,7 @@ class FavoritesController < ApplicationController
@favorite_set = PostSets::Favorite.new(CurrentUser.user, params[:page]) @favorite_set = PostSets::Favorite.new(CurrentUser.user, params[:page])
end end
end end
def create def create
if CurrentUser.favorite_limit.nil? || CurrentUser.favorite_count < CurrentUser.favorite_limit if CurrentUser.favorite_limit.nil? || CurrentUser.favorite_count < CurrentUser.favorite_limit
@post = Post.find(params[:post_id]) @post = Post.find(params[:post_id])
@@ -17,7 +17,7 @@ class FavoritesController < ApplicationController
@error_msg = "You can only keep up to #{CurrentUser.favorite_limit} favorites. Upgrade your account to save more." @error_msg = "You can only keep up to #{CurrentUser.favorite_limit} favorites. Upgrade your account to save more."
end end
end end
def destroy def destroy
@post = Post.find(params[:id]) @post = Post.find(params[:id])
@post.remove_favorite!(CurrentUser.user) @post.remove_favorite!(CurrentUser.user)

View File

@@ -8,19 +8,19 @@ class ForumPostsController < ApplicationController
@forum_post = ForumPost.new_reply(params) @forum_post = ForumPost.new_reply(params)
respond_with(@forum_post) respond_with(@forum_post)
end end
def edit def edit
@forum_post = ForumPost.find(params[:id]) @forum_post = ForumPost.find(params[:id])
check_privilege(@forum_post) check_privilege(@forum_post)
respond_with(@forum_post) respond_with(@forum_post)
end end
def index def index
@search = ForumPost.active.search(params[:search]) @search = ForumPost.active.search(params[:search])
@forum_posts = @search.order("forum_posts.id DESC").paginate(params[:page], :search_count => params[:search]) @forum_posts = @search.order("forum_posts.id DESC").paginate(params[:page], :search_count => params[:search])
respond_with(@forum_posts) respond_with(@forum_posts)
end end
def search def search
end end
@@ -32,33 +32,33 @@ class ForumPostsController < ApplicationController
respond_with(@forum_post) respond_with(@forum_post)
end end
end end
def create def create
@forum_post = ForumPost.create(params[:forum_post]) @forum_post = ForumPost.create(params[:forum_post])
respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.topic.last_page)) respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.topic.last_page))
end end
def update def update
@forum_post = ForumPost.find(params[:id]) @forum_post = ForumPost.find(params[:id])
check_privilege(@forum_post) check_privilege(@forum_post)
@forum_post.update_attributes(params[:forum_post]) @forum_post.update_attributes(params[:forum_post])
respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.forum_topic_page)) respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.forum_topic_page))
end end
def destroy def destroy
@forum_post = ForumPost.find(params[:id]) @forum_post = ForumPost.find(params[:id])
raise User::PrivilegeError unless @forum_post.editable_by?(CurrentUser.user) raise User::PrivilegeError unless @forum_post.editable_by?(CurrentUser.user)
@forum_post.update_attribute(:is_deleted, true) @forum_post.update_attribute(:is_deleted, true)
respond_with(@forum_post) respond_with(@forum_post)
end end
def undelete def undelete
@forum_post = ForumPost.find(params[:id]) @forum_post = ForumPost.find(params[:id])
check_privilege(@forum_post) check_privilege(@forum_post)
@forum_post.update_attribute(:is_deleted, false) @forum_post.update_attribute(:is_deleted, false)
respond_with(@forum_post) respond_with(@forum_post)
end end
private private
def check_privilege(forum_post) def check_privilege(forum_post)
if !forum_post.editable_by?(CurrentUser.user) if !forum_post.editable_by?(CurrentUser.user)

View File

@@ -10,45 +10,45 @@ class ForumTopicsController < ApplicationController
@forum_topic.original_post = ForumPost.new @forum_topic.original_post = ForumPost.new
respond_with(@forum_topic) respond_with(@forum_topic)
end end
def edit def edit
@forum_topic = ForumTopic.find(params[:id]) @forum_topic = ForumTopic.find(params[:id])
check_privilege(@forum_topic) check_privilege(@forum_topic)
respond_with(@forum_topic) respond_with(@forum_topic)
end end
def index def index
@search = ForumTopic.active.search(params[:search]) @search = ForumTopic.active.search(params[:search])
@forum_topics = @search.order("is_sticky DESC, updated_at DESC").paginate(params[:page], :search_count => params[:search]) @forum_topics = @search.order("is_sticky DESC, updated_at DESC").paginate(params[:page], :search_count => params[:search])
respond_with(@forum_topics) respond_with(@forum_topics)
end end
def show def show
@forum_topic = ForumTopic.find(params[:id]) @forum_topic = ForumTopic.find(params[:id])
@forum_posts = ForumPost.search(:topic_id => @forum_topic.id).order("forum_posts.id").paginate(params[:page]) @forum_posts = ForumPost.search(:topic_id => @forum_topic.id).order("forum_posts.id").paginate(params[:page])
@forum_posts.all @forum_posts.all
respond_with(@forum_topic) respond_with(@forum_topic)
end end
def create def create
@forum_topic = ForumTopic.create(params[:forum_topic], :as => CurrentUser.role) @forum_topic = ForumTopic.create(params[:forum_topic], :as => CurrentUser.role)
respond_with(@forum_topic) respond_with(@forum_topic)
end end
def update def update
@forum_topic = ForumTopic.find(params[:id]) @forum_topic = ForumTopic.find(params[:id])
check_privilege(@forum_topic) check_privilege(@forum_topic)
@forum_topic.update_attributes(params[:forum_topic], :as => CurrentUser.role) @forum_topic.update_attributes(params[:forum_topic], :as => CurrentUser.role)
respond_with(@forum_topic) respond_with(@forum_topic)
end end
def destroy def destroy
@forum_topic = ForumTopic.find(params[:id]) @forum_topic = ForumTopic.find(params[:id])
check_privilege(@forum_topic) check_privilege(@forum_topic)
@forum_topic.update_attribute(:is_deleted, true) @forum_topic.update_attribute(:is_deleted, true)
respond_with(@forum_topic) respond_with(@forum_topic)
end end
def undelete def undelete
@forum_topic = ForumTopic.find(params[:id]) @forum_topic = ForumTopic.find(params[:id])
check_privilege(@forum_topic) check_privilege(@forum_topic)
@@ -64,18 +64,18 @@ class ForumTopicsController < ApplicationController
private private
def update_last_forum_read_at def update_last_forum_read_at
return if CurrentUser.is_anonymous? return if CurrentUser.is_anonymous?
if CurrentUser.last_forum_read_at.nil? || CurrentUser.last_forum_read_at < @forum_topic.updated_at if CurrentUser.last_forum_read_at.nil? || CurrentUser.last_forum_read_at < @forum_topic.updated_at
CurrentUser.update_column(:last_forum_read_at, @forum_topic.updated_at) CurrentUser.update_column(:last_forum_read_at, @forum_topic.updated_at)
end end
end end
def normalize_search def normalize_search
if params[:title_matches] if params[:title_matches]
params[:search] ||= {} params[:search] ||= {}
params[:search][:title_matches] = params.delete(:title_matches) params[:search][:title_matches] = params.delete(:title_matches)
end end
if params[:title] if params[:title]
params[:search] ||= {} params[:search] ||= {}
params[:search][:title] = params.delete(:title) params[:search][:title] = params.delete(:title)

View File

@@ -14,12 +14,12 @@ class IpBansController < ApplicationController
redirect_to ip_bans_path redirect_to ip_bans_path
end end
end end
def index def index
@search = IpBan.search(params[:search]) @search = IpBan.search(params[:search])
@ip_bans = @search.order("id desc").paginate(params[:page]) @ip_bans = @search.order("id desc").paginate(params[:page])
end end
def destroy def destroy
@ip_ban = IpBan.find(params[:id]) @ip_ban = IpBan.find(params[:id])
@ip_ban.destroy @ip_ban.destroy

View File

@@ -1,28 +1,28 @@
class JanitorTrialsController < ApplicationController class JanitorTrialsController < ApplicationController
respond_to :html, :xml, :json respond_to :html, :xml, :json
before_filter :moderator_only, :only => [:create, :promote, :demote] before_filter :moderator_only, :only => [:create, :promote, :demote]
def new def new
@janitor_trial = JanitorTrial.new @janitor_trial = JanitorTrial.new
respond_with(@janitor_trial) respond_with(@janitor_trial)
end end
def edit def edit
@janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial = JanitorTrial.find(params[:id])
respond_with(@janitor_trial) respond_with(@janitor_trial)
end end
def index def index
@search = JanitorTrial.search(params[:search]) @search = JanitorTrial.search(params[:search])
@janitor_trials = @search.order("id desc").paginate(params[:page]) @janitor_trials = @search.order("id desc").paginate(params[:page])
respond_with(@janitor_trials) respond_with(@janitor_trials)
end end
def create def create
@janitor_trial = JanitorTrial.create(params[:janitor_trial]) @janitor_trial = JanitorTrial.create(params[:janitor_trial])
respond_with(@janitor_trial, :location => janitor_trials_path) respond_with(@janitor_trial, :location => janitor_trials_path)
end end
def promote def promote
@janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial = JanitorTrial.find(params[:id])
@janitor_trial.promote! @janitor_trial.promote!
@@ -30,7 +30,7 @@ class JanitorTrialsController < ApplicationController
format.js format.js
end end
end end
def demote def demote
@janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial = JanitorTrial.find(params[:id])
@janitor_trial.demote! @janitor_trial.demote!
@@ -38,7 +38,7 @@ class JanitorTrialsController < ApplicationController
format.js format.js
end end
end end
def test def test
@tester = JanitorTrialTester.new(params[:janitor_trial][:user_name]) @tester = JanitorTrialTester.new(params[:janitor_trial][:user_name])
end end

View File

@@ -6,7 +6,7 @@ class LegacyController < ApplicationController
@post_set = PostSets::Post.new(tag_query, params[:page], params[:limit]) @post_set = PostSets::Post.new(tag_query, params[:page], params[:limit])
@posts = @post_set.posts @posts = @post_set.posts
end end
def create_post def create_post
@upload = Upload.new @upload = Upload.new
@upload.server = Socket.gethostname @upload.server = Socket.gethostname
@@ -19,19 +19,19 @@ class LegacyController < ApplicationController
@upload.save @upload.save
@upload.process! @upload.process!
end end
def users def users
@users = User.limit(100).search(params).paginate(params[:page]) @users = User.limit(100).search(params).paginate(params[:page])
end end
def tags def tags
@tags = Tag.limit(100).search(params).paginate(params[:page], :limit => params[:limit]) @tags = Tag.limit(100).search(params).paginate(params[:page], :limit => params[:limit])
end end
def artists def artists
@artists = Artist.limit(100).search(params[:search]).paginate(params[:page]) @artists = Artist.limit(100).search(params[:search]).paginate(params[:page])
end end
def unavailable def unavailable
render :text => "this resource is no longer available", :status => 410 render :text => "this resource is no longer available", :status => 410
end end

View File

@@ -3,7 +3,7 @@ module Maintenance
class LoginRemindersController < ApplicationController class LoginRemindersController < ApplicationController
def new def new
end end
def create def create
@user = ::User.with_email(params[:user][:email]).first @user = ::User.with_email(params[:user][:email]).first
if @user if @user
@@ -12,7 +12,7 @@ module Maintenance
else else
flash[:notice] = "Email address not found" flash[:notice] = "Email address not found"
end end
redirect_to new_maintenance_user_login_reminder_path redirect_to new_maintenance_user_login_reminder_path
end end
end end

View File

@@ -4,7 +4,7 @@ module Maintenance
def new def new
@nonce = UserPasswordResetNonce.new @nonce = UserPasswordResetNonce.new
end end
def create def create
@nonce = UserPasswordResetNonce.create(params[:nonce]) @nonce = UserPasswordResetNonce.create(params[:nonce])
if @nonce.errors.any? if @nonce.errors.any?
@@ -13,14 +13,14 @@ module Maintenance
redirect_to new_maintenance_user_password_reset_path, :notice => "Email request sent" redirect_to new_maintenance_user_password_reset_path, :notice => "Email request sent"
end end
end end
def edit def edit
@nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first @nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first
end end
def update def update
@nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first @nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first
if @nonce if @nonce
@nonce.reset_user! @nonce.reset_user!
@nonce.destroy @nonce.destroy

View File

@@ -2,7 +2,7 @@ module Moderator
class DashboardsController < ApplicationController class DashboardsController < ApplicationController
before_filter :janitor_only before_filter :janitor_only
helper :post_flags, :post_appeals helper :post_flags, :post_appeals
def show def show
@dashboard = Moderator::Dashboard::Report.new(params[:min_date] || 2.days.ago.to_date, params[:max_level] || 20) @dashboard = Moderator::Dashboard::Report.new(params[:min_date] || 2.days.ago.to_date, params[:max_level] || 20)
end end

View File

@@ -1,15 +1,15 @@
module Moderator module Moderator
class InvitationsController < ApplicationController class InvitationsController < ApplicationController
before_filter :moderator_only before_filter :moderator_only
def new def new
end end
def create def create
User.find(params[:invitation][:user_id]).invite!(params[:invitation][:level]) User.find(params[:invitation][:user_id]).invite!(params[:invitation][:level])
redirect_to moderator_invitations_path redirect_to moderator_invitations_path
end end
def index def index
@users = User.where("inviter_id = ?", CurrentUser.id).paginate(params[:page]) @users = User.where("inviter_id = ?", CurrentUser.id).paginate(params[:page])
end end

View File

@@ -1,11 +1,11 @@
module Moderator module Moderator
class IpAddrsController < ApplicationController class IpAddrsController < ApplicationController
before_filter :janitor_only before_filter :janitor_only
def index def index
@search = IpAddrSearch.new(params[:search]) @search = IpAddrSearch.new(params[:search])
end end
def search def search
end end
end end

View File

@@ -2,7 +2,7 @@ module Moderator
module Post module Post
class ApprovalsController < ApplicationController class ApprovalsController < ApplicationController
before_filter :janitor_only before_filter :janitor_only
def create def create
@post = ::Post.find(params[:post_id]) @post = ::Post.find(params[:post_id])
if @post.is_deleted? || @post.is_flagged? || @post.is_pending? if @post.is_deleted? || @post.is_flagged? || @post.is_pending?

View File

@@ -2,7 +2,7 @@ module Moderator
module Post module Post
class DisapprovalsController < ApplicationController class DisapprovalsController < ApplicationController
before_filter :janitor_only before_filter :janitor_only
def create def create
@post = ::Post.find(params[:post_id]) @post = ::Post.find(params[:post_id])
@post_disapproval = PostDisapproval.create(:post => @post, :user => CurrentUser.user) @post_disapproval = PostDisapproval.create(:post => @post, :user => CurrentUser.user)

View File

@@ -8,7 +8,7 @@ module Moderator
def confirm_delete def confirm_delete
@post = ::Post.find(params[:id]) @post = ::Post.find(params[:id])
end end
def delete def delete
@post = ::Post.find(params[:id]) @post = ::Post.find(params[:id])
if params[:commit] == "Delete" if params[:commit] == "Delete"
@@ -17,12 +17,12 @@ module Moderator
end end
redirect_to(post_path(@post)) redirect_to(post_path(@post))
end end
def undelete def undelete
@post = ::Post.find(params[:id]) @post = ::Post.find(params[:id])
@post.undelete! @post.undelete!
end end
def annihilate def annihilate
@post = ::Post.find(params[:id]) @post = ::Post.find(params[:id])
@post.annihilate! @post.annihilate!

View File

@@ -3,7 +3,7 @@ module Moderator
class QueuesController < ApplicationController class QueuesController < ApplicationController
respond_to :html, :json respond_to :html, :json
before_filter :janitor_only before_filter :janitor_only
def show def show
::Post.without_timeout do ::Post.without_timeout do
@posts = ::Post.order("posts.id asc").pending_or_flagged.available_for_moderation(params[:hidden]).search(:tag_match => "#{params[:query]} status:any").paginate(params[:page], :limit => 100) @posts = ::Post.order("posts.id asc").pending_or_flagged.available_for_moderation(params[:hidden]).search(:tag_match => "#{params[:query]} status:any").paginate(params[:page], :limit => 100)

View File

@@ -2,15 +2,15 @@ module Moderator
class TagsController < ApplicationController class TagsController < ApplicationController
before_filter :moderator_only before_filter :moderator_only
rescue_from TagBatchChange::Error, :with => :error rescue_from TagBatchChange::Error, :with => :error
def edit def edit
end end
def update def update
Delayed::Job.enqueue(TagBatchChange.new(params[:tag][:antecedent], params[:tag][:consequent], CurrentUser.user, CurrentUser.ip_addr)) Delayed::Job.enqueue(TagBatchChange.new(params[:tag][:antecedent], params[:tag][:consequent], CurrentUser.user, CurrentUser.ip_addr))
redirect_to edit_moderator_tag_path, :notice => "Post changes queued" redirect_to edit_moderator_tag_path, :notice => "Post changes queued"
end end
def error def error
redirect_to edit_moderator_tag_path, :notice => "Error" redirect_to edit_moderator_tag_path, :notice => "Error"
end end

View File

@@ -1,33 +1,33 @@
class NewsUpdatesController < ApplicationController class NewsUpdatesController < ApplicationController
before_filter :admin_only before_filter :admin_only
respond_to :html respond_to :html
def index def index
@news_updates = NewsUpdate.order("id desc").paginate(params[:page]) @news_updates = NewsUpdate.order("id desc").paginate(params[:page])
respond_with(@news_updates) respond_with(@news_updates)
end end
def edit def edit
@news_update = NewsUpdate.find(params[:id]) @news_update = NewsUpdate.find(params[:id])
respond_with(@news_update) respond_with(@news_update)
end end
def update def update
@news_update = NewsUpdate.find(params[:id]) @news_update = NewsUpdate.find(params[:id])
@news_update.update_attributes(params[:news_update]) @news_update.update_attributes(params[:news_update])
respond_with(@news_update, :location => news_updates_path) respond_with(@news_update, :location => news_updates_path)
end end
def new def new
@news_update = NewsUpdate.new @news_update = NewsUpdate.new
respond_with(@news_update) respond_with(@news_update)
end end
def create def create
@news_update = NewsUpdate.create(params[:news_update]) @news_update = NewsUpdate.create(params[:news_update])
respond_with(@news_update, :location => news_updates_path) respond_with(@news_update, :location => news_updates_path)
end end
def destroy def destroy
@news_update = NewsUpdate.find(params[:id]) @news_update = NewsUpdate.find(params[:id])
@news_update.destroy @news_update.destroy

View File

@@ -1,7 +1,7 @@
class NoteVersionsController < ApplicationController class NoteVersionsController < ApplicationController
respond_to :html, :xml, :json respond_to :html, :xml, :json
before_filter :member_only, :except => [:index, :show] before_filter :member_only, :except => [:index, :show]
def index def index
@search = NoteVersion.search(params[:search]) @search = NoteVersion.search(params[:search])
@note_versions = @search.order("note_versions.id desc").paginate(params[:page]) @note_versions = @search.order("note_versions.id desc").paginate(params[:page])

View File

@@ -2,10 +2,10 @@ class NotesController < ApplicationController
respond_to :html, :xml, :json, :js respond_to :html, :xml, :json, :js
before_filter :member_only, :except => [:index, :show] before_filter :member_only, :except => [:index, :show]
before_filter :pass_html_id, :only => [:create] before_filter :pass_html_id, :only => [:create]
def search def search
end end
def index def index
if params[:group_by] == "note" if params[:group_by] == "note"
index_by_note index_by_note
@@ -13,12 +13,12 @@ class NotesController < ApplicationController
index_by_post index_by_post
end end
end end
def show def show
@note = Note.find(params[:id]) @note = Note.find(params[:id])
respond_with(@note) respond_with(@note)
end end
def create def create
@note = Note.create(params[:note]) @note = Note.create(params[:note])
respond_with(@note) do |fmt| respond_with(@note) do |fmt|
@@ -27,19 +27,19 @@ class NotesController < ApplicationController
end end
end end
end end
def update def update
@note = Note.find(params[:id]) @note = Note.find(params[:id])
@note.update_attributes(params[:note]) @note.update_attributes(params[:note])
respond_with(@note) respond_with(@note)
end end
def destroy def destroy
@note = Note.find(params[:id]) @note = Note.find(params[:id])
@note.update_attribute(:is_active, false) @note.update_attribute(:is_active, false)
respond_with(@note) respond_with(@note)
end end
def revert def revert
@note = Note.find(params[:id]) @note = Note.find(params[:id])
@version = NoteVersion.find(params[:version_id]) @version = NoteVersion.find(params[:version_id])

View File

@@ -1,30 +1,30 @@
class PoolElementsController < ApplicationController class PoolElementsController < ApplicationController
respond_to :html, :xml, :json, :js respond_to :html, :xml, :json, :js
before_filter :member_only before_filter :member_only
def create def create
@pool = Pool.find_by_name(params[:pool_name]) || Pool.find_by_id(params[:pool_id]) @pool = Pool.find_by_name(params[:pool_name]) || Pool.find_by_id(params[:pool_id])
if @pool.present? if @pool.present?
@post = Post.find(params[:post_id]) @post = Post.find(params[:post_id])
@pool.add!(@post) @pool.add!(@post)
append_pool_to_session(@pool) append_pool_to_session(@pool)
end end
respond_with(@pool, :location => post_path(@post)) respond_with(@pool, :location => post_path(@post))
end end
def destroy def destroy
@pool = Pool.find(params[:pool_id]) @pool = Pool.find(params[:pool_id])
@post = Post.find(params[:post_id]) @post = Post.find(params[:post_id])
@pool.remove!(@post) @pool.remove!(@post)
respond_with(@pool, :location => post_path(@post)) respond_with(@pool, :location => post_path(@post))
end end
def all_select def all_select
@pools = Pool.active.order("name").select("id, name").all @pools = Pool.active.order("name").select("id, name").all
end end
private private
def append_pool_to_session(pool) def append_pool_to_session(pool)
recent_pool_ids = session[:recent_pool_ids].to_s.scan(/\d+/) recent_pool_ids = session[:recent_pool_ids].to_s.scan(/\d+/)

View File

@@ -3,7 +3,7 @@ class PoolVersionsController < ApplicationController
if params[:search] && params[:search][:pool_id] if params[:search] && params[:search][:pool_id]
@pool = Pool.find(params[:search][:pool_id]) @pool = Pool.find(params[:search][:pool_id])
end end
@pool_versions = PoolVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) @pool_versions = PoolVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search])
end end
end end

View File

@@ -8,31 +8,31 @@ class PoolsController < ApplicationController
@pool = Pool.new @pool = Pool.new
respond_with(@pool) respond_with(@pool)
end end
def edit def edit
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
respond_with(@pool) respond_with(@pool)
end end
def index def index
@pools = Pool.active.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) @pools = Pool.active.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search])
respond_with(@pools) respond_with(@pools)
end end
def search def search
end end
def show def show
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
@post_set = PostSets::Pool.new(@pool, params[:page]) @post_set = PostSets::Pool.new(@pool, params[:page])
respond_with(@pool) respond_with(@pool)
end end
def create def create
@pool = Pool.create(params[:pool]) @pool = Pool.create(params[:pool])
respond_with(@pool, :notice => "Pool created") respond_with(@pool, :notice => "Pool created")
end end
def update def update
# need to do this in order for synchronize! to work correctly # need to do this in order for synchronize! to work correctly
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
@@ -41,7 +41,7 @@ class PoolsController < ApplicationController
@pool.save @pool.save
respond_with(@pool, :notice => "Pool updated") respond_with(@pool, :notice => "Pool updated")
end end
def destroy def destroy
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
if !@pool.deletable_by?(CurrentUser.user) if !@pool.deletable_by?(CurrentUser.user)
@@ -50,7 +50,7 @@ class PoolsController < ApplicationController
@pool.update_attribute(:is_deleted, true) @pool.update_attribute(:is_deleted, true)
respond_with(@pool, :notice => "Pool deleted") respond_with(@pool, :notice => "Pool deleted")
end end
def undelete def undelete
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
if !@pool.deletable_by?(CurrentUser.user) if !@pool.deletable_by?(CurrentUser.user)
@@ -59,7 +59,7 @@ class PoolsController < ApplicationController
@pool.update_attribute(:is_deleted, false) @pool.update_attribute(:is_deleted, false)
respond_with(@pool, :notice => "Pool undeleted") respond_with(@pool, :notice => "Pool undeleted")
end end
def revert def revert
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
@version = PoolVersion.find(params[:version_id]) @version = PoolVersion.find(params[:version_id])

View File

@@ -7,12 +7,12 @@ class PostAppealsController < ApplicationController
@post_appeal = PostAppeal.new @post_appeal = PostAppeal.new
respond_with(@post_appeal) respond_with(@post_appeal)
end end
def index def index
@search = PostAppeal.order("id desc").search(params[:search]) @search = PostAppeal.order("id desc").search(params[:search])
@post_appeals = @search.paginate(params[:page]) @post_appeals = @search.paginate(params[:page])
end end
def create def create
@post_appeal = PostAppeal.create(params[:post_appeal]) @post_appeal = PostAppeal.create(params[:post_appeal])
respond_with(@post_appeal) respond_with(@post_appeal)

View File

@@ -7,12 +7,12 @@ class PostFlagsController < ApplicationController
@post_flag = PostFlag.new @post_flag = PostFlag.new
respond_with(@post_flag) respond_with(@post_flag)
end end
def index def index
@search = PostFlag.order("id desc").search(params[:search]) @search = PostFlag.order("id desc").search(params[:search])
@post_flags = @search.paginate(params[:page]) @post_flags = @search.paginate(params[:page])
end end
def create def create
@post_flag = PostFlag.create(params[:post_flag].merge(:is_resolved => false)) @post_flag = PostFlag.create(params[:post_flag].merge(:is_resolved => false))
respond_with(@post_flag) respond_with(@post_flag)

View File

@@ -6,7 +6,7 @@ class PostVersionsController < ApplicationController
@post_versions = PostVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) @post_versions = PostVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search])
respond_with(@post_versions) respond_with(@post_versions)
end end
def search def search
end end
end end

View File

@@ -1,6 +1,6 @@
class PostVotesController < ApplicationController class PostVotesController < ApplicationController
before_filter :privileged_only before_filter :privileged_only
def create def create
@post = Post.find(params[:post_id]) @post = Post.find(params[:post_id])
@post.vote!(params[:score]) @post.vote!(params[:score])

View File

@@ -6,7 +6,7 @@ class PostsController < ApplicationController
rescue_from Post::SearchError, :with => :rescue_exception rescue_from Post::SearchError, :with => :rescue_exception
rescue_from ActiveRecord::StatementInvalid, :with => :rescue_exception rescue_from ActiveRecord::StatementInvalid, :with => :rescue_exception
rescue_from ActiveRecord::RecordNotFound, :with => :rescue_exception rescue_from ActiveRecord::RecordNotFound, :with => :rescue_exception
def index def index
@post_set = PostSets::Post.new(tag_query, params[:page], params[:limit]) @post_set = PostSets::Post.new(tag_query, params[:page], params[:limit])
@posts = @post_set.posts @posts = @post_set.posts
@@ -14,14 +14,14 @@ class PostsController < ApplicationController
format.atom format.atom
end end
end end
def show def show
@post = Post.find(params[:id]) @post = Post.find(params[:id])
@post_flag = PostFlag.new(:post_id => @post.id) @post_flag = PostFlag.new(:post_id => @post.id)
@post_appeal = PostAppeal.new(:post_id => @post.id) @post_appeal = PostAppeal.new(:post_id => @post.id)
respond_with(@post) respond_with(@post)
end end
def show_seq def show_seq
context = PostSearchContext.new(params) context = PostSearchContext.new(params)
if context.post_id if context.post_id
@@ -30,14 +30,14 @@ class PostsController < ApplicationController
redirect_to(post_path(params[:id], :tags => params[:tags])) redirect_to(post_path(params[:id], :tags => params[:tags]))
end end
end end
def update def update
@post = Post.find(params[:id]) @post = Post.find(params[:id])
if Danbooru.config.can_user_see_post?(CurrentUser.user, @post) if Danbooru.config.can_user_see_post?(CurrentUser.user, @post)
@post.update_attributes(params[:post], :as => CurrentUser.role) @post.update_attributes(params[:post], :as => CurrentUser.role)
end end
respond_with(@post) do |format| respond_with(@post) do |format|
format.html do format.html do
if @post.errors.any? if @post.errors.any?
@@ -49,13 +49,13 @@ class PostsController < ApplicationController
redirect_to post_path(@post) redirect_to post_path(@post)
end end
end end
format.json do format.json do
render :json => @post.to_json render :json => @post.to_json
end end
end end
end end
def revert def revert
@post = Post.find(params[:id]) @post = Post.find(params[:id])
@version = PostVersion.find(params[:version_id]) @version = PostVersion.find(params[:version_id])

View File

@@ -1,6 +1,6 @@
class RelatedTagsController < ApplicationController class RelatedTagsController < ApplicationController
respond_to :json respond_to :json
def show def show
@query = RelatedTagQuery.new(params[:query].to_s.downcase, params[:category]) @query = RelatedTagQuery.new(params[:query].to_s.downcase, params[:category])
respond_with(@query) do |format| respond_with(@query) do |format|

View File

@@ -2,24 +2,24 @@ class SessionsController < ApplicationController
def new def new
@user = User.new @user = User.new
end end
def create def create
session_creator = SessionCreator.new(session, cookies, params[:name], params[:password], params[:remember]) session_creator = SessionCreator.new(session, cookies, params[:name], params[:password], params[:remember])
if session_creator.authenticate if session_creator.authenticate
redirect_to(params[:url] || session[:previous_uri] || posts_path, :notice => "You are now logged in.") redirect_to(params[:url] || session[:previous_uri] || posts_path, :notice => "You are now logged in.")
else else
redirect_to(new_session_path, :notice => "Password was incorrect.") redirect_to(new_session_path, :notice => "Password was incorrect.")
end end
end end
def destroy def destroy
session.delete(:user_id) session.delete(:user_id)
cookies.delete(:cookie_password_hash) cookies.delete(:cookie_password_hash)
cookies.delete(:user_name) cookies.delete(:user_name)
redirect_to(posts_path, :notice => "You are now logged out.") redirect_to(posts_path, :notice => "You are now logged out.")
end end
def sign_out def sign_out
destroy() destroy()
end end

View File

@@ -1,11 +1,11 @@
class SourcesController < ApplicationController class SourcesController < ApplicationController
# before_filter :member_only # before_filter :member_only
respond_to :json respond_to :json
def show def show
@source = Sources::Site.new(params[:url]) @source = Sources::Site.new(params[:url])
@source.get @source.get
respond_with(@source) do |format| respond_with(@source) do |format|
format.json do format.json do
render :json => @source.to_json render :json => @source.to_json

View File

@@ -2,7 +2,7 @@ class StaticController < ApplicationController
def terms_of_service def terms_of_service
render :layout => "blank" render :layout => "blank"
end end
def error def error
end end
end end

View File

@@ -1,6 +1,6 @@
class TagAliasCorrectionsController < ApplicationController class TagAliasCorrectionsController < ApplicationController
before_filter :moderator_only before_filter :moderator_only
def create def create
@correction = TagAliasCorrection.new(params[:tag_alias_id]) @correction = TagAliasCorrection.new(params[:tag_alias_id])
@@ -8,10 +8,10 @@ class TagAliasCorrectionsController < ApplicationController
@correction.fix! @correction.fix!
flash[:notice] = "The fix has been queued and will be processed" flash[:notice] = "The fix has been queued and will be processed"
end end
redirect_to tag_alias_correction_path(:tag_alias_id => params[:tag_alias_id]) redirect_to tag_alias_correction_path(:tag_alias_id => params[:tag_alias_id])
end end
def show def show
@correction = TagAliasCorrection.new(params[:tag_alias_id]) @correction = TagAliasCorrection.new(params[:tag_alias_id])
end end

View File

@@ -1,10 +1,10 @@
class TagAliasRequestsController < ApplicationController class TagAliasRequestsController < ApplicationController
before_filter :member_only before_filter :member_only
rescue_from TagAliasRequest::ValidationError, :with => :rescue_exception rescue_from TagAliasRequest::ValidationError, :with => :rescue_exception
def new def new
end end
def create def create
@tag_alias_request = TagAliasRequest.new( @tag_alias_request = TagAliasRequest.new(
params[:tag_alias_request][:antecedent_name], params[:tag_alias_request][:antecedent_name],

View File

@@ -1,12 +1,12 @@
class TagAliasesController < ApplicationController class TagAliasesController < ApplicationController
before_filter :admin_only, :only => [:approve, :destroy, :new, :create] before_filter :admin_only, :only => [:approve, :destroy, :new, :create]
respond_to :html, :xml, :json, :js respond_to :html, :xml, :json, :js
def new def new
@tag_alias = TagAlias.new(params[:tag_alias]) @tag_alias = TagAlias.new(params[:tag_alias])
respond_with(@tag_alias) respond_with(@tag_alias)
end end
def general_search def general_search
if params[:commit] == "Search Aliases" if params[:commit] == "Search Aliases"
redirect_to tag_aliases_path(:search => {:name_matches => params[:query]}) redirect_to tag_aliases_path(:search => {:name_matches => params[:query]})
@@ -14,18 +14,18 @@ class TagAliasesController < ApplicationController
redirect_to tag_implications_path(:search => {:name_matches => params[:query]}) redirect_to tag_implications_path(:search => {:name_matches => params[:query]})
end end
end end
def index def index
@search = TagAlias.search(params[:search]) @search = TagAlias.search(params[:search])
@tag_aliases = @search.order("(case status when 'pending' then 0 when 'queued' then 1 else 2 end), antecedent_name, consequent_name").paginate(params[:page]) @tag_aliases = @search.order("(case status when 'pending' then 0 when 'queued' then 1 else 2 end), antecedent_name, consequent_name").paginate(params[:page])
respond_with(@tag_aliases) respond_with(@tag_aliases)
end end
def create def create
@tag_alias = TagAlias.create(params[:tag_alias]) @tag_alias = TagAlias.create(params[:tag_alias])
respond_with(@tag_alias, :location => tag_aliases_path(:search => {:id => @tag_alias.id})) respond_with(@tag_alias, :location => tag_aliases_path(:search => {:id => @tag_alias.id}))
end end
def destroy def destroy
@tag_alias = TagAlias.find(params[:id]) @tag_alias = TagAlias.find(params[:id])
@tag_alias.update_column(:status, "deleted") @tag_alias.update_column(:status, "deleted")
@@ -33,7 +33,7 @@ class TagAliasesController < ApplicationController
@tag_alias.destroy @tag_alias.destroy
respond_with(@tag_alias, :location => tag_aliases_path) respond_with(@tag_alias, :location => tag_aliases_path)
end end
def approve def approve
@tag_alias = TagAlias.find(params[:id]) @tag_alias = TagAlias.find(params[:id])
@tag_alias.update_column(:status, "queued") @tag_alias.update_column(:status, "queued")

View File

@@ -1,16 +1,16 @@
class TagCorrectionsController < ApplicationController class TagCorrectionsController < ApplicationController
before_filter :member_only before_filter :member_only
def new def new
@correction = TagCorrection.new(params[:tag_id]) @correction = TagCorrection.new(params[:tag_id])
end end
def create def create
if params[:commit] == "Fix" if params[:commit] == "Fix"
@correction = TagCorrection.new(params[:tag_id]) @correction = TagCorrection.new(params[:tag_id])
@correction.fix! @correction.fix!
end end
redirect_to tags_path(:search => {:name_matches => @correction.tag.name}), :notice => "Tag will be fixed in a few seconds" redirect_to tags_path(:search => {:name_matches => @correction.tag.name}), :notice => "Tag will be fixed in a few seconds"
end end
end end

View File

@@ -1,10 +1,10 @@
class TagImplicationRequestsController < ApplicationController class TagImplicationRequestsController < ApplicationController
before_filter :member_only before_filter :member_only
rescue_from TagImplicationRequest::ValidationError, :with => :rescue_exception rescue_from TagImplicationRequest::ValidationError, :with => :rescue_exception
def new def new
end end
def create def create
@tag_implication_request = TagImplicationRequest.new( @tag_implication_request = TagImplicationRequest.new(
params[:tag_implication_request][:antecedent_name], params[:tag_implication_request][:antecedent_name],

View File

@@ -1,29 +1,29 @@
class TagImplicationsController < ApplicationController class TagImplicationsController < ApplicationController
before_filter :admin_only, :only => [:new, :create, :approve, :destroy] before_filter :admin_only, :only => [:new, :create, :approve, :destroy]
respond_to :html, :xml, :json, :js respond_to :html, :xml, :json, :js
def new def new
@tag_implication = TagImplication.new @tag_implication = TagImplication.new
respond_with(@tag_implication) respond_with(@tag_implication)
end end
def index def index
@search = TagImplication.search(params[:search]) @search = TagImplication.search(params[:search])
@tag_implications = @search.order("(case status when 'pending' then 0 when 'queued' then 1 else 2 end), antecedent_name, consequent_name").paginate(params[:page]) @tag_implications = @search.order("(case status when 'pending' then 0 when 'queued' then 1 else 2 end), antecedent_name, consequent_name").paginate(params[:page])
respond_with(@tag_implications) respond_with(@tag_implications)
end end
def create def create
@tag_implication = TagImplication.create(params[:tag_implication]) @tag_implication = TagImplication.create(params[:tag_implication])
respond_with(@tag_implication, :location => tag_implications_path(:search => {:id => @tag_implication.id})) respond_with(@tag_implication, :location => tag_implications_path(:search => {:id => @tag_implication.id}))
end end
def destroy def destroy
@tag_implication = TagImplication.find(params[:id]) @tag_implication = TagImplication.find(params[:id])
@tag_implication.destroy @tag_implication.destroy
respond_with(@tag_implication) respond_with(@tag_implication)
end end
def approve def approve
@tag_implication = TagImplication.find(params[:id]) @tag_implication = TagImplication.find(params[:id])
@tag_implication.update_column(:status, "queued") @tag_implication.update_column(:status, "queued")

View File

@@ -7,20 +7,20 @@ class TagSubscriptionsController < ApplicationController
@tag_subscription = TagSubscription.new @tag_subscription = TagSubscription.new
respond_with(@tag_subscription) respond_with(@tag_subscription)
end end
def edit def edit
@tag_subscription = TagSubscription.find(params[:id]) @tag_subscription = TagSubscription.find(params[:id])
check_privilege(@tag_subscription) check_privilege(@tag_subscription)
respond_with(@tag_subscription) respond_with(@tag_subscription)
end end
def index def index
@user = CurrentUser.user @user = CurrentUser.user
@search = TagSubscription.owned_by(@user).order("name").search(params[:search]) @search = TagSubscription.owned_by(@user).order("name").search(params[:search])
@tag_subscriptions = @search.paginate(params[:page]) @tag_subscriptions = @search.paginate(params[:page])
respond_with(@tag_subscriptions) respond_with(@tag_subscriptions)
end end
def create def create
@tag_subscription = TagSubscription.create(params[:tag_subscription]) @tag_subscription = TagSubscription.create(params[:tag_subscription])
respond_with(@tag_subscription) do |format| respond_with(@tag_subscription) do |format|
@@ -33,7 +33,7 @@ class TagSubscriptionsController < ApplicationController
end end
end end
end end
def update def update
@tag_subscription = TagSubscription.find(params[:id]) @tag_subscription = TagSubscription.find(params[:id])
check_privilege(@tag_subscription) check_privilege(@tag_subscription)
@@ -48,20 +48,20 @@ class TagSubscriptionsController < ApplicationController
end end
end end
end end
def destroy def destroy
@tag_subscription = TagSubscription.find(params[:id]) @tag_subscription = TagSubscription.find(params[:id])
check_privilege(@tag_subscription) check_privilege(@tag_subscription)
@tag_subscription.destroy @tag_subscription.destroy
respond_with(@tag_subscription) respond_with(@tag_subscription)
end end
def posts def posts
@user = User.find(params[:id]) @user = User.find(params[:id])
@post_set = PostSets::Post.new("sub:#{@user.name} #{params[:tags]}", params[:page]) @post_set = PostSets::Post.new("sub:#{@user.name} #{params[:tags]}", params[:page])
@posts = @post_set.posts @posts = @post_set.posts
end end
private private
def check_privilege(tag_subscription) def check_privilege(tag_subscription)
raise User::PrivilegeError unless tag_subscription.editable_by?(CurrentUser.user) raise User::PrivilegeError unless tag_subscription.editable_by?(CurrentUser.user)

View File

@@ -1,20 +1,20 @@
class TagsController < ApplicationController class TagsController < ApplicationController
before_filter :member_only, :only => [:edit, :update] before_filter :member_only, :only => [:edit, :update]
respond_to :html, :xml, :json respond_to :html, :xml, :json
def edit def edit
@tag = Tag.find(params[:id]) @tag = Tag.find(params[:id])
respond_with(@tag) respond_with(@tag)
end end
def index def index
@tags = Tag.search(params[:search]).paginate(params[:page], :search_count => params[:search]) @tags = Tag.search(params[:search]).paginate(params[:page], :search_count => params[:search])
respond_with(@tags) respond_with(@tags)
end end
def search def search
end end
def show def show
@tag = Tag.find(params[:id]) @tag = Tag.find(params[:id])
respond_with(@tag) respond_with(@tag)
@@ -25,5 +25,5 @@ class TagsController < ApplicationController
@tag.update_attributes(params[:tag]) @tag.update_attributes(params[:tag])
@tag.update_category_cache_for_all @tag.update_category_cache_for_all
respond_with(@tag) respond_with(@tag)
end end
end end

View File

@@ -3,7 +3,7 @@ class UploadsController < ApplicationController
after_filter :save_recent_tags, :only => [:create] after_filter :save_recent_tags, :only => [:create]
respond_to :html, :xml, :json, :js respond_to :html, :xml, :json, :js
rescue_from Upload::Error, :with => :rescue_exception rescue_from Upload::Error, :with => :rescue_exception
def new def new
@upload = Upload.new(:rating => "q") @upload = Upload.new(:rating => "q")
if params[:url] if params[:url]
@@ -15,13 +15,13 @@ class UploadsController < ApplicationController
end end
respond_with(@upload) respond_with(@upload)
end end
def index def index
@search = Upload.search(params[:search]) @search = Upload.search(params[:search])
@uploads = @search.order("id desc").paginate(params[:page]) @uploads = @search.order("id desc").paginate(params[:page])
respond_with(@uploads) respond_with(@uploads)
end end
def show def show
@upload = Upload.find(params[:id]) @upload = Upload.find(params[:id])
respond_with(@upload) do |format| respond_with(@upload) do |format|
@@ -38,7 +38,7 @@ class UploadsController < ApplicationController
@upload.process! if @upload.errors.empty? @upload.process! if @upload.errors.empty?
respond_with(@upload) respond_with(@upload)
end end
def update def update
@upload = Upload.find(params[:id]) @upload = Upload.find(params[:id])
@upload.process! @upload.process!

View File

@@ -7,29 +7,29 @@ class UserFeedbacksController < ApplicationController
@user_feedback = UserFeedback.new(params[:user_feedback]) @user_feedback = UserFeedback.new(params[:user_feedback])
respond_with(@user_feedback) respond_with(@user_feedback)
end end
def edit def edit
@user_feedback = UserFeedback.find(params[:id]) @user_feedback = UserFeedback.find(params[:id])
check_privilege(@user_feedback) check_privilege(@user_feedback)
respond_with(@user_feedback) respond_with(@user_feedback)
end end
def show def show
@user_feedback = UserFeedback.find(params[:id]) @user_feedback = UserFeedback.find(params[:id])
respond_with(@user_feedback) respond_with(@user_feedback)
end end
def index def index
@search = UserFeedback.search(params[:search]) @search = UserFeedback.search(params[:search])
@user_feedbacks = @search.paginate(params[:page]).order("created_at desc") @user_feedbacks = @search.paginate(params[:page]).order("created_at desc")
respond_with(@user_feedbacks) respond_with(@user_feedbacks)
end end
def create def create
@user_feedback = UserFeedback.create(params[:user_feedback]) @user_feedback = UserFeedback.create(params[:user_feedback])
respond_with(@user_feedback) respond_with(@user_feedback)
end end
def destroy def destroy
@user_feedback = UserFeedback.find(params[:id]) @user_feedback = UserFeedback.find(params[:id])
check_privilege(@user_feedback) check_privilege(@user_feedback)

View File

@@ -7,27 +7,27 @@ class UsersController < ApplicationController
@user = User.new @user = User.new
respond_with(@user) respond_with(@user)
end end
def edit def edit
@user = User.find(params[:id]) @user = User.find(params[:id])
check_privilege(@user) check_privilege(@user)
respond_with(@user) respond_with(@user)
end end
def index def index
@users = User.search(params[:search]).order("users.id desc").paginate(params[:page], :search_count => params[:search]) @users = User.search(params[:search]).order("users.id desc").paginate(params[:page], :search_count => params[:search])
respond_with(@users) respond_with(@users)
end end
def search def search
end end
def show def show
@user = User.find(params[:id]) @user = User.find(params[:id])
@presenter = UserPresenter.new(@user) @presenter = UserPresenter.new(@user)
respond_with(@user) respond_with(@user)
end end
def create def create
@user = User.create(params[:user], :as => CurrentUser.role) @user = User.create(params[:user], :as => CurrentUser.role)
if @user.errors.empty? if @user.errors.empty?
@@ -36,32 +36,32 @@ class UsersController < ApplicationController
set_current_user set_current_user
respond_with(@user) respond_with(@user)
end end
def update def update
@user = User.find(params[:id]) @user = User.find(params[:id])
check_privilege(@user) check_privilege(@user)
@user.update_attributes(params[:user], :as => CurrentUser.role) @user.update_attributes(params[:user], :as => CurrentUser.role)
respond_with(@user) respond_with(@user)
end end
def upgrade def upgrade
@user = User.find(params[:id]) @user = User.find(params[:id])
if params[:email] =~ /paypal/ if params[:email] =~ /paypal/
UserMailer.upgrade_fail(params[:email]).deliver UserMailer.upgrade_fail(params[:email]).deliver
else else
UserMailer.upgrade(@user, params[:email]).deliver UserMailer.upgrade(@user, params[:email]).deliver
end end
redirect_to user_path(@user), :notice => "Email was sent" redirect_to user_path(@user), :notice => "Email was sent"
end end
def cache def cache
@user = User.find(params[:id]) @user = User.find(params[:id])
@user.update_cache @user.update_cache
render :nothing => true render :nothing => true
end end
def restore_uploaded_tags def restore_uploaded_tags
@user = User.find(params[:id]) @user = User.find(params[:id])
importer = UploadedTagsImporter.new(@user) importer = UploadedTagsImporter.new(@user)

View File

@@ -1,16 +1,16 @@
class WikiPageVersionsController < ApplicationController class WikiPageVersionsController < ApplicationController
respond_to :json, :html, :xml respond_to :json, :html, :xml
def index def index
@wiki_page_versions = WikiPageVersion.search(params[:search]).order("id desc").paginate(params[:page], :search_count => params[:search]) @wiki_page_versions = WikiPageVersion.search(params[:search]).order("id desc").paginate(params[:page], :search_count => params[:search])
respond_with(@wiki_page_versions) respond_with(@wiki_page_versions)
end end
def show def show
@wiki_page_version = WikiPageVersion.find(params[:id]) @wiki_page_version = WikiPageVersion.find(params[:id])
respond_with(@wiki_page_version) respond_with(@wiki_page_version)
end end
def diff def diff
@thispage = WikiPageVersion.find(params[:thispage]) @thispage = WikiPageVersion.find(params[:thispage])
@otherpage = WikiPageVersion.find(params[:otherpage]) @otherpage = WikiPageVersion.find(params[:otherpage])

View File

@@ -9,12 +9,12 @@ class WikiPagesController < ApplicationController
@wiki_page = WikiPage.new(params[:wiki_page]) @wiki_page = WikiPage.new(params[:wiki_page])
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def edit def edit
@wiki_page = WikiPage.find(params[:id]) @wiki_page = WikiPage.find(params[:id])
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def index def index
@wiki_pages = WikiPage.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) @wiki_pages = WikiPage.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search])
respond_with(@wiki_pages) do |format| respond_with(@wiki_pages) do |format|
@@ -25,7 +25,7 @@ class WikiPagesController < ApplicationController
end end
end end
end end
def show def show
if params[:id] =~ /[a-zA-Z]/ if params[:id] =~ /[a-zA-Z]/
@wiki_page = WikiPage.find_by_title(params[:id]) @wiki_page = WikiPage.find_by_title(params[:id])
@@ -34,31 +34,31 @@ class WikiPagesController < ApplicationController
end end
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def create def create
@wiki_page = WikiPage.create(params[:wiki_page]) @wiki_page = WikiPage.create(params[:wiki_page])
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def update def update
@wiki_page = WikiPage.find(params[:id]) @wiki_page = WikiPage.find(params[:id])
@wiki_page.update_attributes(params[:wiki_page]) @wiki_page.update_attributes(params[:wiki_page])
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def destroy def destroy
@wiki_page = WikiPage.find(params[:id]) @wiki_page = WikiPage.find(params[:id])
@wiki_page.destroy @wiki_page.destroy
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def revert def revert
@wiki_page = WikiPage.find(params[:id]) @wiki_page = WikiPage.find(params[:id])
@version = WikiPageVersion.find(params[:version_id]) @version = WikiPageVersion.find(params[:version_id])
@wiki_page.revert_to!(@version) @wiki_page.revert_to!(@version)
respond_with(@wiki_page) respond_with(@wiki_page)
end end
def show_or_new def show_or_new
@wiki_page = WikiPage.find_by_title(params[:title]) @wiki_page = WikiPage.find_by_title(params[:title])
if @wiki_page if @wiki_page

View File

@@ -4,14 +4,14 @@ module AdvertisementsHelper
@advertisement = Advertisement.find(:first, :conditions => ["ad_type = ? AND status = 'active'", ad_type], :order => "random()") @advertisement = Advertisement.find(:first, :conditions => ["ad_type = ? AND status = 'active'", ad_type], :order => "random()")
if @advertisement if @advertisement
content_tag( content_tag(
"div", "div",
link_to( link_to(
image_tag( image_tag(
@advertisement.image_url, @advertisement.image_url,
:alt => "Advertisement", :alt => "Advertisement",
:width => @advertisement.width, :width => @advertisement.width,
:height => @advertisement.height :height => @advertisement.height
), ),
advertisement_hits_path(:advertisement_id => @advertisement.id), advertisement_hits_path(:advertisement_id => @advertisement.id),
:method => :post :method => :post
), ),
@@ -22,7 +22,7 @@ module AdvertisementsHelper
"" ""
end end
end end
def render_rss_advertisement(short_or_long, safe) def render_rss_advertisement(short_or_long, safe)
if Danbooru.config.can_see_ads?(CurrentUser.user) if Danbooru.config.can_see_ads?(CurrentUser.user)
if safe if safe

View File

@@ -8,27 +8,27 @@ module ApplicationHelper
content_tag("li", link_to(text, url, options), :class => klass) content_tag("li", link_to(text, url, options), :class => klass)
end end
def fast_link_to(text, link_params, options = {}) def fast_link_to(text, link_params, options = {})
if options if options
attributes = options.map do |k, v| attributes = options.map do |k, v|
%{#{k}="#{h(v)}"} %{#{k}="#{h(v)}"}
end.join(" ") end.join(" ")
else else
attributes = "" attributes = ""
end end
if link_params.is_a?(Hash) if link_params.is_a?(Hash)
action = link_params.delete(:action) action = link_params.delete(:action)
controller = link_params.delete(:controller) || controller_name controller = link_params.delete(:controller) || controller_name
id = link_params.delete(:id) id = link_params.delete(:id)
link_params = link_params.map {|k, v| "#{k}=#{u(v)}"}.join("&") link_params = link_params.map {|k, v| "#{k}=#{u(v)}"}.join("&")
if link_params.present? if link_params.present?
link_params = "?#{link_params}" link_params = "?#{link_params}"
end end
if id if id
url = "/#{controller}/#{action}/#{id}#{link_params}" url = "/#{controller}/#{action}/#{id}#{link_params}"
else else
@@ -37,43 +37,43 @@ module ApplicationHelper
else else
url = link_params url = link_params
end end
raw %{<a href="#{h(url)}" #{attributes}>#{text}</a>} raw %{<a href="#{h(url)}" #{attributes}>#{text}</a>}
end end
def format_text(text, options = {}) def format_text(text, options = {})
DText.parse(text) DText.parse(text)
end end
def error_messages_for(instance_name) def error_messages_for(instance_name)
instance = instance_variable_get("@#{instance_name}") instance = instance_variable_get("@#{instance_name}")
if instance && instance.errors.any? if instance && instance.errors.any?
%{<div class="error-messages ui-state-error ui-corner-all"><strong>Error</strong>: #{instance.__send__(:errors).full_messages.join(", ")}</div>}.html_safe %{<div class="error-messages ui-state-error ui-corner-all"><strong>Error</strong>: #{instance.__send__(:errors).full_messages.join(", ")}</div>}.html_safe
else else
"" ""
end end
end end
def time_tag(content, time) def time_tag(content, time)
zone = time.strftime("%z") zone = time.strftime("%z")
datetime = time.strftime("%Y-%m-%dT%H:%M" + zone[0, 3] + ":" + zone[3, 2]) datetime = time.strftime("%Y-%m-%dT%H:%M" + zone[0, 3] + ":" + zone[3, 2])
content_tag(:time, content || datetime, :datetime => datetime, :title => time.to_formatted_s) content_tag(:time, content || datetime, :datetime => datetime, :title => time.to_formatted_s)
end end
def time_ago_in_words_tagged(time) def time_ago_in_words_tagged(time)
raw time_tag(time_ago_in_words(time) + " ago", time) raw time_tag(time_ago_in_words(time) + " ago", time)
end end
def compact_time(time) def compact_time(time)
time_tag(time.strftime("%Y-%m-%d %H:%M"), time) time_tag(time.strftime("%Y-%m-%d %H:%M"), time)
end end
def mod_link_to_user(user, positive_or_negative) def mod_link_to_user(user, positive_or_negative)
html = "" html = ""
html << link_to(user.name, user_path(user)) html << link_to(user.name, user_path(user))
if positive_or_negative == :positive if positive_or_negative == :positive
html << " [" + link_to("+", new_user_feedback_path(:user_feedback => {:category => "positive", :user_id => user.id})) + "]" html << " [" + link_to("+", new_user_feedback_path(:user_feedback => {:category => "positive", :user_id => user.id})) + "]"
@@ -83,26 +83,26 @@ module ApplicationHelper
else else
html << " [" + link_to("&ndash;".html_safe, new_user_feedback_path(:user_feedback => {:category => "negative", :user_id => user.id})) + "]" html << " [" + link_to("&ndash;".html_safe, new_user_feedback_path(:user_feedback => {:category => "negative", :user_id => user.id})) + "]"
end end
html.html_safe html.html_safe
end end
def dtext_field(object, name, options = {}) def dtext_field(object, name, options = {})
options[:name] ||= "Body" options[:name] ||= "Body"
options[:input_id] ||= "#{object}_#{name}" options[:input_id] ||= "#{object}_#{name}"
options[:input_name] ||= "#{object}[#{name}]" options[:input_name] ||= "#{object}[#{name}]"
options[:value] ||= instance_variable_get("@#{object}").try(name) options[:value] ||= instance_variable_get("@#{object}").try(name)
options[:preview_id] ||= "dtext-preview" options[:preview_id] ||= "dtext-preview"
render "dtext/form", options render "dtext/form", options
end end
def dtext_preview_button(object, name, options = {}) def dtext_preview_button(object, name, options = {})
options[:input_id] ||= "#{object}_#{name}" options[:input_id] ||= "#{object}_#{name}"
options[:preview_id] ||= "dtext-preview" options[:preview_id] ||= "dtext-preview"
submit_tag("Preview", "data-input-id" => options[:input_id], "data-preview-id" => options[:preview_id]) submit_tag("Preview", "data-input-id" => options[:input_id], "data-preview-id" => options[:preview_id])
end end
def search_field(method, options = {}) def search_field(method, options = {})
name = options[:label] || method.titleize name = options[:label] || method.titleize
string = '<div class="input"><label for="search_' + method + '">' + name + '</label><input type="text" name="search[' + method + ']" id="search_' + method + '">' string = '<div class="input"><label for="search_' + method + '">' + name + '</label><input type="text" name="search[' + method + ']" id="search_' + method + '">'
@@ -112,49 +112,49 @@ module ApplicationHelper
string += '</div>' string += '</div>'
string.html_safe string.html_safe
end end
protected protected
def nav_link_match(controller, url) def nav_link_match(controller, url)
url =~ case controller url =~ case controller
when "sessions", "users", "maintenance/user/login_reminders", "maintenance/user/password_resets", "admin/users", "tag_subscriptions" when "sessions", "users", "maintenance/user/login_reminders", "maintenance/user/password_resets", "admin/users", "tag_subscriptions"
/^\/(session|users)/ /^\/(session|users)/
when "forum_posts" when "forum_posts"
/^\/forum_topics/ /^\/forum_topics/
when "comments" when "comments"
/^\/comments/ /^\/comments/
when "notes", "note_versions" when "notes", "note_versions"
/^\/notes/ /^\/notes/
when "posts", "uploads", "post_versions", "explore/posts", "moderator/post/dashboards", "favorites" when "posts", "uploads", "post_versions", "explore/posts", "moderator/post/dashboards", "favorites"
/^\/post/ /^\/post/
when "artists", "artist_versions" when "artists", "artist_versions"
/^\/artist/ /^\/artist/
when "tags" when "tags"
/^\/tags/ /^\/tags/
when "pools" when "pools"
/^\/pools/ /^\/pools/
when "moderator/dashboards" when "moderator/dashboards"
/^\/moderator/ /^\/moderator/
when "tag_aliases", "tag_alias_corrections", "tag_alias_requests" when "tag_aliases", "tag_alias_corrections", "tag_alias_requests"
/^\/tag_aliases/ /^\/tag_aliases/
when "tag_implications", "tag_implication_requests" when "tag_implications", "tag_implication_requests"
/^\/tag_implications/ /^\/tag_implications/
when "wiki_pages", "wiki_page_versions" when "wiki_pages", "wiki_page_versions"
/^\/wiki_pages/ /^\/wiki_pages/
when "forum_topics", "forum_posts" when "forum_topics", "forum_posts"
/^\/forum_topics/ /^\/forum_topics/
else else
/^\/static/ /^\/static/
end end

View File

@@ -1,16 +1,16 @@
module ArtistsHelper module ArtistsHelper
def link_to_artist(name) def link_to_artist(name)
artist = Artist.find_by_name(name) artist = Artist.find_by_name(name)
if artist if artist
link_to(artist.name, artist_path(artist)) link_to(artist.name, artist_path(artist))
else else
link_to(name, new_artist_path(:name => name)) + " " + content_tag("span", "*", :class => "new-artist") link_to(name, new_artist_path(:name => name)) + " " + content_tag("span", "*", :class => "new-artist")
end end
end end
def link_to_artists(names) def link_to_artists(names)
names.map do |name| names.map do |name|
link_to_artist(name) link_to_artist(name)
end.join(", ").html_safe end.join(", ").html_safe
end end

View File

@@ -3,28 +3,28 @@ module DelayedJobsHelper
case job.name case job.name
when "Class#expire_cache" when "Class#expire_cache"
"<strong>expire post count cache</strong>: " + job.payload_object.args.flatten.join(" ") "<strong>expire post count cache</strong>: " + job.payload_object.args.flatten.join(" ")
when "Upload#process!" when "Upload#process!"
'<strong>upload post</strong>: <a href="/uploads/' + job.payload_object.object.id.to_s + '">record</a>' '<strong>upload post</strong>: <a href="/uploads/' + job.payload_object.object.id.to_s + '">record</a>'
when "Tag#update_related" when "Tag#update_related"
"<strong>update related tags</strong>: " + job.payload_object.name "<strong>update related tags</strong>: " + job.payload_object.name
when "TagAlias#process!" when "TagAlias#process!"
'<strong>alias</strong>: ' + job.payload_object.antecedent_name + " -&gt; " + job.payload_object.consequent_name '<strong>alias</strong>: ' + job.payload_object.antecedent_name + " -&gt; " + job.payload_object.consequent_name
when "TagImplication#process!" when "TagImplication#process!"
'<strong>implication</strong>: ' + job.payload_object.antecedent_name + " -&gt; " + job.payload_object.consequent_name '<strong>implication</strong>: ' + job.payload_object.antecedent_name + " -&gt; " + job.payload_object.consequent_name
when "Class#clear_cache_for" when "Class#clear_cache_for"
"<strong>expire tag alias cache</strong>: " + job.payload_object.flatten.join(" ") "<strong>expire tag alias cache</strong>: " + job.payload_object.flatten.join(" ")
when "Tag#update_category_cache" when "Tag#update_category_cache"
"<strong>update tag category cache</strong>: " + job.payload_object.name "<strong>update tag category cache</strong>: " + job.payload_object.name
when "Tag#update_category_post_counts" when "Tag#update_category_post_counts"
"<strong>update category post counts</strong>: " + job.payload_object.name "<strong>update category post counts</strong>: " + job.payload_object.name
else else
job.handler job.handler
end end

View File

@@ -10,7 +10,7 @@ module Moderator
["Moderator", 40], ["Moderator", 40],
["Admin", 50] ["Admin", 50]
] ]
select_tag(name, options_for_select(choices, params[name].to_i), options) select_tag(name, options_for_select(choices, params[name].to_i), options)
end end
end end

View File

@@ -1,31 +1,31 @@
module PaginationHelper module PaginationHelper
def sequential_paginator(records) def sequential_paginator(records)
html = '<div class="paginator"><menu>' html = '<div class="paginator"><menu>'
if records.any? if records.any?
if params[:page] =~ /[ab]/ if params[:page] =~ /[ab]/
html << '<li>' + link_to("< Previous", params.merge(:page => "a#{records[0].id}"), :rel => "prev") + '</li>' html << '<li>' + link_to("< Previous", params.merge(:page => "a#{records[0].id}"), :rel => "prev") + '</li>'
end end
html << '<li>' + link_to("Next >", params.merge(:page => "b#{records[-1].id}"), :rel => "next") + '</li>' html << '<li>' + link_to("Next >", params.merge(:page => "b#{records[-1].id}"), :rel => "next") + '</li>'
end end
html << "</menu></div>" html << "</menu></div>"
html.html_safe html.html_safe
end end
def use_sequential_paginator?(records) def use_sequential_paginator?(records)
params[:page] =~ /[ab]/ || records.current_page >= Danbooru.config.max_numbered_pages params[:page] =~ /[ab]/ || records.current_page >= Danbooru.config.max_numbered_pages
end end
def numbered_paginator(records, switch_to_sequential = true) def numbered_paginator(records, switch_to_sequential = true)
if use_sequential_paginator?(records) && switch_to_sequential if use_sequential_paginator?(records) && switch_to_sequential
return sequential_paginator(records) return sequential_paginator(records)
end end
html = '<div class="paginator"><menu>' html = '<div class="paginator"><menu>'
window = 3 window = 3
if records.current_page >= 2 if records.current_page >= 2
html << "<li>" + link_to("<<", params.merge(:page => records.current_page - 1), :rel => "prev") + "</li>" html << "<li>" + link_to("<<", params.merge(:page => records.current_page - 1), :rel => "prev") + "</li>"
end end
@@ -34,7 +34,7 @@ module PaginationHelper
1.upto(records.total_pages) do |page| 1.upto(records.total_pages) do |page|
html << numbered_paginator_item(page, records.current_page) html << numbered_paginator_item(page, records.current_page)
end end
elsif records.current_page <= window + 2 elsif records.current_page <= window + 2
1.upto(records.current_page + window) do |page| 1.upto(records.current_page + window) do |page|
html << numbered_paginator_item(page, records.current_page) html << numbered_paginator_item(page, records.current_page)
@@ -63,15 +63,15 @@ module PaginationHelper
html << numbered_paginator_final_item(records.total_pages, records.current_page) html << numbered_paginator_final_item(records.total_pages, records.current_page)
end end
end end
if records.current_page < records.total_pages && records.size > 0 if records.current_page < records.total_pages && records.size > 0
html << "<li>" + link_to(">>", params.merge(:page => records.current_page + 1), :rel => "next") + "</li>" html << "<li>" + link_to(">>", params.merge(:page => records.current_page + 1), :rel => "next") + "</li>"
end end
html << "</menu></div>" html << "</menu></div>"
html.html_safe html.html_safe
end end
def numbered_paginator_final_item(total_pages, current_page) def numbered_paginator_final_item(total_pages, current_page)
if total_pages <= Danbooru.config.max_numbered_pages if total_pages <= Danbooru.config.max_numbered_pages
numbered_paginator_item(total_pages, current_page) numbered_paginator_item(total_pages, current_page)
@@ -79,10 +79,10 @@ module PaginationHelper
"" ""
end end
end end
def numbered_paginator_item(page, current_page) def numbered_paginator_item(page, current_page)
return "" if page.to_i > Danbooru.config.max_numbered_pages return "" if page.to_i > Danbooru.config.max_numbered_pages
html = "<li>" html = "<li>"
if page == "..." if page == "..."
html << "..." html << "..."

View File

@@ -2,11 +2,11 @@ module PostAppealsHelper
def post_appeal_reasons(post) def post_appeal_reasons(post)
html = [] html = []
html << '<ul>' html << '<ul>'
post.appeals.each do |appeal| post.appeals.each do |appeal|
html << '<li>' + DText.parse_inline(appeal.reason).html_safe + ' - ' + link_to(appeal.creator.name, user_path(appeal.creator)) + ' ' + time_ago_in_words_tagged(appeal.created_at) + '</li>' html << '<li>' + DText.parse_inline(appeal.reason).html_safe + ' - ' + link_to(appeal.creator.name, user_path(appeal.creator)) + ' ' + time_ago_in_words_tagged(appeal.created_at) + '</li>'
end end
html << '</ul>' html << '</ul>'
html.join("\n").html_safe html.join("\n").html_safe
end end

View File

@@ -2,24 +2,24 @@ module PostFlagsHelper
def post_flag_reasons(post) def post_flag_reasons(post)
html = [] html = []
html << '<ul>' html << '<ul>'
post.flags.each do |flag| post.flags.each do |flag|
html << '<li>' html << '<li>'
html << DText.parse_inline(flag.reason).html_safe html << DText.parse_inline(flag.reason).html_safe
if CurrentUser.is_janitor? if CurrentUser.is_janitor?
html << ' - ' + link_to(flag.creator.name, user_path(flag.creator)) html << ' - ' + link_to(flag.creator.name, user_path(flag.creator))
end end
html << ' - ' + time_ago_in_words_tagged(flag.created_at) html << ' - ' + time_ago_in_words_tagged(flag.created_at)
if flag.is_resolved? if flag.is_resolved?
html << ' <span class="resolved">RESOLVED</span>' html << ' <span class="resolved">RESOLVED</span>'
end end
html << '</li>' html << '</li>'
end end
html << '</ul>' html << '</ul>'
html.join("\n").html_safe html.join("\n").html_safe
end end

View File

@@ -5,18 +5,18 @@ module PostsHelper
if post.has_large? if post.has_large?
links << link_to("L", post.large_file_url, :id => "large-file-link") links << link_to("L", post.large_file_url, :id => "large-file-link")
end end
if post.has_large? if post.has_large?
links << link_to("O", post.file_url, :id => "original-file-link") links << link_to("O", post.file_url, :id => "original-file-link")
end end
if links.any? if links.any?
content_tag("span", raw("Resize: " + links.join(" "))) content_tag("span", raw("Resize: " + links.join(" ")))
else else
nil nil
end end
end end
def post_source_tag(post) def post_source_tag(post)
if post.source =~ /^http/ if post.source =~ /^http/
text = truncate(post.normalized_source.sub(/^https?:\/\//, "")) text = truncate(post.normalized_source.sub(/^https?:\/\//, ""))

View File

@@ -1,18 +1,18 @@
class AliasAndImplicationImporter class AliasAndImplicationImporter
attr_accessor :text, :commands, :forum_id attr_accessor :text, :commands, :forum_id
def initialize(text, forum_id) def initialize(text, forum_id)
@forum_id = forum_id @forum_id = forum_id
@text = text @text = text
end end
def process! def process!
tokens = tokenize(text) tokens = tokenize(text)
parse(tokens) parse(tokens)
end end
private private
def tokenize(text) def tokenize(text)
text.gsub!(/^\s+/, "") text.gsub!(/^\s+/, "")
text.gsub!(/\s+$/, "") text.gsub!(/\s+$/, "")
@@ -33,7 +33,7 @@ private
end end
end end
end end
def parse(tokens) def parse(tokens)
ActiveRecord::Base.transaction do ActiveRecord::Base.transaction do
tokens.map do |token| tokens.map do |token|
@@ -41,21 +41,21 @@ private
when :create_alias when :create_alias
tag_alias = TagAlias.create(:forum_topic_id => forum_id, :status => "pending", :antecedent_name => token[1], :consequent_name => token[2]) tag_alias = TagAlias.create(:forum_topic_id => forum_id, :status => "pending", :antecedent_name => token[1], :consequent_name => token[2])
tag_alias.delay(:queue => "default").process! tag_alias.delay(:queue => "default").process!
when :create_implication when :create_implication
tag_implication = TagImplication.create(:forum_topic_id => forum_id, :status => "pending", :antecedent_name => token[1], :consequent_name => token[2]) tag_implication = TagImplication.create(:forum_topic_id => forum_id, :status => "pending", :antecedent_name => token[1], :consequent_name => token[2])
tag_implication.delay(:queue => "default").process! tag_implication.delay(:queue => "default").process!
when :remove_alias when :remove_alias
tag_alias = TagAlias.where("antecedent_name = ?", token[1]).first tag_alias = TagAlias.where("antecedent_name = ?", token[1]).first
raise "Alias for #{token[1]} not found" if tag_alias.nil? raise "Alias for #{token[1]} not found" if tag_alias.nil?
tag_alias.destroy tag_alias.destroy
when :remove_implication when :remove_implication
tag_implication = TagImplication.where("antecedent_name = ? and consequent_name = ?", token[1], token[2]).first tag_implication = TagImplication.where("antecedent_name = ? and consequent_name = ?", token[1], token[2]).first
raise "Implication for #{token[1]} not found" if tag_implication.nil? raise "Implication for #{token[1]} not found" if tag_implication.nil?
tag_implication.destroy tag_implication.destroy
else else
raise "Unknown token: #{token[0]}" raise "Unknown token: #{token[0]}"
end end

View File

@@ -11,15 +11,15 @@ class AnonymousUser
def comment_threshold def comment_threshold
0 0
end end
def created_at def created_at
Time.now Time.now
end end
def updated_at def updated_at
Time.now Time.now
end end
def name def name
"Anonymous" "Anonymous"
end end
@@ -31,11 +31,11 @@ class AnonymousUser
def is_anonymous? def is_anonymous?
true true
end end
def has_mail? def has_mail?
false false
end end
def has_forum_been_updated? def has_forum_been_updated?
false false
end end
@@ -47,11 +47,11 @@ class AnonymousUser
def ban def ban
false false
end end
def always_resize_images? def always_resize_images?
false false
end end
def show_samples? def show_samples?
true true
end end
@@ -59,15 +59,15 @@ class AnonymousUser
def tag_subscriptions def tag_subscriptions
[] []
end end
def favorite_tags def favorite_tags
nil nil
end end
def upload_limit def upload_limit
0 0
end end
def base_upload_limit def base_upload_limit
0 0
end end
@@ -75,15 +75,15 @@ class AnonymousUser
def uploaded_tags def uploaded_tags
"" ""
end end
def uploaded_tags_with_types def uploaded_tags_with_types
[] []
end end
def recent_tags def recent_tags
"" ""
end end
def recent_tags_with_types def recent_tags_with_types
[] []
end end
@@ -91,15 +91,15 @@ class AnonymousUser
def can_upload? def can_upload?
false false
end end
def can_comment? def can_comment?
false false
end end
def can_remove_from_pools? def can_remove_from_pools?
false false
end end
def blacklisted_tags def blacklisted_tags
"" ""
end end
@@ -107,64 +107,64 @@ class AnonymousUser
def time_zone def time_zone
"Eastern Time (US & Canada)" "Eastern Time (US & Canada)"
end end
def default_image_size def default_image_size
"large" "large"
end end
def blacklisted_tags def blacklisted_tags
[] []
end end
def email def email
"" ""
end end
def last_forum_read_at def last_forum_read_at
Time.now Time.now
end end
def update_column(*params) def update_column(*params)
end end
def increment!(field) def increment!(field)
end end
def decrement!(field) def decrement!(field)
end end
def role def role
:anonymous :anonymous
end end
def tag_query_limit def tag_query_limit
2 2
end end
def favorite_limit def favorite_limit
0 0
end end
def favorite_count def favorite_count
0 0
end end
def enable_post_navigation def enable_post_navigation
true true
end end
def new_post_navigation_layout def new_post_navigation_layout
true true
end end
def enable_privacy_mode def enable_privacy_mode
false false
end end
def enable_sequential_post_navigation def enable_sequential_post_navigation
true true
end end
%w(member banned privileged builder platinum contributor janitor moderator admin).each do |name| %w(member banned privileged builder platinum contributor janitor moderator admin).each do |name|
define_method("is_#{name}?") do define_method("is_#{name}?") do
false false

View File

@@ -4,7 +4,7 @@ class Cache
Cache.put(key, val.to_i + 1) Cache.put(key, val.to_i + 1)
ActiveRecord::Base.logger.debug('MemCache Incr %s' % [key]) ActiveRecord::Base.logger.debug('MemCache Incr %s' % [key])
end end
def self.decr(key, expiry = 0) def self.decr(key, expiry = 0)
val = Cache.get(key, expiry) val = Cache.get(key, expiry)
if val.to_i > 0 if val.to_i > 0
@@ -12,7 +12,7 @@ class Cache
end end
ActiveRecord::Base.logger.debug('MemCache Decr %s' % [key]) ActiveRecord::Base.logger.debug('MemCache Decr %s' % [key])
end end
def self.get_multi(keys, prefix, expiry = 0) def self.get_multi(keys, prefix, expiry = 0)
key_to_sanitized_key_hash = keys.inject({}) do |hash, x| key_to_sanitized_key_hash = keys.inject({}) do |hash, x|
hash[x] = "#{prefix}:#{Cache.sanitize(x)}" hash[x] = "#{prefix}:#{Cache.sanitize(x)}"
@@ -30,11 +30,11 @@ class Cache
Cache.put(sanitized_key, result_hash[key], expiry) Cache.put(sanitized_key, result_hash[key], expiry)
end end
end end
ActiveRecord::Base.logger.debug('MemCache Multi-Get (%0.6f) %s' % [elapsed, keys.join(",")]) ActiveRecord::Base.logger.debug('MemCache Multi-Get (%0.6f) %s' % [elapsed, keys.join(",")])
end end
end end
def self.get(key, expiry = 0) def self.get(key, expiry = 0)
begin begin
start_time = Time.now start_time = Time.now
@@ -55,11 +55,11 @@ class Cache
value value
end end
end end
def self.put(key, value, expiry = 0) def self.put(key, value, expiry = 0)
key.gsub!(/\s/, "_") key.gsub!(/\s/, "_")
key = key[0, 200] key = key[0, 200]
begin begin
start_time = Time.now start_time = Time.now
MEMCACHE.set key, value, expiry MEMCACHE.set key, value, expiry
@@ -71,7 +71,7 @@ class Cache
nil nil
end end
end end
def self.delete(key, delay = nil) def self.delete(key, delay = nil)
begin begin
start_time = Time.now start_time = Time.now
@@ -84,7 +84,7 @@ class Cache
nil nil
end end
end end
def self.sanitize(key) def self.sanitize(key)
key.gsub(/\W/) {|x| "%#{x.ord}"}.slice(0, 240) key.gsub(/\W/) {|x| "%#{x.ord}"}.slice(0, 240)
end end

View File

@@ -2,10 +2,10 @@ class CurrentUser
def self.scoped(user, ip_addr) def self.scoped(user, ip_addr)
old_user = self.user old_user = self.user
old_ip_addr = self.ip_addr old_ip_addr = self.ip_addr
self.user = user self.user = user
self.ip_addr = ip_addr self.ip_addr = ip_addr
begin begin
yield yield
ensure ensure
@@ -17,19 +17,19 @@ class CurrentUser
def self.user=(user) def self.user=(user)
Thread.current[:current_user] = user Thread.current[:current_user] = user
end end
def self.ip_addr=(ip_addr) def self.ip_addr=(ip_addr)
Thread.current[:current_ip_addr] = ip_addr Thread.current[:current_ip_addr] = ip_addr
end end
def self.user def self.user
Thread.current[:current_user] Thread.current[:current_user]
end end
def self.ip_addr def self.ip_addr
Thread.current[:current_ip_addr] Thread.current[:current_ip_addr]
end end
def self.id def self.id
if user.nil? if user.nil?
nil nil
@@ -37,11 +37,11 @@ class CurrentUser
user.id user.id
end end
end end
def self.name def self.name
user.name user.name
end end
def self.method_missing(method, *params, &block) def self.method_missing(method, *params, &block)
if user.respond_to?(method) if user.respond_to?(method)
user.__send__(method, *params, &block) user.__send__(method, *params, &block)

View File

@@ -5,11 +5,11 @@ class DText
def self.u(string) def self.u(string)
CGI.escape(string) CGI.escape(string)
end end
def self.h(string) def self.h(string)
CGI.escapeHTML(string) CGI.escapeHTML(string)
end end
def self.parse_inline(str, options = {}) def self.parse_inline(str, options = {})
str.gsub!(/&/, "&amp;") str.gsub!(/&/, "&amp;")
str.gsub!(/</, "&lt;") str.gsub!(/</, "&lt;")
@@ -25,7 +25,7 @@ class DText
str = parse_id_links(str) str = parse_id_links(str)
str str
end end
def self.parse_links(str) def self.parse_links(str)
str.gsub(/("[^"]+":(https?:\/\/|\/)[^\s\r\n<>]+|https?:\/\/[^\s\r\n<>]+)+/) do |url| str.gsub(/("[^"]+":(https?:\/\/|\/)[^\s\r\n<>]+|https?:\/\/[^\s\r\n<>]+)+/) do |url|
if url =~ /^"([^"]+)":(.+)$/ if url =~ /^"([^"]+)":(.+)$/
@@ -34,7 +34,7 @@ class DText
else else
text = url text = url
end end
if url =~ /([;,.!?\)\]<>])$/ if url =~ /([;,.!?\)\]<>])$/
url.chop! url.chop!
ch = $1 ch = $1
@@ -45,7 +45,7 @@ class DText
'<a href="' + url + '">' + text + '</a>' + ch '<a href="' + url + '">' + text + '</a>' + ch
end end
end end
def self.parse_aliased_wiki_links(str) def self.parse_aliased_wiki_links(str)
str.gsub(/\[\[([^\|\]]+)\|([^\]]+)\]\]/m) do str.gsub(/\[\[([^\|\]]+)\|([^\]]+)\]\]/m) do
text = CGI.unescapeHTML($2) text = CGI.unescapeHTML($2)
@@ -53,7 +53,7 @@ class DText
%{<a href="/wiki_pages/show_or_new?title=#{u(title)}">#{h(text)}</a>} %{<a href="/wiki_pages/show_or_new?title=#{u(title)}">#{h(text)}</a>}
end end
end end
def self.parse_wiki_links(str) def self.parse_wiki_links(str)
str.gsub(/\[\[([^\]]+)\]\]/) do str.gsub(/\[\[([^\]]+)\]\]/) do
text = CGI.unescapeHTML($1) text = CGI.unescapeHTML($1)
@@ -61,14 +61,14 @@ class DText
%{<a href="/wiki_pages/show_or_new?title=#{u(title)}">#{h(text)}</a>} %{<a href="/wiki_pages/show_or_new?title=#{u(title)}">#{h(text)}</a>}
end end
end end
def self.parse_post_links(str) def self.parse_post_links(str)
str.gsub(/\{\{([^\}]+)\}\}/) do str.gsub(/\{\{([^\}]+)\}\}/) do
tags = CGI.unescapeHTML($1) tags = CGI.unescapeHTML($1)
%{<a href="/posts?tags=#{u(tags)}">#{h(tags)}</a>} %{<a href="/posts?tags=#{u(tags)}">#{h(tags)}</a>}
end end
end end
def self.parse_id_links(str) def self.parse_id_links(str)
str = str.gsub(/\bpost #(\d+)/i, %{<a href="/posts/\\1">post #\\1</a>}) str = str.gsub(/\bpost #(\d+)/i, %{<a href="/posts/\\1">post #\\1</a>})
str = str.gsub(/\bforum #(\d+)/i, %{<a href="/forum_posts/\\1">forum #\\1</a>}) str = str.gsub(/\bforum #(\d+)/i, %{<a href="/forum_posts/\\1">forum #\\1</a>})
@@ -76,7 +76,7 @@ class DText
str = str.gsub(/\bpool #(\d+)/i, %{<a href="/pools/\\1">pool #\\1</a>}) str = str.gsub(/\bpool #(\d+)/i, %{<a href="/pools/\\1">pool #\\1</a>})
str = str.gsub(/\buser #(\d+)/i, %{<a href="/users/\\1">user #\\1</a>}) str = str.gsub(/\buser #(\d+)/i, %{<a href="/users/\\1">user #\\1</a>})
end end
def self.parse_list(str, options = {}) def self.parse_list(str, options = {})
html = "" html = ""
layout = [] layout = []
@@ -115,27 +115,27 @@ class DText
def self.parse(str, options = {}) def self.parse(str, options = {})
return "" if str.blank? return "" if str.blank?
# Make sure quote tags are surrounded by newlines # Make sure quote tags are surrounded by newlines
unless options[:inline] unless options[:inline]
str.gsub!(/\s*\[quote\]\s*/m, "\n\n[quote]\n\n") str.gsub!(/\s*\[quote\]\s*/m, "\n\n[quote]\n\n")
str.gsub!(/\s*\[\/quote\]\s*/m, "\n\n[/quote]\n\n") str.gsub!(/\s*\[\/quote\]\s*/m, "\n\n[/quote]\n\n")
str.gsub!(/\s*\[spoilers?\](?!\])\s*/m, "\n\n[spoiler]\n\n") str.gsub!(/\s*\[spoilers?\](?!\])\s*/m, "\n\n[spoiler]\n\n")
str.gsub!(/\s*\[\/spoilers?\]\s*/m, "\n\n[/spoiler]\n\n") str.gsub!(/\s*\[\/spoilers?\]\s*/m, "\n\n[/spoiler]\n\n")
end end
str.gsub!(/(?:\r?\n){3,}/, "\n\n") str.gsub!(/(?:\r?\n){3,}/, "\n\n")
str.strip! str.strip!
blocks = str.split(/(?:\r?\n){2}/) blocks = str.split(/(?:\r?\n){2}/)
stack = [] stack = []
html = blocks.map do |block| html = blocks.map do |block|
case block case block
when /^(h[1-6])\.\s*(.+)$/ when /^(h[1-6])\.\s*(.+)$/
tag = $1 tag = $1
content = $2 content = $2
if options[:inline] if options[:inline]
"<h6>" + parse_inline(content, options) + "</h6>" "<h6>" + parse_inline(content, options) + "</h6>"
else else
@@ -144,7 +144,7 @@ class DText
when /^\s*\*+ / when /^\s*\*+ /
parse_list(block, options) parse_list(block, options)
when "[quote]" when "[quote]"
if options[:inline] if options[:inline]
"" ""
@@ -152,7 +152,7 @@ class DText
stack << "blockquote" stack << "blockquote"
"<blockquote>" "<blockquote>"
end end
when "[/quote]" when "[/quote]"
if options[:inline] if options[:inline]
"" ""
@@ -166,7 +166,7 @@ class DText
when /\[spoilers?\](?!\])/ when /\[spoilers?\](?!\])/
stack << "div" stack << "div"
'<div class="spoiler">' '<div class="spoiler">'
when /\[\/spoilers?\]/ when /\[\/spoilers?\]/
if stack.last == "div" if stack.last == "div"
stack.pop stack.pop
@@ -177,7 +177,7 @@ class DText
'<p>' + parse_inline(block) + "</p>" '<p>' + parse_inline(block) + "</p>"
end end
end end
stack.reverse.each do |tag| stack.reverse.each do |tag|
if tag == "blockquote" if tag == "blockquote"
html << "</blockquote>" html << "</blockquote>"
@@ -188,10 +188,10 @@ class DText
sanitize(html.join("")).html_safe sanitize(html.join("")).html_safe
end end
def self.sanitize(text) def self.sanitize(text)
text.gsub!(/<( |-|\Z)/, "&lt;\\1") text.gsub!(/<( |-|\Z)/, "&lt;\\1")
Sanitize.clean( Sanitize.clean(
text, text,
:elements => %w(code center tn h1 h2 h3 h4 h5 h6 a span div blockquote br p ul li ol em strong small big b i font u s), :elements => %w(code center tn h1 h2 h3 h4 h5 h6 a span div blockquote br p ul li ol em strong small big b i font u s),

View File

@@ -1,14 +1,14 @@
module Downloads module Downloads
class File class File
class Error < Exception ; end class Error < Exception ; end
attr_accessor :source, :content_type, :file_path attr_accessor :source, :content_type, :file_path
def initialize(source, file_path) def initialize(source, file_path)
@source = source @source = source
@file_path = file_path @file_path = file_path
end end
def download! def download!
http_get_streaming do |response| http_get_streaming do |response|
self.content_type = response["Content-Type"] self.content_type = response["Content-Type"]
@@ -18,23 +18,23 @@ module Downloads
end end
after_download after_download
end end
def before_download(url, headers) def before_download(url, headers)
Strategies::Base.strategies.each do |strategy| Strategies::Base.strategies.each do |strategy|
url, headers = strategy.new.rewrite(url, headers) url, headers = strategy.new.rewrite(url, headers)
end end
return [url, headers] return [url, headers]
end end
def after_download def after_download
fix_image_board_sources fix_image_board_sources
end end
def url def url
URI.parse(source) URI.parse(source)
end end
def http_get_streaming(options = {}) def http_get_streaming(options = {})
max_size = options[:max_size] || Danbooru.config.max_file_size max_size = options[:max_size] || Danbooru.config.max_file_size
max_size = nil if max_size == 0 # unlimited max_size = nil if max_size == 0 # unlimited
@@ -49,7 +49,7 @@ module Downloads
"User-Agent" => "#{Danbooru.config.safe_app_name}/#{Danbooru.config.version}" "User-Agent" => "#{Danbooru.config.safe_app_name}/#{Danbooru.config.version}"
} }
@source, headers = before_download(source, headers) @source, headers = before_download(source, headers)
Net::HTTP.start(url.host, url.port, :use_ssl => url.is_a?(URI::HTTPS)) do |http| Net::HTTP.start(url.host, url.port, :use_ssl => url.is_a?(URI::HTTPS)) do |http|
http.read_timeout = 10 http.read_timeout = 10
http.request_get(url.request_uri, headers) do |res| http.request_get(url.request_uri, headers) do |res|
@@ -76,7 +76,7 @@ module Downloads
end # http.start end # http.start
end # while end # while
end # def end # def
def fix_image_board_sources def fix_image_board_sources
if source =~ /\/src\/\d{12,}|urnc\.yi\.org|yui\.cynthia\.bne\.jp/ if source =~ /\/src\/\d{12,}|urnc\.yi\.org|yui\.cynthia\.bne\.jp/
@source = "Image board" @source = "Image board"

View File

@@ -4,7 +4,7 @@ module Downloads
def self.strategies def self.strategies
[Pixiv] [Pixiv]
end end
def rewrite(url, headers) def rewrite(url, headers)
return [url, headers] return [url, headers]
end end

View File

@@ -8,16 +8,16 @@ module Downloads
url, headers = rewrite_small_images(url, headers) url, headers = rewrite_small_images(url, headers)
url, headers = rewrite_small_manga_pages(url, headers) url, headers = rewrite_small_manga_pages(url, headers)
end end
return [url, headers] return [url, headers]
end end
protected protected
def rewrite_headers(url, headers) def rewrite_headers(url, headers)
headers["Referer"] = "http://www.pixiv.net" headers["Referer"] = "http://www.pixiv.net"
return [url, headers] return [url, headers]
end end
def rewrite_html_pages(url, headers) def rewrite_html_pages(url, headers)
# example: http://www.pixiv.net/member_illust.php?mode=big&illust_id=23828655 # example: http://www.pixiv.net/member_illust.php?mode=big&illust_id=23828655
@@ -29,16 +29,16 @@ module Downloads
return [url, headers] return [url, headers]
end end
end end
def rewrite_small_images(url, headers) def rewrite_small_images(url, headers)
if url =~ %r!(/img/.+?/.+?)_m.+$! if url =~ %r!(/img/.+?/.+?)_m.+$!
match = $1 match = $1
url.sub!(match + "_m", match) url.sub!(match + "_m", match)
end end
return [url, headers] return [url, headers]
end end
def rewrite_small_manga_pages(url, headers) def rewrite_small_manga_pages(url, headers)
if url =~ %r!(\d+_p\d+)\.! if url =~ %r!(\d+_p\d+)\.!
match = $1 match = $1
@@ -48,7 +48,7 @@ module Downloads
url = big_url url = big_url
end end
end end
return [url, headers] return [url, headers]
end end

View File

@@ -1,10 +1,10 @@
class JanitorTrialTester class JanitorTrialTester
attr_reader :user attr_reader :user
def initialize(user_name) def initialize(user_name)
@user = User.find_by_name(user_name) @user = User.find_by_name(user_name)
end end
def test def test
if user.nil? if user.nil?
"User not found" "User not found"

View File

@@ -7,16 +7,16 @@ module Moderator
def self.all(min_date, max_level) def self.all(min_date, max_level)
sql = <<-EOS sql = <<-EOS
SELECT artist_versions.updater_id AS updater_id, count(*) SELECT artist_versions.updater_id AS updater_id, count(*)
FROM artist_versions FROM artist_versions
JOIN users ON users.id = artist_versions.updater_id JOIN users ON users.id = artist_versions.updater_id
WHERE WHERE
artist_versions.created_at > ? artist_versions.created_at > ?
AND users.level <= ? AND users.level <= ?
GROUP BY artist_versions.updater_id GROUP BY artist_versions.updater_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
end end

View File

@@ -6,20 +6,20 @@ module Moderator
def self.all(min_date, max_level) def self.all(min_date, max_level)
sql = <<-EOS sql = <<-EOS
SELECT comment_votes.comment_id, count(*) SELECT comment_votes.comment_id, count(*)
FROM comment_votes FROM comment_votes
JOIN comments ON comments.id = comment_id JOIN comments ON comments.id = comment_id
JOIN users ON users.id = comments.creator_id JOIN users ON users.id = comments.creator_id
WHERE WHERE
comment_votes.created_at > ? comment_votes.created_at > ?
AND comments.score < 0 AND comments.score < 0
AND users.level <= ? AND users.level <= ?
GROUP BY comment_votes.comment_id GROUP BY comment_votes.comment_id
HAVING count(*) >= 3 HAVING count(*) >= 3
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
end end

View File

@@ -3,23 +3,23 @@ module Moderator
module Queries module Queries
class Note class Note
attr_reader :user, :count attr_reader :user, :count
def self.all(min_date, max_level) def self.all(min_date, max_level)
sql = <<-EOS sql = <<-EOS
SELECT note_versions.updater_id, count(*) SELECT note_versions.updater_id, count(*)
FROM note_versions FROM note_versions
JOIN users ON users.id = note_versions.updater_id JOIN users ON users.id = note_versions.updater_id
WHERE WHERE
note_versions.created_at > ? note_versions.created_at > ?
AND users.level <= ? AND users.level <= ?
GROUP BY note_versions.updater_id GROUP BY note_versions.updater_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
end end
def initialize(hash) def initialize(hash)
@user = ::User.find(hash["updater_id"]) @user = ::User.find(hash["updater_id"])
@count = hash["count"] @count = hash["count"]

View File

@@ -10,14 +10,14 @@ module Moderator
FROM post_appeals FROM post_appeals
JOIN posts ON posts.id = post_appeals.post_id JOIN posts ON posts.id = post_appeals.post_id
WHERE WHERE
post_appeals.created_at > ? post_appeals.created_at > ?
and posts.is_deleted = true and posts.is_deleted = true
and posts.is_pending = false and posts.is_pending = false
GROUP BY post_appeals.post_id GROUP BY post_appeals.post_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date).map {|x| new(x)}
end end

View File

@@ -6,22 +6,22 @@ module Moderator
def self.all(min_date) def self.all(min_date)
sql = <<-EOS sql = <<-EOS
SELECT post_flags.post_id, count(*) SELECT post_flags.post_id, count(*)
FROM post_flags FROM post_flags
JOIN posts ON posts.id = post_flags.post_id JOIN posts ON posts.id = post_flags.post_id
WHERE WHERE
post_flags.created_at > ? post_flags.created_at > ?
AND post_flags.reason <> ? AND post_flags.reason <> ?
AND posts.is_deleted = false AND posts.is_deleted = false
and posts.is_pending = false and posts.is_pending = false
GROUP BY post_flags.post_id GROUP BY post_flags.post_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date, "Unapproved in three days").map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, "Unapproved in three days").map {|x| new(x)}
end end
def initialize(hash) def initialize(hash)
@post = Post.find(hash["post_id"]) @post = Post.find(hash["post_id"])
@count = hash["count"] @count = hash["count"]

View File

@@ -3,25 +3,25 @@ module Moderator
module Queries module Queries
class Tag class Tag
attr_reader :user, :count attr_reader :user, :count
def self.all(min_date, max_level) def self.all(min_date, max_level)
sql = <<-EOS sql = <<-EOS
SELECT post_versions.updater_id, count(*) SELECT post_versions.updater_id, count(*)
FROM post_versions FROM post_versions
JOIN users ON users.id = post_versions.updater_id JOIN users ON users.id = post_versions.updater_id
WHERE WHERE
post_versions.updated_at > ? post_versions.updated_at > ?
AND users.level <= ? AND users.level <= ?
GROUP BY post_versions.updater_id GROUP BY post_versions.updater_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.without_timeout do ActiveRecord::Base.without_timeout do
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
end end
end end
def initialize(hash) def initialize(hash)
@user = ::User.find(hash["updater_id"]) @user = ::User.find(hash["updater_id"])
@count = hash["count"] @count = hash["count"]

View File

@@ -3,23 +3,23 @@ module Moderator
module Queries module Queries
class Upload class Upload
attr_reader :user, :count attr_reader :user, :count
def self.all(min_date, max_level) def self.all(min_date, max_level)
sql = <<-EOS sql = <<-EOS
select uploader_id, count(*) select uploader_id, count(*)
from posts from posts
join users on uploader_id = users.id join users on uploader_id = users.id
where where
posts.created_at > ? posts.created_at > ?
and level <= ? and level <= ?
group by posts.uploader_id group by posts.uploader_id
order by count(*) desc order by count(*) desc
limit 10 limit 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
end end
def initialize(hash) def initialize(hash)
@user = ::User.find(hash["uploader_id"]) @user = ::User.find(hash["uploader_id"])
@count = hash["count"] @count = hash["count"]

View File

@@ -3,23 +3,23 @@ module Moderator
module Queries module Queries
class WikiPage class WikiPage
attr_reader :user, :count attr_reader :user, :count
def self.all(min_date, max_level) def self.all(min_date, max_level)
sql = <<-EOS sql = <<-EOS
SELECT wiki_page_versions.updater_id, count(*) SELECT wiki_page_versions.updater_id, count(*)
FROM wiki_page_versions FROM wiki_page_versions
JOIN users ON users.id = wiki_page_versions.updater_id JOIN users ON users.id = wiki_page_versions.updater_id
WHERE WHERE
wiki_page_versions.created_at > ? wiki_page_versions.created_at > ?
AND users.level <= ? AND users.level <= ?
GROUP BY wiki_page_versions.updater_id GROUP BY wiki_page_versions.updater_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 10 LIMIT 10
EOS EOS
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
end end
def initialize(hash) def initialize(hash)
@user = ::User.find(hash["updater_id"]) @user = ::User.find(hash["updater_id"])
@count = hash["count"] @count = hash["count"]

View File

@@ -2,18 +2,18 @@ module Moderator
module Dashboard module Dashboard
class Report class Report
attr_reader :min_date, :max_level attr_reader :min_date, :max_level
def initialize(min_date, max_level) def initialize(min_date, max_level)
@min_date = min_date.present? ? min_date.to_date : 1.week.ago @min_date = min_date.present? ? min_date.to_date : 1.week.ago
@max_level = max_level.present? ? User::Levels::MEMBER : max_level.to_i @max_level = max_level.present? ? User::Levels::MEMBER : max_level.to_i
end end
def artists def artists
ActiveRecord::Base.without_timeout do ActiveRecord::Base.without_timeout do
Queries::Artist.all(min_date, max_level) Queries::Artist.all(min_date, max_level)
end end
end end
def comments def comments
ActiveRecord::Base.without_timeout do ActiveRecord::Base.without_timeout do
Queries::Comment.all(min_date, max_level) Queries::Comment.all(min_date, max_level)
@@ -55,7 +55,7 @@ module Moderator
Queries::Upload.all(min_date, max_level) Queries::Upload.all(min_date, max_level)
end end
end end
def user_feedbacks def user_feedbacks
ActiveRecord::Base.without_timeout do ActiveRecord::Base.without_timeout do
Queries::UserFeedback.all Queries::UserFeedback.all

View File

@@ -1,12 +1,12 @@
module Moderator module Moderator
class IpAddrSearch class IpAddrSearch
attr_reader :params, :errors attr_reader :params, :errors
def initialize(params) def initialize(params)
@params = params @params = params
@errors = [] @errors = []
end end
def execute def execute
if params[:user_id].present? if params[:user_id].present?
search_by_user_id(params[:user_id].split(/,/)) search_by_user_id(params[:user_id].split(/,/))
@@ -18,41 +18,41 @@ module Moderator
[] []
end end
end end
private private
def select_all_sql(sql, *params) def select_all_sql(sql, *params)
ActiveRecord::Base.select_all_sql(sql, *params) ActiveRecord::Base.select_all_sql(sql, *params)
end end
def search_by_ip_addr(ip_addrs) def search_by_ip_addr(ip_addrs)
sums = Hash.new {|h, k| h[k] = 0} sums = Hash.new {|h, k| h[k] = 0}
add_row(sums, "select creator_id as k, count(*) from comments where ip_addr in (?) group by k", ip_addrs) add_row(sums, "select creator_id as k, count(*) from comments where ip_addr in (?) group by k", ip_addrs)
add_row(sums, "select updater_id as k, count(*) from post_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from post_versions where updater_ip_addr in (?) group by k", ip_addrs)
add_row(sums, "select updater_id as k, count(*) from note_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from note_versions where updater_ip_addr in (?) group by k", ip_addrs)
add_row(sums, "select updater_id as k, count(*) from pool_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from pool_versions where updater_ip_addr in (?) group by k", ip_addrs)
add_row(sums, "select updater_id as k, count(*) from wiki_page_versions where updater_ip_addr in (?) group by k", ip_addrs) add_row(sums, "select updater_id as k, count(*) from wiki_page_versions where updater_ip_addr in (?) group by k", ip_addrs)
sums sums
end end
def search_by_user_name(user_names) def search_by_user_name(user_names)
users = User.where("name in (?)", user_names) users = User.where("name in (?)", user_names)
search_by_user_id(users.map(&:id)) search_by_user_id(users.map(&:id))
end end
def search_by_user_id(user_ids) def search_by_user_id(user_ids)
sums = Hash.new {|h, k| h[k] = 0} sums = Hash.new {|h, k| h[k] = 0}
add_row(sums, "select ip_addr as k, count(*) from comments where creator_id in (?) group by k", user_ids) add_row(sums, "select ip_addr as k, count(*) from comments where creator_id in (?) group by k", user_ids)
add_row(sums, "select updater_ip_addr as k, count(*) from post_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from post_versions where updater_id in (?) group by k", user_ids)
add_row(sums, "select updater_ip_addr as k, count(*) from note_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from note_versions where updater_id in (?) group by k", user_ids)
add_row(sums, "select updater_ip_addr as k, count(*) from pool_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from pool_versions where updater_id in (?) group by k", user_ids)
add_row(sums, "select updater_ip_addr as k, count(*) from wiki_page_versions where updater_id in (?) group by k", user_ids) add_row(sums, "select updater_ip_addr as k, count(*) from wiki_page_versions where updater_id in (?) group by k", user_ids)
sums sums
end end
def add_row(sums, sql, ip_addrs) def add_row(sums, sql, ip_addrs)
select_all_sql(sql, ip_addrs).each do |row| select_all_sql(sql, ip_addrs).each do |row|
sums[row["k"]] += row["count"].to_i sums[row["k"]] += row["count"].to_i

View File

@@ -1,15 +1,15 @@
module Moderator module Moderator
class TagBatchChange < Struct.new(:antecedent, :consequent, :updater_id, :updater_ip_addr) class TagBatchChange < Struct.new(:antecedent, :consequent, :updater_id, :updater_ip_addr)
class Error < Exception ; end class Error < Exception ; end
def perform def perform
raise Error.new("antecedent is missing") if antecedent.blank? raise Error.new("antecedent is missing") if antecedent.blank?
normalized_antecedent = TagAlias.to_aliased(::Tag.scan_tags(antecedent)) normalized_antecedent = TagAlias.to_aliased(::Tag.scan_tags(antecedent))
normalized_consequent = TagAlias.to_aliased(::Tag.scan_tags(consequent)) normalized_consequent = TagAlias.to_aliased(::Tag.scan_tags(consequent))
updater = User.find(updater_id) updater = User.find(updater_id)
CurrentUser.scoped(updater, updater_ip_addr) do CurrentUser.scoped(updater, updater_ip_addr) do
::Post.tag_match(antecedent).each do |post| ::Post.tag_match(antecedent).each do |post|
tags = (post.tag_array - normalized_antecedent + normalized_consequent).join(" ") tags = (post.tag_array - normalized_antecedent + normalized_consequent).join(" ")

View File

@@ -1,16 +1,16 @@
class PostPruner class PostPruner
attr_reader :admin attr_reader :admin
def initialize def initialize
@admin = User.where(:level => User::Levels::ADMIN).first @admin = User.where(:level => User::Levels::ADMIN).first
end end
def prune! def prune!
prune_pending! prune_pending!
prune_flagged! prune_flagged!
prune_mod_actions! prune_mod_actions!
end end
protected protected
def prune_pending! def prune_pending!
@@ -25,7 +25,7 @@ protected
end end
end end
end end
def prune_flagged! def prune_flagged!
CurrentUser.scoped(admin, "127.0.0.1") do CurrentUser.scoped(admin, "127.0.0.1") do
Post.where("is_deleted = ? and is_flagged = ?", false, true).each do |post| Post.where("is_deleted = ? and is_flagged = ?", false, true).each do |post|
@@ -40,7 +40,7 @@ protected
end end
end end
end end
def prune_mod_actions! def prune_mod_actions!
ModAction.destroy_all(["creator_id = ? and description like ?", admin.id, "deleted post %"]) ModAction.destroy_all(["creator_id = ? and description like ?", admin.id, "deleted post %"])
end end

View File

@@ -1,24 +1,24 @@
class PostQueryBuilder class PostQueryBuilder
attr_accessor :query_string, :has_constraints attr_accessor :query_string, :has_constraints
def initialize(query_string) def initialize(query_string)
@query_string = query_string @query_string = query_string
@has_constraint = false @has_constraint = false
end end
def has_constraints? def has_constraints?
@has_constraints @has_constraints
end end
def has_constraints! def has_constraints!
@has_constraints = true @has_constraints = true
end end
def add_range_relation(arr, field, relation) def add_range_relation(arr, field, relation)
return relation if arr.nil? return relation if arr.nil?
has_constraints! has_constraints!
case arr[0] case arr[0]
when :eq when :eq
if arr[1].is_a?(Time) if arr[1].is_a?(Time)
@@ -38,7 +38,7 @@ class PostQueryBuilder
when :lte when :lte
relation.where(["#{field} <= ?", arr[1]]) relation.where(["#{field} <= ?", arr[1]])
when :in when :in
relation.where(["#{field} in (?)", arr[1]]) relation.where(["#{field} in (?)", arr[1]])
@@ -76,10 +76,10 @@ class PostQueryBuilder
if tag_query_sql.any? if tag_query_sql.any?
relation = relation.where("posts.tag_index @@ to_tsquery('danbooru', E?)", tag_query_sql.join(" & ")) relation = relation.where("posts.tag_index @@ to_tsquery('danbooru', E?)", tag_query_sql.join(" & "))
end end
relation relation
end end
def add_tag_subscription_relation(subscriptions, relation) def add_tag_subscription_relation(subscriptions, relation)
subscriptions.each do |subscription| subscriptions.each do |subscription|
if subscription =~ /^(.+?):(.+)$/ if subscription =~ /^(.+?):(.+)$/
@@ -93,25 +93,25 @@ class PostQueryBuilder
return relation if user.nil? return relation if user.nil?
post_ids = TagSubscription.find_post_ids(user.id) post_ids = TagSubscription.find_post_ids(user.id)
end end
post_ids = [0] if post_ids.empty? post_ids = [0] if post_ids.empty?
relation = relation.where(["posts.id IN (?)", post_ids]) relation = relation.where(["posts.id IN (?)", post_ids])
end end
relation relation
end end
def build def build
unless query_string.is_a?(Hash) unless query_string.is_a?(Hash)
q = Tag.parse_query(query_string) q = Tag.parse_query(query_string)
end end
relation = Post.scoped relation = Post.scoped
if q[:tag_count].to_i > Danbooru.config.tag_query_limit if q[:tag_count].to_i > Danbooru.config.tag_query_limit
raise ::Post::SearchError.new("You cannot search for more than #{Danbooru.config.tag_query_limit} tags at a time") raise ::Post::SearchError.new("You cannot search for more than #{Danbooru.config.tag_query_limit} tags at a time")
end end
relation = add_range_relation(q[:post_id], "posts.id", relation) relation = add_range_relation(q[:post_id], "posts.id", relation)
relation = add_range_relation(q[:mpixels], "posts.image_width * posts.image_height / 1000000.0", relation) relation = add_range_relation(q[:mpixels], "posts.image_width * posts.image_height / 1000000.0", relation)
relation = add_range_relation(q[:width], "posts.image_width", relation) relation = add_range_relation(q[:width], "posts.image_width", relation)
@@ -125,12 +125,12 @@ class PostQueryBuilder
relation = add_range_relation(q[:character_tag_count], "posts.tag_count_character", relation) relation = add_range_relation(q[:character_tag_count], "posts.tag_count_character", relation)
relation = add_range_relation(q[:post_tag_count], "posts.tag_count", relation) relation = add_range_relation(q[:post_tag_count], "posts.tag_count", relation)
relation = add_range_relation(q[:pixiv], "substring(posts.source, 'pixiv.net/img.*/([0-9]+)[^/]*$')::integer", relation) relation = add_range_relation(q[:pixiv], "substring(posts.source, 'pixiv.net/img.*/([0-9]+)[^/]*$')::integer", relation)
if q[:md5] if q[:md5]
relation = relation.where(["posts.md5 IN (?)", q[:md5]]) relation = relation.where(["posts.md5 IN (?)", q[:md5]])
has_constraints! has_constraints!
end end
if q[:status] == "pending" if q[:status] == "pending"
relation = relation.where("posts.is_pending = TRUE") relation = relation.where("posts.is_pending = TRUE")
elsif q[:status] == "flagged" elsif q[:status] == "flagged"
@@ -167,26 +167,26 @@ class PostQueryBuilder
if q[:uploader_id_neg] if q[:uploader_id_neg]
relation = relation.where("posts.uploader_id not in (?)", q[:uploader_id_neg]) relation = relation.where("posts.uploader_id not in (?)", q[:uploader_id_neg])
end end
if q[:uploader_id] if q[:uploader_id]
relation = relation.where("posts.uploader_id = ?", q[:uploader_id]) relation = relation.where("posts.uploader_id = ?", q[:uploader_id])
has_constraints! has_constraints!
end end
if q[:approver_id_neg] if q[:approver_id_neg]
relation = relation.where("posts.approver_id not in (?)", q[:approver_id_neg]) relation = relation.where("posts.approver_id not in (?)", q[:approver_id_neg])
end end
if q[:approver_id] if q[:approver_id]
relation = relation.where("posts.approver_id = ?", q[:approver_id]) relation = relation.where("posts.approver_id = ?", q[:approver_id])
has_constraints! has_constraints!
end end
if q[:parent_id] if q[:parent_id]
relation = relation.where("(posts.id = ? or posts.parent_id = ?)", q[:parent_id], q[:parent_id]) relation = relation.where("(posts.id = ? or posts.parent_id = ?)", q[:parent_id], q[:parent_id])
has_constraints! has_constraints!
end end
if q[:rating] =~ /^q/ if q[:rating] =~ /^q/
relation = relation.where("posts.rating = 'q'") relation = relation.where("posts.rating = 'q'")
elsif q[:rating] =~ /^s/ elsif q[:rating] =~ /^s/
@@ -202,13 +202,13 @@ class PostQueryBuilder
elsif q[:rating_negated] =~ /^e/ elsif q[:rating_negated] =~ /^e/
relation = relation.where("posts.rating <> 'e'") relation = relation.where("posts.rating <> 'e'")
end end
relation = add_tag_string_search_relation(q[:tags], relation) relation = add_tag_string_search_relation(q[:tags], relation)
if q[:order] == "rank" if q[:order] == "rank"
relation = relation.where("posts.score > 0 and posts.created_at >= ?", 2.days.ago) relation = relation.where("posts.score > 0 and posts.created_at >= ?", 2.days.ago)
end end
case q[:order] case q[:order]
when "id", "id_asc" when "id", "id_asc"
relation = relation.order("posts.id ASC") relation = relation.order("posts.id ASC")
@@ -221,10 +221,10 @@ class PostQueryBuilder
when "score_asc" when "score_asc"
relation = relation.order("posts.score ASC, posts.id DESC") relation = relation.order("posts.score ASC, posts.id DESC")
when "favcount" when "favcount"
relation = relation.order("posts.fav_count DESC, posts.id DESC") relation = relation.order("posts.fav_count DESC, posts.id DESC")
when "favcount_asc" when "favcount_asc"
relation = relation.order("posts.fav_count ASC, posts.id DESC") relation = relation.order("posts.fav_count ASC, posts.id DESC")

View File

@@ -1,14 +1,14 @@
class PostSearchContext class PostSearchContext
attr_reader :params, :post_id attr_reader :params, :post_id
def initialize(params) def initialize(params)
@params = params @params = params
raise unless params[:seq].present? raise unless params[:seq].present?
raise unless params[:id].present? raise unless params[:id].present?
@post_id = find_post_id @post_id = find_post_id
end end
def find_post_id def find_post_id
if params[:seq] == "prev" if params[:seq] == "prev"
post = Post.tag_match(params[:tags]).where("posts.id > ?", params[:id].to_i).reorder("posts.id asc").first post = Post.tag_match(params[:tags]).where("posts.id > ?", params[:id].to_i).reorder("posts.id asc").first

View File

@@ -1,12 +1,12 @@
module PostSets module PostSets
class Artist < PostSets::Post class Artist < PostSets::Post
attr_reader :artist attr_reader :artist
def initialize(artist) def initialize(artist)
super(artist.name) super(artist.name)
@artist = artist @artist = artist
end end
def posts def posts
::Post.tag_match(@artist.name).limit(10) ::Post.tag_match(@artist.name).limit(10)
rescue ::Post::SearchError rescue ::Post::SearchError

View File

@@ -3,38 +3,38 @@ module PostSets
def has_wiki? def has_wiki?
false false
end end
def wiki_page def wiki_page
nil nil
end end
def has_artist? def has_artist?
false false
end end
def artist def artist
nil nil
end end
def is_single_tag? def is_single_tag?
false false
end end
def presenter def presenter
raise NotImplementedError raise NotImplementedError
end end
def arbitrary_sql_order_clause(ids, table_name) def arbitrary_sql_order_clause(ids, table_name)
if ids.empty? if ids.empty?
return "#{table_name}.id desc" return "#{table_name}.id desc"
end end
conditions = [] conditions = []
ids.each_with_index do |x, n| ids.each_with_index do |x, n|
conditions << "when #{x} then #{n}" conditions << "when #{x} then #{n}"
end end
"case #{table_name}.id " + conditions.join(" ") + " end" "case #{table_name}.id " + conditions.join(" ") + " end"
end end
end end

View File

@@ -1,28 +1,28 @@
module PostSets module PostSets
class Favorite < Base class Favorite < Base
attr_reader :user, :page, :favorites attr_reader :user, :page, :favorites
def initialize(user_id, page = 1) def initialize(user_id, page = 1)
@user = ::User.find(user_id) @user = ::User.find(user_id)
@favorites = ::Favorite.for_user(user.id).paginate(page).order("favorites.id desc") @favorites = ::Favorite.for_user(user.id).paginate(page).order("favorites.id desc")
end end
def tag_array def tag_array
@tag_array ||= ["fav:#{user.name}"] @tag_array ||= ["fav:#{user.name}"]
end end
def tag_string def tag_string
tag_array.uniq.join(" ") tag_array.uniq.join(" ")
end end
def humanized_tag_string def humanized_tag_string
"fav:#{user.pretty_name}" "fav:#{user.pretty_name}"
end end
def posts def posts
favorites.includes(:post).map(&:post) favorites.includes(:post).map(&:post)
end end
def presenter def presenter
@presenter ||= ::PostSetPresenters::Favorite.new(self) @presenter ||= ::PostSetPresenters::Favorite.new(self)
end end

View File

@@ -3,26 +3,26 @@ module PostSets
module ActiveRecordExtension module ActiveRecordExtension
attr_accessor :total_pages, :current_page attr_accessor :total_pages, :current_page
end end
attr_reader :pool, :page attr_reader :pool, :page
def initialize(pool, page = 1) def initialize(pool, page = 1)
@pool = pool @pool = pool
@page = page @page = page
end end
def offset def offset
(current_page - 1) * limit (current_page - 1) * limit
end end
def limit def limit
Danbooru.config.posts_per_page Danbooru.config.posts_per_page
end end
def tag_array def tag_array
["pool:#{pool.id}"] ["pool:#{pool.id}"]
end end
def posts def posts
@posts ||= begin @posts ||= begin
x = pool.posts(:offset => offset, :limit => limit) x = pool.posts(:offset => offset, :limit => limit)
@@ -32,27 +32,27 @@ module PostSets
x x
end end
end end
def tag_string def tag_string
tag_array.join("") tag_array.join("")
end end
def humanized_tag_string def humanized_tag_string
"pool:#{pool.pretty_name}" "pool:#{pool.pretty_name}"
end end
def presenter def presenter
@presenter ||= PostSetPresenters::Pool.new(self) @presenter ||= PostSetPresenters::Pool.new(self)
end end
def total_pages def total_pages
(pool.post_count.to_f / limit).ceil (pool.post_count.to_f / limit).ceil
end end
def size def size
posts.size posts.size
end end
def current_page def current_page
[page.to_i, 1].max [page.to_i, 1].max
end end

View File

@@ -1,41 +1,41 @@
module PostSets module PostSets
class Popular < Base class Popular < Base
attr_reader :date, :scale attr_reader :date, :scale
def initialize(date, scale) def initialize(date, scale)
@date = date.blank? ? Time.zone.now : Time.zone.parse(date) @date = date.blank? ? Time.zone.now : Time.zone.parse(date)
@scale = scale @scale = scale
end end
def posts def posts
::Post.where("created_at between ? and ?", min_date.beginning_of_day, max_date.end_of_day).order("score desc").limit(limit) ::Post.where("created_at between ? and ?", min_date.beginning_of_day, max_date.end_of_day).order("score desc").limit(limit)
end end
def limit def limit
25 25
end end
def min_date def min_date
case scale case scale
when "week" when "week"
date.beginning_of_week date.beginning_of_week
when "month" when "month"
date.beginning_of_month date.beginning_of_month
else else
date date
end end
end end
def max_date def max_date
case scale case scale
when "week" when "week"
date.end_of_week date.end_of_week
when "month" when "month"
date.end_of_month date.end_of_month
else else
date date
end end

View File

@@ -1,22 +1,22 @@
module PostSets module PostSets
class Post < Base class Post < Base
attr_reader :tag_array, :page, :per_page attr_reader :tag_array, :page, :per_page
def initialize(tags, page = 1, per_page = nil) def initialize(tags, page = 1, per_page = nil)
@tag_array = Tag.scan_query(tags) @tag_array = Tag.scan_query(tags)
@page = page @page = page
@per_page = (per_page || Danbooru.config.posts_per_page).to_i @per_page = (per_page || Danbooru.config.posts_per_page).to_i
@per_page = 200 if @per_page > 200 @per_page = 200 if @per_page > 200
end end
def tag_string def tag_string
@tag_string ||= tag_array.uniq.join(" ") @tag_string ||= tag_array.uniq.join(" ")
end end
def humanized_tag_string def humanized_tag_string
tag_array.slice(0, 25).join(" ").tr("_", " ") tag_array.slice(0, 25).join(" ").tr("_", " ")
end end
def has_wiki? def has_wiki?
tag_array.size == 1 && ::WikiPage.titled(tag_string).exists? tag_array.size == 1 && ::WikiPage.titled(tag_string).exists?
end end
@@ -28,15 +28,15 @@ module PostSets
nil nil
end end
end end
def has_deleted? def has_deleted?
CurrentUser.is_privileged? && tag_string !~ /status/ && ::Post.tag_match("#{tag_string} status:deleted").exists? CurrentUser.is_privileged? && tag_string !~ /status/ && ::Post.tag_match("#{tag_string} status:deleted").exists?
end end
def has_explicit? def has_explicit?
posts.any? {|x| x.rating == "e"} posts.any? {|x| x.rating == "e"}
end end
def posts def posts
if tag_array.size > 2 && !CurrentUser.is_privileged? if tag_array.size > 2 && !CurrentUser.is_privileged?
raise SearchError.new("Upgrade your account to search more than two tags at once") raise SearchError.new("Upgrade your account to search more than two tags at once")
@@ -45,50 +45,50 @@ module PostSets
if tag_array.any? {|x| x =~ /^source:.*\*.*pixiv/} && !CurrentUser.user.is_builder? if tag_array.any? {|x| x =~ /^source:.*\*.*pixiv/} && !CurrentUser.user.is_builder?
raise SearchError.new("Your search took too long to execute and was canceled") raise SearchError.new("Your search took too long to execute and was canceled")
end end
@posts ||= begin @posts ||= begin
temp = ::Post.tag_match(tag_string).paginate(page, :count => ::Post.fast_count(tag_string), :limit => per_page) temp = ::Post.tag_match(tag_string).paginate(page, :count => ::Post.fast_count(tag_string), :limit => per_page)
temp.all temp.all
temp temp
end end
end end
def has_artist? def has_artist?
tag_array.any? && ::Artist.name_equals(tag_string).exists? tag_array.any? && ::Artist.name_equals(tag_string).exists?
end end
def artist def artist
::Artist.name_matches(tag_string).first ::Artist.name_matches(tag_string).first
end end
def is_single_tag? def is_single_tag?
tag_array.size == 1 tag_array.size == 1
end end
def is_empty_tag? def is_empty_tag?
tag_array.size == 0 tag_array.size == 0
end end
def is_pattern_search? def is_pattern_search?
tag_string =~ /\*/ tag_string =~ /\*/
end end
def current_page def current_page
[page.to_i, 1].max [page.to_i, 1].max
end end
def is_tag_subscription? def is_tag_subscription?
tag_subscription.present? tag_subscription.present?
end end
def tag_subscription def tag_subscription
@tag_subscription ||= tag_array.select {|x| x =~ /^sub:/}.map {|x| x.sub(/^sub:/, "")}.first @tag_subscription ||= tag_array.select {|x| x =~ /^sub:/}.map {|x| x.sub(/^sub:/, "")}.first
end end
def tag_subscription_tags def tag_subscription_tags
@tag_subscription_tags ||= TagSubscription.find_tags(tag_subscription) @tag_subscription_tags ||= TagSubscription.find_tags(tag_subscription)
end end
def presenter def presenter
@presenter ||= ::PostSetPresenters::Post.new(self) @presenter ||= ::PostSetPresenters::Post.new(self)
end end

View File

@@ -1,7 +1,7 @@
module PostSets module PostSets
class SearchError < Exception class SearchError < Exception
end end
class WikiPage < Post class WikiPage < Post
def presenter def presenter
@presenter ||= ::PostSetPresenters::WikiPage.new(self) @presenter ||= ::PostSetPresenters::WikiPage.new(self)

View File

@@ -2,25 +2,25 @@ class RelatedTagCalculator
def self.find_tags(tag, limit) def self.find_tags(tag, limit)
Post.tag_match(tag).limit(limit).select("posts.tag_string").reorder("posts.md5").map(&:tag_string) Post.tag_match(tag).limit(limit).select("posts.tag_string").reorder("posts.md5").map(&:tag_string)
end end
def self.calculate_from_sample_to_array(tags, category_constraint = nil) def self.calculate_from_sample_to_array(tags, category_constraint = nil)
convert_hash_to_array(calculate_from_sample(tags, Danbooru.config.post_sample_size, category_constraint)) convert_hash_to_array(calculate_from_sample(tags, Danbooru.config.post_sample_size, category_constraint))
end end
def self.calculate_from_sample(tags, limit, category_constraint = nil) def self.calculate_from_sample(tags, limit, category_constraint = nil)
counts = Hash.new {|h, k| h[k] = 0} counts = Hash.new {|h, k| h[k] = 0}
case category_constraint case category_constraint
when Tag.categories.artist when Tag.categories.artist
limit *= 4 limit *= 4
when Tag.categories.copyright when Tag.categories.copyright
limit *= 3 limit *= 3
when Tag.categories.character when Tag.categories.character
limit *= 2 limit *= 2
end end
find_tags(tags, limit).each do |tags| find_tags(tags, limit).each do |tags|
tag_array = Tag.scan_tags(tags) tag_array = Tag.scan_tags(tags)
if category_constraint if category_constraint
@@ -36,14 +36,14 @@ class RelatedTagCalculator
end end
end end
end end
counts counts
end end
def self.convert_hash_to_array(hash) def self.convert_hash_to_array(hash)
hash.to_a.sort_by {|x| -x[1]}.slice(0, 25) hash.to_a.sort_by {|x| -x[1]}.slice(0, 25)
end end
def self.convert_hash_to_string(hash) def self.convert_hash_to_string(hash)
convert_hash_to_array(hash).flatten.join(" ") convert_hash_to_array(hash).flatten.join(" ")
end end

View File

@@ -1,6 +1,6 @@
class RelatedTagQuery class RelatedTagQuery
attr_reader :query, :category attr_reader :query, :category
def initialize(query, category) def initialize(query, category)
@query = query.strip @query = query.strip
@category = category @category = category
@@ -17,7 +17,7 @@ class RelatedTagQuery
[] []
end end
end end
def wiki_page_tags def wiki_page_tags
results = wiki_page.try(:tags) || [] results = wiki_page.try(:tags) || []
results.reject! do |name| results.reject! do |name|
@@ -25,31 +25,31 @@ class RelatedTagQuery
end end
results results
end end
def to_json def to_json
{:query => query, :category => category, :tags => map_with_category_data(tags), :wiki_page_tags => map_with_category_data(wiki_page_tags)}.to_json {:query => query, :category => category, :tags => map_with_category_data(tags), :wiki_page_tags => map_with_category_data(wiki_page_tags)}.to_json
end end
protected protected
def map_with_category_data(list_of_tag_names) def map_with_category_data(list_of_tag_names)
Tag.categories_for(list_of_tag_names).to_a Tag.categories_for(list_of_tag_names).to_a
end end
def pattern_matching_tags def pattern_matching_tags
Tag.name_matches(query).where("post_count > 0").order("post_count desc").limit(50).sort_by {|x| x.name}.map(&:name) Tag.name_matches(query).where("post_count > 0").order("post_count desc").limit(50).sort_by {|x| x.name}.map(&:name)
end end
def related_tags def related_tags
tag = Tag.named(query.strip).first tag = Tag.named(query.strip).first
if tag if tag
tag.related_tag_array.map(&:first) tag.related_tag_array.map(&:first)
else else
[] []
end end
end end
def related_tags_by_category def related_tags_by_category
RelatedTagCalculator.calculate_from_sample_to_array(query, Tag.categories.value_for(category)).map(&:first) RelatedTagCalculator.calculate_from_sample_to_array(query, Tag.categories.value_for(category)).map(&:first)
end end

View File

@@ -1,10 +1,10 @@
class RemoteFileManager class RemoteFileManager
attr_reader :path attr_reader :path
def initialize(path) def initialize(path)
@path = path @path = path
end end
def distribute def distribute
Danbooru.config.other_server_hosts.each do |hostname| Danbooru.config.other_server_hosts.each do |hostname|
Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp| Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp|
@@ -12,7 +12,7 @@ class RemoteFileManager
end end
end end
end end
def delete def delete
Danbooru.config.other_server_hosts.each do |hostname| Danbooru.config.other_server_hosts.each do |hostname|
Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp| Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp|

View File

@@ -1,6 +1,6 @@
class SessionCreator class SessionCreator
attr_reader :session, :cookies, :name, :password, :remember attr_reader :session, :cookies, :name, :password, :remember
def initialize(session, cookies, name, password, remember) def initialize(session, cookies, name, password, remember)
@session = session @session = session
@cookies = cookies @cookies = cookies
@@ -8,17 +8,17 @@ class SessionCreator
@password = password @password = password
@remember = remember @remember = remember
end end
def authenticate def authenticate
if User.authenticate(name, password) if User.authenticate(name, password)
user = User.find_by_name(name) user = User.find_by_name(name)
user.update_column(:last_logged_in_at, Time.now) user.update_column(:last_logged_in_at, Time.now)
if remember.present? if remember.present?
cookies.permanent.signed[:user_name] = user.name cookies.permanent.signed[:user_name] = user.name
cookies.permanent[:password_hash] = user.bcrypt_cookie_password_hash cookies.permanent[:password_hash] = user.bcrypt_cookie_password_hash
end end
session[:user_id] = user.id session[:user_id] = user.id
return true return true
else else

View File

@@ -1,55 +1,55 @@
class SessionLoader class SessionLoader
attr_reader :session, :cookies, :request attr_reader :session, :cookies, :request
def initialize(session, cookies, request) def initialize(session, cookies, request)
@session = session @session = session
@cookies = cookies @cookies = cookies
@request = request @request = request
end end
def load def load
if session[:user_id] if session[:user_id]
load_session_user load_session_user
elsif cookie_password_hash_valid? elsif cookie_password_hash_valid?
load_cookie_user load_cookie_user
end end
if CurrentUser.user if CurrentUser.user
CurrentUser.user.unban! if ban_expired? CurrentUser.user.unban! if ban_expired?
else else
CurrentUser.user = AnonymousUser.new CurrentUser.user = AnonymousUser.new
end end
update_last_logged_in_at update_last_logged_in_at
set_time_zone set_time_zone
end end
private private
def load_session_user def load_session_user
CurrentUser.user = User.find_by_id(session[:user_id]) CurrentUser.user = User.find_by_id(session[:user_id])
CurrentUser.ip_addr = request.remote_ip CurrentUser.ip_addr = request.remote_ip
end end
def load_cookie_user def load_cookie_user
CurrentUser.user = User.find_by_name(cookies.signed[:user_name]) CurrentUser.user = User.find_by_name(cookies.signed[:user_name])
CurrentUser.ip_addr = request.remote_ip CurrentUser.ip_addr = request.remote_ip
end end
def ban_expired? def ban_expired?
CurrentUser.user.is_banned? && CurrentUser.user.ban && CurrentUser.user.ban.expired? CurrentUser.user.is_banned? && CurrentUser.user.ban && CurrentUser.user.ban.expired?
end end
def cookie_password_hash_valid? def cookie_password_hash_valid?
cookies[:password_hash] && cookies.signed[:user_name] && User.authenticate_cookie_hash(cookies.signed[:user_name], cookies[:password_hash]) cookies[:password_hash] && cookies.signed[:user_name] && User.authenticate_cookie_hash(cookies.signed[:user_name], cookies[:password_hash])
end end
def update_last_logged_in_at def update_last_logged_in_at
return if CurrentUser.is_anonymous? return if CurrentUser.is_anonymous?
return if CurrentUser.last_logged_in_at && CurrentUser.last_logged_in_at > 1.week.ago return if CurrentUser.last_logged_in_at && CurrentUser.last_logged_in_at > 1.week.ago
CurrentUser.user.update_attribute(:last_logged_in_at, Time.now) CurrentUser.user.update_attribute(:last_logged_in_at, Time.now)
end end
def set_time_zone def set_time_zone
Time.zone = CurrentUser.user.time_zone Time.zone = CurrentUser.user.time_zone
end end

View File

@@ -2,14 +2,14 @@ module Sources
class Site class Site
attr_reader :url, :strategy attr_reader :url, :strategy
delegate :get, :referer_url, :site_name, :artist_name, :profile_url, :image_url, :tags, :artist_record, :unique_id, :to => :strategy delegate :get, :referer_url, :site_name, :artist_name, :profile_url, :image_url, :tags, :artist_record, :unique_id, :to => :strategy
def self.strategies def self.strategies
[Strategies::NicoSeiga, Strategies::Pixiv] [Strategies::NicoSeiga, Strategies::Pixiv]
end end
def initialize(url) def initialize(url)
@url = url @url = url
Site.strategies.each do |strategy| Site.strategies.each do |strategy|
if strategy.url_match?(url) if strategy.url_match?(url)
@strategy = strategy.new(url) @strategy = strategy.new(url)
@@ -18,7 +18,7 @@ module Sources
end end
end end
end end
def to_json def to_json
return { return {
:artist_name => artist_name, :artist_name => artist_name,
@@ -30,7 +30,7 @@ module Sources
:unique_id => unique_id :unique_id => unique_id
}.to_json }.to_json
end end
def available? def available?
strategy.present? strategy.present?
end end

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