]> git.openstreetmap.org Git - rails.git/blob - app/models/user.rb
Ensure report details are not blank.
[rails.git] / app / models / user.rb
1 class User < ActiveRecord::Base
2   require "xml/libxml"
3
4   has_many :traces, -> { where(:visible => true) }
5   has_many :diary_entries, -> { order(:created_at => :desc) }
6   has_many :diary_comments, -> { order(:created_at => :desc) }
7   has_many :diary_entry_subscriptions, :class_name => "DiaryEntrySubscription"
8   has_many :diary_subscriptions, :through => :diary_entry_subscriptions, :source => :diary_entry
9   has_many :messages, -> { where(:to_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :foreign_key => :to_user_id
10   has_many :new_messages, -> { where(:to_user_visible => true, :message_read => false).order(:sent_on => :desc) }, :class_name => "Message", :foreign_key => :to_user_id
11   has_many :sent_messages, -> { where(:from_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :class_name => "Message", :foreign_key => :from_user_id
12   has_many :friends, -> { joins(:befriendee).where(:users => { :status => %w[active confirmed] }) }
13   has_many :friend_users, :through => :friends, :source => :befriendee
14   has_many :tokens, :class_name => "UserToken"
15   has_many :preferences, :class_name => "UserPreference"
16   has_many :changesets, -> { order(:created_at => :desc) }
17   has_many :changeset_comments, :foreign_key => :author_id
18   has_and_belongs_to_many :changeset_subscriptions, :class_name => "Changeset", :join_table => "changesets_subscribers", :foreign_key => "subscriber_id"
19   has_many :note_comments, :foreign_key => :author_id
20   has_many :notes, :through => :note_comments
21
22   has_many :client_applications
23   has_many :oauth_tokens, -> { order(:authorized_at => :desc).preload(:client_application) }, :class_name => "OauthToken"
24
25   has_many :blocks, :class_name => "UserBlock"
26   has_many :blocks_created, :class_name => "UserBlock", :foreign_key => :creator_id
27   has_many :blocks_revoked, :class_name => "UserBlock", :foreign_key => :revoker_id
28
29   has_many :roles, :class_name => "UserRole"
30
31   has_many :issues, :class_name => "Issue", :foreign_key => :reported_user_id
32   has_one :issue, :class_name => "Issue", :foreign_key => :updated_by
33   has_many :issue_comments
34
35   has_many :reports
36
37   scope :visible, -> { where(:status => %w[pending active confirmed]) }
38   scope :active, -> { where(:status => %w[active confirmed]) }
39   scope :identifiable, -> { where(:data_public => true) }
40
41   has_attached_file :image,
42                     :default_url => "/assets/:class/:attachment/:style.png",
43                     :styles => { :large => "100x100>", :small => "50x50>" }
44
45   validates :display_name, :presence => true, :allow_nil => true, :length => 3..255,
46                            :exclusion => %w[new terms save confirm confirm-email go_public reset-password forgot-password suspended]
47   validates :display_name, :if => proc { |u| u.display_name_changed? },
48                            :uniqueness => { :case_sensitive => false }
49   validates :display_name, :if => proc { |u| u.display_name_changed? },
50                            :format => { :with => %r{\A[^\x00-\x1f\x7f\ufffe\uffff/;.,?%#]*\z} }
51   validates :display_name, :if => proc { |u| u.display_name_changed? },
52                            :format => { :with => /\A\S/, :message => "has leading whitespace" }
53   validates :display_name, :if => proc { |u| u.display_name_changed? },
54                            :format => { :with => /\S\z/, :message => "has trailing whitespace" }
55   validates :email, :presence => true, :confirmation => true
56   validates :email, :if => proc { |u| u.email_changed? },
57                     :uniqueness => { :case_sensitive => false }
58   validates :pass_crypt, :confirmation => true, :length => 8..255
59   validates :home_lat, :home_lon, :allow_nil => true, :numericality => true
60   validates :home_zoom, :allow_nil => true, :numericality => { :only_integer => true }
61   validates :preferred_editor, :inclusion => Editors::ALL_EDITORS, :allow_nil => true
62   validates :image, :attachment_content_type => { :content_type => %r{\Aimage/.*\Z} }
63   validates :auth_uid, :unless => proc { |u| u.auth_provider.nil? },
64                        :uniqueness => { :scope => :auth_provider }
65
66   validates_email_format_of :email, :if => proc { |u| u.email_changed? }
67   validates_email_format_of :new_email, :allow_blank => true, :if => proc { |u| u.new_email_changed? }
68
69   after_initialize :set_defaults
70   before_save :encrypt_password
71   after_save :spam_check
72
73   def self.authenticate(options)
74     if options[:username] && options[:password]
75       user = find_by("email = ? OR display_name = ?", options[:username], options[:username])
76
77       if user.nil?
78         users = where("LOWER(email) = LOWER(?) OR LOWER(display_name) = LOWER(?)", options[:username], options[:username])
79
80         user = users.first if users.count == 1
81       end
82
83       if user && PasswordHash.check(user.pass_crypt, user.pass_salt, options[:password])
84         if PasswordHash.upgrade?(user.pass_crypt, user.pass_salt)
85           user.pass_crypt, user.pass_salt = PasswordHash.create(options[:password])
86           user.save
87         end
88       else
89         user = nil
90       end
91     elsif options[:token]
92       token = UserToken.find_by(:token => options[:token])
93       user = token.user if token
94     end
95
96     if user &&
97        (user.status == "deleted" ||
98          (user.status == "pending" && !options[:pending]) ||
99          (user.status == "suspended" && !options[:suspended]))
100       user = nil
101     end
102
103     token.update(:expiry => 1.week.from_now) if token && user
104
105     user
106   end
107
108   def to_xml
109     doc = OSM::API.new.get_xml_doc
110     doc.root << to_xml_node
111     doc
112   end
113
114   def to_xml_node
115     el1 = XML::Node.new "user"
116     el1["display_name"] = display_name.to_s
117     el1["account_created"] = creation_time.xmlschema
118     if home_lat && home_lon
119       home = XML::Node.new "home"
120       home["lat"] = home_lat.to_s
121       home["lon"] = home_lon.to_s
122       home["zoom"] = home_zoom.to_s
123       el1 << home
124     end
125     el1
126   end
127
128   def description
129     RichText.new(self[:description_format], self[:description])
130   end
131
132   def languages
133     attribute_present?(:languages) ? self[:languages].split(/ *[, ] */) : []
134   end
135
136   def languages=(languages)
137     self[:languages] = languages.join(",")
138   end
139
140   def preferred_language
141     languages.find { |l| Language.exists?(:code => l) }
142   end
143
144   def preferred_languages
145     @locales ||= Locale.list(languages)
146   end
147
148   def nearby(radius = NEARBY_RADIUS, num = NEARBY_USERS)
149     if home_lon && home_lat
150       gc = OSM::GreatCircle.new(home_lat, home_lon)
151       sql_for_distance = gc.sql_for_distance("home_lat", "home_lon")
152       nearby = User.where("id != ? AND status IN (\'active\', \'confirmed\') AND data_public = ? AND #{sql_for_distance} <= ?", id, true, radius).order(sql_for_distance).limit(num)
153     else
154       nearby = []
155     end
156     nearby
157   end
158
159   def distance(nearby_user)
160     OSM::GreatCircle.new(home_lat, home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
161   end
162
163   def is_friends_with?(new_friend)
164     friends.where(:friend_user_id => new_friend.id).exists?
165   end
166
167   ##
168   # returns true if a user is visible
169   def visible?
170     %w[pending active confirmed].include? status
171   end
172
173   ##
174   # returns true if a user is active
175   def active?
176     %w[active confirmed].include? status
177   end
178
179   ##
180   # returns true if the user has the moderator role, false otherwise
181   def moderator?
182     has_role? "moderator"
183   end
184
185   ##
186   # returns true if the user has the administrator role, false otherwise
187   def administrator?
188     has_role? "administrator"
189   end
190
191   ##
192   # returns true if the user has the requested role
193   def has_role?(role)
194     roles.any? { |r| r.role == role }
195   end
196
197   ##
198   # returns the first active block which would require users to view
199   # a message, or nil if there are none.
200   def blocked_on_view
201     blocks.active.detect(&:needs_view?)
202   end
203
204   ##
205   # delete a user - leave the account but purge most personal data
206   def delete
207     self.display_name = "user_#{id}"
208     self.description = ""
209     self.home_lat = nil
210     self.home_lon = nil
211     self.image = nil
212     self.email_valid = false
213     self.new_email = nil
214     self.auth_provider = nil
215     self.auth_uid = nil
216     self.status = "deleted"
217     save
218   end
219
220   ##
221   # return a spam score for a user
222   def spam_score
223     changeset_score = changesets.size * 50
224     trace_score = traces.size * 50
225     diary_entry_score = diary_entries.inject(0) { |acc, elem| acc + elem.body.spam_score }
226     diary_comment_score = diary_comments.inject(0) { |acc, elem| acc + elem.body.spam_score }
227
228     score = description.spam_score / 4.0
229     score += diary_entries.where("created_at > ?", 1.day.ago).count * 10
230     score += diary_entry_score / diary_entries.length unless diary_entries.empty?
231     score += diary_comment_score / diary_comments.length unless diary_comments.empty?
232     score -= changeset_score
233     score -= trace_score
234
235     score.to_i
236   end
237
238   ##
239   # perform a spam check on a user
240   def spam_check
241     if status == "active" && spam_score > SPAM_THRESHOLD
242       update(:status => "suspended")
243     end
244   end
245
246   ##
247   # return an oauth access token for a specified application
248   def access_token(application_key)
249     ClientApplication.find_by(:key => application_key).access_token_for_user(self)
250   end
251
252   private
253
254   def set_defaults
255     self.creation_time = Time.now.getutc unless attribute_present?(:creation_time)
256   end
257
258   def encrypt_password
259     if pass_crypt_confirmation
260       self.pass_crypt, self.pass_salt = PasswordHash.create(pass_crypt)
261       self.pass_crypt_confirmation = nil
262     end
263   end
264 end