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