From cba839ba76085dd614a0eff0f885ab60e7ad42e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=A4=AA?= Date: Tue, 19 Mar 2013 23:10:10 +1100 Subject: [PATCH] Kill trailing whitespace in ruby files --- ...lias_and_implication_imports_controller.rb | 4 +- app/controllers/admin/users_controller.rb | 4 +- .../advertisement_hits_controller.rb | 2 +- app/controllers/advertisements_controller.rb | 16 +- app/controllers/application_controller.rb | 18 +- app/controllers/artists_controller.rb | 22 +- app/controllers/bans_controller.rb | 18 +- app/controllers/comment_votes_controller.rb | 2 +- app/controllers/comments_controller.rb | 24 +- app/controllers/dmails_controller.rb | 14 +- app/controllers/explore/posts_controller.rb | 2 +- app/controllers/favorites_controller.rb | 6 +- app/controllers/forum_posts_controller.rb | 16 +- app/controllers/forum_topics_controller.rb | 20 +- app/controllers/ip_bans_controller.rb | 4 +- app/controllers/janitor_trials_controller.rb | 14 +- app/controllers/legacy_controller.rb | 10 +- .../user/login_reminders_controller.rb | 4 +- .../user/password_resets_controller.rb | 8 +- .../moderator/dashboards_controller.rb | 2 +- .../moderator/invitations_controller.rb | 6 +- .../moderator/ip_addrs_controller.rb | 4 +- .../moderator/post/approvals_controller.rb | 2 +- .../moderator/post/disapprovals_controller.rb | 2 +- .../moderator/post/posts_controller.rb | 6 +- .../moderator/post/queues_controller.rb | 2 +- app/controllers/moderator/tags_controller.rb | 6 +- app/controllers/news_updates_controller.rb | 12 +- app/controllers/note_versions_controller.rb | 2 +- app/controllers/notes_controller.rb | 14 +- app/controllers/pool_elements_controller.rb | 12 +- app/controllers/pool_versions_controller.rb | 2 +- app/controllers/pools_controller.rb | 18 +- app/controllers/post_appeals_controller.rb | 4 +- app/controllers/post_flags_controller.rb | 4 +- app/controllers/post_versions_controller.rb | 2 +- app/controllers/post_votes_controller.rb | 2 +- app/controllers/posts_controller.rb | 14 +- app/controllers/related_tags_controller.rb | 2 +- app/controllers/sessions_controller.rb | 8 +- app/controllers/sources_controller.rb | 4 +- app/controllers/static_controller.rb | 2 +- .../tag_alias_corrections_controller.rb | 6 +- .../tag_alias_requests_controller.rb | 4 +- app/controllers/tag_aliases_controller.rb | 12 +- app/controllers/tag_corrections_controller.rb | 6 +- .../tag_implication_requests_controller.rb | 4 +- .../tag_implications_controller.rb | 10 +- .../tag_subscriptions_controller.rb | 14 +- app/controllers/tags_controller.rb | 10 +- app/controllers/uploads_controller.rb | 8 +- app/controllers/user_feedbacks_controller.rb | 10 +- app/controllers/users_controller.rb | 22 +- .../wiki_page_versions_controller.rb | 6 +- app/controllers/wiki_pages_controller.rb | 16 +- app/helpers/advertisements_helper.rb | 12 +- app/helpers/application_helper.rb | 68 ++-- app/helpers/artists_helper.rb | 6 +- app/helpers/delayed_jobs_helper.rb | 14 +- app/helpers/moderator/dashboards_helper.rb | 2 +- app/helpers/pagination_helper.rb | 28 +- app/helpers/post_appeals_helper.rb | 4 +- app/helpers/post_flags_helper.rb | 10 +- app/helpers/posts_helper.rb | 6 +- app/logical/alias_and_implication_importer.rb | 18 +- app/logical/anonymous_user.rb | 64 ++-- app/logical/cache.rb | 16 +- app/logical/current_user.rb | 16 +- app/logical/d_text.rb | 42 +-- app/logical/downloads/file.rb | 20 +- app/logical/downloads/strategies/base.rb | 2 +- app/logical/downloads/strategies/pixiv.rb | 14 +- app/logical/janitor_trial_tester.rb | 4 +- .../moderator/dashboard/queries/artist.rb | 16 +- .../moderator/dashboard/queries/comment.rb | 22 +- .../moderator/dashboard/queries/note.rb | 22 +- .../dashboard/queries/post_appeal.rb | 4 +- .../moderator/dashboard/queries/post_flag.rb | 18 +- .../moderator/dashboard/queries/tag.rb | 22 +- .../moderator/dashboard/queries/upload.rb | 22 +- .../moderator/dashboard/queries/wiki_page.rb | 22 +- app/logical/moderator/dashboard/report.rb | 8 +- app/logical/moderator/ip_addr_search.rb | 22 +- app/logical/moderator/tag_batch_change.rb | 8 +- app/logical/post_pruner.rb | 10 +- app/logical/post_query_builder.rb | 54 ++-- app/logical/post_search_context.rb | 6 +- app/logical/post_sets/artist.rb | 4 +- app/logical/post_sets/base.rb | 18 +- app/logical/post_sets/favorite.rb | 12 +- app/logical/post_sets/pool.rb | 24 +- app/logical/post_sets/popular.rb | 18 +- app/logical/post_sets/post.rb | 36 +-- app/logical/post_sets/wiki_page.rb | 2 +- app/logical/related_tag_calculator.rb | 18 +- app/logical/related_tag_query.rb | 18 +- app/logical/remote_file_manager.rb | 6 +- app/logical/session_creator.rb | 8 +- app/logical/session_loader.rb | 20 +- app/logical/sources/site.rb | 10 +- app/logical/sources/strategies/base.rb | 16 +- app/logical/sources/strategies/nico_seiga.rb | 14 +- app/logical/sources/strategies/pixiv.rb | 22 +- app/logical/tag_alias_correction.rb | 18 +- app/logical/tag_alias_request.rb | 12 +- app/logical/tag_correction.rb | 16 +- app/logical/tag_implication_request.rb | 12 +- app/logical/uploaded_tags_importer.rb | 6 +- .../maintenance/user/password_reset_mailer.rb | 2 +- app/mailers/user_mailer.rb | 6 +- app/models/advertisement.rb | 22 +- app/models/advertisement_hit.rb | 2 +- app/models/amazon_backup.rb | 10 +- app/models/artist.rb | 70 ++-- app/models/artist_url.rb | 10 +- app/models/artist_version.rb | 14 +- app/models/ban.rb | 32 +- app/models/comment.rb | 40 +-- app/models/comment_vote.rb | 20 +- app/models/dmail.rb | 70 ++-- app/models/favorite.rb | 2 +- app/models/forum_post.rb | 54 ++-- app/models/forum_topic.rb | 22 +- app/models/ip_ban.rb | 14 +- app/models/janitor_trial.rb | 28 +- app/models/mod_action.rb | 8 +- app/models/news_update.rb | 4 +- app/models/note.rb | 46 +-- app/models/note_version.rb | 10 +- app/models/pool.rb | 90 +++--- app/models/pool_version.rb | 20 +- app/models/post.rb | 300 +++++++++--------- app/models/post_appeal.rb | 26 +- app/models/post_flag.rb | 32 +- app/models/post_version.rb | 32 +- app/models/post_vote.rb | 4 +- app/models/report_mailer.rb | 2 +- app/models/tag.rb | 134 ++++---- app/models/tag_alias.rb | 42 +-- app/models/tag_implication.rb | 40 +-- app/models/tag_subscription.rb | 36 +-- app/models/upload.rb | 96 +++--- app/models/user.rb | 194 +++++------ app/models/user_feedback.rb | 30 +- app/models/user_password_reset_nonce.rb | 6 +- app/models/wiki_page.rb | 38 +-- app/models/wiki_page_version.rb | 12 +- app/presenters/forum_topic_presenter.rb | 2 +- app/presenters/note_presenter.rb | 4 +- app/presenters/post_presenter.rb | 54 ++-- app/presenters/post_set_presenters/base.rb | 2 +- .../post_set_presenters/favorite.rb | 4 +- app/presenters/post_set_presenters/pool.rb | 4 +- app/presenters/post_set_presenters/popular.rb | 48 +-- app/presenters/post_set_presenters/post.rb | 16 +- .../post_set_presenters/wiki_page.rb | 2 +- app/presenters/post_version_presenter.rb | 6 +- app/presenters/presenter.rb | 6 +- app/presenters/tag_set_presenter.rb | 36 +-- app/presenters/upload_presenter.rb | 4 +- app/presenters/user_presenter.rb | 56 ++-- app/presenters/wiki_page_presenter.rb | 12 +- config/application.rb | 2 +- config/danbooru_default_config.rb | 104 +++--- config/deploy.rb | 24 +- .../active_record_api_extensions.rb | 6 +- .../initializers/active_record_extensions.rb | 16 +- config/initializers/core_extensions.rb | 2 +- config/initializers/danbooru_config.rb | 2 +- config/initializers/query_trace.rb | 2 +- config/routes.rb | 24 +- config/schedule.rb | 2 +- config/state_checker.rb | 6 +- db/migrate/20100204211522_create_users.rb | 8 +- db/migrate/20100204214746_create_posts.rb | 10 +- db/migrate/20100205162521_create_tags.rb | 2 +- .../20100205163027_create_post_versions.rb | 4 +- db/migrate/20100205224030_create_uploads.rb | 2 +- db/migrate/20100211025616_create_pools.rb | 2 +- db/migrate/20100211181944_create_favorites.rb | 14 +- .../20100211191709_create_tag_aliases.rb | 2 +- .../20100211191716_create_tag_implications.rb | 2 +- db/migrate/20100213181847_create_comments.rb | 2 +- .../20100213183712_create_comment_votes.rb | 2 +- .../20100214080557_create_artist_versions.rb | 2 +- .../20100214080605_create_artist_urls.rb | 4 +- .../20100215182234_create_wiki_pages.rb | 2 +- ...0100215213756_create_wiki_page_versions.rb | 2 +- .../20100215223541_create_post_votes.rb | 2 +- .../20100215224629_create_advertisements.rb | 2 +- ...0100215224635_create_advertisement_hits.rb | 2 +- db/migrate/20100215225710_create_bans.rb | 2 +- .../20100215230642_create_user_feedback.rb | 2 +- db/migrate/20100219230537_create_dmails.rb | 4 +- .../20100221003655_create_forum_topics.rb | 2 +- ...20100223001012_create_post_disapprovals.rb | 2 +- db/migrate/20100224171915_create_notes.rb | 2 +- .../20100224172146_create_note_versions.rb | 2 +- ...20100307073438_create_tag_subscriptions.rb | 2 +- .../20100309211553_create_janitor_trials.rb | 2 +- db/migrate/20100318213503_create_ip_bans.rb | 2 +- .../20100826232512_create_delayed_jobs.rb | 2 +- .../20110328215652_create_post_flags.rb | 2 +- .../20110328215701_create_post_appeals.rb | 2 +- .../20110607194023_create_pool_versions.rb | 2 +- .../20111101212358_create_news_updates.rb | 2 +- ...130305005138_add_bcrypt_fields_to_users.rb | 2 +- db/seeds.rb | 16 +- .../paginator/active_record_extension.rb | 26 +- .../numbered_collection_extension.rb | 4 +- .../sequential_collection_extension.rb | 6 +- .../danbooru_image_resizer.rb | 12 +- lib/imagesize/setup.rb | 8 +- lib/imagesize/test/test_image_size.rb | 6 +- script/fixes/005.rb | 12 +- test/factories/tag.rb | 2 +- test/factories/tag_alias.rb | 2 +- test/factories/tag_implication.rb | 2 +- test/factories/upload.rb | 2 +- test/factories/user.rb | 2 +- .../advertisements_controller_test.rb | 16 +- .../artist_versions_controller_test.rb | 6 +- test/functional/artists_controller_test.rb | 18 +- test/functional/bans_controller_test.rb | 16 +- .../comment_votes_controller_test.rb | 6 +- test/functional/comments_controller_test.rb | 8 +- test/functional/dmails_controller_test.rb | 24 +- test/functional/favorites_controller_test.rb | 14 +- .../functional/forum_posts_controller_test.rb | 24 +- .../forum_topics_controller_test.rb | 26 +- test/functional/ip_bans_controller_test.rb | 12 +- .../janitor_trials_controller_test.rb | 18 +- .../user/login_reminders_controller_test.rb | 2 +- .../user/password_resets_controller_test.rb | 28 +- .../moderator/dashboards_controller_test.rb | 32 +- .../moderator/invitations_controller_test.rb | 8 +- .../moderator/ip_addrs_controller_test.rb | 4 +- .../post/approvals_controller_test.rb | 4 +- .../post/disapprovals_controller_test.rb | 4 +- .../moderator/post/posts_controller_test.rb | 6 +- .../moderator/post/queues_controller_test.rb | 4 +- .../moderator/tags_controller_test.rb | 4 +- .../news_updates_controller_test.rb | 14 +- .../note_versions_controller_test.rb | 12 +- test/functional/notes_controller_test.rb | 22 +- .../pool_elements_controller_test.rb | 12 +- .../pool_versions_controller_test.rb | 12 +- test/functional/pools_controller_test.rb | 30 +- .../post_appeals_controller_test.rb | 16 +- test/functional/post_flags_controller_test.rb | 16 +- .../post_versions_controller_test.rb | 8 +- test/functional/post_votes_controller_test.rb | 8 +- test/functional/posts_controller_test.rb | 16 +- test/functional/sessions_controller_test.rb | 10 +- .../tag_alias_corrections_controller_test.rb | 6 +- .../tag_alias_requests_controller_test.rb | 6 +- .../functional/tag_aliases_controller_test.rb | 12 +- .../tag_implication_requests_controller.rb | 6 +- .../tag_implications_controller_test.rb | 12 +- .../tag_subscriptions_controller_test.rb | 20 +- test/functional/tags_controller_test.rb | 22 +- test/functional/uploads_controller_test.rb | 24 +- .../user_feedbacks_controller_test.rb | 20 +- test/functional/users_controller_test.rb | 22 +- .../wiki_page_versions_controller_test.rb | 8 +- test/functional/wiki_pages_controller_test.rb | 28 +- test/test_helper.rb | 6 +- test/unit/advertisement_test.rb | 6 +- .../alias_and_implication_importer_test.rb | 14 +- test/unit/artist_test.rb | 48 +-- test/unit/artist_url_test.rb | 6 +- test/unit/ban_test.rb | 36 +-- test/unit/comment_test.rb | 12 +- test/unit/current_user_test.rb | 16 +- test/unit/dmail_test.rb | 20 +- test/unit/downloads/file_test.rb | 10 +- test/unit/downloads/nico_seiga_test.rb | 2 +- test/unit/downloads/pixa_test.rb | 4 +- test/unit/downloads/pixiv_test.rb | 12 +- test/unit/downloads/tinami_test.rb | 4 +- test/unit/dtext_test.rb | 26 +- test/unit/favorite_test.rb | 20 +- test/unit/forum_post_test.rb | 26 +- test/unit/forum_topic_test.rb | 18 +- test/unit/ip_ban_test.rb | 4 +- test/unit/janitor_trial_test.rb | 12 +- .../user/login_reminder_mailer_test.rb | 2 +- test/unit/moderator/ip_addr_search_test.rb | 6 +- test/unit/moderator/tag_batch_change_test.rb | 4 +- test/unit/note_test.rb | 36 +-- test/unit/pool_test.rb | 72 ++--- test/unit/post_appeal_test.rb | 14 +- test/unit/post_disapproval_test.rb | 10 +- test/unit/post_flag_test.rb | 14 +- test/unit/post_pruner_test.rb | 12 +- test/unit/post_sets/favorite_test.rb | 10 +- test/unit/post_sets/pool_test.rb | 10 +- test/unit/post_sets/post_test.rb | 52 +-- test/unit/post_test.rb | 232 +++++++------- test/unit/post_version_test.rb | 18 +- test/unit/post_vote_test.rb | 8 +- test/unit/related_tag_calculator_test.rb | 16 +- test/unit/related_tag_query_test.rb | 22 +- test/unit/sources/nico_seiga_test.rb | 8 +- test/unit/sources/pixa_test.rb | 14 +- test/unit/sources/pixiv_test.rb | 10 +- test/unit/sources/tinami_test.rb | 14 +- test/unit/tag_alias_correction_test.rb | 14 +- test/unit/tag_alias_request_test.rb | 4 +- test/unit/tag_alias_test.rb | 14 +- test/unit/tag_implication_request_test.rb | 4 +- test/unit/tag_implication_test.rb | 18 +- test/unit/tag_subscription_test.rb | 12 +- test/unit/tag_test.rb | 44 +-- test/unit/upload_test.rb | 16 +- test/unit/user_feedback_test.rb | 10 +- test/unit/user_password_reset_nonce_test.rb | 12 +- test/unit/user_test.rb | 82 ++--- test/unit/wiki_page_test.rb | 12 +- 319 files changed, 2710 insertions(+), 2710 deletions(-) diff --git a/app/controllers/admin/alias_and_implication_imports_controller.rb b/app/controllers/admin/alias_and_implication_imports_controller.rb index 1bf119be1..4f3860bbd 100644 --- a/app/controllers/admin/alias_and_implication_imports_controller.rb +++ b/app/controllers/admin/alias_and_implication_imports_controller.rb @@ -1,10 +1,10 @@ module Admin class AliasAndImplicationImportsController < ApplicationController before_filter :admin_only - + def new end - + def create @importer = AliasAndImplicationImporter.new(params[:batch][:text], params[:batch][:forum_id]) @importer.process! diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index db16c0b9c..0a48f367d 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -1,11 +1,11 @@ module Admin class UsersController < ApplicationController before_filter :moderator_only - + def edit @user = User.find(params[:id]) end - + def update @user = User.find(params[:id]) @user.level = params[:user][:level] diff --git a/app/controllers/advertisement_hits_controller.rb b/app/controllers/advertisement_hits_controller.rb index f250cafc2..926304707 100644 --- a/app/controllers/advertisement_hits_controller.rb +++ b/app/controllers/advertisement_hits_controller.rb @@ -8,5 +8,5 @@ class AdvertisementHitsController < ApplicationController protected def set_title @page_title = Danbooru.config.app_name + "/advertisements" - end + end end diff --git a/app/controllers/advertisements_controller.rb b/app/controllers/advertisements_controller.rb index 922324af7..f808216f1 100644 --- a/app/controllers/advertisements_controller.rb +++ b/app/controllers/advertisements_controller.rb @@ -1,27 +1,27 @@ class AdvertisementsController < ApplicationController before_filter :advertiser_only - + def new @advertisement = Advertisement.new( :ad_type => "vertical", :status => "active" ) end - + def edit @advertisement = Advertisement.find(params[:id]) end - + def index @advertisements = Advertisement.order("id desc").all @start_date = 1.month.ago.to_date @end_date = Date.today end - + def show @advertisement = Advertisement.find(params[:id]) end - + def create @advertisement = Advertisement.new(params[:advertisement]) if @advertisement.save @@ -31,7 +31,7 @@ class AdvertisementsController < ApplicationController render :action => "new" end end - + def update @advertisement = Advertisement.find(params[:id]) if @advertisement.update_attributes(params[:advertisement]) @@ -41,13 +41,13 @@ class AdvertisementsController < ApplicationController render :action => "edit" end end - + def destroy @advertisement = Advertisement.find(params[:id]) @advertisement.destroy redirect_to advertisements_path, :notice => "Advertisement destroyed" end - + private def advertiser_only if !Danbooru.config.is_user_advertiser?(CurrentUser.user) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index c6cce8c31..dd589d8ac 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -6,14 +6,14 @@ class ApplicationController < ActionController::Base before_filter :set_title before_filter :set_started_at_session layout "default" - + rescue_from User::PrivilegeError, :with => :access_denied rescue_from Danbooru::Paginator::PaginationError, :with => :render_pagination_limit protected def rescue_exception(exception) @exception = exception - + if exception.is_a?(::ActiveRecord::StatementInvalid) && exception.to_s =~ /statement timeout/ @exception = nil @error_message = "The database timed out running your query." @@ -26,17 +26,17 @@ protected render :template => "static/error", :status => 500 end end - + def render_pagination_limit @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 end - + def access_denied previous_url = params[:url] || request.fullpath respond_to do |fmt| - fmt.html do + fmt.html do if request.get? redirect_to new_session_path(:url => previous_url), :notice => "Access denied" else @@ -56,18 +56,18 @@ protected session_loader = SessionLoader.new(session, cookies, request) session_loader.load end - + def reset_current_user CurrentUser.user = nil CurrentUser.ip_addr = nil end - + def set_started_at_session if session[:started_at].blank? session[:started_at] = Time.now end end - + %w(member banned privileged platinum contributor janitor moderator admin).each do |level| define_method("#{level}_only") do if CurrentUser.user.__send__("is_#{level}?") @@ -78,7 +78,7 @@ protected end end end - + def set_title @page_title = Danbooru.config.app_name + "/#{params[:controller]}" end diff --git a/app/controllers/artists_controller.rb b/app/controllers/artists_controller.rb index b485515d5..7ccb68aad 100644 --- a/app/controllers/artists_controller.rb +++ b/app/controllers/artists_controller.rb @@ -2,28 +2,28 @@ class ArtistsController < ApplicationController respond_to :html, :xml, :json before_filter :member_only, :except => [:index, :show, :banned] before_filter :admin_only, :only => [:ban] - + def new @artist = Artist.new_with_defaults(params) respond_with(@artist) end - + def edit @artist = Artist.find(params[:id]) respond_with(@artist) end - + def banned @artists = Artist.where("is_banned = ?", true).order("name") respond_with(@artists) end - + def ban @artist = Artist.find(params[:id]) @artist.ban! redirect_to(artist_path(@artist), :notice => "Artist was banned") end - + def index @artists = Artist.search(params[:search] || params).order("id desc").paginate(params[:page]) respond_with(@artists) do |format| @@ -35,34 +35,34 @@ class ArtistsController < ApplicationController end end end - + def search end - + def show @artist = Artist.find(params[:id]) @post_set = PostSets::Artist.new(@artist) respond_with(@artist) end - + def create @artist = Artist.create(params[:artist], :as => CurrentUser.role) respond_with(@artist) end - + def update @artist = Artist.find(params[:id]) @artist.update_attributes(params[:artist], :as => CurrentUser.role) respond_with(@artist) end - + def revert @artist = Artist.find(params[:id]) @version = ArtistVersion.find(params[:version_id]) @artist.revert_to!(@version) respond_with(@artist) end - + def show_or_new @artist = Artist.find_by_name(params[:name]) if @artist diff --git a/app/controllers/bans_controller.rb b/app/controllers/bans_controller.rb index 74effffbd..b0dd2b44f 100644 --- a/app/controllers/bans_controller.rb +++ b/app/controllers/bans_controller.rb @@ -1,33 +1,33 @@ class BansController < ApplicationController before_filter :moderator_only, :except => [:show, :index] - + def new @ban = Ban.new end - + def edit @ban = Ban.find(params[:id]) end - + def index @search = Ban.search(params[:search]).order("id desc") @bans = @search.paginate(params[:page]) end - + def show @ban = Ban.find(params[:id]) end - + def create @ban = Ban.create(params[:ban]) - + if @ban.errors.any? render :action => "new" else redirect_to ban_path(@ban), :notice => "Ban created" end end - + def update @ban = Ban.find(params[:id]) if @ban.update_attributes(params[:ban]) @@ -35,8 +35,8 @@ class BansController < ApplicationController else render :action => "edit" end - end - + end + def destroy @ban = Ban.find(params[:id]) @ban.destroy diff --git a/app/controllers/comment_votes_controller.rb b/app/controllers/comment_votes_controller.rb index f1702021e..c0c8c75f7 100644 --- a/app/controllers/comment_votes_controller.rb +++ b/app/controllers/comment_votes_controller.rb @@ -1,7 +1,7 @@ class CommentVotesController < ApplicationController respond_to :js before_filter :member_only - + def create @comment = Comment.find(params[:comment_id]) @comment_vote = @comment.vote!(params[:score]) diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index 0321a52fa..9ee3c8ea3 100644 --- a/app/controllers/comments_controller.rb +++ b/app/controllers/comments_controller.rb @@ -3,7 +3,7 @@ class CommentsController < ApplicationController before_filter :member_only, :only => [:update, :create, :edit, :destroy] rescue_from User::PrivilegeError, :with => "static/access_denied" rescue_from ActiveRecord::StatementInvalid, :with => :search_error - + def index if params[:group_by] == "comment" index_by_comment @@ -13,21 +13,21 @@ class CommentsController < ApplicationController index_by_post end end - + def search end - + def new redirect_to comments_path end - + def update @comment = Comment.find(params[:id]) check_privilege(@comment) @comment.update_attributes(params[:comment]) respond_with(@comment, :location => post_path(@comment.post_id)) end - + def create @comment = Comment.create(params[:comment]) respond_with(@comment) do |format| @@ -40,20 +40,20 @@ class CommentsController < ApplicationController end end end - + def edit @comment = Comment.find(params[:id]) check_privilege(@comment) respond_with(@comment) end - + def show @comment = Comment.find(params[:id]) respond_with(@comment) do |format| format.json {render :json => @comment.to_json(:methods => [:creator_name])} end end - + def destroy @comment = Comment.find(params[:id]) check_privilege(@comment) @@ -62,7 +62,7 @@ class CommentsController < ApplicationController format.js end end - + private def index_for_post @post = Post.find(params[:post_id]) @@ -78,14 +78,14 @@ private format.html {render :action => "index_by_post"} end end - + def index_by_comment @comments = Comment.search(params[:search]).order("comments.id DESC").paginate(params[:page], :search_count => params[:search]) respond_with(@comments) do |format| format.html {render :action => "index_by_comment"} end end - + def check_privilege(comment) if !comment.editable_by?(CurrentUser.user) raise User::PrivilegeError @@ -93,7 +93,7 @@ private end protected - + def search_error(e) if e.message =~ /syntax error in tsquery/ @error_message = "Meta-tags are not supported in comment searches by tag" diff --git a/app/controllers/dmails_controller.rb b/app/controllers/dmails_controller.rb index a164631ab..c9812d990 100644 --- a/app/controllers/dmails_controller.rb +++ b/app/controllers/dmails_controller.rb @@ -9,19 +9,19 @@ class DmailsController < ApplicationController else @dmail = Dmail.new(params[:dmail]) end - + respond_with(@dmail) end - + def index @search = Dmail.visible.search(params[:search]) @dmails = @search.order("dmails.created_at desc").paginate(params[:page]) respond_with(@dmails) end - + def search end - + def show @dmail = Dmail.find(params[:id]) check_privilege(@dmail) @@ -33,20 +33,20 @@ class DmailsController < ApplicationController @dmail = Dmail.create_split(params[:dmail]) respond_with(@dmail) end - + def destroy @dmail = Dmail.find(params[:id]) check_privilege(@dmail) @dmail.destroy redirect_to dmails_path, :notice => "Message destroyed" end - + def mark_all_as_read Dmail.visible.unread.each do |x| x.update_column(:is_read, true) end end - + private def check_privilege(dmail) if !dmail.visible_to?(CurrentUser.user) diff --git a/app/controllers/explore/posts_controller.rb b/app/controllers/explore/posts_controller.rb index 324e013cd..e19ca0c95 100644 --- a/app/controllers/explore/posts_controller.rb +++ b/app/controllers/explore/posts_controller.rb @@ -1,7 +1,7 @@ module Explore class PostsController < ApplicationController respond_to :html, :xml, :json - + def popular @post_set = PostSets::Popular.new(params[:date], params[:scale]) @posts = @post_set.posts diff --git a/app/controllers/favorites_controller.rb b/app/controllers/favorites_controller.rb index 9148c8aa6..7a0e7bd6d 100644 --- a/app/controllers/favorites_controller.rb +++ b/app/controllers/favorites_controller.rb @@ -1,6 +1,6 @@ class FavoritesController < ApplicationController before_filter :member_only - + def index if 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]) end end - + def create if CurrentUser.favorite_limit.nil? || CurrentUser.favorite_count < CurrentUser.favorite_limit @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." end end - + def destroy @post = Post.find(params[:id]) @post.remove_favorite!(CurrentUser.user) diff --git a/app/controllers/forum_posts_controller.rb b/app/controllers/forum_posts_controller.rb index 88a40b51c..3d1ee7956 100644 --- a/app/controllers/forum_posts_controller.rb +++ b/app/controllers/forum_posts_controller.rb @@ -8,19 +8,19 @@ class ForumPostsController < ApplicationController @forum_post = ForumPost.new_reply(params) respond_with(@forum_post) end - + def edit @forum_post = ForumPost.find(params[:id]) check_privilege(@forum_post) respond_with(@forum_post) end - + def index @search = ForumPost.active.search(params[:search]) @forum_posts = @search.order("forum_posts.id DESC").paginate(params[:page], :search_count => params[:search]) respond_with(@forum_posts) end - + def search end @@ -32,33 +32,33 @@ class ForumPostsController < ApplicationController respond_with(@forum_post) end end - + def create @forum_post = ForumPost.create(params[:forum_post]) respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => @forum_post.topic.last_page)) end - + def update @forum_post = ForumPost.find(params[:id]) check_privilege(@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)) end - + def destroy @forum_post = ForumPost.find(params[:id]) raise User::PrivilegeError unless @forum_post.editable_by?(CurrentUser.user) @forum_post.update_attribute(:is_deleted, true) respond_with(@forum_post) end - + def undelete @forum_post = ForumPost.find(params[:id]) check_privilege(@forum_post) @forum_post.update_attribute(:is_deleted, false) respond_with(@forum_post) end - + private def check_privilege(forum_post) if !forum_post.editable_by?(CurrentUser.user) diff --git a/app/controllers/forum_topics_controller.rb b/app/controllers/forum_topics_controller.rb index c9cc1827e..a964c83e3 100644 --- a/app/controllers/forum_topics_controller.rb +++ b/app/controllers/forum_topics_controller.rb @@ -10,45 +10,45 @@ class ForumTopicsController < ApplicationController @forum_topic.original_post = ForumPost.new respond_with(@forum_topic) end - + def edit @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) respond_with(@forum_topic) end - + def index @search = ForumTopic.active.search(params[:search]) @forum_topics = @search.order("is_sticky DESC, updated_at DESC").paginate(params[:page], :search_count => params[:search]) respond_with(@forum_topics) end - + def show @forum_topic = ForumTopic.find(params[:id]) @forum_posts = ForumPost.search(:topic_id => @forum_topic.id).order("forum_posts.id").paginate(params[:page]) @forum_posts.all respond_with(@forum_topic) end - + def create @forum_topic = ForumTopic.create(params[:forum_topic], :as => CurrentUser.role) respond_with(@forum_topic) end - + def update @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) @forum_topic.update_attributes(params[:forum_topic], :as => CurrentUser.role) respond_with(@forum_topic) end - + def destroy @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) @forum_topic.update_attribute(:is_deleted, true) respond_with(@forum_topic) end - + def undelete @forum_topic = ForumTopic.find(params[:id]) check_privilege(@forum_topic) @@ -64,18 +64,18 @@ class ForumTopicsController < ApplicationController private def update_last_forum_read_at return if CurrentUser.is_anonymous? - + 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) end end - + def normalize_search if params[:title_matches] params[:search] ||= {} params[:search][:title_matches] = params.delete(:title_matches) end - + if params[:title] params[:search] ||= {} params[:search][:title] = params.delete(:title) diff --git a/app/controllers/ip_bans_controller.rb b/app/controllers/ip_bans_controller.rb index a278d2a68..9873ee26f 100644 --- a/app/controllers/ip_bans_controller.rb +++ b/app/controllers/ip_bans_controller.rb @@ -14,12 +14,12 @@ class IpBansController < ApplicationController redirect_to ip_bans_path end end - + def index @search = IpBan.search(params[:search]) @ip_bans = @search.order("id desc").paginate(params[:page]) end - + def destroy @ip_ban = IpBan.find(params[:id]) @ip_ban.destroy diff --git a/app/controllers/janitor_trials_controller.rb b/app/controllers/janitor_trials_controller.rb index d96bc7ec2..d2f35e324 100644 --- a/app/controllers/janitor_trials_controller.rb +++ b/app/controllers/janitor_trials_controller.rb @@ -1,28 +1,28 @@ class JanitorTrialsController < ApplicationController respond_to :html, :xml, :json before_filter :moderator_only, :only => [:create, :promote, :demote] - + def new @janitor_trial = JanitorTrial.new respond_with(@janitor_trial) end - + def edit @janitor_trial = JanitorTrial.find(params[:id]) respond_with(@janitor_trial) end - + def index @search = JanitorTrial.search(params[:search]) @janitor_trials = @search.order("id desc").paginate(params[:page]) respond_with(@janitor_trials) end - + def create @janitor_trial = JanitorTrial.create(params[:janitor_trial]) respond_with(@janitor_trial, :location => janitor_trials_path) end - + def promote @janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial.promote! @@ -30,7 +30,7 @@ class JanitorTrialsController < ApplicationController format.js end end - + def demote @janitor_trial = JanitorTrial.find(params[:id]) @janitor_trial.demote! @@ -38,7 +38,7 @@ class JanitorTrialsController < ApplicationController format.js end end - + def test @tester = JanitorTrialTester.new(params[:janitor_trial][:user_name]) end diff --git a/app/controllers/legacy_controller.rb b/app/controllers/legacy_controller.rb index 9cc2dd955..11e01264a 100644 --- a/app/controllers/legacy_controller.rb +++ b/app/controllers/legacy_controller.rb @@ -6,7 +6,7 @@ class LegacyController < ApplicationController @post_set = PostSets::Post.new(tag_query, params[:page], params[:limit]) @posts = @post_set.posts end - + def create_post @upload = Upload.new @upload.server = Socket.gethostname @@ -19,19 +19,19 @@ class LegacyController < ApplicationController @upload.save @upload.process! end - + def users @users = User.limit(100).search(params).paginate(params[:page]) end - + def tags @tags = Tag.limit(100).search(params).paginate(params[:page], :limit => params[:limit]) end - + def artists @artists = Artist.limit(100).search(params[:search]).paginate(params[:page]) end - + def unavailable render :text => "this resource is no longer available", :status => 410 end diff --git a/app/controllers/maintenance/user/login_reminders_controller.rb b/app/controllers/maintenance/user/login_reminders_controller.rb index 15b043798..4f86c2945 100644 --- a/app/controllers/maintenance/user/login_reminders_controller.rb +++ b/app/controllers/maintenance/user/login_reminders_controller.rb @@ -3,7 +3,7 @@ module Maintenance class LoginRemindersController < ApplicationController def new end - + def create @user = ::User.with_email(params[:user][:email]).first if @user @@ -12,7 +12,7 @@ module Maintenance else flash[:notice] = "Email address not found" end - + redirect_to new_maintenance_user_login_reminder_path end end diff --git a/app/controllers/maintenance/user/password_resets_controller.rb b/app/controllers/maintenance/user/password_resets_controller.rb index 22116c39b..d11110714 100644 --- a/app/controllers/maintenance/user/password_resets_controller.rb +++ b/app/controllers/maintenance/user/password_resets_controller.rb @@ -4,7 +4,7 @@ module Maintenance def new @nonce = UserPasswordResetNonce.new end - + def create @nonce = UserPasswordResetNonce.create(params[:nonce]) if @nonce.errors.any? @@ -13,14 +13,14 @@ module Maintenance redirect_to new_maintenance_user_password_reset_path, :notice => "Email request sent" end end - + def edit @nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first end - + def update @nonce = UserPasswordResetNonce.where(:email => params[:email], :key => params[:key]).first - + if @nonce @nonce.reset_user! @nonce.destroy diff --git a/app/controllers/moderator/dashboards_controller.rb b/app/controllers/moderator/dashboards_controller.rb index 37e41a7a8..f309de217 100644 --- a/app/controllers/moderator/dashboards_controller.rb +++ b/app/controllers/moderator/dashboards_controller.rb @@ -2,7 +2,7 @@ module Moderator class DashboardsController < ApplicationController before_filter :janitor_only helper :post_flags, :post_appeals - + def show @dashboard = Moderator::Dashboard::Report.new(params[:min_date] || 2.days.ago.to_date, params[:max_level] || 20) end diff --git a/app/controllers/moderator/invitations_controller.rb b/app/controllers/moderator/invitations_controller.rb index 82a725cfc..2d475756f 100644 --- a/app/controllers/moderator/invitations_controller.rb +++ b/app/controllers/moderator/invitations_controller.rb @@ -1,15 +1,15 @@ module Moderator class InvitationsController < ApplicationController before_filter :moderator_only - + def new end - + def create User.find(params[:invitation][:user_id]).invite!(params[:invitation][:level]) redirect_to moderator_invitations_path end - + def index @users = User.where("inviter_id = ?", CurrentUser.id).paginate(params[:page]) end diff --git a/app/controllers/moderator/ip_addrs_controller.rb b/app/controllers/moderator/ip_addrs_controller.rb index 94c38a9c7..4f923742f 100644 --- a/app/controllers/moderator/ip_addrs_controller.rb +++ b/app/controllers/moderator/ip_addrs_controller.rb @@ -1,11 +1,11 @@ module Moderator class IpAddrsController < ApplicationController before_filter :janitor_only - + def index @search = IpAddrSearch.new(params[:search]) end - + def search end end diff --git a/app/controllers/moderator/post/approvals_controller.rb b/app/controllers/moderator/post/approvals_controller.rb index fbbb4affd..eeaa6c91f 100644 --- a/app/controllers/moderator/post/approvals_controller.rb +++ b/app/controllers/moderator/post/approvals_controller.rb @@ -2,7 +2,7 @@ module Moderator module Post class ApprovalsController < ApplicationController before_filter :janitor_only - + def create @post = ::Post.find(params[:post_id]) if @post.is_deleted? || @post.is_flagged? || @post.is_pending? diff --git a/app/controllers/moderator/post/disapprovals_controller.rb b/app/controllers/moderator/post/disapprovals_controller.rb index 830fd7d09..a7f86582f 100644 --- a/app/controllers/moderator/post/disapprovals_controller.rb +++ b/app/controllers/moderator/post/disapprovals_controller.rb @@ -2,7 +2,7 @@ module Moderator module Post class DisapprovalsController < ApplicationController before_filter :janitor_only - + def create @post = ::Post.find(params[:post_id]) @post_disapproval = PostDisapproval.create(:post => @post, :user => CurrentUser.user) diff --git a/app/controllers/moderator/post/posts_controller.rb b/app/controllers/moderator/post/posts_controller.rb index 80d58212f..0deddf3f8 100644 --- a/app/controllers/moderator/post/posts_controller.rb +++ b/app/controllers/moderator/post/posts_controller.rb @@ -8,7 +8,7 @@ module Moderator def confirm_delete @post = ::Post.find(params[:id]) end - + def delete @post = ::Post.find(params[:id]) if params[:commit] == "Delete" @@ -17,12 +17,12 @@ module Moderator end redirect_to(post_path(@post)) end - + def undelete @post = ::Post.find(params[:id]) @post.undelete! end - + def annihilate @post = ::Post.find(params[:id]) @post.annihilate! diff --git a/app/controllers/moderator/post/queues_controller.rb b/app/controllers/moderator/post/queues_controller.rb index 49be12c7a..d0dfa2fbc 100644 --- a/app/controllers/moderator/post/queues_controller.rb +++ b/app/controllers/moderator/post/queues_controller.rb @@ -3,7 +3,7 @@ module Moderator class QueuesController < ApplicationController respond_to :html, :json before_filter :janitor_only - + def show ::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) diff --git a/app/controllers/moderator/tags_controller.rb b/app/controllers/moderator/tags_controller.rb index 7bc4bc7fd..d44a6285f 100644 --- a/app/controllers/moderator/tags_controller.rb +++ b/app/controllers/moderator/tags_controller.rb @@ -2,15 +2,15 @@ module Moderator class TagsController < ApplicationController before_filter :moderator_only rescue_from TagBatchChange::Error, :with => :error - + def edit end - + def update 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" end - + def error redirect_to edit_moderator_tag_path, :notice => "Error" end diff --git a/app/controllers/news_updates_controller.rb b/app/controllers/news_updates_controller.rb index 6e88c509a..784186b02 100644 --- a/app/controllers/news_updates_controller.rb +++ b/app/controllers/news_updates_controller.rb @@ -1,33 +1,33 @@ class NewsUpdatesController < ApplicationController before_filter :admin_only respond_to :html - + def index @news_updates = NewsUpdate.order("id desc").paginate(params[:page]) respond_with(@news_updates) end - + def edit @news_update = NewsUpdate.find(params[:id]) respond_with(@news_update) end - + def update @news_update = NewsUpdate.find(params[:id]) @news_update.update_attributes(params[:news_update]) respond_with(@news_update, :location => news_updates_path) end - + def new @news_update = NewsUpdate.new respond_with(@news_update) end - + def create @news_update = NewsUpdate.create(params[:news_update]) respond_with(@news_update, :location => news_updates_path) end - + def destroy @news_update = NewsUpdate.find(params[:id]) @news_update.destroy diff --git a/app/controllers/note_versions_controller.rb b/app/controllers/note_versions_controller.rb index 9af07a3af..d26d97875 100644 --- a/app/controllers/note_versions_controller.rb +++ b/app/controllers/note_versions_controller.rb @@ -1,7 +1,7 @@ class NoteVersionsController < ApplicationController respond_to :html, :xml, :json before_filter :member_only, :except => [:index, :show] - + def index @search = NoteVersion.search(params[:search]) @note_versions = @search.order("note_versions.id desc").paginate(params[:page]) diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb index 8df8b85f7..78a597e24 100644 --- a/app/controllers/notes_controller.rb +++ b/app/controllers/notes_controller.rb @@ -2,10 +2,10 @@ class NotesController < ApplicationController respond_to :html, :xml, :json, :js before_filter :member_only, :except => [:index, :show] before_filter :pass_html_id, :only => [:create] - + def search end - + def index if params[:group_by] == "note" index_by_note @@ -13,12 +13,12 @@ class NotesController < ApplicationController index_by_post end end - + def show @note = Note.find(params[:id]) respond_with(@note) end - + def create @note = Note.create(params[:note]) respond_with(@note) do |fmt| @@ -27,19 +27,19 @@ class NotesController < ApplicationController end end end - + def update @note = Note.find(params[:id]) @note.update_attributes(params[:note]) respond_with(@note) end - + def destroy @note = Note.find(params[:id]) @note.update_attribute(:is_active, false) respond_with(@note) end - + def revert @note = Note.find(params[:id]) @version = NoteVersion.find(params[:version_id]) diff --git a/app/controllers/pool_elements_controller.rb b/app/controllers/pool_elements_controller.rb index 0e9dd3de9..898b76c98 100644 --- a/app/controllers/pool_elements_controller.rb +++ b/app/controllers/pool_elements_controller.rb @@ -1,30 +1,30 @@ class PoolElementsController < ApplicationController respond_to :html, :xml, :json, :js before_filter :member_only - + def create @pool = Pool.find_by_name(params[:pool_name]) || Pool.find_by_id(params[:pool_id]) - + if @pool.present? @post = Post.find(params[:post_id]) @pool.add!(@post) append_pool_to_session(@pool) end - + respond_with(@pool, :location => post_path(@post)) end - + def destroy @pool = Pool.find(params[:pool_id]) @post = Post.find(params[:post_id]) @pool.remove!(@post) respond_with(@pool, :location => post_path(@post)) end - + def all_select @pools = Pool.active.order("name").select("id, name").all end - + private def append_pool_to_session(pool) recent_pool_ids = session[:recent_pool_ids].to_s.scan(/\d+/) diff --git a/app/controllers/pool_versions_controller.rb b/app/controllers/pool_versions_controller.rb index f11a8de64..ed23ba526 100644 --- a/app/controllers/pool_versions_controller.rb +++ b/app/controllers/pool_versions_controller.rb @@ -3,7 +3,7 @@ class PoolVersionsController < ApplicationController if params[:search] && params[:search][:pool_id] @pool = Pool.find(params[:search][:pool_id]) end - + @pool_versions = PoolVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) end end diff --git a/app/controllers/pools_controller.rb b/app/controllers/pools_controller.rb index 32c5c0f13..9708d13f6 100644 --- a/app/controllers/pools_controller.rb +++ b/app/controllers/pools_controller.rb @@ -8,31 +8,31 @@ class PoolsController < ApplicationController @pool = Pool.new respond_with(@pool) end - + def edit @pool = Pool.find(params[:id]) respond_with(@pool) end - + def index @pools = Pool.active.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) respond_with(@pools) end - + def search end - + def show @pool = Pool.find(params[:id]) @post_set = PostSets::Pool.new(@pool, params[:page]) respond_with(@pool) end - + def create @pool = Pool.create(params[:pool]) respond_with(@pool, :notice => "Pool created") end - + def update # need to do this in order for synchronize! to work correctly @pool = Pool.find(params[:id]) @@ -41,7 +41,7 @@ class PoolsController < ApplicationController @pool.save respond_with(@pool, :notice => "Pool updated") end - + def destroy @pool = Pool.find(params[:id]) if !@pool.deletable_by?(CurrentUser.user) @@ -50,7 +50,7 @@ class PoolsController < ApplicationController @pool.update_attribute(:is_deleted, true) respond_with(@pool, :notice => "Pool deleted") end - + def undelete @pool = Pool.find(params[:id]) if !@pool.deletable_by?(CurrentUser.user) @@ -59,7 +59,7 @@ class PoolsController < ApplicationController @pool.update_attribute(:is_deleted, false) respond_with(@pool, :notice => "Pool undeleted") end - + def revert @pool = Pool.find(params[:id]) @version = PoolVersion.find(params[:version_id]) diff --git a/app/controllers/post_appeals_controller.rb b/app/controllers/post_appeals_controller.rb index 602598209..06508a602 100644 --- a/app/controllers/post_appeals_controller.rb +++ b/app/controllers/post_appeals_controller.rb @@ -7,12 +7,12 @@ class PostAppealsController < ApplicationController @post_appeal = PostAppeal.new respond_with(@post_appeal) end - + def index @search = PostAppeal.order("id desc").search(params[:search]) @post_appeals = @search.paginate(params[:page]) end - + def create @post_appeal = PostAppeal.create(params[:post_appeal]) respond_with(@post_appeal) diff --git a/app/controllers/post_flags_controller.rb b/app/controllers/post_flags_controller.rb index b3028ac17..0c05ec3d8 100644 --- a/app/controllers/post_flags_controller.rb +++ b/app/controllers/post_flags_controller.rb @@ -7,12 +7,12 @@ class PostFlagsController < ApplicationController @post_flag = PostFlag.new respond_with(@post_flag) end - + def index @search = PostFlag.order("id desc").search(params[:search]) @post_flags = @search.paginate(params[:page]) end - + def create @post_flag = PostFlag.create(params[:post_flag].merge(:is_resolved => false)) respond_with(@post_flag) diff --git a/app/controllers/post_versions_controller.rb b/app/controllers/post_versions_controller.rb index e607f40df..7cef5efd1 100644 --- a/app/controllers/post_versions_controller.rb +++ b/app/controllers/post_versions_controller.rb @@ -6,7 +6,7 @@ class PostVersionsController < ApplicationController @post_versions = PostVersion.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) respond_with(@post_versions) end - + def search end end diff --git a/app/controllers/post_votes_controller.rb b/app/controllers/post_votes_controller.rb index ff17d60aa..f5cfe71c9 100644 --- a/app/controllers/post_votes_controller.rb +++ b/app/controllers/post_votes_controller.rb @@ -1,6 +1,6 @@ class PostVotesController < ApplicationController before_filter :privileged_only - + def create @post = Post.find(params[:post_id]) @post.vote!(params[:score]) diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index a72d35132..e7de7239a 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -6,7 +6,7 @@ class PostsController < ApplicationController rescue_from Post::SearchError, :with => :rescue_exception rescue_from ActiveRecord::StatementInvalid, :with => :rescue_exception rescue_from ActiveRecord::RecordNotFound, :with => :rescue_exception - + def index @post_set = PostSets::Post.new(tag_query, params[:page], params[:limit]) @posts = @post_set.posts @@ -14,14 +14,14 @@ class PostsController < ApplicationController format.atom end end - + def show @post = Post.find(params[:id]) @post_flag = PostFlag.new(:post_id => @post.id) @post_appeal = PostAppeal.new(:post_id => @post.id) respond_with(@post) end - + def show_seq context = PostSearchContext.new(params) if context.post_id @@ -30,14 +30,14 @@ class PostsController < ApplicationController redirect_to(post_path(params[:id], :tags => params[:tags])) end end - + def update @post = Post.find(params[:id]) if Danbooru.config.can_user_see_post?(CurrentUser.user, @post) @post.update_attributes(params[:post], :as => CurrentUser.role) end - + respond_with(@post) do |format| format.html do if @post.errors.any? @@ -49,13 +49,13 @@ class PostsController < ApplicationController redirect_to post_path(@post) end end - + format.json do render :json => @post.to_json end end end - + def revert @post = Post.find(params[:id]) @version = PostVersion.find(params[:version_id]) diff --git a/app/controllers/related_tags_controller.rb b/app/controllers/related_tags_controller.rb index a11fecd8e..921ca7d37 100644 --- a/app/controllers/related_tags_controller.rb +++ b/app/controllers/related_tags_controller.rb @@ -1,6 +1,6 @@ class RelatedTagsController < ApplicationController respond_to :json - + def show @query = RelatedTagQuery.new(params[:query].to_s.downcase, params[:category]) respond_with(@query) do |format| diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 9641e3977..53957e2fb 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -2,24 +2,24 @@ class SessionsController < ApplicationController def new @user = User.new end - + def create session_creator = SessionCreator.new(session, cookies, params[:name], params[:password], params[:remember]) - + if session_creator.authenticate redirect_to(params[:url] || session[:previous_uri] || posts_path, :notice => "You are now logged in.") else redirect_to(new_session_path, :notice => "Password was incorrect.") end end - + def destroy session.delete(:user_id) cookies.delete(:cookie_password_hash) cookies.delete(:user_name) redirect_to(posts_path, :notice => "You are now logged out.") end - + def sign_out destroy() end diff --git a/app/controllers/sources_controller.rb b/app/controllers/sources_controller.rb index b19f2d1cf..b098ac5f7 100644 --- a/app/controllers/sources_controller.rb +++ b/app/controllers/sources_controller.rb @@ -1,11 +1,11 @@ class SourcesController < ApplicationController # before_filter :member_only respond_to :json - + def show @source = Sources::Site.new(params[:url]) @source.get - + respond_with(@source) do |format| format.json do render :json => @source.to_json diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rb index ce98dc6cc..1294027cd 100644 --- a/app/controllers/static_controller.rb +++ b/app/controllers/static_controller.rb @@ -2,7 +2,7 @@ class StaticController < ApplicationController def terms_of_service render :layout => "blank" end - + def error end end diff --git a/app/controllers/tag_alias_corrections_controller.rb b/app/controllers/tag_alias_corrections_controller.rb index 2ceb919d2..1320fe993 100644 --- a/app/controllers/tag_alias_corrections_controller.rb +++ b/app/controllers/tag_alias_corrections_controller.rb @@ -1,6 +1,6 @@ class TagAliasCorrectionsController < ApplicationController before_filter :moderator_only - + def create @correction = TagAliasCorrection.new(params[:tag_alias_id]) @@ -8,10 +8,10 @@ class TagAliasCorrectionsController < ApplicationController @correction.fix! flash[:notice] = "The fix has been queued and will be processed" end - + redirect_to tag_alias_correction_path(:tag_alias_id => params[:tag_alias_id]) end - + def show @correction = TagAliasCorrection.new(params[:tag_alias_id]) end diff --git a/app/controllers/tag_alias_requests_controller.rb b/app/controllers/tag_alias_requests_controller.rb index 58737998a..ad256b29f 100644 --- a/app/controllers/tag_alias_requests_controller.rb +++ b/app/controllers/tag_alias_requests_controller.rb @@ -1,10 +1,10 @@ class TagAliasRequestsController < ApplicationController before_filter :member_only rescue_from TagAliasRequest::ValidationError, :with => :rescue_exception - + def new end - + def create @tag_alias_request = TagAliasRequest.new( params[:tag_alias_request][:antecedent_name], diff --git a/app/controllers/tag_aliases_controller.rb b/app/controllers/tag_aliases_controller.rb index 3bde039cd..b634bf5f7 100644 --- a/app/controllers/tag_aliases_controller.rb +++ b/app/controllers/tag_aliases_controller.rb @@ -1,12 +1,12 @@ class TagAliasesController < ApplicationController before_filter :admin_only, :only => [:approve, :destroy, :new, :create] respond_to :html, :xml, :json, :js - + def new @tag_alias = TagAlias.new(params[:tag_alias]) respond_with(@tag_alias) end - + def general_search if params[:commit] == "Search Aliases" 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]}) end end - + def index @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]) respond_with(@tag_aliases) end - + def create @tag_alias = TagAlias.create(params[:tag_alias]) respond_with(@tag_alias, :location => tag_aliases_path(:search => {:id => @tag_alias.id})) end - + def destroy @tag_alias = TagAlias.find(params[:id]) @tag_alias.update_column(:status, "deleted") @@ -33,7 +33,7 @@ class TagAliasesController < ApplicationController @tag_alias.destroy respond_with(@tag_alias, :location => tag_aliases_path) end - + def approve @tag_alias = TagAlias.find(params[:id]) @tag_alias.update_column(:status, "queued") diff --git a/app/controllers/tag_corrections_controller.rb b/app/controllers/tag_corrections_controller.rb index ba44d9976..5a0b95515 100644 --- a/app/controllers/tag_corrections_controller.rb +++ b/app/controllers/tag_corrections_controller.rb @@ -1,16 +1,16 @@ class TagCorrectionsController < ApplicationController before_filter :member_only - + def new @correction = TagCorrection.new(params[:tag_id]) end - + def create if params[:commit] == "Fix" @correction = TagCorrection.new(params[:tag_id]) @correction.fix! end - + redirect_to tags_path(:search => {:name_matches => @correction.tag.name}), :notice => "Tag will be fixed in a few seconds" end end diff --git a/app/controllers/tag_implication_requests_controller.rb b/app/controllers/tag_implication_requests_controller.rb index c212fc3fc..ebb53de36 100644 --- a/app/controllers/tag_implication_requests_controller.rb +++ b/app/controllers/tag_implication_requests_controller.rb @@ -1,10 +1,10 @@ class TagImplicationRequestsController < ApplicationController before_filter :member_only rescue_from TagImplicationRequest::ValidationError, :with => :rescue_exception - + def new end - + def create @tag_implication_request = TagImplicationRequest.new( params[:tag_implication_request][:antecedent_name], diff --git a/app/controllers/tag_implications_controller.rb b/app/controllers/tag_implications_controller.rb index 134970435..e7576725e 100644 --- a/app/controllers/tag_implications_controller.rb +++ b/app/controllers/tag_implications_controller.rb @@ -1,29 +1,29 @@ class TagImplicationsController < ApplicationController before_filter :admin_only, :only => [:new, :create, :approve, :destroy] respond_to :html, :xml, :json, :js - + def new @tag_implication = TagImplication.new respond_with(@tag_implication) end - + def index @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]) respond_with(@tag_implications) end - + def create @tag_implication = TagImplication.create(params[:tag_implication]) respond_with(@tag_implication, :location => tag_implications_path(:search => {:id => @tag_implication.id})) end - + def destroy @tag_implication = TagImplication.find(params[:id]) @tag_implication.destroy respond_with(@tag_implication) end - + def approve @tag_implication = TagImplication.find(params[:id]) @tag_implication.update_column(:status, "queued") diff --git a/app/controllers/tag_subscriptions_controller.rb b/app/controllers/tag_subscriptions_controller.rb index 425954b75..b1023451f 100644 --- a/app/controllers/tag_subscriptions_controller.rb +++ b/app/controllers/tag_subscriptions_controller.rb @@ -7,20 +7,20 @@ class TagSubscriptionsController < ApplicationController @tag_subscription = TagSubscription.new respond_with(@tag_subscription) end - + def edit @tag_subscription = TagSubscription.find(params[:id]) check_privilege(@tag_subscription) respond_with(@tag_subscription) end - + def index @user = CurrentUser.user @search = TagSubscription.owned_by(@user).order("name").search(params[:search]) @tag_subscriptions = @search.paginate(params[:page]) respond_with(@tag_subscriptions) end - + def create @tag_subscription = TagSubscription.create(params[:tag_subscription]) respond_with(@tag_subscription) do |format| @@ -33,7 +33,7 @@ class TagSubscriptionsController < ApplicationController end end end - + def update @tag_subscription = TagSubscription.find(params[:id]) check_privilege(@tag_subscription) @@ -48,20 +48,20 @@ class TagSubscriptionsController < ApplicationController end end end - + def destroy @tag_subscription = TagSubscription.find(params[:id]) check_privilege(@tag_subscription) @tag_subscription.destroy respond_with(@tag_subscription) end - + def posts @user = User.find(params[:id]) @post_set = PostSets::Post.new("sub:#{@user.name} #{params[:tags]}", params[:page]) @posts = @post_set.posts end - + private def check_privilege(tag_subscription) raise User::PrivilegeError unless tag_subscription.editable_by?(CurrentUser.user) diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 8d7f1be28..7a25bb83e 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -1,20 +1,20 @@ class TagsController < ApplicationController before_filter :member_only, :only => [:edit, :update] respond_to :html, :xml, :json - + def edit @tag = Tag.find(params[:id]) respond_with(@tag) end - + def index @tags = Tag.search(params[:search]).paginate(params[:page], :search_count => params[:search]) respond_with(@tags) end - + def search end - + def show @tag = Tag.find(params[:id]) respond_with(@tag) @@ -25,5 +25,5 @@ class TagsController < ApplicationController @tag.update_attributes(params[:tag]) @tag.update_category_cache_for_all respond_with(@tag) - end + end end diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb index 2f2ecf793..c9cff26fd 100644 --- a/app/controllers/uploads_controller.rb +++ b/app/controllers/uploads_controller.rb @@ -3,7 +3,7 @@ class UploadsController < ApplicationController after_filter :save_recent_tags, :only => [:create] respond_to :html, :xml, :json, :js rescue_from Upload::Error, :with => :rescue_exception - + def new @upload = Upload.new(:rating => "q") if params[:url] @@ -15,13 +15,13 @@ class UploadsController < ApplicationController end respond_with(@upload) end - + def index @search = Upload.search(params[:search]) @uploads = @search.order("id desc").paginate(params[:page]) respond_with(@uploads) end - + def show @upload = Upload.find(params[:id]) respond_with(@upload) do |format| @@ -38,7 +38,7 @@ class UploadsController < ApplicationController @upload.process! if @upload.errors.empty? respond_with(@upload) end - + def update @upload = Upload.find(params[:id]) @upload.process! diff --git a/app/controllers/user_feedbacks_controller.rb b/app/controllers/user_feedbacks_controller.rb index 97b129392..1056f16da 100644 --- a/app/controllers/user_feedbacks_controller.rb +++ b/app/controllers/user_feedbacks_controller.rb @@ -7,29 +7,29 @@ class UserFeedbacksController < ApplicationController @user_feedback = UserFeedback.new(params[:user_feedback]) respond_with(@user_feedback) end - + def edit @user_feedback = UserFeedback.find(params[:id]) check_privilege(@user_feedback) respond_with(@user_feedback) end - + def show @user_feedback = UserFeedback.find(params[:id]) respond_with(@user_feedback) end - + def index @search = UserFeedback.search(params[:search]) @user_feedbacks = @search.paginate(params[:page]).order("created_at desc") respond_with(@user_feedbacks) end - + def create @user_feedback = UserFeedback.create(params[:user_feedback]) respond_with(@user_feedback) end - + def destroy @user_feedback = UserFeedback.find(params[:id]) check_privilege(@user_feedback) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 2a2eb0574..4a350eb3b 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -7,27 +7,27 @@ class UsersController < ApplicationController @user = User.new respond_with(@user) end - + def edit @user = User.find(params[:id]) check_privilege(@user) respond_with(@user) end - + def index @users = User.search(params[:search]).order("users.id desc").paginate(params[:page], :search_count => params[:search]) respond_with(@users) end - + def search end - + def show @user = User.find(params[:id]) @presenter = UserPresenter.new(@user) respond_with(@user) end - + def create @user = User.create(params[:user], :as => CurrentUser.role) if @user.errors.empty? @@ -36,32 +36,32 @@ class UsersController < ApplicationController set_current_user respond_with(@user) end - + def update @user = User.find(params[:id]) check_privilege(@user) @user.update_attributes(params[:user], :as => CurrentUser.role) respond_with(@user) end - + def upgrade @user = User.find(params[:id]) - + if params[:email] =~ /paypal/ UserMailer.upgrade_fail(params[:email]).deliver else UserMailer.upgrade(@user, params[:email]).deliver end - + redirect_to user_path(@user), :notice => "Email was sent" end - + def cache @user = User.find(params[:id]) @user.update_cache render :nothing => true end - + def restore_uploaded_tags @user = User.find(params[:id]) importer = UploadedTagsImporter.new(@user) diff --git a/app/controllers/wiki_page_versions_controller.rb b/app/controllers/wiki_page_versions_controller.rb index d53767c5c..ccc30524e 100644 --- a/app/controllers/wiki_page_versions_controller.rb +++ b/app/controllers/wiki_page_versions_controller.rb @@ -1,16 +1,16 @@ class WikiPageVersionsController < ApplicationController respond_to :json, :html, :xml - + def index @wiki_page_versions = WikiPageVersion.search(params[:search]).order("id desc").paginate(params[:page], :search_count => params[:search]) respond_with(@wiki_page_versions) end - + def show @wiki_page_version = WikiPageVersion.find(params[:id]) respond_with(@wiki_page_version) end - + def diff @thispage = WikiPageVersion.find(params[:thispage]) @otherpage = WikiPageVersion.find(params[:otherpage]) diff --git a/app/controllers/wiki_pages_controller.rb b/app/controllers/wiki_pages_controller.rb index cf692fdd6..8a2653087 100644 --- a/app/controllers/wiki_pages_controller.rb +++ b/app/controllers/wiki_pages_controller.rb @@ -9,12 +9,12 @@ class WikiPagesController < ApplicationController @wiki_page = WikiPage.new(params[:wiki_page]) respond_with(@wiki_page) end - + def edit @wiki_page = WikiPage.find(params[:id]) respond_with(@wiki_page) end - + def index @wiki_pages = WikiPage.search(params[:search]).order("updated_at desc").paginate(params[:page], :search_count => params[:search]) respond_with(@wiki_pages) do |format| @@ -25,7 +25,7 @@ class WikiPagesController < ApplicationController end end end - + def show if params[:id] =~ /[a-zA-Z]/ @wiki_page = WikiPage.find_by_title(params[:id]) @@ -34,31 +34,31 @@ class WikiPagesController < ApplicationController end respond_with(@wiki_page) end - + def create @wiki_page = WikiPage.create(params[:wiki_page]) respond_with(@wiki_page) end - + def update @wiki_page = WikiPage.find(params[:id]) @wiki_page.update_attributes(params[:wiki_page]) respond_with(@wiki_page) end - + def destroy @wiki_page = WikiPage.find(params[:id]) @wiki_page.destroy respond_with(@wiki_page) end - + def revert @wiki_page = WikiPage.find(params[:id]) @version = WikiPageVersion.find(params[:version_id]) @wiki_page.revert_to!(@version) respond_with(@wiki_page) end - + def show_or_new @wiki_page = WikiPage.find_by_title(params[:title]) if @wiki_page diff --git a/app/helpers/advertisements_helper.rb b/app/helpers/advertisements_helper.rb index 8047fd686..1904c8214 100644 --- a/app/helpers/advertisements_helper.rb +++ b/app/helpers/advertisements_helper.rb @@ -4,14 +4,14 @@ module AdvertisementsHelper @advertisement = Advertisement.find(:first, :conditions => ["ad_type = ? AND status = 'active'", ad_type], :order => "random()") if @advertisement content_tag( - "div", + "div", link_to( image_tag( - @advertisement.image_url, - :alt => "Advertisement", - :width => @advertisement.width, + @advertisement.image_url, + :alt => "Advertisement", + :width => @advertisement.width, :height => @advertisement.height - ), + ), advertisement_hits_path(:advertisement_id => @advertisement.id), :method => :post ), @@ -22,7 +22,7 @@ module AdvertisementsHelper "" end end - + def render_rss_advertisement(short_or_long, safe) if Danbooru.config.can_see_ads?(CurrentUser.user) if safe diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 7aa494cf3..6a0330f64 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -8,27 +8,27 @@ module ApplicationHelper content_tag("li", link_to(text, url, options), :class => klass) end - + def fast_link_to(text, link_params, options = {}) if options - attributes = options.map do |k, v| + attributes = options.map do |k, v| %{#{k}="#{h(v)}"} end.join(" ") else attributes = "" end - + if link_params.is_a?(Hash) action = link_params.delete(:action) controller = link_params.delete(:controller) || controller_name id = link_params.delete(:id) - + link_params = link_params.map {|k, v| "#{k}=#{u(v)}"}.join("&") - + if link_params.present? link_params = "?#{link_params}" end - + if id url = "/#{controller}/#{action}/#{id}#{link_params}" else @@ -37,43 +37,43 @@ module ApplicationHelper else url = link_params end - + raw %{#{text}} end - + def format_text(text, options = {}) DText.parse(text) end def error_messages_for(instance_name) instance = instance_variable_get("@#{instance_name}") - + if instance && instance.errors.any? %{
Error: #{instance.__send__(:errors).full_messages.join(", ")}
}.html_safe else "" end end - + def time_tag(content, time) zone = time.strftime("%z") 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) end - + def time_ago_in_words_tagged(time) raw time_tag(time_ago_in_words(time) + " ago", time) end - + def compact_time(time) time_tag(time.strftime("%Y-%m-%d %H:%M"), time) end - + def mod_link_to_user(user, positive_or_negative) html = "" html << link_to(user.name, user_path(user)) - + if positive_or_negative == :positive html << " [" + link_to("+", new_user_feedback_path(:user_feedback => {:category => "positive", :user_id => user.id})) + "]" @@ -83,26 +83,26 @@ module ApplicationHelper else html << " [" + link_to("–".html_safe, new_user_feedback_path(:user_feedback => {:category => "negative", :user_id => user.id})) + "]" end - + html.html_safe end - + def dtext_field(object, name, options = {}) options[:name] ||= "Body" options[:input_id] ||= "#{object}_#{name}" options[:input_name] ||= "#{object}[#{name}]" options[:value] ||= instance_variable_get("@#{object}").try(name) options[:preview_id] ||= "dtext-preview" - + render "dtext/form", options end - + def dtext_preview_button(object, name, options = {}) options[:input_id] ||= "#{object}_#{name}" options[:preview_id] ||= "dtext-preview" submit_tag("Preview", "data-input-id" => options[:input_id], "data-preview-id" => options[:preview_id]) end - + def search_field(method, options = {}) name = options[:label] || method.titleize string = '
' @@ -112,49 +112,49 @@ module ApplicationHelper string += '
' string.html_safe end - + protected def nav_link_match(controller, url) url =~ case controller when "sessions", "users", "maintenance/user/login_reminders", "maintenance/user/password_resets", "admin/users", "tag_subscriptions" /^\/(session|users)/ - + when "forum_posts" /^\/forum_topics/ - + when "comments" /^\/comments/ - + when "notes", "note_versions" /^\/notes/ - + when "posts", "uploads", "post_versions", "explore/posts", "moderator/post/dashboards", "favorites" /^\/post/ - + when "artists", "artist_versions" /^\/artist/ - + when "tags" /^\/tags/ - + when "pools" /^\/pools/ - + when "moderator/dashboards" /^\/moderator/ - + when "tag_aliases", "tag_alias_corrections", "tag_alias_requests" /^\/tag_aliases/ - + when "tag_implications", "tag_implication_requests" /^\/tag_implications/ - + when "wiki_pages", "wiki_page_versions" /^\/wiki_pages/ - + when "forum_topics", "forum_posts" /^\/forum_topics/ - + else /^\/static/ end diff --git a/app/helpers/artists_helper.rb b/app/helpers/artists_helper.rb index e40c82124..09393b25f 100644 --- a/app/helpers/artists_helper.rb +++ b/app/helpers/artists_helper.rb @@ -1,16 +1,16 @@ module ArtistsHelper def link_to_artist(name) artist = Artist.find_by_name(name) - + if artist link_to(artist.name, artist_path(artist)) else link_to(name, new_artist_path(:name => name)) + " " + content_tag("span", "*", :class => "new-artist") end end - + def link_to_artists(names) - names.map do |name| + names.map do |name| link_to_artist(name) end.join(", ").html_safe end diff --git a/app/helpers/delayed_jobs_helper.rb b/app/helpers/delayed_jobs_helper.rb index 64f9fdde3..7dacffbb0 100644 --- a/app/helpers/delayed_jobs_helper.rb +++ b/app/helpers/delayed_jobs_helper.rb @@ -3,28 +3,28 @@ module DelayedJobsHelper case job.name when "Class#expire_cache" "expire post count cache: " + job.payload_object.args.flatten.join(" ") - + when "Upload#process!" 'upload post: record' - + when "Tag#update_related" "update related tags: " + job.payload_object.name - + when "TagAlias#process!" 'alias: ' + job.payload_object.antecedent_name + " -> " + job.payload_object.consequent_name - + when "TagImplication#process!" 'implication: ' + job.payload_object.antecedent_name + " -> " + job.payload_object.consequent_name - + when "Class#clear_cache_for" "expire tag alias cache: " + job.payload_object.flatten.join(" ") - + when "Tag#update_category_cache" "update tag category cache: " + job.payload_object.name when "Tag#update_category_post_counts" "update category post counts: " + job.payload_object.name - + else job.handler end diff --git a/app/helpers/moderator/dashboards_helper.rb b/app/helpers/moderator/dashboards_helper.rb index 53b6aa951..8a59cf293 100644 --- a/app/helpers/moderator/dashboards_helper.rb +++ b/app/helpers/moderator/dashboards_helper.rb @@ -10,7 +10,7 @@ module Moderator ["Moderator", 40], ["Admin", 50] ] - + select_tag(name, options_for_select(choices, params[name].to_i), options) end end diff --git a/app/helpers/pagination_helper.rb b/app/helpers/pagination_helper.rb index 880dc14e7..47f33a185 100644 --- a/app/helpers/pagination_helper.rb +++ b/app/helpers/pagination_helper.rb @@ -1,31 +1,31 @@ module PaginationHelper def sequential_paginator(records) html = '
' - - if records.any? + + if records.any? if params[:page] =~ /[ab]/ html << '
  • ' + link_to("< Previous", params.merge(:page => "a#{records[0].id}"), :rel => "prev") + '
  • ' end - + html << '
  • ' + link_to("Next >", params.merge(:page => "b#{records[-1].id}"), :rel => "next") + '
  • ' end - + html << "
    " html.html_safe end - + def use_sequential_paginator?(records) params[:page] =~ /[ab]/ || records.current_page >= Danbooru.config.max_numbered_pages end - + def numbered_paginator(records, switch_to_sequential = true) if use_sequential_paginator?(records) && switch_to_sequential return sequential_paginator(records) end - + html = '
    ' window = 3 - + if records.current_page >= 2 html << "
  • " + link_to("<<", params.merge(:page => records.current_page - 1), :rel => "prev") + "
  • " end @@ -34,7 +34,7 @@ module PaginationHelper 1.upto(records.total_pages) do |page| html << numbered_paginator_item(page, records.current_page) end - + elsif records.current_page <= window + 2 1.upto(records.current_page + window) do |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) end end - + if records.current_page < records.total_pages && records.size > 0 html << "
  • " + link_to(">>", params.merge(:page => records.current_page + 1), :rel => "next") + "
  • " end - + html << "
    " html.html_safe end - + def numbered_paginator_final_item(total_pages, current_page) if total_pages <= Danbooru.config.max_numbered_pages numbered_paginator_item(total_pages, current_page) @@ -79,10 +79,10 @@ module PaginationHelper "" end end - + def numbered_paginator_item(page, current_page) return "" if page.to_i > Danbooru.config.max_numbered_pages - + html = "
  • " if page == "..." html << "..." diff --git a/app/helpers/post_appeals_helper.rb b/app/helpers/post_appeals_helper.rb index c01d84914..be3e8058f 100644 --- a/app/helpers/post_appeals_helper.rb +++ b/app/helpers/post_appeals_helper.rb @@ -2,11 +2,11 @@ module PostAppealsHelper def post_appeal_reasons(post) html = [] html << '' html.join("\n").html_safe end diff --git a/app/helpers/post_flags_helper.rb b/app/helpers/post_flags_helper.rb index 8a6751358..5ae5ff1ee 100644 --- a/app/helpers/post_flags_helper.rb +++ b/app/helpers/post_flags_helper.rb @@ -2,24 +2,24 @@ module PostFlagsHelper def post_flag_reasons(post) html = [] html << '' html.join("\n").html_safe end diff --git a/app/helpers/posts_helper.rb b/app/helpers/posts_helper.rb index 7963f1e93..7a880fe9e 100644 --- a/app/helpers/posts_helper.rb +++ b/app/helpers/posts_helper.rb @@ -5,18 +5,18 @@ module PostsHelper if post.has_large? links << link_to("L", post.large_file_url, :id => "large-file-link") end - + if post.has_large? links << link_to("O", post.file_url, :id => "original-file-link") end - + if links.any? content_tag("span", raw("Resize: " + links.join(" "))) else nil end end - + def post_source_tag(post) if post.source =~ /^http/ text = truncate(post.normalized_source.sub(/^https?:\/\//, "")) diff --git a/app/logical/alias_and_implication_importer.rb b/app/logical/alias_and_implication_importer.rb index acb05b8df..5ee2887d8 100644 --- a/app/logical/alias_and_implication_importer.rb +++ b/app/logical/alias_and_implication_importer.rb @@ -1,18 +1,18 @@ class AliasAndImplicationImporter attr_accessor :text, :commands, :forum_id - + def initialize(text, forum_id) @forum_id = forum_id @text = text end - + def process! tokens = tokenize(text) parse(tokens) end - + private - + def tokenize(text) text.gsub!(/^\s+/, "") text.gsub!(/\s+$/, "") @@ -33,7 +33,7 @@ private end end end - + def parse(tokens) ActiveRecord::Base.transaction do tokens.map do |token| @@ -41,21 +41,21 @@ private when :create_alias 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! - + when :create_implication 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! - + when :remove_alias tag_alias = TagAlias.where("antecedent_name = ?", token[1]).first raise "Alias for #{token[1]} not found" if tag_alias.nil? tag_alias.destroy - + when :remove_implication 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? tag_implication.destroy - + else raise "Unknown token: #{token[0]}" end diff --git a/app/logical/anonymous_user.rb b/app/logical/anonymous_user.rb index 80f764062..409b25e63 100644 --- a/app/logical/anonymous_user.rb +++ b/app/logical/anonymous_user.rb @@ -11,15 +11,15 @@ class AnonymousUser def comment_threshold 0 end - + def created_at Time.now end - + def updated_at Time.now end - + def name "Anonymous" end @@ -31,11 +31,11 @@ class AnonymousUser def is_anonymous? true end - + def has_mail? false end - + def has_forum_been_updated? false end @@ -47,11 +47,11 @@ class AnonymousUser def ban false end - + def always_resize_images? false end - + def show_samples? true end @@ -59,15 +59,15 @@ class AnonymousUser def tag_subscriptions [] end - + def favorite_tags nil end - + def upload_limit 0 end - + def base_upload_limit 0 end @@ -75,15 +75,15 @@ class AnonymousUser def uploaded_tags "" end - + def uploaded_tags_with_types [] end - + def recent_tags "" end - + def recent_tags_with_types [] end @@ -91,15 +91,15 @@ class AnonymousUser def can_upload? false end - + def can_comment? false end - + def can_remove_from_pools? false end - + def blacklisted_tags "" end @@ -107,64 +107,64 @@ class AnonymousUser def time_zone "Eastern Time (US & Canada)" end - + def default_image_size "large" end - + def blacklisted_tags [] end - + def email "" end - + def last_forum_read_at Time.now end - + def update_column(*params) end - + def increment!(field) end - + def decrement!(field) end - + def role :anonymous end - + def tag_query_limit 2 end - + def favorite_limit 0 end - + def favorite_count 0 end - + def enable_post_navigation true end - + def new_post_navigation_layout true end - + def enable_privacy_mode false end - + def enable_sequential_post_navigation true end - + %w(member banned privileged builder platinum contributor janitor moderator admin).each do |name| define_method("is_#{name}?") do false diff --git a/app/logical/cache.rb b/app/logical/cache.rb index c5f54bea9..73016c56d 100644 --- a/app/logical/cache.rb +++ b/app/logical/cache.rb @@ -4,7 +4,7 @@ class Cache Cache.put(key, val.to_i + 1) ActiveRecord::Base.logger.debug('MemCache Incr %s' % [key]) end - + def self.decr(key, expiry = 0) val = Cache.get(key, expiry) if val.to_i > 0 @@ -12,7 +12,7 @@ class Cache end ActiveRecord::Base.logger.debug('MemCache Decr %s' % [key]) end - + def self.get_multi(keys, prefix, expiry = 0) key_to_sanitized_key_hash = keys.inject({}) do |hash, x| hash[x] = "#{prefix}:#{Cache.sanitize(x)}" @@ -30,11 +30,11 @@ class Cache Cache.put(sanitized_key, result_hash[key], expiry) end end - + ActiveRecord::Base.logger.debug('MemCache Multi-Get (%0.6f) %s' % [elapsed, keys.join(",")]) end end - + def self.get(key, expiry = 0) begin start_time = Time.now @@ -55,11 +55,11 @@ class Cache value end end - + def self.put(key, value, expiry = 0) key.gsub!(/\s/, "_") key = key[0, 200] - + begin start_time = Time.now MEMCACHE.set key, value, expiry @@ -71,7 +71,7 @@ class Cache nil end end - + def self.delete(key, delay = nil) begin start_time = Time.now @@ -84,7 +84,7 @@ class Cache nil end end - + def self.sanitize(key) key.gsub(/\W/) {|x| "%#{x.ord}"}.slice(0, 240) end diff --git a/app/logical/current_user.rb b/app/logical/current_user.rb index 34be49c7a..09f56a924 100644 --- a/app/logical/current_user.rb +++ b/app/logical/current_user.rb @@ -2,10 +2,10 @@ class CurrentUser def self.scoped(user, ip_addr) old_user = self.user old_ip_addr = self.ip_addr - + self.user = user self.ip_addr = ip_addr - + begin yield ensure @@ -17,19 +17,19 @@ class CurrentUser def self.user=(user) Thread.current[:current_user] = user end - + def self.ip_addr=(ip_addr) Thread.current[:current_ip_addr] = ip_addr end - + def self.user Thread.current[:current_user] end - + def self.ip_addr Thread.current[:current_ip_addr] end - + def self.id if user.nil? nil @@ -37,11 +37,11 @@ class CurrentUser user.id end end - + def self.name user.name end - + def self.method_missing(method, *params, &block) if user.respond_to?(method) user.__send__(method, *params, &block) diff --git a/app/logical/d_text.rb b/app/logical/d_text.rb index d87efa0bb..7a1993e5f 100644 --- a/app/logical/d_text.rb +++ b/app/logical/d_text.rb @@ -5,11 +5,11 @@ class DText def self.u(string) CGI.escape(string) end - + def self.h(string) CGI.escapeHTML(string) end - + def self.parse_inline(str, options = {}) str.gsub!(/&/, "&") str.gsub!(/]+|https?:\/\/[^\s\r\n<>]+)+/) do |url| if url =~ /^"([^"]+)":(.+)$/ @@ -34,7 +34,7 @@ class DText else text = url end - + if url =~ /([;,.!?\)\]<>])$/ url.chop! ch = $1 @@ -45,7 +45,7 @@ class DText '' + text + '' + ch end end - + def self.parse_aliased_wiki_links(str) str.gsub(/\[\[([^\|\]]+)\|([^\]]+)\]\]/m) do text = CGI.unescapeHTML($2) @@ -53,7 +53,7 @@ class DText %{#{h(text)}} end end - + def self.parse_wiki_links(str) str.gsub(/\[\[([^\]]+)\]\]/) do text = CGI.unescapeHTML($1) @@ -61,14 +61,14 @@ class DText %{#{h(text)}} end end - + def self.parse_post_links(str) str.gsub(/\{\{([^\}]+)\}\}/) do tags = CGI.unescapeHTML($1) %{#{h(tags)}} end end - + def self.parse_id_links(str) str = str.gsub(/\bpost #(\d+)/i, %{post #\\1}) str = str.gsub(/\bforum #(\d+)/i, %{forum #\\1}) @@ -76,7 +76,7 @@ class DText str = str.gsub(/\bpool #(\d+)/i, %{pool #\\1}) str = str.gsub(/\buser #(\d+)/i, %{user #\\1}) end - + def self.parse_list(str, options = {}) html = "" layout = [] @@ -115,27 +115,27 @@ class DText def self.parse(str, options = {}) return "" if str.blank? - + # Make sure quote tags are surrounded by newlines - + 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*\[spoilers?\](?!\])\s*/m, "\n\n[spoiler]\n\n") str.gsub!(/\s*\[\/spoilers?\]\s*/m, "\n\n[/spoiler]\n\n") end - + str.gsub!(/(?:\r?\n){3,}/, "\n\n") str.strip! blocks = str.split(/(?:\r?\n){2}/) stack = [] - + html = blocks.map do |block| case block when /^(h[1-6])\.\s*(.+)$/ tag = $1 - content = $2 - + content = $2 + if options[:inline] "
    " + parse_inline(content, options) + "
    " else @@ -144,7 +144,7 @@ class DText when /^\s*\*+ / parse_list(block, options) - + when "[quote]" if options[:inline] "" @@ -152,7 +152,7 @@ class DText stack << "blockquote" "
    " end - + when "[/quote]" if options[:inline] "" @@ -166,7 +166,7 @@ class DText when /\[spoilers?\](?!\])/ stack << "div" '
    ' - + when /\[\/spoilers?\]/ if stack.last == "div" stack.pop @@ -177,7 +177,7 @@ class DText '

    ' + parse_inline(block) + "

    " end end - + stack.reverse.each do |tag| if tag == "blockquote" html << "
    " @@ -188,10 +188,10 @@ class DText sanitize(html.join("")).html_safe end - + def self.sanitize(text) text.gsub!(/<( |-|\Z)/, "<\\1") - + Sanitize.clean( 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), diff --git a/app/logical/downloads/file.rb b/app/logical/downloads/file.rb index 85bdd529b..6498ba650 100644 --- a/app/logical/downloads/file.rb +++ b/app/logical/downloads/file.rb @@ -1,14 +1,14 @@ module Downloads class File class Error < Exception ; end - + attr_accessor :source, :content_type, :file_path - + def initialize(source, file_path) @source = source @file_path = file_path end - + def download! http_get_streaming do |response| self.content_type = response["Content-Type"] @@ -18,23 +18,23 @@ module Downloads end after_download end - + def before_download(url, headers) Strategies::Base.strategies.each do |strategy| url, headers = strategy.new.rewrite(url, headers) end - + return [url, headers] end - + def after_download fix_image_board_sources end - + def url URI.parse(source) end - + def http_get_streaming(options = {}) max_size = options[:max_size] || Danbooru.config.max_file_size max_size = nil if max_size == 0 # unlimited @@ -49,7 +49,7 @@ module Downloads "User-Agent" => "#{Danbooru.config.safe_app_name}/#{Danbooru.config.version}" } @source, headers = before_download(source, headers) - + Net::HTTP.start(url.host, url.port, :use_ssl => url.is_a?(URI::HTTPS)) do |http| http.read_timeout = 10 http.request_get(url.request_uri, headers) do |res| @@ -76,7 +76,7 @@ module Downloads end # http.start end # while end # def - + def fix_image_board_sources if source =~ /\/src\/\d{12,}|urnc\.yi\.org|yui\.cynthia\.bne\.jp/ @source = "Image board" diff --git a/app/logical/downloads/strategies/base.rb b/app/logical/downloads/strategies/base.rb index 177ccaf95..cddee48ee 100644 --- a/app/logical/downloads/strategies/base.rb +++ b/app/logical/downloads/strategies/base.rb @@ -4,7 +4,7 @@ module Downloads def self.strategies [Pixiv] end - + def rewrite(url, headers) return [url, headers] end diff --git a/app/logical/downloads/strategies/pixiv.rb b/app/logical/downloads/strategies/pixiv.rb index dfce088fa..2cf37dec9 100644 --- a/app/logical/downloads/strategies/pixiv.rb +++ b/app/logical/downloads/strategies/pixiv.rb @@ -8,16 +8,16 @@ module Downloads url, headers = rewrite_small_images(url, headers) url, headers = rewrite_small_manga_pages(url, headers) end - + return [url, headers] end - + protected def rewrite_headers(url, headers) headers["Referer"] = "http://www.pixiv.net" return [url, headers] end - + def rewrite_html_pages(url, headers) # example: http://www.pixiv.net/member_illust.php?mode=big&illust_id=23828655 @@ -29,16 +29,16 @@ module Downloads return [url, headers] end end - + def rewrite_small_images(url, headers) if url =~ %r!(/img/.+?/.+?)_m.+$! match = $1 url.sub!(match + "_m", match) end - + return [url, headers] end - + def rewrite_small_manga_pages(url, headers) if url =~ %r!(\d+_p\d+)\.! match = $1 @@ -48,7 +48,7 @@ module Downloads url = big_url end end - + return [url, headers] end diff --git a/app/logical/janitor_trial_tester.rb b/app/logical/janitor_trial_tester.rb index f2254a5be..37b402790 100644 --- a/app/logical/janitor_trial_tester.rb +++ b/app/logical/janitor_trial_tester.rb @@ -1,10 +1,10 @@ class JanitorTrialTester attr_reader :user - + def initialize(user_name) @user = User.find_by_name(user_name) end - + def test if user.nil? "User not found" diff --git a/app/logical/moderator/dashboard/queries/artist.rb b/app/logical/moderator/dashboard/queries/artist.rb index 48968e793..842f00716 100644 --- a/app/logical/moderator/dashboard/queries/artist.rb +++ b/app/logical/moderator/dashboard/queries/artist.rb @@ -7,16 +7,16 @@ module Moderator def self.all(min_date, max_level) sql = <<-EOS SELECT artist_versions.updater_id AS updater_id, count(*) - FROM artist_versions - JOIN users ON users.id = artist_versions.updater_id - WHERE - artist_versions.created_at > ? - AND users.level <= ? - GROUP BY artist_versions.updater_id - ORDER BY count(*) DESC + FROM artist_versions + JOIN users ON users.id = artist_versions.updater_id + WHERE + artist_versions.created_at > ? + AND users.level <= ? + GROUP BY artist_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end diff --git a/app/logical/moderator/dashboard/queries/comment.rb b/app/logical/moderator/dashboard/queries/comment.rb index 3e09075ba..b86d189f0 100644 --- a/app/logical/moderator/dashboard/queries/comment.rb +++ b/app/logical/moderator/dashboard/queries/comment.rb @@ -6,20 +6,20 @@ module Moderator def self.all(min_date, max_level) sql = <<-EOS - SELECT comment_votes.comment_id, count(*) - FROM comment_votes - JOIN comments ON comments.id = comment_id - JOIN users ON users.id = comments.creator_id - WHERE - comment_votes.created_at > ? - AND comments.score < 0 - AND users.level <= ? - GROUP BY comment_votes.comment_id + SELECT comment_votes.comment_id, count(*) + FROM comment_votes + JOIN comments ON comments.id = comment_id + JOIN users ON users.id = comments.creator_id + WHERE + comment_votes.created_at > ? + AND comments.score < 0 + AND users.level <= ? + GROUP BY comment_votes.comment_id HAVING count(*) >= 3 - ORDER BY count(*) DESC + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end diff --git a/app/logical/moderator/dashboard/queries/note.rb b/app/logical/moderator/dashboard/queries/note.rb index 59b1825e8..3e58257f1 100644 --- a/app/logical/moderator/dashboard/queries/note.rb +++ b/app/logical/moderator/dashboard/queries/note.rb @@ -3,23 +3,23 @@ module Moderator module Queries class Note attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - SELECT note_versions.updater_id, count(*) - FROM note_versions - JOIN users ON users.id = note_versions.updater_id - WHERE - note_versions.created_at > ? - AND users.level <= ? - GROUP BY note_versions.updater_id - ORDER BY count(*) DESC + SELECT note_versions.updater_id, count(*) + FROM note_versions + JOIN users ON users.id = note_versions.updater_id + WHERE + note_versions.created_at > ? + AND users.level <= ? + GROUP BY note_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end - + def initialize(hash) @user = ::User.find(hash["updater_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/post_appeal.rb b/app/logical/moderator/dashboard/queries/post_appeal.rb index 0a0b9ca9a..c84ed0d9c 100644 --- a/app/logical/moderator/dashboard/queries/post_appeal.rb +++ b/app/logical/moderator/dashboard/queries/post_appeal.rb @@ -10,14 +10,14 @@ module Moderator FROM post_appeals JOIN posts ON posts.id = post_appeals.post_id WHERE - post_appeals.created_at > ? + post_appeals.created_at > ? and posts.is_deleted = true and posts.is_pending = false GROUP BY post_appeals.post_id ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date).map {|x| new(x)} end diff --git a/app/logical/moderator/dashboard/queries/post_flag.rb b/app/logical/moderator/dashboard/queries/post_flag.rb index 3334f4989..9bc1152e0 100644 --- a/app/logical/moderator/dashboard/queries/post_flag.rb +++ b/app/logical/moderator/dashboard/queries/post_flag.rb @@ -6,22 +6,22 @@ module Moderator def self.all(min_date) sql = <<-EOS - SELECT post_flags.post_id, count(*) - FROM post_flags - JOIN posts ON posts.id = post_flags.post_id - WHERE - post_flags.created_at > ? - AND post_flags.reason <> ? + SELECT post_flags.post_id, count(*) + FROM post_flags + JOIN posts ON posts.id = post_flags.post_id + WHERE + post_flags.created_at > ? + AND post_flags.reason <> ? AND posts.is_deleted = false and posts.is_pending = false - GROUP BY post_flags.post_id - ORDER BY count(*) DESC + GROUP BY post_flags.post_id + ORDER BY count(*) DESC LIMIT 10 EOS ActiveRecord::Base.select_all_sql(sql, min_date, "Unapproved in three days").map {|x| new(x)} end - + def initialize(hash) @post = Post.find(hash["post_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/tag.rb b/app/logical/moderator/dashboard/queries/tag.rb index de056c7a9..a3411bbdb 100644 --- a/app/logical/moderator/dashboard/queries/tag.rb +++ b/app/logical/moderator/dashboard/queries/tag.rb @@ -3,25 +3,25 @@ module Moderator module Queries class Tag attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - SELECT post_versions.updater_id, count(*) - FROM post_versions - JOIN users ON users.id = post_versions.updater_id - WHERE - post_versions.updated_at > ? - AND users.level <= ? - GROUP BY post_versions.updater_id - ORDER BY count(*) DESC + SELECT post_versions.updater_id, count(*) + FROM post_versions + JOIN users ON users.id = post_versions.updater_id + WHERE + post_versions.updated_at > ? + AND users.level <= ? + GROUP BY post_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.without_timeout do ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end end - + def initialize(hash) @user = ::User.find(hash["updater_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/upload.rb b/app/logical/moderator/dashboard/queries/upload.rb index b6a3206ce..588ff4169 100644 --- a/app/logical/moderator/dashboard/queries/upload.rb +++ b/app/logical/moderator/dashboard/queries/upload.rb @@ -3,23 +3,23 @@ module Moderator module Queries class Upload attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - select uploader_id, count(*) - from posts - join users on uploader_id = users.id - where - posts.created_at > ? - and level <= ? - group by posts.uploader_id - order by count(*) desc + select uploader_id, count(*) + from posts + join users on uploader_id = users.id + where + posts.created_at > ? + and level <= ? + group by posts.uploader_id + order by count(*) desc limit 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end - + def initialize(hash) @user = ::User.find(hash["uploader_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/queries/wiki_page.rb b/app/logical/moderator/dashboard/queries/wiki_page.rb index 016e566f6..9b4c15f36 100644 --- a/app/logical/moderator/dashboard/queries/wiki_page.rb +++ b/app/logical/moderator/dashboard/queries/wiki_page.rb @@ -3,23 +3,23 @@ module Moderator module Queries class WikiPage attr_reader :user, :count - + def self.all(min_date, max_level) sql = <<-EOS - SELECT wiki_page_versions.updater_id, count(*) - FROM wiki_page_versions - JOIN users ON users.id = wiki_page_versions.updater_id - WHERE - wiki_page_versions.created_at > ? - AND users.level <= ? - GROUP BY wiki_page_versions.updater_id - ORDER BY count(*) DESC + SELECT wiki_page_versions.updater_id, count(*) + FROM wiki_page_versions + JOIN users ON users.id = wiki_page_versions.updater_id + WHERE + wiki_page_versions.created_at > ? + AND users.level <= ? + GROUP BY wiki_page_versions.updater_id + ORDER BY count(*) DESC LIMIT 10 EOS - + ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)} end - + def initialize(hash) @user = ::User.find(hash["updater_id"]) @count = hash["count"] diff --git a/app/logical/moderator/dashboard/report.rb b/app/logical/moderator/dashboard/report.rb index a24ca5000..3694988f9 100644 --- a/app/logical/moderator/dashboard/report.rb +++ b/app/logical/moderator/dashboard/report.rb @@ -2,18 +2,18 @@ module Moderator module Dashboard class Report attr_reader :min_date, :max_level - + def initialize(min_date, max_level) @min_date = min_date.present? ? min_date.to_date : 1.week.ago @max_level = max_level.present? ? User::Levels::MEMBER : max_level.to_i end - + def artists ActiveRecord::Base.without_timeout do Queries::Artist.all(min_date, max_level) end end - + def comments ActiveRecord::Base.without_timeout do Queries::Comment.all(min_date, max_level) @@ -55,7 +55,7 @@ module Moderator Queries::Upload.all(min_date, max_level) end end - + def user_feedbacks ActiveRecord::Base.without_timeout do Queries::UserFeedback.all diff --git a/app/logical/moderator/ip_addr_search.rb b/app/logical/moderator/ip_addr_search.rb index b5b10dcca..95c7a9bbd 100644 --- a/app/logical/moderator/ip_addr_search.rb +++ b/app/logical/moderator/ip_addr_search.rb @@ -1,12 +1,12 @@ module Moderator class IpAddrSearch attr_reader :params, :errors - + def initialize(params) @params = params @errors = [] end - + def execute if params[:user_id].present? search_by_user_id(params[:user_id].split(/,/)) @@ -18,41 +18,41 @@ module Moderator [] end end - + private def select_all_sql(sql, *params) ActiveRecord::Base.select_all_sql(sql, *params) end - + def search_by_ip_addr(ip_addrs) 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 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 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) - + sums end - + def search_by_user_name(user_names) users = User.where("name in (?)", user_names) search_by_user_id(users.map(&:id)) end - + def search_by_user_id(user_ids) 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 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 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) - + sums end - + def add_row(sums, sql, ip_addrs) select_all_sql(sql, ip_addrs).each do |row| sums[row["k"]] += row["count"].to_i diff --git a/app/logical/moderator/tag_batch_change.rb b/app/logical/moderator/tag_batch_change.rb index 08453060e..1b1ab2bdb 100644 --- a/app/logical/moderator/tag_batch_change.rb +++ b/app/logical/moderator/tag_batch_change.rb @@ -1,15 +1,15 @@ module Moderator class TagBatchChange < Struct.new(:antecedent, :consequent, :updater_id, :updater_ip_addr) class Error < Exception ; end - + def perform raise Error.new("antecedent is missing") if antecedent.blank? - + normalized_antecedent = TagAlias.to_aliased(::Tag.scan_tags(antecedent)) normalized_consequent = TagAlias.to_aliased(::Tag.scan_tags(consequent)) - + updater = User.find(updater_id) - + CurrentUser.scoped(updater, updater_ip_addr) do ::Post.tag_match(antecedent).each do |post| tags = (post.tag_array - normalized_antecedent + normalized_consequent).join(" ") diff --git a/app/logical/post_pruner.rb b/app/logical/post_pruner.rb index 3932da151..652da1b7c 100644 --- a/app/logical/post_pruner.rb +++ b/app/logical/post_pruner.rb @@ -1,16 +1,16 @@ class PostPruner attr_reader :admin - + def initialize @admin = User.where(:level => User::Levels::ADMIN).first end - + def prune! prune_pending! prune_flagged! prune_mod_actions! end - + protected def prune_pending! @@ -25,7 +25,7 @@ protected end end end - + def prune_flagged! CurrentUser.scoped(admin, "127.0.0.1") do Post.where("is_deleted = ? and is_flagged = ?", false, true).each do |post| @@ -40,7 +40,7 @@ protected end end end - + def prune_mod_actions! ModAction.destroy_all(["creator_id = ? and description like ?", admin.id, "deleted post %"]) end diff --git a/app/logical/post_query_builder.rb b/app/logical/post_query_builder.rb index 5d9055f52..1fee842e0 100644 --- a/app/logical/post_query_builder.rb +++ b/app/logical/post_query_builder.rb @@ -1,24 +1,24 @@ class PostQueryBuilder attr_accessor :query_string, :has_constraints - + def initialize(query_string) @query_string = query_string @has_constraint = false end - + def has_constraints? @has_constraints end - + def has_constraints! @has_constraints = true end - + def add_range_relation(arr, field, relation) return relation if arr.nil? - + has_constraints! - + case arr[0] when :eq if arr[1].is_a?(Time) @@ -38,7 +38,7 @@ class PostQueryBuilder when :lte relation.where(["#{field} <= ?", arr[1]]) - + when :in relation.where(["#{field} in (?)", arr[1]]) @@ -76,10 +76,10 @@ class PostQueryBuilder if tag_query_sql.any? relation = relation.where("posts.tag_index @@ to_tsquery('danbooru', E?)", tag_query_sql.join(" & ")) end - + relation end - + def add_tag_subscription_relation(subscriptions, relation) subscriptions.each do |subscription| if subscription =~ /^(.+?):(.+)$/ @@ -93,25 +93,25 @@ class PostQueryBuilder return relation if user.nil? post_ids = TagSubscription.find_post_ids(user.id) end - + post_ids = [0] if post_ids.empty? relation = relation.where(["posts.id IN (?)", post_ids]) end - + relation end - + def build unless query_string.is_a?(Hash) q = Tag.parse_query(query_string) end - + relation = Post.scoped - + 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") end - + 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[: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[:post_tag_count], "posts.tag_count", relation) relation = add_range_relation(q[:pixiv], "substring(posts.source, 'pixiv.net/img.*/([0-9]+)[^/]*$')::integer", relation) - + if q[:md5] relation = relation.where(["posts.md5 IN (?)", q[:md5]]) has_constraints! end - + if q[:status] == "pending" relation = relation.where("posts.is_pending = TRUE") elsif q[:status] == "flagged" @@ -167,26 +167,26 @@ class PostQueryBuilder if q[:uploader_id_neg] relation = relation.where("posts.uploader_id not in (?)", q[:uploader_id_neg]) end - + if q[:uploader_id] relation = relation.where("posts.uploader_id = ?", q[:uploader_id]) has_constraints! end - + if q[:approver_id_neg] relation = relation.where("posts.approver_id not in (?)", q[:approver_id_neg]) end - + if q[:approver_id] relation = relation.where("posts.approver_id = ?", q[:approver_id]) has_constraints! end - + if q[:parent_id] relation = relation.where("(posts.id = ? or posts.parent_id = ?)", q[:parent_id], q[:parent_id]) has_constraints! end - + if q[:rating] =~ /^q/ relation = relation.where("posts.rating = 'q'") elsif q[:rating] =~ /^s/ @@ -202,13 +202,13 @@ class PostQueryBuilder elsif q[:rating_negated] =~ /^e/ relation = relation.where("posts.rating <> 'e'") end - + relation = add_tag_string_search_relation(q[:tags], relation) - + if q[:order] == "rank" relation = relation.where("posts.score > 0 and posts.created_at >= ?", 2.days.ago) end - + case q[:order] when "id", "id_asc" relation = relation.order("posts.id ASC") @@ -221,10 +221,10 @@ class PostQueryBuilder when "score_asc" relation = relation.order("posts.score ASC, posts.id DESC") - + when "favcount" relation = relation.order("posts.fav_count DESC, posts.id DESC") - + when "favcount_asc" relation = relation.order("posts.fav_count ASC, posts.id DESC") diff --git a/app/logical/post_search_context.rb b/app/logical/post_search_context.rb index db3b5b38a..67ddde396 100644 --- a/app/logical/post_search_context.rb +++ b/app/logical/post_search_context.rb @@ -1,14 +1,14 @@ class PostSearchContext attr_reader :params, :post_id - + def initialize(params) @params = params raise unless params[:seq].present? raise unless params[:id].present? - + @post_id = find_post_id end - + def find_post_id if params[:seq] == "prev" post = Post.tag_match(params[:tags]).where("posts.id > ?", params[:id].to_i).reorder("posts.id asc").first diff --git a/app/logical/post_sets/artist.rb b/app/logical/post_sets/artist.rb index b04809268..1fb619498 100644 --- a/app/logical/post_sets/artist.rb +++ b/app/logical/post_sets/artist.rb @@ -1,12 +1,12 @@ module PostSets class Artist < PostSets::Post attr_reader :artist - + def initialize(artist) super(artist.name) @artist = artist end - + def posts ::Post.tag_match(@artist.name).limit(10) rescue ::Post::SearchError diff --git a/app/logical/post_sets/base.rb b/app/logical/post_sets/base.rb index dcd62826e..6dd73cbcb 100644 --- a/app/logical/post_sets/base.rb +++ b/app/logical/post_sets/base.rb @@ -3,38 +3,38 @@ module PostSets def has_wiki? false end - + def wiki_page nil end - + def has_artist? false end - + def artist nil end - + def is_single_tag? false end - + def presenter raise NotImplementedError end - + def arbitrary_sql_order_clause(ids, table_name) if ids.empty? return "#{table_name}.id desc" end - + conditions = [] - + ids.each_with_index do |x, n| conditions << "when #{x} then #{n}" end - + "case #{table_name}.id " + conditions.join(" ") + " end" end end diff --git a/app/logical/post_sets/favorite.rb b/app/logical/post_sets/favorite.rb index 73efc90bb..f932a4977 100644 --- a/app/logical/post_sets/favorite.rb +++ b/app/logical/post_sets/favorite.rb @@ -1,28 +1,28 @@ module PostSets class Favorite < Base attr_reader :user, :page, :favorites - + def initialize(user_id, page = 1) @user = ::User.find(user_id) @favorites = ::Favorite.for_user(user.id).paginate(page).order("favorites.id desc") end - + def tag_array @tag_array ||= ["fav:#{user.name}"] end - + def tag_string tag_array.uniq.join(" ") end - + def humanized_tag_string "fav:#{user.pretty_name}" end - + def posts favorites.includes(:post).map(&:post) end - + def presenter @presenter ||= ::PostSetPresenters::Favorite.new(self) end diff --git a/app/logical/post_sets/pool.rb b/app/logical/post_sets/pool.rb index b34ae1ade..e80670fa5 100644 --- a/app/logical/post_sets/pool.rb +++ b/app/logical/post_sets/pool.rb @@ -3,26 +3,26 @@ module PostSets module ActiveRecordExtension attr_accessor :total_pages, :current_page end - + attr_reader :pool, :page - + def initialize(pool, page = 1) @pool = pool @page = page end - + def offset (current_page - 1) * limit end - + def limit Danbooru.config.posts_per_page end - + def tag_array ["pool:#{pool.id}"] end - + def posts @posts ||= begin x = pool.posts(:offset => offset, :limit => limit) @@ -32,27 +32,27 @@ module PostSets x end end - + def tag_string tag_array.join("") end - + def humanized_tag_string "pool:#{pool.pretty_name}" end - + def presenter @presenter ||= PostSetPresenters::Pool.new(self) end - + def total_pages (pool.post_count.to_f / limit).ceil end - + def size posts.size end - + def current_page [page.to_i, 1].max end diff --git a/app/logical/post_sets/popular.rb b/app/logical/post_sets/popular.rb index 99e4dd956..0950abf6b 100644 --- a/app/logical/post_sets/popular.rb +++ b/app/logical/post_sets/popular.rb @@ -1,41 +1,41 @@ module PostSets class Popular < Base attr_reader :date, :scale - + def initialize(date, scale) @date = date.blank? ? Time.zone.now : Time.zone.parse(date) @scale = scale end - + def posts ::Post.where("created_at between ? and ?", min_date.beginning_of_day, max_date.end_of_day).order("score desc").limit(limit) end - + def limit 25 end - + def min_date case scale when "week" date.beginning_of_week - + when "month" date.beginning_of_month - + else date end end - + def max_date case scale when "week" date.end_of_week - + when "month" date.end_of_month - + else date end diff --git a/app/logical/post_sets/post.rb b/app/logical/post_sets/post.rb index ef97af9ed..c535f2871 100644 --- a/app/logical/post_sets/post.rb +++ b/app/logical/post_sets/post.rb @@ -1,22 +1,22 @@ module PostSets class Post < Base attr_reader :tag_array, :page, :per_page - + def initialize(tags, page = 1, per_page = nil) @tag_array = Tag.scan_query(tags) @page = page @per_page = (per_page || Danbooru.config.posts_per_page).to_i @per_page = 200 if @per_page > 200 end - + def tag_string @tag_string ||= tag_array.uniq.join(" ") end - + def humanized_tag_string tag_array.slice(0, 25).join(" ").tr("_", " ") end - + def has_wiki? tag_array.size == 1 && ::WikiPage.titled(tag_string).exists? end @@ -28,15 +28,15 @@ module PostSets nil end end - + def has_deleted? CurrentUser.is_privileged? && tag_string !~ /status/ && ::Post.tag_match("#{tag_string} status:deleted").exists? end - + def has_explicit? posts.any? {|x| x.rating == "e"} end - + def posts if tag_array.size > 2 && !CurrentUser.is_privileged? 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? raise SearchError.new("Your search took too long to execute and was canceled") end - + @posts ||= begin temp = ::Post.tag_match(tag_string).paginate(page, :count => ::Post.fast_count(tag_string), :limit => per_page) temp.all temp end end - + def has_artist? tag_array.any? && ::Artist.name_equals(tag_string).exists? end - + def artist ::Artist.name_matches(tag_string).first end - + def is_single_tag? tag_array.size == 1 end - + def is_empty_tag? tag_array.size == 0 end - + def is_pattern_search? tag_string =~ /\*/ end - + def current_page [page.to_i, 1].max end - + def is_tag_subscription? tag_subscription.present? end - + def tag_subscription @tag_subscription ||= tag_array.select {|x| x =~ /^sub:/}.map {|x| x.sub(/^sub:/, "")}.first end - + def tag_subscription_tags @tag_subscription_tags ||= TagSubscription.find_tags(tag_subscription) end - + def presenter @presenter ||= ::PostSetPresenters::Post.new(self) end diff --git a/app/logical/post_sets/wiki_page.rb b/app/logical/post_sets/wiki_page.rb index 81ac2bd81..2c83d5c2c 100644 --- a/app/logical/post_sets/wiki_page.rb +++ b/app/logical/post_sets/wiki_page.rb @@ -1,7 +1,7 @@ module PostSets class SearchError < Exception end - + class WikiPage < Post def presenter @presenter ||= ::PostSetPresenters::WikiPage.new(self) diff --git a/app/logical/related_tag_calculator.rb b/app/logical/related_tag_calculator.rb index 4e1543b94..a780aeb71 100644 --- a/app/logical/related_tag_calculator.rb +++ b/app/logical/related_tag_calculator.rb @@ -2,25 +2,25 @@ class RelatedTagCalculator def self.find_tags(tag, limit) Post.tag_match(tag).limit(limit).select("posts.tag_string").reorder("posts.md5").map(&:tag_string) end - + 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)) end - + def self.calculate_from_sample(tags, limit, category_constraint = nil) counts = Hash.new {|h, k| h[k] = 0} - + case category_constraint when Tag.categories.artist limit *= 4 - + when Tag.categories.copyright limit *= 3 - + when Tag.categories.character limit *= 2 end - + find_tags(tags, limit).each do |tags| tag_array = Tag.scan_tags(tags) if category_constraint @@ -36,14 +36,14 @@ class RelatedTagCalculator end end end - + counts end - + def self.convert_hash_to_array(hash) hash.to_a.sort_by {|x| -x[1]}.slice(0, 25) end - + def self.convert_hash_to_string(hash) convert_hash_to_array(hash).flatten.join(" ") end diff --git a/app/logical/related_tag_query.rb b/app/logical/related_tag_query.rb index dab1c273f..e2eb55007 100644 --- a/app/logical/related_tag_query.rb +++ b/app/logical/related_tag_query.rb @@ -1,6 +1,6 @@ class RelatedTagQuery attr_reader :query, :category - + def initialize(query, category) @query = query.strip @category = category @@ -17,7 +17,7 @@ class RelatedTagQuery [] end end - + def wiki_page_tags results = wiki_page.try(:tags) || [] results.reject! do |name| @@ -25,31 +25,31 @@ class RelatedTagQuery end results end - + 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 end - + protected - + def map_with_category_data(list_of_tag_names) Tag.categories_for(list_of_tag_names).to_a end - + 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) end - + def related_tags tag = Tag.named(query.strip).first - + if tag tag.related_tag_array.map(&:first) else [] end end - + def related_tags_by_category RelatedTagCalculator.calculate_from_sample_to_array(query, Tag.categories.value_for(category)).map(&:first) end diff --git a/app/logical/remote_file_manager.rb b/app/logical/remote_file_manager.rb index beb2c7af5..e80e0ce68 100644 --- a/app/logical/remote_file_manager.rb +++ b/app/logical/remote_file_manager.rb @@ -1,10 +1,10 @@ class RemoteFileManager attr_reader :path - + def initialize(path) @path = path end - + def distribute Danbooru.config.other_server_hosts.each do |hostname| Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp| @@ -12,7 +12,7 @@ class RemoteFileManager end end end - + def delete Danbooru.config.other_server_hosts.each do |hostname| Net::SFTP.start(hostname, Danbooru.config.remote_server_login) do |ftp| diff --git a/app/logical/session_creator.rb b/app/logical/session_creator.rb index d346ad31f..4230a6037 100644 --- a/app/logical/session_creator.rb +++ b/app/logical/session_creator.rb @@ -1,6 +1,6 @@ class SessionCreator attr_reader :session, :cookies, :name, :password, :remember - + def initialize(session, cookies, name, password, remember) @session = session @cookies = cookies @@ -8,17 +8,17 @@ class SessionCreator @password = password @remember = remember end - + def authenticate if User.authenticate(name, password) user = User.find_by_name(name) user.update_column(:last_logged_in_at, Time.now) - + if remember.present? cookies.permanent.signed[:user_name] = user.name cookies.permanent[:password_hash] = user.bcrypt_cookie_password_hash end - + session[:user_id] = user.id return true else diff --git a/app/logical/session_loader.rb b/app/logical/session_loader.rb index 1924e7dc8..e7c2ffa8c 100644 --- a/app/logical/session_loader.rb +++ b/app/logical/session_loader.rb @@ -1,55 +1,55 @@ class SessionLoader attr_reader :session, :cookies, :request - + def initialize(session, cookies, request) @session = session @cookies = cookies @request = request end - + def load if session[:user_id] load_session_user elsif cookie_password_hash_valid? load_cookie_user end - + if CurrentUser.user CurrentUser.user.unban! if ban_expired? else CurrentUser.user = AnonymousUser.new end - + update_last_logged_in_at set_time_zone end private - + def load_session_user CurrentUser.user = User.find_by_id(session[:user_id]) CurrentUser.ip_addr = request.remote_ip end - + def load_cookie_user CurrentUser.user = User.find_by_name(cookies.signed[:user_name]) CurrentUser.ip_addr = request.remote_ip end - + def ban_expired? CurrentUser.user.is_banned? && CurrentUser.user.ban && CurrentUser.user.ban.expired? end - + def cookie_password_hash_valid? cookies[:password_hash] && cookies.signed[:user_name] && User.authenticate_cookie_hash(cookies.signed[:user_name], cookies[:password_hash]) end - + def update_last_logged_in_at return if CurrentUser.is_anonymous? 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) end - + def set_time_zone Time.zone = CurrentUser.user.time_zone end diff --git a/app/logical/sources/site.rb b/app/logical/sources/site.rb index 4f8ff0776..4c14285d0 100644 --- a/app/logical/sources/site.rb +++ b/app/logical/sources/site.rb @@ -2,14 +2,14 @@ module Sources class Site attr_reader :url, :strategy delegate :get, :referer_url, :site_name, :artist_name, :profile_url, :image_url, :tags, :artist_record, :unique_id, :to => :strategy - + def self.strategies [Strategies::NicoSeiga, Strategies::Pixiv] end - + def initialize(url) @url = url - + Site.strategies.each do |strategy| if strategy.url_match?(url) @strategy = strategy.new(url) @@ -18,7 +18,7 @@ module Sources end end end - + def to_json return { :artist_name => artist_name, @@ -30,7 +30,7 @@ module Sources :unique_id => unique_id }.to_json end - + def available? strategy.present? end diff --git a/app/logical/sources/strategies/base.rb b/app/logical/sources/strategies/base.rb index cd73898ca..1df257e71 100644 --- a/app/logical/sources/strategies/base.rb +++ b/app/logical/sources/strategies/base.rb @@ -3,28 +3,28 @@ module Sources class Base attr_reader :url attr_reader :artist_name, :profile_url, :image_url, :tags - + def self.url_match?(url) false end - + def initialize(url) @url = url end - + # No remote calls are made until this method is called. def get raise NotImplementedError end - + def site_name raise NotImplementedError end - + def unique_id artist_name end - + def artist_record if artist_name.present? Artist.other_names_match(artist_name) @@ -32,11 +32,11 @@ module Sources nil end end - + def referer_url(template) template.params[:ref] || template.params[:url] end - + protected def agent raise NotImplementedError diff --git a/app/logical/sources/strategies/nico_seiga.rb b/app/logical/sources/strategies/nico_seiga.rb index e74c8e2a5..35f483559 100644 --- a/app/logical/sources/strategies/nico_seiga.rb +++ b/app/logical/sources/strategies/nico_seiga.rb @@ -8,7 +8,7 @@ module Sources def site_name "Nico Seiga" end - + def unique_id profile_url =~ /\/illust\/(\d+)/ "nicoseiga" + $1 @@ -21,9 +21,9 @@ module Sources @tags = get_tags_from_page(page) end end - + protected - + def get_profile_from_page(page) links = page.search("div.illust_user_name a") @@ -34,10 +34,10 @@ module Sources profile_url = nil artist_name = nil end - + return [artist_name, profile_url].compact end - + def get_image_url_from_page(page) links = page.search("a#illust_link") @@ -47,7 +47,7 @@ module Sources nil end end - + def get_tags_from_page(page) links = page.search("div#tag_block nobr a.tag") @@ -55,7 +55,7 @@ module Sources [node.text, "http://seiga.nicovideo.jp" + node.attr("href")] end end - + def agent @agent ||= begin mech = Mechanize.new diff --git a/app/logical/sources/strategies/pixiv.rb b/app/logical/sources/strategies/pixiv.rb index a7be61358..016e48ad6 100644 --- a/app/logical/sources/strategies/pixiv.rb +++ b/app/logical/sources/strategies/pixiv.rb @@ -4,7 +4,7 @@ module Sources def self.url_match?(url) url =~ /^https?:\/\/(?:\w+\.)?pixiv\.net/ end - + def referer_url(template) if template.params[:ref] =~ /pixiv\.net\/member_illust/ && template.params[:ref] !~ /mode=manga/ template.params[:ref] @@ -12,16 +12,16 @@ module Sources template.params[:url] end end - + def site_name "Pixiv" end - + def unique_id image_url =~ /\/img\/([^\/]+)/ $1 end - + def get agent.get(URI.parse(normalized_url).request_uri) do |page| @artist_name, @profile_url = get_profile_from_page(page) @@ -31,13 +31,13 @@ module Sources end protected - + def get_profile_from_page(page) profile_url = page.search("a.user-link").first if profile_url profile_url = "http://www.pixiv.net" + profile_url["href"] end - + artist_name = page.search("h1.user").first if artist_name artist_name = artist_name.inner_text @@ -45,7 +45,7 @@ module Sources return [artist_name, profile_url] end - + def get_image_url_from_page(page) element = page.search("div.works_display a img").first if element @@ -54,10 +54,10 @@ module Sources nil end end - + def get_tags_from_page(page) # puts page.root.to_xhtml - + links = page.search("ul.tags a.text").find_all do |node| node["href"] =~ /search\.php/ end @@ -70,7 +70,7 @@ module Sources [] end end - + def normalized_url @normalized_url ||= begin if url =~ /\/(\d+)(?:_big)?(?:_m|_p\d+)?\.(?:jpg|jpeg|png|gif)/i @@ -84,7 +84,7 @@ module Sources end end end - + def agent @agent ||= begin mech = Mechanize.new diff --git a/app/logical/tag_alias_correction.rb b/app/logical/tag_alias_correction.rb index f33b6b403..4afd1e39b 100644 --- a/app/logical/tag_alias_correction.rb +++ b/app/logical/tag_alias_correction.rb @@ -1,17 +1,17 @@ class TagAliasCorrection attr_reader :tag_alias_id, :tag_alias, :hostname delegate :antecedent_name, :consequent_name, :to => :tag_alias - + def initialize(tag_alias_id, hostname = Socket.gethostname) @tag_alias_id = tag_alias_id @tag_alias = TagAlias.find(tag_alias_id) @hostname = hostname end - + def to_json(options = {}) statistics_hash.to_json end - + def statistics_hash @statistics_hash ||= { "antecedent_cache" => Cache.get("ta:" + Cache.sanitize(tag_alias.antecedent_name)), @@ -20,7 +20,7 @@ class TagAliasCorrection "consequent_count" => Tag.find_by_name(tag_alias.consequent_name).try(:post_count) } end - + def fill_hash! Net::HTTP.start(hostname, 80) do |http| http.request_get("/tag_aliases/#{tag_alias_id}/correction.json") do |res| @@ -32,23 +32,23 @@ class TagAliasCorrection end end end - + def each_server Danbooru.config.all_server_hosts.each do |host| other = TagAliasCorrection.new(tag_alias_id, host) - + if host != Socket.gethostname other.fill_hash! end - + yield other end end - + def clear_cache tag_alias.clear_all_cache end - + def fix! clear_cache tag_alias.delay(:queue => "default").update_posts diff --git a/app/logical/tag_alias_request.rb b/app/logical/tag_alias_request.rb index 407901b82..b71a72efd 100644 --- a/app/logical/tag_alias_request.rb +++ b/app/logical/tag_alias_request.rb @@ -1,28 +1,28 @@ class TagAliasRequest class ValidationError < Exception ; end - + attr_reader :antecedent_name, :consequent_name, :reason, :tag_alias, :forum_topic - + def initialize(antecedent_name, consequent_name, reason) @antecedent_name = antecedent_name.tr(" ", "_") @consequent_name = consequent_name.tr(" ", "_") @reason = reason end - + def create TagAlias.transaction do create_alias create_forum_topic end end - + def create_alias @tag_alias = TagAlias.create(:antecedent_name => antecedent_name, :consequent_name => consequent_name, :status => "pending") if @tag_alias.errors.any? raise ValidationError.new(@tag_alias.errors.full_messages.join("; ")) end end - + def create_forum_topic @forum_topic = ForumTopic.create( :title => "Tag alias: #{antecedent_name} -> #{consequent_name}", @@ -33,7 +33,7 @@ class TagAliasRequest if @forum_topic.errors.any? raise ValidationError.new(@forum_topic.errors.full_messages.join("; ")) end - + tag_alias.update_attribute(:forum_topic_id, @forum_topic.id) end end diff --git a/app/logical/tag_correction.rb b/app/logical/tag_correction.rb index 834f625d6..8bd56fd09 100644 --- a/app/logical/tag_correction.rb +++ b/app/logical/tag_correction.rb @@ -1,23 +1,23 @@ class TagCorrection attr_reader :tag_id, :tag, :hostname - + def initialize(tag_id, hostname = Socket.gethostname) @tag_id = tag_id @tag = Tag.find(tag_id) @hostname = hostname end - + def to_json(options = {}) statistics_hash.to_json end - + def statistics_hash @statistics_hash ||= { "category_cache" => Cache.get("tc:" + Cache.sanitize(tag.name)), "post_fast_count_cache" => Cache.get("pfc:" + Cache.sanitize(tag.name)) } end - + def fill_hash! Net::HTTP.start(hostname, 80) do |http| http.request_get("/tags/#{tag_id}/correction.json") do |res| @@ -29,19 +29,19 @@ class TagCorrection end end end - + def each_server Danbooru.config.all_server_hosts.each do |host| other = TagCorrection.new(tag_id, host) - + if host != Socket.gethostname other.fill_hash! end - + yield other end end - + def fix! tag.delay(:queue => "default").fix_post_count Post.expire_cache_for_all([tag.name]) diff --git a/app/logical/tag_implication_request.rb b/app/logical/tag_implication_request.rb index 80754658f..f4a831746 100644 --- a/app/logical/tag_implication_request.rb +++ b/app/logical/tag_implication_request.rb @@ -1,28 +1,28 @@ class TagImplicationRequest class ValidationError < Exception ; end - + attr_reader :antecedent_name, :consequent_name, :reason, :tag_implication, :forum_topic - + def initialize(antecedent_name, consequent_name, reason) @antecedent_name = antecedent_name.tr(" ", "_") @consequent_name = consequent_name.tr(" ", "_") @reason = reason end - + def create TagImplication.transaction do create_implication create_forum_topic end end - + def create_implication @tag_implication = TagImplication.create(:antecedent_name => antecedent_name, :consequent_name => consequent_name, :status => "pending") if @tag_implication.errors.any? raise ValidationError.new(@tag_implication.errors.full_messages.join("; ")) end end - + def create_forum_topic @forum_topic = ForumTopic.create( :title => "Tag implication: #{antecedent_name} -> #{consequent_name}", @@ -33,7 +33,7 @@ class TagImplicationRequest if @forum_topic.errors.any? raise ValidationError.new(@forum_topic.errors.full_messages.join("; ")) end - + tag_implication.update_attribute(:forum_topic_id, @forum_topic.id) end end diff --git a/app/logical/uploaded_tags_importer.rb b/app/logical/uploaded_tags_importer.rb index 349d72db9..c9b99e9bb 100644 --- a/app/logical/uploaded_tags_importer.rb +++ b/app/logical/uploaded_tags_importer.rb @@ -1,10 +1,10 @@ class UploadedTagsImporter attr_reader :user - + def initialize(user) @user = user end - + def import! row = connection.exec("SELECT uploaded_tags FROM users WHERE id = #{user.id}").first if row @@ -13,7 +13,7 @@ class UploadedTagsImporter connection.close rescue Exception end - + def connection @connection ||= PGconn.connect(:dbname => "danbooru", :host => "dbserver", :user => "albert") end diff --git a/app/mailers/maintenance/user/password_reset_mailer.rb b/app/mailers/maintenance/user/password_reset_mailer.rb index 8ad1f6d0a..7910bacbd 100644 --- a/app/mailers/maintenance/user/password_reset_mailer.rb +++ b/app/mailers/maintenance/user/password_reset_mailer.rb @@ -6,7 +6,7 @@ module Maintenance @nonce = nonce mail(:to => @user.email, :subject => "#{Danbooru.config.app_name} password reset request", :from => Danbooru.config.contact_email) end - + def confirmation(user, new_password) @user = user @new_password = new_password diff --git a/app/mailers/user_mailer.rb b/app/mailers/user_mailer.rb index 69d15921a..7a9689b70 100644 --- a/app/mailers/user_mailer.rb +++ b/app/mailers/user_mailer.rb @@ -3,13 +3,13 @@ class UserMailer < ActionMailer::Base def dmail_notice(dmail) @dmail = dmail - mail(:to => "#{dmail.to.name} <#{dmail.to.email}>", :subject => "#{Danbooru.config.app_name} - Message received from #{dmail.from.name}") + mail(:to => "#{dmail.to.name} <#{dmail.to.email}>", :subject => "#{Danbooru.config.app_name} - Message received from #{dmail.from.name}") end - + def upgrade(user, email) mail(:to => "#{user.name} <#{email}>", :subject => "#{Danbooru.config.app_name} account upgrade") end - + def upgrade_fail(email) mail(:to => "#{user.name} <#{email}>", :subject => "#{Danbooru.config.app_name} account upgrade") end diff --git a/app/models/advertisement.rb b/app/models/advertisement.rb index 26a2bb095..598baf62c 100644 --- a/app/models/advertisement.rb +++ b/app/models/advertisement.rb @@ -7,7 +7,7 @@ class Advertisement < ActiveRecord::Base def copy_to_servers RemoteFileManager.new(image_path).distribute end - + def delete_from_servers RemoteFileManager.new(image_path).delete end @@ -19,15 +19,15 @@ class Advertisement < ActiveRecord::Base def hit_sum(start_date, end_date) hits.where(["created_at BETWEEN ? AND ?", start_date, end_date]).count end - + def unique_identifier @unique_identifier ||= ("%.0f" % (Time.now.to_f * 1_000)) end - + def image_url "/images/advertisements/ads-#{date_prefix}/#{file_name}" end - + def date_prefix created_at.try(:strftime, "%Y%m%d") end @@ -35,11 +35,11 @@ class Advertisement < ActiveRecord::Base def image_path "#{Danbooru.config.advertisement_path}/ads-#{date_prefix}/#{file_name}" end - + def file nil end - + def file=(f) if f.size > 0 self.file_name = unique_identifier + File.extname(f.original_filename) @@ -55,7 +55,7 @@ class Advertisement < ActiveRecord::Base image_size = ImageSize.new(File.open(image_path, "rb")) self.width = image_size.get_width self.height = image_size.get_height - + if width > height self.ad_type = "horizontal" else @@ -63,7 +63,7 @@ class Advertisement < ActiveRecord::Base end end end - + def preview_width if width > 100 || height > 100 if width < height @@ -72,9 +72,9 @@ class Advertisement < ActiveRecord::Base else return 100 end - end + end end - + def preview_height if width > 100 || height > 100 if height < width @@ -83,6 +83,6 @@ class Advertisement < ActiveRecord::Base else return 100 end - end + end end end diff --git a/app/models/advertisement_hit.rb b/app/models/advertisement_hit.rb index b20905e59..4d2c40c20 100644 --- a/app/models/advertisement_hit.rb +++ b/app/models/advertisement_hit.rb @@ -1,5 +1,5 @@ class AdvertisementHit < ActiveRecord::Base belongs_to :advertisement - + scope :between, lambda {|start_date, end_date| where("created_at BETWEEN ? AND ?", start_date, end_date)} end diff --git a/app/models/amazon_backup.rb b/app/models/amazon_backup.rb index 2c33383e4..bdcbf17d2 100644 --- a/app/models/amazon_backup.rb +++ b/app/models/amazon_backup.rb @@ -5,17 +5,17 @@ class AmazonBackup < ActiveRecord::Base def self.last_id first.last_id end - + def self.update_id(new_id) first.update_column(:last_id, new_id) end - + def self.execute last_id = AmazonBackup.last_id - + Post.where("id > ?", last_id).limit(200).order("id").each do |post| AWS::S3::Base.establish_connection!( - :access_key_id => Danbooru.config.amazon_s3_access_key_id, + :access_key_id => Danbooru.config.amazon_s3_access_key_id, :secret_access_key => Danbooru.config.amazon_s3_secret_access_key ) @@ -31,7 +31,7 @@ class AmazonBackup < ActiveRecord::Base if File.exists?(post.large_file_path) AWS::S3::S3Object.store("large/#{post.md5}.jpg", open(post.large_file_path, "rb"), Danbooru.config.amazon_s3_bucket_name) end - + AmazonBackup.update_id(last_id) end rescue Exception => x diff --git a/app/models/artist.rb b/app/models/artist.rb index 285e5baa5..145d02acc 100644 --- a/app/models/artist.rb +++ b/app/models/artist.rb @@ -13,10 +13,10 @@ class Artist < ActiveRecord::Base accepts_nested_attributes_for :wiki_page attr_accessible :body, :name, :url_string, :other_names, :other_names_comma, :group_name, :wiki_page_attributes, :notes, :is_active, :as => [:member, :privileged, :builder, :platinum, :contributor, :janitor, :moderator, :default, :admin] attr_accessible :is_banned, :as => :admin - + module UrlMethods extend ActiveSupport::Concern - + module ClassMethods def find_all_by_url(url) url = ArtistUrl.normalize(url) @@ -43,11 +43,11 @@ class Artist < ActiveRecord::Base end end end - + def url_string=(string) @url_string = string end - + def url_string @url_string || urls.map {|x| x.url}.join("\n") end @@ -55,7 +55,7 @@ class Artist < ActiveRecord::Base module NameMethods extend ActiveSupport::Concern - + module ClassMethods def normalize_name(name) name.to_s.downcase.strip.gsub(/ /, '_') @@ -65,26 +65,26 @@ class Artist < ActiveRecord::Base def normalize_name self.name = Artist.normalize_name(name) end - + def other_names_array other_names.try(:split, / /) end - + def other_names_comma other_names_array.try(:join, ", ") end - + def other_names_comma=(string) self.other_names = string.split(/,/).map {|x| Artist.normalize_name(x)}.join(" ") end end - + module GroupMethods def member_names members.map(&:name).join(", ") end end - + module VersionMethods def create_version ArtistVersion.create( @@ -98,14 +98,14 @@ class Artist < ActiveRecord::Base :group_name => group_name ) end - + def revert_to!(version) self.name = version.name self.url_string = version.url_string self.is_active = version.is_active self.other_names = version.other_names self.group_name = version.group_name - save + save end end @@ -119,11 +119,11 @@ class Artist < ActiveRecord::Base artist.url_string = post.source end end - + if params[:other_names] artist.other_names = params[:other_names] end - + if params[:urls] artist.url_string = params[:urls] end @@ -139,7 +139,7 @@ class Artist < ActiveRecord::Base nil end end - + def notes=(msg) if wiki_page wiki_page.title = name @@ -152,7 +152,7 @@ class Artist < ActiveRecord::Base end end end - + module TagMethods def has_tag_alias? TagAlias.exists?(["antecedent_name = ?", name]) @@ -162,7 +162,7 @@ class Artist < ActiveRecord::Base TagAlias.find_by_antecedent_name(name).consequent_name end end - + module BanMethods def ban! Post.transaction do @@ -178,24 +178,24 @@ class Artist < ActiveRecord::Base rescue Post::SearchError # swallow end - + # potential race condition but unlikely unless TagImplication.where(:antecedent_name => name, :consequent_name => "banned_artist").exists? tag_implication = TagImplication.create(:antecedent_name => name, :consequent_name => "banned_artist") tag_implication.delay(:queue => "default").process! end - + update_column(:is_active, false) update_column(:is_banned, true) end end end - + module SearchMethods def active where("is_active = true") end - + def banned where("is_banned = true") end @@ -209,27 +209,27 @@ class Artist < ActiveRecord::Base where("false") end end - + def other_names_match(string) where("other_names_index @@ to_tsquery('danbooru', E?)", Artist.normalize_name(string).to_escaped_for_tsquery) end - + def group_name_matches(name) stripped_name = normalize_name(name).to_escaped_for_sql_like where("group_name LIKE ? ESCAPE E'\\\\'", stripped_name) end - + def name_matches(name) stripped_name = normalize_name(name).to_escaped_for_sql_like where("name LIKE ? ESCAPE E'\\\\'", stripped_name) end - + def any_name_matches(name) stripped_name = normalize_name(name).to_escaped_for_sql_like name_for_tsquery = normalize_name(name).to_escaped_for_tsquery where("(name LIKE ? ESCAPE E'\\\\' OR other_names_index @@ to_tsquery('danbooru', E?))", stripped_name, name_for_tsquery) end - + def search(params) q = active params = {} if params.blank? @@ -240,7 +240,7 @@ class Artist < ActiveRecord::Base when /name:(.+)/ q = q.name_matches($1) - + when /other:(.+)/ q = q.other_names_match($1) @@ -253,7 +253,7 @@ class Artist < ActiveRecord::Base when /./ q = q.any_name_matches(params[:name]) end - + if params[:sort] == "Name" q = q.reorder("name") else @@ -263,11 +263,11 @@ class Artist < ActiveRecord::Base if params[:id].present? q = q.where("id = ?", params[:id]) end - + q end end - + include UrlMethods include NameMethods include GroupMethods @@ -277,7 +277,7 @@ class Artist < ActiveRecord::Base include TagMethods include BanMethods extend SearchMethods - + def status if is_banned? "Banned" @@ -287,11 +287,11 @@ class Artist < ActiveRecord::Base "Deleted" end end - + def legacy_api_hash return { - :id => id, - :name => name, + :id => id, + :name => name, :other_names => other_names, :group_name => group_name, :urls => artist_urls.map {|x| x.url}, @@ -299,7 +299,7 @@ class Artist < ActiveRecord::Base :updater_id => 0 } end - + def initialize_creator self.creator_id = CurrentUser.user.id end diff --git a/app/models/artist_url.rb b/app/models/artist_url.rb index 3c05a5d04..834b0921b 100644 --- a/app/models/artist_url.rb +++ b/app/models/artist_url.rb @@ -2,7 +2,7 @@ class ArtistUrl < ActiveRecord::Base before_save :normalize validates_presence_of :url belongs_to :artist - + def self.normalize(url) if url.nil? nil @@ -17,24 +17,24 @@ class ArtistUrl < ActiveRecord::Base url + "/" end end - + def self.normalize_for_search(url) if url =~ /\.\w+\Z/ && url =~ /\w\/\w/ url = File.dirname(url) end - + url = url.gsub(/^https:\/\//, "http://") url = url.gsub(/^http:\/\/blog\d+\.fc2/, "http://blog*.fc2") url = url.gsub(/^http:\/\/blog-imgs-\d+\.fc2/, "http://blog*.fc2") url = url.gsub(/^http:\/\/blog-imgs-\d+-\w+\.fc2/, "http://blog*.fc2") - url = url.gsub(/^http:\/\/img\d+\.pixiv\.net/, "http://img*.pixiv.net") + url = url.gsub(/^http:\/\/img\d+\.pixiv\.net/, "http://img*.pixiv.net") url = url.gsub(/^http:\/\/i\d+\.pixiv\.net\/img\d+/, "http://*.pixiv.net/img*") end def normalize self.normalized_url = self.class.normalize(url) end - + def to_s url end diff --git a/app/models/artist_version.rb b/app/models/artist_version.rb index c2b1feb0a..1e5b15a3c 100644 --- a/app/models/artist_version.rb +++ b/app/models/artist_version.rb @@ -1,32 +1,32 @@ class ArtistVersion < ActiveRecord::Base belongs_to :updater belongs_to :artist - + def self.search(params) q = scoped return q if params.blank? - + if params[:name] q = q.where("name like ? escape E'\\\\'", params[:name].to_escaped_for_sql_like) end - + if params[:artist_id] q = q.where("artist_id = ?", params[:artist_id].to_i) end - + if params[:sort] == "Name" q = q.reorder("name") else q = q.reorder("id desc") end - + q end - + def url_array url_string.scan(/\S+/) end - + def updater_name User.id_to_name(updater_id).tr("_", " ") end diff --git a/app/models/ban.rb b/app/models/ban.rb index 94edc8216..98d5a5231 100644 --- a/app/models/ban.rb +++ b/app/models/ban.rb @@ -6,42 +6,42 @@ class Ban < ActiveRecord::Base validate :user_is_inferior validates_presence_of :user_id, :reason, :duration before_validation :initialize_banner_id, :on => :create - + def self.is_banned?(user) exists?(["user_id = ? AND expires_at > ?", user.id, Time.now]) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:banner_name] q = q.where("banner_id = (select _.id from users _ where lower(_.name) = ?)", params[:banner_name].downcase) end - + if params[:banner_id] q = q.where("banner_id = ?", params[:banner_id].to_i) end - + if params[:user_name] q = q.where("user_id = (select _.id from users _ where lower(_.name) = ?)", params[:user_name].downcase) end - + if params[:user_id] q = q.where("user_id = ?", params[:user_id].to_i) end - + q end - + def initialize_banner_id self.banner_id = CurrentUser.id end - + def user_is_inferior if user if user.is_admin? - errors[:base] << "You can never ban an admin." + errors[:base] << "You can never ban an admin." false elsif user.is_moderator? && banner.is_admin? true @@ -56,7 +56,7 @@ class Ban < ActiveRecord::Base end end end - + def update_feedback if user feedback = user.feedback.build @@ -66,24 +66,24 @@ class Ban < ActiveRecord::Base feedback.save end end - + def user_name user ? user.name : nil end - + def user_name=(username) self.user_id = User.name_to_id(username) end - + def duration=(dur) self.expires_at = dur.to_i.days.from_now @duration = dur end - + def duration @duration end - + def expired? expires_at < Time.now end diff --git a/app/models/comment.rb b/app/models/comment.rb index 485a0a56e..eb10fab60 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -10,62 +10,62 @@ class Comment < ActiveRecord::Base after_destroy :update_last_commented_at attr_accessible :body, :post_id, :do_not_bump_post attr_accessor :do_not_bump_post - + module SearchMethods def recent reorder("comments.id desc").limit(6) end - + def body_matches(query) where("body_index @@ plainto_tsquery(?)", query.to_escaped_for_tsquery_split).order("comments.id DESC") end - + def hidden(user) where("score < ?", user.comment_threshold) end - + def visible(user) where("score >= ?", user.comment_threshold) end - + def post_tags_match(query) joins(:post).where("posts.tag_index @@ to_tsquery('danbooru', ?)", query.to_escaped_for_tsquery_split) end - + def for_creator(user_id) where("creator_id = ?", user_id) end - + def for_creator_name(user_name) where("creator_id = (select _.id from users _ where lower(_.name) = lower(?))", user_name.downcase) end - + def search(params) q = scoped return q if params.blank? - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end - + if params[:post_tags_match].present? q = q.post_tags_match(params[:post_tags_match]) end - + if params[:creator_name].present? q = q.for_creator_name(params[:creator_name]) end - + if params[:creator_id].present? q = q.for_creator(params[:creator_id].to_i) end - + q end end - + extend SearchMethods - + def initialize_creator self.creator_id = CurrentUser.user.id self.ip_addr = CurrentUser.ip_addr @@ -79,7 +79,7 @@ class Comment < ActiveRecord::Base def creator_name User.id_to_name(creator_id) end - + def updater_name User.id_to_name(updater_id) end @@ -100,15 +100,15 @@ class Comment < ActiveRecord::Base Post.update_all(["last_commented_at = ?", created_at], ["id = ?", post_id]) end end - + def do_not_bump_post? do_not_bump_post == "1" end - + def vote!(val) numerical_score = val == "up" ? 1 : -1 vote = votes.create(:score => numerical_score) - + if vote.errors.empty? if vote.is_positive? update_column(:score, score + 1) @@ -119,7 +119,7 @@ class Comment < ActiveRecord::Base return vote end - + def editable_by?(user) creator_id == user.id || user.is_janitor? end diff --git a/app/models/comment_vote.rb b/app/models/comment_vote.rb index a4c3831c2..728da2b0a 100644 --- a/app/models/comment_vote.rb +++ b/app/models/comment_vote.rb @@ -9,22 +9,22 @@ class CommentVote < ActiveRecord::Base validate :validate_user_can_vote validate :validate_comment_can_be_down_voted validates_inclusion_of :score, :in => [-1, 1], :message => "must be 1 or -1" - + def self.prune! destroy_all("created_at < ?", 14.days.ago) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:comment_id] q = q.where("comment_id = ?", params[:comment_id].to_i) end - + q end - + def validate_user_can_vote if !user.can_comment_vote? errors.add :base, "You cannot vote on comments" @@ -33,24 +33,24 @@ class CommentVote < ActiveRecord::Base true end end - + def validate_comment_can_be_down_voted - if is_negative? && comment.creator.is_janitor? + if is_negative? && comment.creator.is_janitor? errors.add :base, "You cannot downvote a janitor comment" false else true end end - + def is_positive? score == 1 end - + def is_negative? score == -1 end - + def initialize_user self.user_id = CurrentUser.user.id end diff --git a/app/models/dmail.rb b/app/models/dmail.rb index 0f4c4a995..2889a45d8 100644 --- a/app/models/dmail.rb +++ b/app/models/dmail.rb @@ -11,7 +11,7 @@ class Dmail < ActiveRecord::Base after_create :update_recipient after_create :send_dmail attr_accessible :title, :body, :is_deleted, :to_id, :to, :to_name - + module AddressMethods def to_name User.id_to_pretty_name(to_id) @@ -26,19 +26,19 @@ class Dmail < ActiveRecord::Base return if user.nil? self.to_id = user.id end - + def initialize_from_id self.from_id = CurrentUser.id end end - + module FactoryMethods extend ActiveSupport::Concern - + module ClassMethods def create_split(params) copy = nil - + Dmail.transaction do copy = Dmail.new(params) copy.owner_id = copy.to_id @@ -51,17 +51,17 @@ class Dmail < ActiveRecord::Base copy.is_read = true copy.save end - + copy end - + def new_blank Dmail.new do |dmail| dmail.from_id = CurrentUser.id end end end - + def build_response(options = {}) Dmail.new do |dmail| if title =~ /Re:/ @@ -76,84 +76,84 @@ class Dmail < ActiveRecord::Base end end end - + module SearchMethods def for(user) where("owner_id = ?", user) end - + def inbox where("to_id = owner_id") end - + def sent where("from_id = owner_id") end - + def active where("is_deleted = ?", false) end - + def deleted where("is_deleted = ?", true) end - + def search_message(query) where("message_index @@ plainto_tsquery(?)", query.to_escaped_for_tsquery_split) end - + def unread where("is_read = false and is_deleted = false") end - + def visible where("owner_id = ?", CurrentUser.id) end - + def to_name_matches(name) where("to_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def from_name_matches(name) where("from_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def search(params) q = scoped return q if params.blank? - + if params[:message_matches].present? q = q.search_message(params[:message_matches]) end - + if params[:owner_id].present? q = q.for(params[:owner_id].to_i) end - + if params[:to_name].present? q = q.to_name_matches(params[:to_name]) end - + if params[:to_id].present? q = q.where("to_id = ?", params[:to_id].to_i) end - + if params[:from_name].present? q = q.from_name_matches(params[:from_name]) end - + if params[:from_id].present? q = q.where("from_id = ?", params[:from_id].to_i) end - + q end end - + include AddressMethods include FactoryMethods extend SearchMethods - + def validate_sender_is_not_banned if from.is_banned? errors[:base] = "Sender is banned and cannot send messages" @@ -162,29 +162,29 @@ class Dmail < ActiveRecord::Base return true end end - + def quoted_body "[quote]#{body}[/quote]" end - + def send_dmail if to.receive_email_notifications? && to.email.include?("@") && owner_id == CurrentUser.id UserMailer.dmail_notice(self).deliver - end + end end - + def mark_as_read! update_column(:is_read, true) - + unless Dmail.exists?(["to_id = ? AND is_read = false", to_id]) to.update_column(:has_mail, false) end end - + def update_recipient to.update_column(:has_mail, true) end - + def visible_to?(user) user.is_moderator? || owner_id == user.id end diff --git a/app/models/favorite.rb b/app/models/favorite.rb index 24a2ba940..9f81edba5 100644 --- a/app/models/favorite.rb +++ b/app/models/favorite.rb @@ -1,7 +1,7 @@ class Favorite < ActiveRecord::Base belongs_to :post scope :for_user, lambda {|user_id| where("user_id % 100 = #{user_id.to_i % 100} and user_id = #{user_id.to_i}")} - + # this is necessary because there's no trigger for deleting favorites def self.destroy_all(hash) connection.execute("delete from favorites_#{hash[:user_id] % 100} where user_id = #{hash[:user_id]} and post_id = #{hash[:post_id]}") diff --git a/app/models/forum_post.rb b/app/models/forum_post.rb index 4ce71fb67..c0fec63b1 100644 --- a/app/models/forum_post.rb +++ b/app/models/forum_post.rb @@ -11,54 +11,54 @@ class ForumPost < ActiveRecord::Base validate :validate_topic_is_unlocked before_destroy :validate_topic_is_unlocked after_save :delete_topic_if_original_post - + module SearchMethods def body_matches(body) where("forum_posts.text_index @@ plainto_tsquery(E?)", body.to_escaped_for_tsquery) end - + def for_user(user_id) where("forum_posts.creator_id = ?", user_id) end - + def creator_name(name) where("forum_posts.creator_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def active where("forum_posts.is_deleted = false") end - + def search(params) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:topic_id].present? q = q.where("topic_id = ?", params[:topic_id].to_i) end - + if params[:topic_title_matches].present? q = q.joins(:topic).where("forum_topics.text_index @@ plainto_tsquery(E?)", params[:topic_title_matches].to_escaped_for_tsquery_split) end - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end - + if params[:creator_name].present? q = q.creator_name(params[:creator_name]) end - + q end end - + extend SearchMethods - + def self.new_reply(params) if params[:topic_id] new(:topic_id => params[:topic_id]) @@ -69,13 +69,13 @@ class ForumPost < ActiveRecord::Base new end end - + def validate_topic_is_unlocked return if CurrentUser.is_moderator? return if topic.nil? - + if topic.is_locked? - errors.add(:topic, "is locked") + errors.add(:topic, "is locked") return false else return true @@ -85,7 +85,7 @@ class ForumPost < ActiveRecord::Base def editable_by?(user) creator_id == user.id || user.is_janitor? end - + def update_topic_updated_at if topic topic.updater_id = CurrentUser.id @@ -93,19 +93,19 @@ class ForumPost < ActiveRecord::Base topic.save end end - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id end - + def initialize_is_deleted self.is_deleted = false if is_deleted.nil? end - + def creator_name User.id_to_name(creator_id) end @@ -113,28 +113,28 @@ class ForumPost < ActiveRecord::Base def updater_name User.id_to_name(updater_id) end - + def quoted_response stripped_body = body.gsub(/\[quote\](?:.|\n|\r)+?\[\/quote\][\n\r]*/m, "") "[quote]\n#{creator_name} said:\n\n#{stripped_body}\n[/quote]\n\n" end - + def forum_topic_page ((ForumPost.where("topic_id = ? and created_at <= ?", topic_id, created_at).count) / Danbooru.config.posts_per_page.to_f).ceil end - + def is_original_post? ForumPost.exists?(["id = ? and id = (select _.id from forum_posts _ where _.topic_id = ? order by _.id asc limit 1)", id, topic_id]) end - + def delete_topic_if_original_post if is_deleted? && is_original_post? topic.update_attribute(:is_deleted, true) end - + true end - + def build_response dup.tap do |x| x.body = x.quoted_response diff --git a/app/models/forum_topic.rb b/app/models/forum_topic.rb index 975e81054..c78e0b4e8 100644 --- a/app/models/forum_topic.rb +++ b/app/models/forum_topic.rb @@ -11,34 +11,34 @@ class ForumTopic < ActiveRecord::Base validates_presence_of :title, :creator_id validates_associated :original_post accepts_nested_attributes_for :original_post - + module SearchMethods def title_matches(title) where("text_index @@ plainto_tsquery(E?)", title.to_escaped_for_tsquery_split) end - + def active where("is_deleted = false") end - + def search(params) q = scoped return q if params.blank? - + if params[:title_matches].present? q = q.title_matches(params[:title_matches]) end - + if params[:title].present? q = q.where("title = ?", params[:title]) end - + q end end - + extend SearchMethods - + def editable_by?(user) creator_id == user.id || user.is_janitor? end @@ -50,15 +50,15 @@ class ForumTopic < ActiveRecord::Base def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id end - + def last_page (posts.count / Danbooru.config.posts_per_page.to_f).ceil end - + def presenter(forum_posts) @presenter ||= ForumTopicPresenter.new(self, forum_posts) end diff --git a/app/models/ip_ban.rb b/app/models/ip_ban.rb index a6921c5e6..e5e6e089c 100644 --- a/app/models/ip_ban.rb +++ b/app/models/ip_ban.rb @@ -5,19 +5,19 @@ class IpBan < ActiveRecord::Base validates_presence_of :reason, :creator, :ip_addr validates_format_of :ip_addr, :with => IP_ADDR_REGEX validates_uniqueness_of :ip_addr, :if => lambda {|rec| rec.ip_addr =~ IP_ADDR_REGEX} - + def self.is_banned?(ip_addr) exists?(["ip_addr = ?", ip_addr]) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:ip_addr].present? q = q.where("ip_addr = ?", params[:ip_addr]) end - + q end @@ -26,7 +26,7 @@ class IpBan < ActiveRecord::Base notes = count_by_ip_addr("note_versions", user_ids, "updater_id", "updater_ip_addr") pools = count_by_ip_addr("pool_versions", user_ids, "updater_id", "updater_ip_addr") wiki_pages = count_by_ip_addr("wiki_page_versions", user_ids, "updater_id", "updater_ip_addr") - + return { "comments" => comments, "notes" => notes, @@ -34,11 +34,11 @@ class IpBan < ActiveRecord::Base "wiki_pages" => wiki_pages } end - + def self.count_by_ip_addr(table, user_ids, user_id_field = "user_id", ip_addr_field = "ip_addr") select_all_sql("SELECT #{ip_addr_field}, count(*) FROM #{table} WHERE #{user_id_field} IN (?) GROUP BY #{ip_addr_field} ORDER BY count(*) DESC", user_ids) end - + def initialize_creator self.creator_id = CurrentUser.id end diff --git a/app/models/janitor_trial.rb b/app/models/janitor_trial.rb index 4039094a7..cd16c8a31 100644 --- a/app/models/janitor_trial.rb +++ b/app/models/janitor_trial.rb @@ -6,59 +6,59 @@ class JanitorTrial < ActiveRecord::Base after_destroy :create_feedback validates_presence_of :user before_validation :initialize_creator - + def self.search(params) q = scoped return q if params.blank? - + if params[:user_name] q = q.where("user_id = (select _.id from users _ where lower(_.name) = ?)", params[:user_name].downcase) end - + if params[:user_id] q = q.where("user_id = ?", params[:user_id].to_i) end - + q end - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_original_level self.original_level = user.level end - + def user_name user.try(:name) end - + def user_name=(name) self.user_id = User.name_to_id(name) end - + def send_dmail body = "You have been selected as a test janitor. You can now approve pending posts and have access to the moderation interface.\n\nOver the next several weeks your approvals will be monitored. If the majority of them are quality uploads, then you will be promoted to full janitor status which grants you the ability to delete and undelete posts, ban users, and revert tag changes from vandals. If you fail the trial period, you will be demoted back to your original level and you'll receive a negative user record indicating you previously attempted and failed a test janitor trial.\n\nThere is a minimum quota of 5 approvals a week to indicate that you are being active. Remember, the goal isn't to approve as much as possible. It's to filter out borderline-quality art.\n\nIf you have any questions please respond to this message." - + Dmail.create_split(:title => "Test Janitor Trial Period", :body => body, :to_id => user_id) end - + def promote_user user.update_column(:level, User::Levels::JANITOR) end - + def create_feedback user.feedback.create( :category => "negative", :body => "Demoted from janitor trial" ) end - + def promote! destroy end - + def demote! user.update_column(:level, original_level) destroy diff --git a/app/models/mod_action.rb b/app/models/mod_action.rb index 97013ef2f..d8459096a 100644 --- a/app/models/mod_action.rb +++ b/app/models/mod_action.rb @@ -1,18 +1,18 @@ class ModAction < ActiveRecord::Base belongs_to :creator, :class_name => "User" before_validation :initialize_creator, :on => :create - + def self.search(params = {}) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + q end - + def initialize_creator self.creator_id = CurrentUser.id end diff --git a/app/models/news_update.rb b/app/models/news_update.rb index 9b844767d..5fa37bbc0 100644 --- a/app/models/news_update.rb +++ b/app/models/news_update.rb @@ -4,11 +4,11 @@ class NewsUpdate < ActiveRecord::Base scope :recent, order("created_at desc").limit(5) before_validation :initialize_creator, :on => :create before_validation :initialize_updater - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id end diff --git a/app/models/note.rb b/app/models/note.rb index d61865e9a..ec36dde35 100644 --- a/app/models/note.rb +++ b/app/models/note.rb @@ -12,28 +12,28 @@ class Note < ActiveRecord::Base after_save :create_version validate :post_must_not_be_note_locked attr_accessible :x, :y, :width, :height, :body, :updater_id, :updater_ip_addr, :is_active, :post_id, :html_id - + module SearchMethods def active where("is_active = TRUE") end - + def body_matches(query) where("body_index @@ plainto_tsquery(E?)", query.to_escaped_for_tsquery_split) end - + def post_tags_match(query) joins(:post).where("posts.tag_index @@ to_tsquery('danbooru', E?)", query.to_escaped_for_tsquery_split) end - + def creator_name(name) where("creator_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def search(params) q = scoped return q if params.blank? - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end @@ -41,23 +41,23 @@ class Note < ActiveRecord::Base if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + if params[:post_tags_match].present? q = q.post_tags_match(params[:post_tags_match]) end - + if params[:creator_name].present? q = q.creator_name(params[:creator_name]) end - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + q end end - + module ApiMethods def serializable_hash(options = {}) options ||= {} @@ -70,7 +70,7 @@ class Note < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -78,34 +78,34 @@ class Note < ActiveRecord::Base super(options, &block) end end - + extend SearchMethods include ApiMethods - + def presenter @presenter ||= NotePresenter.new(self) end - + def initialize_creator self.creator_id = CurrentUser.id end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def post_must_not_be_note_locked if is_locked? errors.add :post, "is note locked" return false end end - + def is_locked? Post.exists?(["id = ? AND is_note_locked = ?", post_id, true]) end - + def blank_body self.body = "(empty)" if body.blank? end @@ -121,10 +121,10 @@ class Note < ActiveRecord::Base execute_sql("UPDATE posts SET last_noted_at = NULL WHERE id = ?", post_id) end end - + def create_version CurrentUser.increment!(:note_update_count) - + versions.create( :updater_id => updater_id, :updater_ip_addr => updater_ip_addr, @@ -137,7 +137,7 @@ class Note < ActiveRecord::Base :body => body ) end - + def revert_to(version) self.x = version.x self.y = version.y @@ -149,7 +149,7 @@ class Note < ActiveRecord::Base self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def revert_to!(version) revert_to(version) save! diff --git a/app/models/note_version.rb b/app/models/note_version.rb index 012bfa731..f88b20324 100644 --- a/app/models/note_version.rb +++ b/app/models/note_version.rb @@ -6,22 +6,22 @@ class NoteVersion < ActiveRecord::Base def self.search(params) q = scoped params = {} if params.blank? - + if params[:updater_id] q = q.where("updater_id = ?", params[:updater_id].to_i) end - + if params[:post_id] q = q.where("post_id = ?", params[:post_id].to_i) end - + if params[:note_id] q = q.where("note_id = ?", params[:note_id].to_i) end - + q end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr diff --git a/app/models/pool.rb b/app/models/pool.rb index dbcce217b..0770332c6 100644 --- a/app/models/pool.rb +++ b/app/models/pool.rb @@ -19,41 +19,41 @@ class Pool < ActiveRecord::Base def active where("is_deleted = false") end - + def search(params) q = scoped params = {} if params.blank? - + if params[:name_matches].present? params[:name_matches] = params[:name_matches].tr(" ", "_") params[:name_matches] = "*#{params[:name_matches]}*" unless params[:name_matches] =~ /\*/ q = q.where("name ilike ? escape E'\\\\'", params[:name_matches].to_escaped_for_sql_like) end - + if params[:description_matches].present? q = q.where("description like ? escape E'\\\\'", "%" + params[:description_matches].to_escaped_for_sql_like + "%") end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:sort] == "name" q = q.order("name") else q = q.order("updated_at desc") end - + q end end - + extend SearchMethods - + def self.name_to_id(name) if name =~ /^\d+$/ name.to_i @@ -61,15 +61,15 @@ class Pool < ActiveRecord::Base select_value_sql("SELECT id FROM pools WHERE lower(name) = ?", name.downcase.tr(" ", "_")).to_i end end - + def self.id_to_name(id) select_value_sql("SELECT name FROM pools WHERE id = ?", id) end - + def self.options select_all_sql("SELECT id, name FROM pools WHERE is_active = true AND is_deleted = false ORDER BY name LIMIT 100").map {|x| [x["name"].tr("_", " "), x["id"]]} end - + def self.create_anonymous Pool.new do |pool| pool.name = "TEMP:#{Time.now.to_f}.#{rand(1_000_000)}" @@ -78,15 +78,15 @@ class Pool < ActiveRecord::Base pool.save end end - + def self.normalize_name(name) name.gsub(/\s+/, "_") end - + def self.normalize_post_ids(post_ids) post_ids.scan(/\d+/).join(" ") end - + def self.find_by_name(name) if name =~ /^\d+$/ where("id = ?", name.to_i).first @@ -96,32 +96,32 @@ class Pool < ActiveRecord::Base nil end end - + def initialize_is_active self.is_deleted = false if is_deleted.nil? self.is_active = true if is_active.nil? end - + def initialize_creator self.creator_id = CurrentUser.id end - + def normalize_name self.name = Pool.normalize_name(name) end - + def pretty_name name.tr("_", " ") end - + def creator_name User.id_to_name(creator_id) end - + def normalize_post_ids self.post_ids = self.class.normalize_post_ids(post_ids) end - + def revert_to!(version) self.post_ids = version.post_ids synchronize! @@ -130,39 +130,39 @@ class Pool < ActiveRecord::Base def contains?(post_id) post_ids =~ /(?:\A| )#{post_id}(?:\Z| )/ end - + def deletable_by?(user) user.is_janitor? end - + def create_mod_action_for_destroy ModAction.create(:description => "deleted pool ##{id} name=#{name} post_ids=#{post_ids}") end - + def add!(post) return if contains?(post.id) - + update_attributes(:post_ids => add_number_to_string(post.id, post_ids), :post_count => post_count + 1) post.add_pool!(self) clear_post_id_array end - + def remove!(post) return unless contains?(post.id) - + update_attributes(:post_ids => remove_number_from_string(post.id, post_ids), :post_count => post_count - 1) post.remove_pool!(self) clear_post_id_array end - + def add_number_to_string(number, string) "#{string} #{number}" end - + def remove_number_from_string(number, string) string.gsub(/(?:\A| )#{number}(?:\Z| )/, " ") end - + def posts(options = {}) offset = options[:offset] || 0 limit = options[:limit] || Danbooru.config.posts_per_page @@ -173,47 +173,47 @@ class Pool < ActiveRecord::Base Post.where("false") end end - + def synchronize! added = post_id_array - post_id_array_was removed = post_id_array_was - post_id_array - + added.each do |post_id| post = Post.find(post_id) post.add_pool!(self) end - + removed.each do |post_id| post = Post.find(post_id) post.remove_pool!(self) end - + self.post_count = post_id_array.size save end - + def post_id_array @post_id_array ||= post_ids.scan(/\d+/).map(&:to_i) end - + def post_id_array=(array) self.post_ids = array.join(" ") clear_post_id_array end - + def post_id_array_was @post_id_array_was ||= post_ids_was.scan(/\d+/).map(&:to_i) end - + def clear_post_id_array @post_id_array = nil @post_id_array_was = nil end - + def neighbors(post) @neighbor_posts ||= begin post_ids =~ /\A#{post.id} (\d+)|(\d+) #{post.id} (\d+)|(\d+) #{post.id}\Z/ - + if $2 && $3 OpenStruct.new(:previous => $2.to_i, :next => $3.to_i) elsif $1 @@ -225,7 +225,7 @@ class Pool < ActiveRecord::Base end end end - + def create_version last_version = versions.last @@ -235,20 +235,20 @@ class Pool < ActiveRecord::Base versions.create(:post_ids => post_ids) end end - + def reload(options = {}) super @neighbor_posts = nil clear_post_id_array end - + def to_xml(options = {}, &block) # to_xml ignores the serializable_hash method options ||= {} options[:methods] = [:creator_name] super(options, &block) end - + def serializable_hash(options = {}) return { "created_at" => created_at, diff --git a/app/models/pool_version.rb b/app/models/pool_version.rb index 5534803e8..04a419fa7 100644 --- a/app/models/pool_version.rb +++ b/app/models/pool_version.rb @@ -1,6 +1,6 @@ class PoolVersion < ActiveRecord::Base class Error < Exception ; end - + validates_presence_of :updater_id, :updater_ip_addr belongs_to :pool belongs_to :updater, :class_name => "User" @@ -10,38 +10,38 @@ class PoolVersion < ActiveRecord::Base def for_user(user_id) where("updater_id = ?", user_id) end - + def search(params) q = scoped return q if params.blank? - + if params[:updater_id].present? q = q.for_user(params[:updater_id].to_i) end - + if params[:updater_name].present? q = q.where("updater_id = (select _.id from users _ where lower(_.name) = ?)", params[:updater_name].downcase) end - + if params[:pool_id].present? q = q.where("pool_id = ?", params[:pool_id].to_i) end - + q end end - + extend SearchMethods - + def updater_name User.id_to_name(updater_id) end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def post_id_array @post_id_array ||= post_ids.scan(/\d+/).map(&:to_i) end diff --git a/app/models/post.rb b/app/models/post.rb index bff6fec83..d7f209976 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -2,7 +2,7 @@ class Post < ActiveRecord::Base class ApprovalError < Exception ; end class DisapprovalError < Exception ; end class SearchError < Exception ; end - + attr_accessor :old_tag_string, :old_parent_id, :has_constraints after_destroy :delete_files after_destroy :delete_remote_files @@ -34,7 +34,7 @@ class Post < ActiveRecord::Base attr_accessible :source, :rating, :tag_string, :old_tag_string, :last_noted_at, :parent_id, :as => [:member, :builder, :privileged, :platinum, :contributor, :janitor, :moderator, :admin, :default] attr_accessible :is_rating_locked, :is_note_locked, :as => [:builder, :contributor, :janitor, :moderator, :admin] attr_accessible :is_status_locked, :as => [:admin] - + module FileMethods def distribute_files RemoteFileManager.new(file_path).distribute @@ -42,14 +42,14 @@ class Post < ActiveRecord::Base RemoteFileManager.new(ssd_preview_file_path).distribute if Danbooru.config.ssd_path RemoteFileManager.new(large_file_path).distribute if has_large? end - + def delete_remote_files RemoteFileManager.new(file_path).delete RemoteFileManager.new(real_preview_file_path).delete RemoteFileManager.new(ssd_preview_file_path).delete if Danbooru.config.ssd_path RemoteFileManager.new(large_file_path).delete if has_large? end - + def delete_files FileUtils.rm_f(file_path) FileUtils.rm_f(large_file_path) @@ -60,11 +60,11 @@ class Post < ActiveRecord::Base def file_path_prefix Rails.env == "test" ? "test." : "" end - + def file_path "#{Rails.root}/public/data/#{file_path_prefix}#{md5}.#{file_ext}" end - + def large_file_path if has_large? "#{Rails.root}/public/data/sample/#{file_path_prefix}#{Danbooru.config.large_image_prefix}#{md5}.jpg" @@ -72,11 +72,11 @@ class Post < ActiveRecord::Base file_path end end - + def real_preview_file_path "#{Rails.root}/public/data/preview/#{file_path_prefix}#{md5}.jpg" end - + def ssd_preview_file_path "#{Danbooru.config.ssd_path}/public/data/preview/#{file_path_prefix}#{md5}.jpg" end @@ -92,7 +92,7 @@ class Post < ActiveRecord::Base def file_url "/data/#{file_path_prefix}#{md5}.#{file_ext}" end - + def large_file_url if has_large? "/data/sample/#{file_path_prefix}#{Danbooru.config.large_image_prefix}#{md5}.jpg" @@ -105,14 +105,14 @@ class Post < ActiveRecord::Base if !is_image? return "/images/download-preview.png" end - + if Danbooru.config.ssd_path "/ssd/data/preview/#{file_path_prefix}#{md5}.jpg" else "/data/preview/#{file_path_prefix}#{md5}.jpg" end end - + def file_url_for(user) case user.default_image_size when "large" @@ -121,12 +121,12 @@ class Post < ActiveRecord::Base else file_url end - + else file_url end end - + def file_path_for(user) case user.default_image_size when "large" @@ -135,34 +135,34 @@ class Post < ActiveRecord::Base else file_path end - + else file_path end end - + def is_image? file_ext =~ /jpg|jpeg|gif|png/ end - + def is_flash? file_ext =~ /swf/ end end - + module ImageMethods def has_large? image_width.present? && image_width > Danbooru.config.large_image_width end - + def has_large has_large? end - + def large_image_width [Danbooru.config.large_image_width, image_width].min end - + def large_image_height ratio = Danbooru.config.large_image_width.to_f / image_width.to_f if ratio < 1 @@ -171,58 +171,58 @@ class Post < ActiveRecord::Base image_height end end - + def image_width_for(user) case user.default_image_size when "large" large_image_width - + else image_width end end - + def image_height_for(user) case user.default_image_size when "large" large_image_height - + else image_height end end - + def resize_percentage 100 * large_image_width.to_f / image_width.to_f end end - + module ApprovalMethods def is_approvable? !is_status_locked? && (is_pending? || is_flagged? || is_deleted?) && approver_id != CurrentUser.id end - + def flag!(reason) if is_status_locked? raise PostFlag::Error.new("Post is locked and cannot be flagged") end - + flag = flags.create(:reason => reason, :is_resolved => false) - + if flag.errors.any? raise PostFlag::Error.new(flag.errors.full_messages.join("; ")) end update_column(:is_flagged, true) unless is_flagged? end - + def appeal!(reason) if is_status_locked? raise PostAppeal::Error.new("Post is locked and cannot be appealed") end - + appeal = appeals.create(:reason => reason) - + if appeal.errors.any? raise PostAppeal::Error.new(appeal.errors.full_messages.join("; ")) end @@ -233,17 +233,17 @@ class Post < ActiveRecord::Base errors.add(:is_status_locked, "; post cannot be approved") raise ApprovalError.new("Post is locked and cannot be approved") end - + if uploader_id == CurrentUser.id errors.add(:base, "You cannot approve a post you uploaded") raise ApprovalError.new("You cannot approve a post you uploaded") end - + if approver_id == CurrentUser.id errors.add(:approver, "have already approved this post") - raise ApprovalError.new("You have previously approved this post and cannot approve it again") + raise ApprovalError.new("You have previously approved this post and cannot approve it again") end - + flags.each {|x| x.resolve!} self.is_flagged = false self.is_pending = false @@ -252,12 +252,12 @@ class Post < ActiveRecord::Base save! # ModAction.create(:description => "approved post ##{id}") end - + def disapproved_by?(user) PostDisapproval.where(:user_id => user.id, :post_id => id).exists? end end - + module PresenterMethods def presenter @presenter ||= PostPresenter.new(self) @@ -267,15 +267,15 @@ class Post < ActiveRecord::Base case rating when "q" "Questionable" - + when "e" "Explicit" - + when "s" "Safe" end end - + def normalized_source if source =~ /pixiv\.net\/img/ img_id = source[/(\d+)(_s|_m|(_big)?_p\d+)?\.[\w\?]+\s*$/, 1] @@ -290,28 +290,28 @@ class Post < ActiveRecord::Base end end end - + module TagMethods def tag_array @tag_array ||= Tag.scan_tags(tag_string) end - + def tag_array_was @tag_array_was ||= Tag.scan_tags(tag_string_was) end - + def create_tags set_tag_string(tag_array.map {|x| Tag.find_or_create_by_name(x).name}.uniq.sort.join(" ")) end - + def increment_tag_post_counts execute_sql("UPDATE tags SET post_count = post_count + 1 WHERE name IN (?)", tag_array) if tag_array.any? end - + def decrement_tag_post_counts execute_sql("UPDATE tags SET post_count = post_count - 1 WHERE name IN (?)", tag_array) if tag_array.any? end - + def update_tag_post_counts decrement_tags = tag_array_was - tag_array increment_tags = tag_array - tag_array_was @@ -321,55 +321,55 @@ class Post < ActiveRecord::Base Post.expire_cache_for_all(increment_tags) Post.expire_cache_for_all([""]) if new_record? || id <= 100_000 end - + def set_tag_counts self.tag_count = 0 self.tag_count_general = 0 self.tag_count_artist = 0 self.tag_count_copyright = 0 self.tag_count_character = 0 - + categories = Tag.categories_for(tag_array) categories.each_value do |category| self.tag_count += 1 - + case category when Tag.categories.general self.tag_count_general += 1 - + when Tag.categories.artist self.tag_count_artist += 1 - + when Tag.categories.copyright self.tag_count_copyright += 1 - + when Tag.categories.character self.tag_count_character += 1 end end end - + def merge_old_tags if old_tag_string # If someone else committed changes to this post before we did, # then try to merge the tag changes together. current_tags = tag_array_was() new_tags = tag_array() - old_tags = Tag.scan_tags(old_tag_string) + old_tags = Tag.scan_tags(old_tag_string) set_tag_string(((current_tags + new_tags) - old_tags + (current_tags & new_tags)).uniq.sort.join(" ")) end end - + def reset_tag_array_cache @tag_array = nil @tag_array_was = nil end - + def set_tag_string(string) self.tag_string = string reset_tag_array_cache end - + def normalize_tags normalized_tags = Tag.scan_tags(tag_string) normalized_tags = TagAlias.to_aliased(normalized_tags) @@ -379,52 +379,52 @@ class Post < ActiveRecord::Base normalized_tags.sort! set_tag_string(normalized_tags.uniq.sort.join(" ")) end - + def filter_metatags(tags) @pre_metatags, tags = tags.partition {|x| x =~ /\A(?:rating|parent):/} @post_metatags, tags = tags.partition {|x| x =~ /\A(?:-pool|pool|fav):/} apply_pre_metatags return tags end - + def apply_post_metatags return unless @post_metatags - + @post_metatags.each do |tag| case tag when /^-pool:(\d+)$/ pool = Pool.find_by_id($1.to_i) remove_pool!(pool) if pool - + when /^-pool:(.+)$/ pool = Pool.find_by_name($1) remove_pool!(pool) if pool - + when /^pool:(\d+)$/ pool = Pool.find_by_id($1.to_i) add_pool!(pool) if pool - + when /^pool:(.+)$/ pool = Pool.find_by_name($1) if pool.nil? pool = Pool.create(:name => $1, :description => "This pool was automatically generated") end add_pool!(pool) if pool - + when /^fav:(.+)$/ add_favorite!(CurrentUser.user) end end end - + def apply_pre_metatags return unless @pre_metatags - + @pre_metatags.each do |tag| case tag when /^parent:none$/, /^parent:0$/ self.parent_id = nil - + when /^parent:(\d+)$/ self.parent_id = $1.to_i @@ -433,31 +433,31 @@ class Post < ActiveRecord::Base end end end - + def has_tag?(tag) tag_string =~ /(?:^| )#{tag}(?:$| )/ end - + def has_dup_tag? has_tag?("duplicate") ? true : false end - + def tag_categories @tag_categories ||= Tag.categories_for(tag_array) end - + def copyright_tags typed_tags("copyright") end - + def character_tags typed_tags("character") end - + def artist_tags typed_tags("artist") end - + def typed_tags(name) @typed_tags ||= {} @typed_tags[name] ||= begin @@ -466,7 +466,7 @@ class Post < ActiveRecord::Base end end end - + def essential_tag_string tag_array.each do |tag| if tag_categories[tag] == Danbooru.config.tag_category_mapping["copyright"] @@ -489,16 +489,16 @@ class Post < ActiveRecord::Base return tag_array.first end end - + module FavoriteMethods def favorited_by?(user_id) fav_string =~ /(?:\A| )fav:#{user_id}(?:\Z| )/ end - + def append_user_to_fav_string(user_id) update_column(:fav_string, (fav_string + " fav:#{user_id}").strip) end - + def add_favorite!(user) return if favorited_by?(user.id) append_user_to_fav_string(user.id) @@ -506,11 +506,11 @@ class Post < ActiveRecord::Base increment!(:score) if CurrentUser.is_privileged? user.add_favorite!(self) end - + def delete_user_from_fav_string(user_id) update_column(:fav_string, fav_string.gsub(/(?:\A| )fav:#{user_id}(?:\Z| )/, " ").strip) end - + def remove_favorite!(user) return unless favorited_by?(user.id) decrement!(:fav_count) @@ -518,12 +518,12 @@ class Post < ActiveRecord::Base delete_user_from_fav_string(user.id) user.remove_favorite!(self) end - + def favorited_user_ids fav_string.scan(/\d+/) end end - + module UploaderMethods def initialize_uploader if uploader_id.blank? @@ -531,12 +531,12 @@ class Post < ActiveRecord::Base self.uploader_ip_addr = CurrentUser.ip_addr end end - + def uploader_name User.id_to_name(uploader_id).tr("_", " ") end end - + module PoolMethods def pools @pools ||= begin @@ -544,18 +544,18 @@ class Post < ActiveRecord::Base Pool.where(["is_deleted = false and id in (?)", pool_ids]) end end - + def belongs_to_pool?(pool) pool_string =~ /(?:\A| )pool:#{pool.id}(?:\Z| )/ end - + def add_pool!(pool) return if belongs_to_pool?(pool) self.pool_string = "#{pool_string} pool:#{pool.id}".strip update_column(:pool_string, pool_string) unless new_record? pool.add!(self) end - + def remove_pool!(pool) return unless belongs_to_pool?(pool) self.pool_string = pool_string.gsub(/(?:\A| )pool:#{pool.id}(?:\Z| )/, " ").strip @@ -563,7 +563,7 @@ class Post < ActiveRecord::Base pool.remove!(self) end end - + module VoteMethods def can_be_voted_by?(user) !votes.exists?(["user_id = ?", user.id]) @@ -585,7 +585,7 @@ class Post < ActiveRecord::Base end end end - + module CountMethods def fix_post_counts post.set_tag_counts @@ -595,17 +595,17 @@ class Post < ActiveRecord::Base post.update_column(:tag_count_copyright, post.tag_count_copyright) post.update_column(:tag_count_character, post.tag_count_character) end - + def get_count_from_cache(tags) count = Cache.get(count_cache_key(tags)) - + if count.nil? count = select_value_sql("SELECT post_count FROM tags WHERE name = ?", tags.to_s) end - + count end - + def set_count_in_cache(tags, count, expiry = nil) if expiry.nil? if count < 100 @@ -614,14 +614,14 @@ class Post < ActiveRecord::Base expiry = (count * 4).minutes end end - + Cache.put(count_cache_key(tags), count, expiry) end - + def count_cache_key(tags) "pfc:#{Cache.sanitize(tags)}" end - + def fast_count(tags = "") tags = tags.to_s.strip @@ -633,7 +633,7 @@ class Post < ActiveRecord::Base count = fast_count_search(tags) else count = get_count_from_cache(tags) - + if count.to_i == 0 count = fast_count_search(tags) end @@ -643,7 +643,7 @@ class Post < ActiveRecord::Base rescue SearchError 0 end - + def fast_count_search(tags) count = Post.with_timeout(500, Danbooru.config.blank_tag_search_fast_count || 1_000_000) do Post.tag_match(tags).count @@ -654,19 +654,19 @@ class Post < ActiveRecord::Base count end end - + module CacheMethods def expire_cache_for_all(tag_names) Danbooru.config.all_server_hosts.each do |host| delay(:queue => host).expire_cache(tag_names) end end - + def expire_cache(tag_names) tag_names.each do |tag_name| Cache.delete(Post.count_cache_key(tag_name)) end - + if Post.fast_count("").to_i < 1000 Cache.delete(Post.count_cache_key("")) end @@ -674,7 +674,7 @@ class Post < ActiveRecord::Base end module ParentMethods - # A parent has many children. A child belongs to a parent. + # A parent has many children. A child belongs to a parent. # A parent cannot have a parent. # # After deleting a child: @@ -686,14 +686,14 @@ class Post < ActiveRecord::Base # After deleting a parent: # - Move favorites to the first child. # - Reparent all active children to the first active child. - + module ClassMethods def update_has_children_flag_for(post_id) return if post_id.nil? has_children = Post.exists?(["is_deleted = ? AND parent_id = ?", false, post_id]) execute_sql("UPDATE posts SET has_children = ? WHERE id = ?", has_children, post_id) end - + def recalculate_has_children_for_all_posts transaction do execute_sql("UPDATE posts SET has_children = false WHERE has_children = true") @@ -701,7 +701,7 @@ class Post < ActiveRecord::Base end end end - + def self.included(m) m.extend(ClassMethods) end @@ -712,13 +712,13 @@ class Post < ActiveRecord::Base errors.add(:parent, "can not have a parent") end end - + def update_parent_on_destroy Post.update_has_children_flag_for(id) Post.update_has_children_flag_for(parent_id) if parent_id Post.update_has_children_flag_for(parent_id_was) if parent_id_was && parent_id != parent_id_was end - + def update_children_on_destroy if children.size == 0 # do nothing @@ -741,7 +741,7 @@ class Post < ActiveRecord::Base Post.update_has_children_flag_for(parent_id) end end - + def give_favorites_to_parent return if parent.nil? @@ -753,26 +753,26 @@ class Post < ActiveRecord::Base update_column(:score, 0) end end - + module DeletionMethods def annihilate! if is_status_locked? self.errors.add(:is_status_locked, "; cannot delete post") return false end - + ModAction.create(:description => "permanently deleted post ##{id}") decrement_tag_post_counts delete!(:without_mod_action => true) destroy end - + def delete!(options = {}) if is_status_locked? self.errors.add(:is_status_locked, "; cannot delete post") return false end - + Post.transaction do update_column(:is_deleted, true) update_column(:is_pending, false) @@ -782,19 +782,19 @@ class Post < ActiveRecord::Base update_parent_on_destroy # decrement_tag_post_counts update_column(:parent_id, nil) - + unless options[:without_mod_action] ModAction.create(:description => "deleted post ##{id}") end end end - + def undelete! if is_status_locked? self.errors.add(:is_status_locked, "; cannot undelete post") return false end - + self.is_deleted = false self.approver_id = CurrentUser.id save @@ -803,7 +803,7 @@ class Post < ActiveRecord::Base ModAction.create(:description => "undeleted post ##{id}") end end - + module VersionMethods def create_version if created_at == updated_at @@ -824,31 +824,31 @@ class Post < ActiveRecord::Base ) end end - + def revert_to(target) self.tag_string = target.tags self.rating = target.rating self.source = target.source self.parent_id = target.parent_id end - + def revert_to!(target) revert_to(target) save! end end - + module NoteMethods def last_noted_at_as_integer last_noted_at.to_i end end - + module ApiMethods def hidden_attributes super + [:tag_index] end - + def serializable_hash(options = {}) options ||= {} options[:except] ||= [] @@ -860,7 +860,7 @@ class Post < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -868,7 +868,7 @@ class Post < ActiveRecord::Base options[:procs] << lambda {|options, record| options[:builder].tag!("has-large", record.has_large?, :type => "boolean")} super(options, &block) end - + def to_legacy_json return { "has_comments" => last_commented_at.present?, @@ -892,7 +892,7 @@ class Post < ActiveRecord::Base "file_url" => file_url }.to_json end - + def status if is_pending? "pending" @@ -905,44 +905,44 @@ class Post < ActiveRecord::Base end end end - + module SearchMethods def pending where("is_pending = ?", true) end - + def flagged where("is_flagged = ?", true) end - + def pending_or_flagged where("(is_pending = ? or (is_flagged = ? and id in (select _.post_id from post_flags _ where _.created_at >= ?)))", true, true, 1.week.ago) end - + def undeleted where("is_deleted = ?", false) end - + def deleted where("is_deleted = ?", true) end - + def visible(user) Danbooru.config.can_user_see_post_conditions(user) end - + def commented_before(date) where("last_commented_at < ?", date).order("last_commented_at DESC") end - + def has_notes where("last_noted_at is not null") end - + def for_user(user_id) where("uploader_id = ?", user_id) end - + def available_for_moderation(hidden) if hidden.present? where("posts.id IN (SELECT pd.post_id FROM post_disapprovals pd WHERE pd.user_id = ?)", CurrentUser.id) @@ -950,31 +950,31 @@ class Post < ActiveRecord::Base where("posts.id NOT IN (SELECT pd.post_id FROM post_disapprovals pd WHERE pd.user_id = ?)", CurrentUser.id) end end - + def hidden_from_moderation where("id IN (SELECT pd.post_id FROM post_disapprovals pd WHERE pd.user_id = ?)", CurrentUser.id) end - + def raw_tag_match(tag) where("posts.tag_index @@ to_tsquery('danbooru', E?)", tag.to_escaped_for_tsquery) end - + def tag_match(query) PostQueryBuilder.new(query).build end - + def positive where("score > 1") end - + def negative where("score < -1") end - + def updater_name_matches(name) where("updater_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def after_id(num) if num.present? where("id > ?", num.to_i).reorder("id asc") @@ -982,7 +982,7 @@ class Post < ActiveRecord::Base where("true") end end - + def before_id(num) if num.present? where("id < ?", num.to_i).reorder("id desc") @@ -990,27 +990,27 @@ class Post < ActiveRecord::Base where("true") end end - + def search(params) q = scoped return q if params.blank? - + if params[:before_id].present? q = q.before_id(params[:before_id].to_i) end - + if params[:after_id].present? q = q.after_id(params[:after_id].to_i) end - + if params[:tag_match].present? q = q.tag_match(params[:tag_match]) end - + q end end - + include FileMethods include ImageMethods include ApprovalMethods @@ -1028,7 +1028,7 @@ class Post < ActiveRecord::Base include NoteMethods include ApiMethods extend SearchMethods - + def reload(options = nil) super reset_tag_array_cache diff --git a/app/models/post_appeal.rb b/app/models/post_appeal.rb index d4999bab1..ac9986b68 100644 --- a/app/models/post_appeal.rb +++ b/app/models/post_appeal.rb @@ -1,6 +1,6 @@ class PostAppeal < ActiveRecord::Base class Error < Exception ; end - + belongs_to :creator, :class_name => "User" belongs_to :post validates_presence_of :reason, :creator_id, :creator_ip_addr @@ -8,38 +8,38 @@ class PostAppeal < ActiveRecord::Base validate :validate_creator_is_not_limited before_validation :initialize_creator, :on => :create validates_uniqueness_of :creator_id, :scope => :post_id, :message => "have already appealed this post" - + module SearchMethods def for_user(user_id) where("creator_id = ?", user_id) end - + def recent where("created_at >= ?", 1.day.ago) end - + def search(params) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.for_user(params[:creator_id].to_i) end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + q end end - + extend SearchMethods - + def validate_creator_is_not_limited if appeal_count_for_creator >= Danbooru.config.max_appeals_per_day errors[:creator] << "can appeal at most #{Danbooru.config.max_appeals_per_day} post a day" @@ -48,7 +48,7 @@ class PostAppeal < ActiveRecord::Base true end end - + def validate_post_is_inactive if !post.is_deleted? && !post.is_flagged? errors[:post] << "is active" @@ -57,12 +57,12 @@ class PostAppeal < ActiveRecord::Base true end end - + def initialize_creator self.creator_id = CurrentUser.id self.creator_ip_addr = CurrentUser.ip_addr end - + def appeal_count_for_creator PostAppeal.for_user(creator_id).recent.count end diff --git a/app/models/post_flag.rb b/app/models/post_flag.rb index 142718905..5d5aba1c2 100644 --- a/app/models/post_flag.rb +++ b/app/models/post_flag.rb @@ -1,6 +1,6 @@ class PostFlag < ActiveRecord::Base class Error < Exception ; end - + belongs_to :creator, :class_name => "User" belongs_to :post validates_presence_of :reason, :creator_id, :creator_ip_addr @@ -14,45 +14,45 @@ class PostFlag < ActiveRecord::Base def resolved where("is_resolved = ?", true) end - + def unresolved where("is_resolved = ?", false) end - + def recent where("created_at >= ?", 1.day.ago) end - + def old where("created_at <= ?", 3.days.ago) end - + def search(params) q = scoped return q if params.blank? - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + q end end - + extend SearchMethods - + def update_post post.update_column(:is_flagged, true) unless post.is_flagged? end - + def validate_creator_is_not_limited if CurrentUser.is_janitor? false @@ -63,7 +63,7 @@ class PostFlag < ActiveRecord::Base true end end - + def validate_post_is_active if post.is_deleted? errors[:post] << "is deleted" @@ -72,16 +72,16 @@ class PostFlag < ActiveRecord::Base true end end - + def initialize_creator self.creator_id = CurrentUser.id self.creator_ip_addr = CurrentUser.ip_addr end - + def resolve! update_column(:is_resolved, true) end - + def flag_count_for_creator PostFlag.where(:creator_id => creator_id).recent.count end diff --git a/app/models/post_version.rb b/app/models/post_version.rb index bb218d4d1..73882d9cb 100644 --- a/app/models/post_version.rb +++ b/app/models/post_version.rb @@ -2,38 +2,38 @@ class PostVersion < ActiveRecord::Base belongs_to :post belongs_to :updater, :class_name => "User" before_validation :initialize_updater - + module SearchMethods def for_user(user_id) where("updater_id = ?", user_id) end - + def updater_name(name) where("updater_id = (select _.id from users _ where lower(_.name) = ?)", name.downcase) end - + def search(params) q = scoped params = {} if params.blank? - + if params[:updater_name].present? q = q.updater_name(params[:updater_name]) end - + if params[:updater_id].present? q = q.where("updater_id = ?", params[:updater_id].to_i) end - + if params[:post_id].present? q = q.where("post_id = ?", params[:post_id].to_i) end - + q end end - + extend SearchMethods - + def self.create_from_post(post) if post.created_at == post.updated_at create_from_created_post(post) @@ -41,20 +41,20 @@ class PostVersion < ActiveRecord::Base create_from_updated_post(post) end end - + def initialize_updater self.updater_id = CurrentUser.id self.updater_ip_addr = CurrentUser.ip_addr end - + def tag_array @tag_array ||= tags.scan(/\S+/) end - + def presenter PostVersionPresenter.new(self) end - + def reload @tag_array = nil super @@ -70,7 +70,7 @@ class PostVersion < ActiveRecord::Base end return diffs end - + def diff(version) latest_tags = post.tag_array new_tags = tag_array @@ -92,11 +92,11 @@ class PostVersion < ActiveRecord::Base :obsolete_removed_tags => old_tags & latest_tags, } end - + def previous PostVersion.where("post_id = ? and updated_at < ?", post_id, updated_at).order("updated_at desc").first end - + def truncated_source source.gsub(/^http:\/\//, "").sub(/\/.+/, "") end diff --git a/app/models/post_vote.rb b/app/models/post_vote.rb index db51f07ef..e2632e0ac 100644 --- a/app/models/post_vote.rb +++ b/app/models/post_vote.rb @@ -1,6 +1,6 @@ class PostVote < ActiveRecord::Base class Error < Exception ; end - + belongs_to :post before_validation :initialize_user, :on => :create validates_presence_of :post_id, :user_id, :score @@ -13,7 +13,7 @@ class PostVote < ActiveRecord::Base write_attribute(:score, -1) end end - + def initialize_user self.user_id = CurrentUser.user.id end diff --git a/app/models/report_mailer.rb b/app/models/report_mailer.rb index 5f8bad38b..9c2313916 100644 --- a/app/models/report_mailer.rb +++ b/app/models/report_mailer.rb @@ -1,6 +1,6 @@ class ReportMailer < ActionMailer::Base default :host => Danbooru.config.server_host, :from => Danbooru.config.contact_email, :content_type => "text/html" - + def moderator_report(email) mail(:to => email, :subject => "#{Danbooru.config.app_name} - Moderator Report") end diff --git a/app/models/tag.rb b/app/models/tag.rb index ebfb64657..9b9f4568c 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -2,7 +2,7 @@ class Tag < ActiveRecord::Base METATAGS = "-user|user|-approver|approver|-pool|pool|-fav|fav|sub|md5|-rating|rating|width|height|mpixels|score|filesize|source|id|date|order|status|tagcount|gentags|arttags|chartags|copytags|parent|pixiv" attr_accessible :category has_one :wiki_page, :foreign_key => "name", :primary_key => "title" - + module ApiMethods def to_legacy_json return { @@ -15,70 +15,70 @@ class Tag < ActiveRecord::Base }.to_json end end - + class CategoryMapping Danbooru.config.reverse_tag_category_mapping.each do |value, category| define_method(category.downcase) do value end end - + def regexp @regexp ||= Regexp.compile(Danbooru.config.tag_category_mapping.keys.sort_by {|x| -x.size}.join("|")) end - + def value_for(string) Danbooru.config.tag_category_mapping[string.to_s.downcase] || 0 end end - + module CountMethods extend ActiveSupport::Concern - + module ClassMethods def counts_for(tag_names) select_all_sql("SELECT name, post_count FROM tags WHERE name IN (?)", tag_names) end end - + def real_post_count @real_post_count ||= Post.raw_tag_match(name).count end - + def fix_post_count update_column(:post_count, real_post_count) end end - + module ViewCountMethods def increment_view_count(name) Cache.incr("tvc:#{Cache.sanitize(name)}") end end - + module CategoryMethods module ClassMethods def categories @category_mapping ||= CategoryMapping.new end - + def select_category_for(tag_name) select_value_sql("SELECT category FROM tags WHERE name = ?", tag_name).to_i end - + def category_for(tag_name) Cache.get("tc:#{Cache.sanitize(tag_name)}") do select_category_for(tag_name) end end - + def categories_for(tag_names) Cache.get_multi(tag_names, "tc") do |name| select_category_for(name) end end end - + def self.included(m) m.extend(ClassMethods) end @@ -86,16 +86,16 @@ class Tag < ActiveRecord::Base def category_name Danbooru.config.reverse_tag_category_mapping[category] end - + def update_category_cache_for_all update_category_cache Danbooru.config.other_server_hosts.each do |host| delay(:queue => host).update_category_cache end - + delay(:queue => "default").update_category_post_counts end - + def update_category_post_counts Post.raw_tag_match(name).find_each do |post| post.reload @@ -107,18 +107,18 @@ class Tag < ActiveRecord::Base post.update_column(:tag_count_character, post.tag_count_character) end end - + def update_category_cache Cache.put("tc:#{Cache.sanitize(name)}", category, 1.hour) end end - + module StatisticsMethods def trending raise NotImplementedError end end - + module NameMethods def normalize_name(name) name.downcase.tr(" ", "_").gsub(/\A[-~]+/, "").gsub(/\*/, "") @@ -138,7 +138,7 @@ class Tag < ActiveRecord::Base if tag if category category_id = categories.value_for(category) - + if category_id != tag.category tag.update_column(:category, category_id) tag.update_category_cache_for_all @@ -160,7 +160,7 @@ class Tag < ActiveRecord::Base def normalize(query) query.to_s.strip end - + def scan_query(query) normalize(query).scan(/\S+/).uniq end @@ -221,7 +221,7 @@ class Tag < ActiveRecord::Base when /\A>(.+)/ return [:gt, parse_cast($1, type)] - + when /,/ return [:in, range.split(/,/)] @@ -230,19 +230,19 @@ class Tag < ActiveRecord::Base end end - + def parse_tag(tag, output) if tag[0] == "-" && tag.size > 1 output[:exclude] << tag[1..-1].downcase - + elsif tag[0] == "~" && tag.size > 1 output[:include] << tag[1..-1].downcase - + elsif tag =~ /\*/ matches = Tag.name_matches(tag.downcase).all(:select => "name", :limit => Danbooru.config.tag_query_limit, :order => "post_count DESC").map(&:name) matches = ["~no_matches~"] if matches.empty? output[:include] += matches - + else output[:related] << tag.downcase end @@ -250,15 +250,15 @@ class Tag < ActiveRecord::Base def parse_query(query, options = {}) q = {} - + q[:tag_count] = 0 - + q[:tags] = { :related => [], :include => [], :exclude => [] } - + scan_query(query).each do |token| q[:tag_count] += 1 unless token == "status:deleted" @@ -267,25 +267,25 @@ class Tag < ActiveRecord::Base when "-user" q[:uploader_id_neg] ||= [] q[:uploader_id_neg] << User.name_to_id($2) - + when "user" q[:uploader_id] = User.name_to_id($2) q[:uploader_id] = -1 if q[:uploader_id].nil? - + when "-approver" q[:approver_id_neg] ||= [] q[:approver_id_neg] << User.name_to_id($2) - + when "approver" q[:approver_id] = User.name_to_id($2) q[:approver_id] = -1 if q[:approver_id].nil? - + when "-pool" q[:tags][:exclude] << "pool:#{Pool.name_to_id($2)}" - + when "pool" q[:tags][:related] << "pool:#{Pool.name_to_id($2)}" - + when "-fav" q[:tags][:exclude] << "fav:#{User.name_to_id($2)}" @@ -304,16 +304,16 @@ class Tag < ActiveRecord::Base when "rating" q[:rating] = $2 - + when "id" q[:post_id] = parse_helper($2) - + when "width" q[:width] = parse_helper($2) - + when "height" q[:height] = parse_helper($2) - + when "mpixels" q[:mpixels] = parse_helper($2, :float) @@ -325,13 +325,13 @@ class Tag < ActiveRecord::Base when "source" q[:source] = ($2.to_escaped_for_sql_like + "%").gsub(/%+/, '%') - + when "date" q[:date] = parse_helper($2, :date) when "tagcount" q[:post_tag_count] = parse_helper($2) - + when "gentags" q[:general_tag_count] = parse_helper($2) @@ -343,26 +343,26 @@ class Tag < ActiveRecord::Base when "copytags" q[:copyright_tag_count] = parse_helper($2) - + when "parent" q[:parent_id] = $2.to_i - + when "order" q[:order] = $2.downcase when "status" q[:status] = $2.downcase - + when "pixiv" q[:pixiv] = parse_helper($2) end - + else parse_tag(token, q[:tags]) end end - + normalize_tags_in_query(q) return q @@ -374,7 +374,7 @@ class Tag < ActiveRecord::Base query_hash[:tags][:related] = TagAlias.to_aliased(query_hash[:tags][:related]) end end - + module RelationMethods def update_related return unless should_update_related? @@ -384,13 +384,13 @@ class Tag < ActiveRecord::Base self.related_tags_updated_at = Time.now save end - + def update_related_if_outdated if should_update_related? && Delayed::Job.count < 200 - delay(:queue => "default").update_related + delay(:queue => "default").update_related end end - + def related_cache_expiry base = Math.sqrt([post_count, 0].max) if base > 24 * 7 @@ -401,21 +401,21 @@ class Tag < ActiveRecord::Base base end end - + def should_update_related? related_tags.blank? || related_tags_updated_at.blank? || related_tags_updated_at < related_cache_expiry.hours.ago end - + def related_tag_array update_related_if_outdated related_tags.to_s.split(/ /).in_groups_of(2) end end - + module SuggestionMethods def find_suggestions(query) query_tokens = query.split(/_/) - + if query_tokens.size == 2 search_for = query_tokens.reverse.join("_").to_escaped_for_sql_like else @@ -425,42 +425,42 @@ class Tag < ActiveRecord::Base Tag.where(["name LIKE ? ESCAPE E'\\\\' AND post_count > 0 AND name <> ?", search_for, query]).all(:order => "post_count DESC", :limit => 6, :select => "name").map(&:name).sort end end - + module SearchMethods def name_matches(name) where("name LIKE ? ESCAPE E'\\\\'", name.downcase.to_escaped_for_sql_like) end - + def named(name) where("name = ?", TagAlias.to_aliased([name]).join("")) end - + def search(params) q = scoped params = {} if params.blank? - + if params[:name_matches].present? q = q.name_matches(params[:name_matches].strip) end - + if params[:category].present? q = q.where("category = ?", params[:category]) end - + if params[:hide_empty].blank? || params[:hide_empty] != "no" q = q.where("post_count > 0") end - + if params[:limit].present? q = q.limit(params[:limit].to_i) end - + if params[:order] == "name" q = q.reorder("name") - + elsif params[:order] == "date" q = q.reorder("id desc") - + elsif params[:sort] == "date" q = q.reorder("id desc") @@ -470,11 +470,11 @@ class Tag < ActiveRecord::Base else q = q.reorder("post_count desc") end - + q end end - + include ApiMethods include CountMethods extend ViewCountMethods diff --git a/app/models/tag_alias.rb b/app/models/tag_alias.rb index edd99cb42..052468557 100644 --- a/app/models/tag_alias.rb +++ b/app/models/tag_alias.rb @@ -8,20 +8,20 @@ class TagAlias < ActiveRecord::Base validate :absence_of_transitive_relation belongs_to :creator, :class_name => "User" belongs_to :forum_topic - + module SearchMethods def name_matches(name) where("(antecedent_name like ? escape E'\\\\' or consequent_name like ? escape E'\\\\')", name.downcase.to_escaped_for_sql_like, name.downcase.to_escaped_for_sql_like) end - + def search(params) q = scoped return q if params.blank? - + if params[:name_matches].present? q = q.name_matches(params[:name_matches]) end - + if params[:antecedent_name].present? q = q.where("antecedent_name = ?", params[:antecedent_name]) end @@ -29,20 +29,20 @@ class TagAlias < ActiveRecord::Base if params[:id].present? q = q.where("id = ?", params[:id].to_i) end - + q end end - + module CacheMethods extend ActiveSupport::Concern - + module ClassMethods def clear_cache_for(name) Cache.delete("ta:#{Cache.sanitize(name)}") end end - + def clear_all_cache Danbooru.config.all_server_hosts.each do |host| TagAlias.delay(:queue => host).clear_cache_for(antecedent_name) @@ -50,10 +50,10 @@ class TagAlias < ActiveRecord::Base end end end - + extend SearchMethods include CacheMethods - + def self.to_aliased(names) alias_hash = Cache.get_multi(names.flatten, "ta") do |name| ta = TagAlias.find_by_antecedent_name(name) @@ -63,10 +63,10 @@ class TagAlias < ActiveRecord::Base name end end - + alias_hash.values.flatten.uniq end - + def process! update_column(:status, "processing") clear_all_cache @@ -75,28 +75,28 @@ class TagAlias < ActiveRecord::Base rescue Exception => e update_column(:status, "error: #{e}") end - + def is_pending? status == "pending" end - + def is_active? status == "active" end - + def initialize_creator self.creator_id = CurrentUser.user.id self.creator_ip_addr = CurrentUser.ip_addr end - + def antecedent_tag Tag.find_by_name(antecedent_name) end - + def consequent_tag Tag.find_by_name(consequent_name) end - + def absence_of_transitive_relation # We don't want a -> b && b -> c chains if self.class.exists?(["antecedent_name = ?", consequent_name]) || self.class.exists?(["consequent_name = ?", antecedent_name]) @@ -104,15 +104,15 @@ class TagAlias < ActiveRecord::Base false end end - + def ensure_category_consistency if antecedent_tag && consequent_tag && antecedent_tag.category != consequent_tag.category consequent_tag.update_attribute(:category, antecedent_tag.category) end - + true end - + def update_posts Post.raw_tag_match(antecedent_name).find_each do |post| escaped_antecedent_name = Regexp.escape(antecedent_name) diff --git a/app/models/tag_implication.rb b/app/models/tag_implication.rb index f5f692d43..3384386b2 100644 --- a/app/models/tag_implication.rb +++ b/app/models/tag_implication.rb @@ -6,17 +6,17 @@ class TagImplication < ActiveRecord::Base validates_presence_of :creator_id, :antecedent_name, :consequent_name validates_uniqueness_of :antecedent_name, :scope => :consequent_name validate :absence_of_circular_relation - + module DescendantMethods extend ActiveSupport::Concern - + module ClassMethods # assumes names are normalized def with_descendants(names) (names + where("antecedent_name in (?) and status = ?", names, "active").map(&:descendant_names_array)).flatten.uniq end end - + def descendants @descendants ||= begin [].tap do |all| @@ -45,7 +45,7 @@ class TagImplication < ActiveRecord::Base def update_descendant_names_for_parent p = parent - + while p p.update_descendant_names! p = p.parent @@ -56,22 +56,22 @@ class TagImplication < ActiveRecord::Base @descendants = nil end end - + module ParentMethods def parent @parent ||= self.class.where(["consequent_name = ?", antecedent_name]).first end - + def clear_parent_cache @parent = nil end end - + module SearchMethods def name_matches(name) where("(antecedent_name like ? escape E'\\\\' or consequent_name like ? escape E'\\\\')", name.downcase.to_escaped_for_sql_like, name.downcase.to_escaped_for_sql_like) end - + def search(params) q = scoped return q if params.blank? @@ -79,11 +79,11 @@ class TagImplication < ActiveRecord::Base if params[:id].present? q = q.where("id = ?", params[:id].to_i) end - + if params[:name_matches].present? q = q.name_matches(params[:name_matches]) end - + if params[:antecedent_name].present? q = q.where("antecedent_name = ?", params[:antecedent_name]) end @@ -91,16 +91,16 @@ class TagImplication < ActiveRecord::Base q end end - + include DescendantMethods include ParentMethods extend SearchMethods - + def initialize_creator self.creator_id = CurrentUser.user.id self.creator_ip_addr = CurrentUser.ip_addr end - + def process! update_column(:status, "processing") update_descendant_names_for_parent @@ -109,7 +109,7 @@ class TagImplication < ActiveRecord::Base rescue Exception => e update_column(:status, "error: #{e}") end - + def absence_of_circular_relation # We don't want a -> b && b -> a chains if self.class.exists?(["antecedent_name = ? and consequent_name = ?", consequent_name, antecedent_name]) @@ -117,7 +117,7 @@ class TagImplication < ActiveRecord::Base false end end - + def update_posts Post.tag_match("#{antecedent_name} status:any").find_each do |post| escaped_antecedent_name = Regexp.escape(antecedent_name) @@ -129,23 +129,23 @@ class TagImplication < ActiveRecord::Base end end end - + def is_pending? status == "pending" end - + def is_active? status == "active" end - + def antecedent_tag Tag.find_by_name(antecedent_name) end - + def consequent_tag Tag.find_by_name(consequent_name) end - + def reload(options = {}) super clear_parent_cache diff --git a/app/models/tag_subscription.rb b/app/models/tag_subscription.rb index e265d1525..bdf733fce 100644 --- a/app/models/tag_subscription.rb +++ b/app/models/tag_subscription.rb @@ -8,15 +8,15 @@ class TagSubscription < ActiveRecord::Base validates_presence_of :name, :tag_query, :creator_id validates_format_of :tag_query, :with => /^(?:\S+\s*){1,20}$/m, :message => "can have up to 20 tags" validate :creator_can_create_subscriptions, :on => :create - + def normalize_name self.name = name.gsub(/\s+/, "_") end - + def pretty_name name.tr("_", " ") end - + def initialize_creator self.creator_id = CurrentUser.id end @@ -24,7 +24,7 @@ class TagSubscription < ActiveRecord::Base def initialize_post_ids process end - + def creator_can_create_subscriptions if TagSubscription.owned_by(creator).count >= Danbooru.config.max_tag_subscriptions self.errors.add(:creator, "can create up to #{Danbooru.config.max_tag_subscriptions} tag subscriptions") @@ -49,38 +49,38 @@ class TagSubscription < ActiveRecord::Base end self.post_ids = post_ids.sort.reverse.slice(0, Danbooru.config.tag_subscription_post_limit).join(",") end - + def is_active? creator.last_logged_in_at && creator.last_logged_in_at > 1.year.ago end - + def editable_by?(user) user.is_moderator? || creator_id == user.id end - + def post_id_array post_ids.split(/,/) end - + def self.search(params) q = scoped return q if params.blank? - + if params[:creator_id] q = q.where("creator_id = ?", params[:creator_id].to_i) end - + if params[:creator_name] q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + q end - + def self.visible_to(user) where("(is_public = TRUE OR creator_id = ? OR ?)", user.id, user.is_moderator?) end - + def self.owned_by(user) where("creator_id = ?", user.id) end @@ -95,10 +95,10 @@ class TagSubscription < ActiveRecord::Base end user = User.find_by_name(user_name) - + if user relation = where(["creator_id = ?", user.id]) - + if sub_group relation = relation.where(["name ILIKE ? ESCAPE E'\\\\'", sub_group.to_escaped_for_sql_like]) end @@ -106,16 +106,16 @@ class TagSubscription < ActiveRecord::Base relation.map {|x| x.tag_query.split(/ /)}.flatten else [] - end + end end def self.find_post_ids(user_id, name = nil, limit = Danbooru.config.tag_subscription_post_limit) relation = where("creator_id = ?", user_id) - + if name relation = relation.where("lower(name) LIKE ? ESCAPE E'\\\\'", name.downcase.to_escaped_for_sql_like) end - + relation.each do |tag_sub| tag_sub.update_column(:last_accessed_at, Time.now) end diff --git a/app/models/upload.rb b/app/models/upload.rb index 9fe0c2e55..d162de1a0 100644 --- a/app/models/upload.rb +++ b/app/models/upload.rb @@ -3,7 +3,7 @@ require "tmpdir" class Upload < ActiveRecord::Base class Error < Exception ; end - + attr_accessor :file, :image_width, :image_height, :file_ext, :md5, :file_size belongs_to :uploader, :class_name => "User" belongs_to :post @@ -13,7 +13,7 @@ class Upload < ActiveRecord::Base after_destroy :delete_temp_file validate :uploader_is_not_limited validate :file_or_source_is_present, :on => :create - + module ValidationMethods def uploader_is_not_limited if !uploader.can_upload? @@ -37,34 +37,34 @@ class Upload < ActiveRecord::Base def validate_md5_uniqueness md5_post = Post.find_by_md5(md5) if md5_post - merge_tags(md5_post) + merge_tags(md5_post) raise "duplicate: #{md5_post.id}" end end - + def validate_file_exists unless file_path && File.exists?(file_path) raise "file does not exist" end end - + def validate_file_content_type unless is_valid_content_type? raise "invalid content type (#{file_ext} not allowed)" end end - + def validate_md5_confirmation if !md5_confirmation.blank? && md5_confirmation != md5 raise "md5 mismatch" end end end - + module ConversionMethods def process! force=false return if !force && status =~ /processing|completed|error/ - + CurrentUser.scoped(uploader, uploader_ip_addr) do update_attribute(:status, "processing") if is_downloadable? @@ -79,7 +79,7 @@ class Upload < ActiveRecord::Base calculate_file_size(file_path) add_file_size_tags!(file_path) if has_dimensions? - calculate_dimensions(file_path) + calculate_dimensions(file_path) add_dimension_tags! end generate_resizes(file_path) @@ -118,18 +118,18 @@ class Upload < ActiveRecord::Base end end end - + def merge_tags(post) post.tag_string += " #{tag_string}" post.save end end - + module FileMethods def delete_temp_file FileUtils.rm_f(temp_file_path) end - + def move_file FileUtils.mv(file_path, md5_file_path) end @@ -142,7 +142,7 @@ class Upload < ActiveRecord::Base def calculate_hash(source_path) self.md5 = Digest::MD5.file(source_path).hexdigest end - + def is_image? ["jpg", "gif", "png"].include?(file_ext) end @@ -176,10 +176,10 @@ class Upload < ActiveRecord::Base self.image_width = image_size.get_width self.image_height = image_size.get_height end - + def add_dimension_tags! return if !Danbooru.config.enable_dimension_autotagging - + if image_width >= 10_000 || image_height >= 10_000 self.tag_string = "#{tag_string} incredibly_absurdres".strip elsif image_width >= 3200 || image_height >= 2400 @@ -190,37 +190,37 @@ class Upload < ActiveRecord::Base self.tag_string = "#{tag_string} lowres".strip end end - + # Does this file have image dimensions? def has_dimensions? %w(jpg gif png swf).include?(file_ext) end end - + module ContentTypeMethods def is_valid_content_type? file_ext =~ /jpg|gif|png|swf/ end - + def content_type_to_file_ext(content_type) case content_type when "image/jpeg" "jpg" - + when "image/gif" "gif" - + when "image/png" "png" - + when "application/x-shockwave-flash" "swf" - + else "bin" end end - + # Converts a content type string to a file extension def file_ext_to_content_type(file_ext) case file_ext @@ -247,12 +247,12 @@ class Upload < ActiveRecord::Base prefix = Rails.env == "test" ? "test." : "" "#{Rails.root}/public/data/#{prefix}#{md5}.#{file_ext}" end - + def ssd_file_path prefix = Rails.env == "test" ? "test." : "" "#{Danbooru.config.ssd_path}/public/data/preview/#{prefix}#{md5}.jpg" end - + def resized_file_path_for(width) prefix = Rails.env == "test" ? "test." : "" @@ -264,12 +264,12 @@ class Upload < ActiveRecord::Base "#{Rails.root}/public/data/sample/#{Danbooru.config.large_image_prefix}#{prefix}#{md5}.jpg" end end - + def temp_file_path @temp_file_path ||= File.join(Rails.root, "tmp", "upload_#{Time.now.to_f}.#{Process.pid}") end end - + module DownloaderMethods # Determines whether the source is downloadable def is_downloadable? @@ -296,7 +296,7 @@ class Upload < ActiveRecord::Base if file.respond_to?(:tempfile) && file.tempfile FileUtils.cp(file.tempfile.path, file_path) else - File.open(file_path, 'wb') do |out| + File.open(file_path, 'wb') do |out| out.write(file.read) end end @@ -305,69 +305,69 @@ class Upload < ActiveRecord::Base self.file_ext = content_type_to_file_ext(content_type) end end - + module StatusMethods def initialize_status self.status = "pending" end - + def is_pending? status == "pending" end - + def is_processing? status == "processing" end - + def is_completed? status == "completed" end - + def is_duplicate? status =~ /duplicate/ end - + def duplicate_post_id @duplicate_post_id ||= status[/duplicate: (\d+)/, 1] end end - + module UploaderMethods def initialize_uploader self.uploader_id = CurrentUser.user.id self.uploader_ip_addr = CurrentUser.ip_addr end end - + module SearchMethods def uploaded_by(user_id) where("uploader_id = ?", user_id) end - + def pending where(:status => "pending") end - + def search(params) q = scoped return q if params.blank? - + if params[:uploader_id].present? q = q.uploaded_by(params[:uploader_id].to_i) end - + if params[:uploader_name].present? q = q.where("uploader_id = (select _.id from users _ where lower(_.name) = ?)", params[:uploader_name].downcase) end - + if params[:source].present? q = q.where("source = ?", params[:source]) end - + q end end - + module ApiMethods def serializable_hash(options = {}) options ||= {} @@ -380,7 +380,7 @@ class Upload < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -388,7 +388,7 @@ class Upload < ActiveRecord::Base super(options, &block) end end - + include ConversionMethods include ValidationMethods include FileMethods @@ -402,17 +402,17 @@ class Upload < ActiveRecord::Base include UploaderMethods extend SearchMethods include ApiMethods - + def add_file_size_tags!(file_path) if file_size >= 10.megabytes self.tag_string = "#{tag_string} huge_filesize".strip end end - + def uploader_name User.id_to_name(uploader_id) end - + def presenter @presenter ||= UploadPresenter.new(self) end diff --git a/app/models/user.rb b/app/models/user.rb index 5195d5617..7b30bc4d4 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -3,7 +3,7 @@ require 'digest/sha1' class User < ActiveRecord::Base class Error < Exception ; end class PrivilegeError < Exception ; end - + module Levels BLOCKED = 10 MEMBER = 20 @@ -15,7 +15,7 @@ class User < ActiveRecord::Base MODERATOR = 40 ADMIN = 50 end - + attr_accessor :password, :old_password attr_accessible :enable_privacy_mode, :enable_post_navigation, :new_post_navigation_layout, :password, :old_password, :password_confirmation, :password_hash, :email, :last_logged_in_at, :last_forum_read_at, :has_mail, :receive_email_notifications, :comment_threshold, :always_resize_images, :favorite_tags, :blacklisted_tags, :name, :ip_addr, :time_zone, :default_image_size, :enable_sequential_post_navigation, :as => [:moderator, :janitor, :contributor, :privileged, :member, :anonymous, :default, :builder, :admin] attr_accessible :level, :as => :admin @@ -44,7 +44,7 @@ class User < ActiveRecord::Base has_many :dmails, :foreign_key => "owner_id", :order => "dmails.id desc" belongs_to :inviter, :class_name => "User" after_update :create_mod_action - + module BanMethods def validate_ip_addr_is_not_banned if IpBan.is_banned?(CurrentUser.ip_addr) @@ -52,13 +52,13 @@ class User < ActiveRecord::Base return false end end - + def unban! update_column(:is_banned, false) ban.destroy end end - + module InvitationMethods def invite!(level) if level.to_i <= Levels::CONTRIBUTOR @@ -68,40 +68,40 @@ class User < ActiveRecord::Base end end end - + module NameMethods extend ActiveSupport::Concern - + module ClassMethods def name_to_id(name) Cache.get("uni:#{Cache.sanitize(name)}", 4.hours) do select_value_sql("SELECT id FROM users WHERE lower(name) = ?", name.mb_chars.downcase) end end - + def id_to_name(user_id) Cache.get("uin:#{user_id}", 4.hours) do select_value_sql("SELECT name FROM users WHERE id = ?", user_id) || Danbooru.config.default_guest_name end end - + def find_by_name(name) where("lower(name) = ?", name.mb_chars.downcase.tr(" ", "_")).first end - + def id_to_pretty_name(user_id) id_to_name(user_id).tr("_", " ") end end - + def pretty_name name.tr("_", " ") end - + def update_cache Cache.put("uin:#{id}", name) end - + def update_remote_cache if name_changed? Danbooru.config.other_server_hosts.each do |server| @@ -111,7 +111,7 @@ class User < ActiveRecord::Base rescue Exception # swallow, since it'll be expired eventually anyway end - + def validate_feedback_on_name_change if feedback.negative.count > 0 && name_changed? self.errors[:base] << "You can not change your name if you have any negative feedback" @@ -119,12 +119,12 @@ class User < ActiveRecord::Base end end end - + module PasswordMethods def bcrypt_password BCrypt::Password.new(bcrypt_password_hash) end - + def bcrypt_cookie_password_hash bcrypt_password_hash.slice(20, 100) end @@ -133,11 +133,11 @@ class User < ActiveRecord::Base self.password_hash = "" self.bcrypt_password_hash = User.bcrypt(password) end - + def encrypt_password_on_update return if password.blank? return if old_password.blank? - + if bcrypt_password == User.sha1(old_password) self.bcrypt_password_hash = User.bcrypt(password) return true @@ -159,18 +159,18 @@ class User < ActiveRecord::Base pass << rand(100).to_s update_column(:bcrypt_password_hash, User.bcrypt(pass)) - pass + pass end - + def reset_password_and_deliver_notice new_password = reset_password() Maintenance::User::PasswordResetMailer.confirmation(self, new_password).deliver end end - + module AuthenticationMethods extend ActiveSupport::Concern - + module ClassMethods def authenticate(name, pass) authenticate_hash(name, sha1(pass)) @@ -193,7 +193,7 @@ class User < ActiveRecord::Base nil end end - + def bcrypt(pass) BCrypt::Password.create(sha1(pass)) end @@ -203,19 +203,19 @@ class User < ActiveRecord::Base end end end - + module FavoriteMethods def favorites Favorite.where("user_id % 100 = #{id % 100} and user_id = #{id}").order("id desc") end - + def add_favorite!(post) return if Favorite.for_user(id).exists?(:user_id => id, :post_id => post.id) Favorite.create(:user_id => id, :post_id => post.id) increment!(:favorite_count) post.add_favorite!(self) end - + def remove_favorite!(post) return unless Favorite.for_user(id).exists?(:user_id => id, :post_id => post.id) Favorite.destroy_all(:user_id => id, :post_id => post.id) @@ -223,10 +223,10 @@ class User < ActiveRecord::Base post.remove_favorite!(self) end end - + module LevelMethods extend ActiveSupport::Concern - + module ClassMethods def level_hash return { @@ -241,68 +241,68 @@ class User < ActiveRecord::Base } end end - + def promote_to_admin_if_first_user return if Rails.env.test? - + if User.count == 0 self.level = Levels::ADMIN else self.level = Levels::MEMBER end end - + def role case level when Levels::MEMBER :member - + when Levels::PRIVILEGED :privileged - + when Levels::BUILDER :builder - + when Levels::CONTRIBUTOR :contributor - + when Levels::MODERATOR :moderator when Levels::JANITOR :janitor - + when Levels::ADMIN :admin end end - + def level_string(value = nil) case (value || level) when Levels::BLOCKED "Banned" - + when Levels::MEMBER "Member" - + when Levels::BUILDER "Builder" - + when Levels::PRIVILEGED "Gold" - + when Levels::PLATINUM "Platinum" - + when Levels::CONTRIBUTOR "Contributor" - + when Levels::JANITOR "Janitor" - + when Levels::MODERATOR "Moderator" - + when Levels::ADMIN "Admin" end @@ -315,55 +315,55 @@ class User < ActiveRecord::Base def is_member? true end - + def is_builder? level >= Levels::BUILDER end - + def is_privileged? level >= Levels::PRIVILEGED end - + def is_platinum? level >= Levels::PLATINUM end - + def is_contributor? level >= Levels::CONTRIBUTOR end - + def is_janitor? level >= Levels::JANITOR end - + def is_moderator? level >= Levels::MODERATOR end - + def is_mod? level >= Levels::MODERATOR end - + def is_admin? level >= Levels::ADMIN end - + def create_mod_action if level_changed? ModAction.create(:description => "#{name} level changed #{level_string(level_was)} -> #{level_string} by #{CurrentUser.name}") end end end - + module EmailMethods def is_verified? email_verification_key.blank? end - + def generate_email_verification_key self.email_verification_key = Digest::SHA1.hexdigest("#{Time.now.to_f}--#{name}--#{rand(1_000_000)}--") end - + def verify!(key) if email_verification_key == key self.update_column(:email_verification_key, nil) @@ -372,17 +372,17 @@ class User < ActiveRecord::Base end end end - + module BlacklistMethods def blacklisted_tag_array Tag.scan_query(blacklisted_tags) end - + def normalize_blacklisted_tags self.blacklisted_tags = blacklisted_tags.downcase if blacklisted_tags.present? end end - + module ForumMethods def has_forum_been_updated? return false unless is_privileged? @@ -392,7 +392,7 @@ class User < ActiveRecord::Base return newest_topic.updated_at > last_forum_read_at end end - + module LimitMethods def can_upload? if is_contributor? @@ -403,7 +403,7 @@ class User < ActiveRecord::Base upload_limit > 0 end end - + def upload_limited_reason if created_at > 1.week.ago "You cannot upload during your first week of registration" @@ -413,7 +413,7 @@ class User < ActiveRecord::Base nil end end - + def can_comment? if is_privileged? true @@ -423,33 +423,33 @@ class User < ActiveRecord::Base Comment.where("creator_id = ? and created_at > ?", id, 1.hour.ago).count < Danbooru.config.member_comment_limit end end - + def can_comment_vote? CommentVote.where("user_id = ? and created_at > ?", id, 1.hour.ago).count < 10 end - + def can_remove_from_pools? created_at <= 1.week.ago end - + def upload_limit deleted_count = Post.for_user(id).deleted.count pending_count = Post.for_user(id).pending.count approved_count = Post.where("is_flagged = false and is_pending = false and is_deleted = false and uploader_id = ?", id).count - + if base_upload_limit limit = base_upload_limit - pending_count else limit = 10 + (approved_count / 10) - (deleted_count / 4) - pending_count end - + if limit < 0 limit = 0 end - + limit end - + def tag_query_limit if is_platinum? Danbooru.config.base_tag_query_limit * 2 @@ -459,7 +459,7 @@ class User < ActiveRecord::Base 2 end end - + def favorite_limit if is_platinum? nil @@ -470,19 +470,19 @@ class User < ActiveRecord::Base end end end - + module ApiMethods def hidden_attributes super + [:password_hash, :bcrypt_password_hash, :email, :email_verification_key, :time_zone, :created_at, :updated_at, :receive_email_notifications, :last_logged_in_at, :last_forum_read_at, :has_mail, :default_image_size, :comment_threshold, :always_resize_images, :favorite_tags, :blacklisted_tags, :base_upload_limit, :recent_tags, :enable_privacy_mode, :enable_post_navigation, :new_post_navigation_layout] end - + def serializable_hash(options = {}) options ||= {} options[:except] ||= [] options[:except] += hidden_attributes super(options) end - + def to_xml(options = {}, &block) # to_xml ignores the serializable_hash method options ||= {} @@ -500,48 +500,48 @@ class User < ActiveRecord::Base }.to_json end end - + module SearchMethods def named(name) where("lower(name) = ?", name) end - + def name_matches(name) where("lower(name) like ? escape E'\\\\'", name.to_escaped_for_sql_like) end - + def admins where("is_admin = TRUE") end - + def with_email(email) - if email.blank? + if email.blank? where("FALSE") - else + else where("email = ?", email) end end - + def find_for_password_reset(name, email) - if email.blank? + if email.blank? where("FALSE") else where(["name = ? AND email = ?", name, email]) end end - + def search(params) q = scoped return q if params.blank? - + if params[:name].present? q = q.name_matches(params[:name].mb_chars.downcase) end - + if params[:name_matches].present? q = q.name_matches(params[:name_matches].mb_chars.downcase) end - + if params[:min_level].present? q = q.where("level >= ?", params[:min_level].to_i) end @@ -549,32 +549,32 @@ class User < ActiveRecord::Base if params[:level].present? q = q.where("level = ?", params[:level].to_i) end - + if params[:id].present? q = q.where("id = ?", params[:id].to_i) end - + case params[:order] when "name" q = q.order("name") - + when "post_upload_count" q = q.order("post_upload_count desc") - + when "note_count" q = q.order("note_update_count desc") - - when "post_update_count" + + when "post_update_count" q = q.order("post_update_count desc") - + else q = q.order("created_at desc") end - + q end end - + include BanMethods include NameMethods include PasswordMethods @@ -588,7 +588,7 @@ class User < ActiveRecord::Base include InvitationMethods include ApiMethods extend SearchMethods - + def initialize_default_image_size self.default_image_size = "large" end @@ -596,7 +596,7 @@ class User < ActiveRecord::Base def can_update?(object, foreign_key = :user_id) is_moderator? || is_admin? || object.__send__(foreign_key) == id end - + def dmail_count if has_mail? "(#{dmails.unread.count})" diff --git a/app/models/user_feedback.rb b/app/models/user_feedback.rb index cc3eb45cf..f758948e8 100644 --- a/app/models/user_feedback.rb +++ b/app/models/user_feedback.rb @@ -12,31 +12,31 @@ class UserFeedback < ActiveRecord::Base def positive where("category = ?", "positive") end - + def neutral where("category = ?", "neutral") end - + def negative where("category = ?", "negative") end - + def for_user(user_id) where("user_id = ?", user_id) end - + def search(params) q = scoped return q if params.blank? - + if params[:user_id].present? q = q.for_user(params[:user_id].to_i) end - + if params[:user_name].present? q = q.where("user_id = (select _.id from users _ where lower(_.name) = ?)", params[:user_name].downcase) end - + if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id].to_i) end @@ -44,34 +44,34 @@ class UserFeedback < ActiveRecord::Base if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + q end end - + extend SearchMethods - + def initialize_creator self.creator_id = CurrentUser.id end - + def user_name User.id_to_name(user_id) end - + def creator_name User.id_to_name(creator_id) end - + def user_name=(name) self.user_id = User.name_to_id(name) end - + def create_dmail body = %{#{creator_name} created a "#{category} record":/user_feedbacks?search[user_id]=#{user_id} for your account. #{body}} Dmail.create_split(:to_id => user_id, :title => "Your user record has been updated", :body => body) end - + def creator_is_privileged if !creator.is_privileged? errors[:creator] << "must be privileged" diff --git a/app/models/user_password_reset_nonce.rb b/app/models/user_password_reset_nonce.rb index d54b9c52e..74dba55c4 100644 --- a/app/models/user_password_reset_nonce.rb +++ b/app/models/user_password_reset_nonce.rb @@ -15,18 +15,18 @@ class UserPasswordResetNonce < ActiveRecord::Base def initialize_key self.key = SecureRandom.hex(16) end - + def validate_existence_of_email if !User.with_email(email).exists? errors[:email] << "is invalid" return false end end - + def reset_user! user.reset_password_and_deliver_notice end - + def user @user ||= User.with_email(email).first end diff --git a/app/models/wiki_page.rb b/app/models/wiki_page.rb index d20760dcd..40a6b2fc5 100644 --- a/app/models/wiki_page.rb +++ b/app/models/wiki_page.rb @@ -10,16 +10,16 @@ class WikiPage < ActiveRecord::Base has_one :tag, :foreign_key => "name", :primary_key => "title" has_one :artist, :foreign_key => "name", :primary_key => "title" has_many :versions, :class_name => "WikiPageVersion", :dependent => :destroy, :order => "wiki_page_versions.id ASC" - + module SearchMethods def titled(title) where("title = ?", title.downcase.tr(" ", "_")) end - + def recent order("updated_at DESC").limit(25) end - + def body_matches(query) where("body_index @@ plainto_tsquery(?)", query.to_escaped_for_tsquery_split) end @@ -35,15 +35,15 @@ class WikiPage < ActiveRecord::Base if params[:creator_id].present? q = q.where("creator_id = ?", params[:creator_id]) end - + if params[:body_matches].present? q = q.body_matches(params[:body_matches]) end - + if params[:creator_name].present? q = q.where("creator_id = (select _.id from users _ where lower(_.name) = ?)", params[:creator_name].downcase) end - + if params[:sort] == "time" || params[:sort] == "Date" q = q.order("updated_at desc") end @@ -51,7 +51,7 @@ class WikiPage < ActiveRecord::Base q end end - + module ApiMethods def serializable_hash(options = {}) options ||= {} @@ -64,7 +64,7 @@ class WikiPage < ActiveRecord::Base hash = super(options) hash end - + def to_xml(options = {}, &block) options ||= {} options[:procs] ||= [] @@ -72,27 +72,27 @@ class WikiPage < ActiveRecord::Base super(options, &block) end end - + extend SearchMethods include ApiMethods - + def self.find_title_and_id(title) titled(title).select("title, id").first end - + def validate_locker_is_janitor if is_locked_changed? && !CurrentUser.is_janitor? errors.add(:is_locked, "can be modified by janitors only") return false end end - + def revert_to(version) self.title = version.title self.body = version.body self.is_locked = version.is_locked end - + def revert_to!(version) revert_to(version) save! @@ -105,7 +105,7 @@ class WikiPage < ActiveRecord::Base def creator_name User.id_to_name(creator_id).tr("_", " ") end - + def category_name Tag.category_for(title) end @@ -113,7 +113,7 @@ class WikiPage < ActiveRecord::Base def pretty_title title.tr("_", " ") end - + def create_version if title_changed? || body_changed? || is_locked_changed? versions.create( @@ -125,19 +125,19 @@ class WikiPage < ActiveRecord::Base ) end end - + def initialize_creator self.creator_id = CurrentUser.user.id end - + def post_set @post_set ||= PostSets::WikiPage.new(title, 1, 4) end - + def presenter @presenter ||= WikiPagePresenter.new(self) end - + def tags body.scan(/\[\[(.+?)\]\]/).flatten.map do |match| if match =~ /^(.+?)\|(.+)/ diff --git a/app/models/wiki_page_version.rb b/app/models/wiki_page_version.rb index 003e61439..c39f1c258 100644 --- a/app/models/wiki_page_version.rb +++ b/app/models/wiki_page_version.rb @@ -6,25 +6,25 @@ class WikiPageVersion < ActiveRecord::Base def for_user(user_id) where("updater_id = ?", user_id) end - + def search(params) q = scoped return q if params.blank? - + if params[:updater_id].present? q = q.for_user(params[:updater_id].to_i) end - + if params[:wiki_page_id].present? q = q.where("wiki_page_id = ?", params[:wiki_page_id].to_i) end - + q end end - + extend SearchMethods - + def updater_name User.id_to_name(updater_id) end diff --git a/app/presenters/forum_topic_presenter.rb b/app/presenters/forum_topic_presenter.rb index a10593cbc..fd38877d5 100644 --- a/app/presenters/forum_topic_presenter.rb +++ b/app/presenters/forum_topic_presenter.rb @@ -1,6 +1,6 @@ class ForumTopicPresenter < Presenter attr_reader :forum_topic, :forum_posts - + def initialize(forum_topic, forum_posts) @forum_posts = forum_posts @forum_topic = forum_topic diff --git a/app/presenters/note_presenter.rb b/app/presenters/note_presenter.rb index 010c2524c..f30297982 100644 --- a/app/presenters/note_presenter.rb +++ b/app/presenters/note_presenter.rb @@ -2,8 +2,8 @@ class NotePresenter def initialize(note) @note = note end - + def formatted_body - note.body.gsub(/(.+?)<\/tn>/m, '

    \1

    ').gsub(/\n/, '
    ') + note.body.gsub(/(.+?)<\/tn>/m, '

    \1

    ').gsub(/\n/, '
    ') end end diff --git a/app/presenters/post_presenter.rb b/app/presenters/post_presenter.rb index dc51bc6b4..0a37a5c86 100644 --- a/app/presenters/post_presenter.rb +++ b/app/presenters/post_presenter.rb @@ -3,18 +3,18 @@ class PostPresenter < Presenter if post.is_deleted? && !CurrentUser.is_privileged? return "" end - + unless Danbooru.config.can_user_see_post?(CurrentUser.user, post) return "" end - + flags = [] flags << "pending" if post.is_pending? flags << "flagged" if post.is_flagged? flags << "deleted" if post.is_deleted? - + path = options[:path_prefix] || "/posts" - + html = %{
    } if options[:tags].present? tag_param = "?tags=#{CGI::escape(options[:tags])}" @@ -29,43 +29,43 @@ class PostPresenter < Presenter html << %{
    } html.html_safe end - + def initialize(post) @post = post end - + def preview_html PostPresenter.preview(@post) end - + def humanized_tag_string @post.tag_string.split(/ /).slice(0, 25).join(", ").tr("_", " ") end - + def humanized_essential_tag_string string = [] - + if @post.character_tags.any? string << @post.character_tags.slice(0, 5).to_sentence end - + if @post.copyright_tags.any? string << "from" string << @post.copyright_tags.slice(0, 5).to_sentence end - + if @post.artist_tags.any? string << "drawn by" string << @post.artist_tags.to_sentence end - + string.join(" ").tr("_", " ") end - + def image_html(template) return template.content_tag("p", "This image was deleted.") if @post.is_deleted? && !CurrentUser.user.is_privileged? return template.content_tag("p", "You need a privileged account to see this image.") if !Danbooru.config.can_user_see_post?(CurrentUser.user, @post) - + if @post.is_flash? template.render("posts/partials/show/flash", :post => @post) elsif !@post.is_image? @@ -74,21 +74,21 @@ class PostPresenter < Presenter template.render("posts/partials/show/image", :post => @post) end end - + def tag_list_html(template, options = {}) @tag_set_presenter ||= TagSetPresenter.new(@post.tag_array) @tag_set_presenter.tag_list_html(template, options.merge(:show_extra_links => CurrentUser.user.is_privileged?)) end - + def split_tag_list_html(template, options = {}) @tag_set_presenter ||= TagSetPresenter.new(@post.tag_array) @tag_set_presenter.split_tag_list_html(template, options.merge(:show_extra_links => CurrentUser.user.is_privileged?)) end - + def has_nav_links?(template) (CurrentUser.user.enable_sequential_post_navigation && template.params[:tags].present? && template.params[:tags] !~ /order:/) || @post.pools.active.any? end - + def post_footer_for_pool_html(template) if template.params[:pool_id] pool = Pool.where(:id => template.params[:pool_id]).first @@ -99,15 +99,15 @@ class PostPresenter < Presenter nil end end - + def pool_html(template) html = ["
      "] - + if template.params[:pool_id].present? pool = Pool.where(:id => template.params[:pool_id]).first return if pool.nil? html += pool_link_html(template, pool, :include_rel => true) - + @post.pools.active.where("id <> ?", template.params[:pool_id]).each do |other_pool| html += pool_link_html(template, other_pool) end @@ -122,15 +122,15 @@ class PostPresenter < Presenter end end end - + html << "
    " html.join("\n").html_safe end - + def pool_link_html(template, pool, options = {}) pool_html = ["
  • "] match_found = false - + if options[:include_rel] prev_rel = "prev" next_rel = "next" @@ -140,14 +140,14 @@ class PostPresenter < Presenter next_rel = nil klass = "" end - + if pool.neighbors(@post).previous pool_html << template.link_to("«prev".html_safe, template.post_path(pool.neighbors(@post).previous, :pool_id => pool.id), :rel => prev_rel, :class => "#{klass} prev") match_found = true else pool_html << '«prev' end - + pool_html << ' ' pool_html << template.link_to("Pool: #{pool.pretty_name}", template.pool_path(pool)) pool_html << ' ' @@ -158,7 +158,7 @@ class PostPresenter < Presenter else pool_html << 'next»' end - + pool_html << "
  • " pool_html end diff --git a/app/presenters/post_set_presenters/base.rb b/app/presenters/post_set_presenters/base.rb index 6c117d28a..7a726bb2f 100644 --- a/app/presenters/post_set_presenters/base.rb +++ b/app/presenters/post_set_presenters/base.rb @@ -3,7 +3,7 @@ module PostSetPresenters def posts raise NotImplementedError end - + def post_previews_html(template) html = "" diff --git a/app/presenters/post_set_presenters/favorite.rb b/app/presenters/post_set_presenters/favorite.rb index 312414057..f719a80b9 100644 --- a/app/presenters/post_set_presenters/favorite.rb +++ b/app/presenters/post_set_presenters/favorite.rb @@ -11,11 +11,11 @@ module PostSetPresenters ).map {|x| x[0]} ) end - + def tag_list_html(template) tag_set_presenter.tag_list_html(template) end - + def posts @posts ||= favorite_set.posts end diff --git a/app/presenters/post_set_presenters/pool.rb b/app/presenters/post_set_presenters/pool.rb index 9157bb15d..4bba321ed 100644 --- a/app/presenters/post_set_presenters/pool.rb +++ b/app/presenters/post_set_presenters/pool.rb @@ -11,11 +11,11 @@ module PostSetPresenters ).map {|x| x[0]} ) end - + def tag_list_html(template) tag_set_presenter.tag_list_html(template) end - + def post_previews_html(template) html = "" diff --git a/app/presenters/post_set_presenters/popular.rb b/app/presenters/post_set_presenters/popular.rb index b474349e9..db95f8c7a 100644 --- a/app/presenters/post_set_presenters/popular.rb +++ b/app/presenters/post_set_presenters/popular.rb @@ -2,7 +2,7 @@ module PostSetPresenters class Popular < Base attr_accessor :post_set, :tag_set_presenter delegate :posts, :date, :min_date, :max_date, :to => :post_set - + def initialize(post_set) @post_set = post_set end @@ -10,42 +10,42 @@ module PostSetPresenters def prev_day date - 1.day end - + def next_day date + 1.day end - + def prev_week date - 7.days end - + def next_week date + 7.days end - + def prev_month 1.month.ago(date) end - + def next_month 1.month.since(date) end - + def link_rel_for_scale?(template, scale) (template.params[:scale].blank? && scale == "day") || template.params[:scale].to_s.include?(scale) end - + def next_date_for_scale(scale) case scale when "Day" next_day - + when "Week" next_week - + when "Month" next_month - + else nil end @@ -55,41 +55,41 @@ module PostSetPresenters case scale when "Day" prev_day - + when "Week" prev_week - + when "Month" prev_month - + else nil end end - + def nav_links_for_scale(template, scale) html = [] html << '' html << template.link_to( - "«prev".html_safe, + "«prev".html_safe, template.popular_explore_posts_path( - :date => prev_date_for_scale(scale), + :date => prev_date_for_scale(scale), :scale => scale.downcase ), :rel => (link_rel_for_scale?(template, scale.downcase) ? "prev" : nil) ) html << template.link_to( - scale, + scale, template.popular_explore_posts_path( - :date => date, + :date => date, :scale => scale.downcase - ), + ), :class => "desc" ) html << template.link_to( - "next»".html_safe, + "next»".html_safe, template.popular_explore_posts_path( - :date => next_date_for_scale(scale), + :date => next_date_for_scale(scale), :scale => scale.downcase ), :rel => (link_rel_for_scale?(template, scale.downcase) ? "next" : nil) @@ -97,7 +97,7 @@ module PostSetPresenters html << '' html.join("\n").html_safe end - + def nav_links(template) html = [] html << '' html.join("\n").html_safe end - + def range_text if min_date == max_date date.strftime("%B %d, %Y") diff --git a/app/presenters/post_set_presenters/post.rb b/app/presenters/post_set_presenters/post.rb index 4b64a70e4..54a516917 100644 --- a/app/presenters/post_set_presenters/post.rb +++ b/app/presenters/post_set_presenters/post.rb @@ -7,7 +7,7 @@ module PostSetPresenters @post_set = post_set @tag_set_presenter = TagSetPresenter.new(related_tags) end - + def related_tags if post_set.is_pattern_search? pattern_tags @@ -21,28 +21,28 @@ module PostSetPresenters related_tags_for_group end end - + def popular_tags n = 1 results = [] - + while results.empty? && n < 256 query = n.days.ago.strftime("date:>%Y-%m-%d") results = RelatedTagCalculator.calculate_from_sample_to_array(query).map(&:first) n *= 2 end - + results end - + def pattern_tags Tag.name_matches(post_set.tag_string).all(:select => "name", :limit => Danbooru.config.tag_query_limit, :order => "post_count DESC").map(&:name) end - + def related_tags_for_group RelatedTagCalculator.calculate_from_sample_to_array(post_set.tag_string).map(&:first) end - + def related_tags_for_single tag = Tag.find_by_name(post_set.tag_string) @@ -53,7 +53,7 @@ module PostSetPresenters tag.related_tag_array.map(&:first) end end - + def tag_list_html(template) tag_set_presenter.tag_list_html(template) end diff --git a/app/presenters/post_set_presenters/wiki_page.rb b/app/presenters/post_set_presenters/wiki_page.rb index 1aabc7ac1..7d057b7c8 100644 --- a/app/presenters/post_set_presenters/wiki_page.rb +++ b/app/presenters/post_set_presenters/wiki_page.rb @@ -5,7 +5,7 @@ module PostSetPresenters rescue ActiveRecord::StatementInvalid, PGError [] end - + def post_previews_html(template) result = super(template) if result =~ /Nobody here but us chickens/ diff --git a/app/presenters/post_version_presenter.rb b/app/presenters/post_version_presenter.rb index b7b875e12..714da7a5e 100644 --- a/app/presenters/post_version_presenter.rb +++ b/app/presenters/post_version_presenter.rb @@ -1,10 +1,10 @@ class PostVersionPresenter < Presenter attr_reader :post_version - + def initialize(post_version) @post_version = post_version end - + def changes html = [] html << post_version.tag_array @@ -13,7 +13,7 @@ class PostVersionPresenter < Presenter html << "parent:#{post_version.parent_id}" if post_version.parent_id html.join(" ").html_safe end - + def updater_name User.id_to_name(post_version.updater_id) end diff --git a/app/presenters/presenter.rb b/app/presenters/presenter.rb index 20dfdd2ed..19497050d 100644 --- a/app/presenters/presenter.rb +++ b/app/presenters/presenter.rb @@ -2,15 +2,15 @@ class Presenter def self.h(s) CGI.escapeHTML(s) end - + def self.u(s) URI.escape(s) end - + def h(s) CGI.escapeHTML(s) end - + def u(s) CGI::escape(s) end diff --git a/app/presenters/tag_set_presenter.rb b/app/presenters/tag_set_presenter.rb index 13ee6510c..3d3cdc5c8 100644 --- a/app/presenters/tag_set_presenter.rb +++ b/app/presenters/tag_set_presenter.rb @@ -1,6 +1,6 @@ =begin rdoc A tag set represents a set of tags that are displayed together. - This class makes it easy to fetch the categories for all the + This class makes it easy to fetch the categories for all the tags in one call instead of fetching them sequentially. =end @@ -8,7 +8,7 @@ class TagSetPresenter < Presenter def initialize(tags) @tags = tags end - + def tag_list_html(template, options = {}) html = "" if @tags.present? @@ -21,10 +21,10 @@ class TagSetPresenter < Presenter html.html_safe end - + def split_tag_list_html(template, options = {}) html = "" - + if copyright_tags.any? html << '

    Copyrights

    ' html << "" end - + if character_tags.any? html << '

    Characters

    ' html << "" end - + if artist_tags.any? html << '

    Artist

    ' html << "" end - + if general_tags.any? html << '

    Tags

    ' html << "