]> git.openstreetmap.org Git - rails.git/blob - app/models/user_block.rb
Merge remote-tracking branch 'upstream/pull/1707'
[rails.git] / app / models / user_block.rb
1 # == Schema Information
2 #
3 # Table name: user_blocks
4 #
5 #  id            :integer          not null, primary key
6 #  user_id       :integer          not null
7 #  creator_id    :integer          not null
8 #  reason        :text             not null
9 #  ends_at       :datetime         not null
10 #  needs_view    :boolean          default(FALSE), not null
11 #  revoker_id    :integer
12 #  created_at    :datetime
13 #  updated_at    :datetime
14 #  reason_format :enum             default("markdown"), not null
15 #
16 # Indexes
17 #
18 #  index_user_blocks_on_user_id  (user_id)
19 #
20 # Foreign Keys
21 #
22 #  user_blocks_moderator_id_fkey  (creator_id => users.id)
23 #  user_blocks_revoker_id_fkey    (revoker_id => users.id)
24 #  user_blocks_user_id_fkey       (user_id => users.id)
25 #
26
27 class UserBlock < ActiveRecord::Base
28   validate :moderator_permissions
29
30   belongs_to :user, :class_name => "User", :foreign_key => :user_id
31   belongs_to :creator, :class_name => "User", :foreign_key => :creator_id
32   belongs_to :revoker, :class_name => "User", :foreign_key => :revoker_id
33
34   PERIODS = USER_BLOCK_PERIODS
35
36   ##
37   # scope to match active blocks
38   def self.active
39     where("needs_view or ends_at > ?", Time.now.getutc)
40   end
41
42   ##
43   # return a renderable version of the reason text.
44   def reason
45     RichText.new(self[:reason_format], self[:reason])
46   end
47
48   ##
49   # returns true if the block is currently active (i.e: the user can't
50   # use the API).
51   def active?
52     needs_view || ends_at > Time.now.getutc
53   end
54
55   ##
56   # returns true if the block is a "zero hour" block
57   def zero_hour?
58     # if the times differ more than 1 minute we probably have more important issues
59     needs_view && (ends_at.to_i - updated_at.to_i) < 60
60   end
61
62   ##
63   # revokes the block, allowing the user to use the API again. the argument
64   # is the user object who is revoking the ban.
65   def revoke!(revoker)
66     update_attributes(
67       :ends_at => Time.now.getutc,
68       :revoker_id => revoker.id,
69       :needs_view => false
70     )
71   end
72
73   private
74
75   ##
76   # validate that only moderators are allowed to change the
77   # block. this should be caught and dealt with in the controller,
78   # but i've also included it here just in case.
79   def moderator_permissions
80     errors.add(:base, I18n.t("user_block.model.non_moderator_update")) if creator_id_changed? && !creator.moderator?
81     errors.add(:base, I18n.t("user_block.model.non_moderator_revoke")) unless revoker_id.nil? || revoker.moderator?
82   end
83 end