]> git.openstreetmap.org Git - rails.git/blob - app/models/user.rb
08325d5b9e0e58bb69c912bad44833bad26d8847
[rails.git] / app / models / user.rb
1 class User < ActiveRecord::Base
2   require 'xml/libxml'
3
4   has_many :traces, :conditions => { :visible => true }
5   has_many :diary_entries, :order => 'created_at DESC'
6   has_many :diary_comments, :order => 'created_at DESC'
7   has_many :messages, :foreign_key => :to_user_id, :conditions => { :to_user_visible => true }, :order => 'sent_on DESC'
8   has_many :new_messages, :class_name => "Message", :foreign_key => :to_user_id, :conditions => { :to_user_visible => true, :message_read => false }, :order => 'sent_on DESC'
9   has_many :sent_messages, :class_name => "Message", :foreign_key => :from_user_id, :conditions => { :from_user_visible => true }, :order => 'sent_on DESC'
10   has_many :friends, :include => :befriendee, :conditions => "users.status IN ('active', 'confirmed')"
11   has_many :tokens, :class_name => "UserToken"
12   has_many :preferences, :class_name => "UserPreference"
13   has_many :changesets, :order => 'created_at DESC'
14
15   has_many :client_applications
16   has_many :oauth_tokens, :class_name => "OauthToken", :order => "authorized_at desc", :include => [:client_application]
17
18   has_many :active_blocks, :class_name => "UserBlock", :conditions => proc { [ "user_blocks.ends_at > :ends_at or user_blocks.needs_view", { :ends_at => Time.now.getutc } ] }
19   has_many :roles, :class_name => "UserRole"
20
21   scope :visible, where(:status => ["pending", "active", "confirmed"])
22   scope :active, where(:status => ["active", "confirmed"])
23
24   validates_presence_of :email, :display_name
25   validates_confirmation_of :email#, :message => ' addresses must match'
26   validates_confirmation_of :pass_crypt#, :message => ' must match the confirmation password'
27   validates_uniqueness_of :display_name, :allow_nil => true, :case_sensitive => false, :if => Proc.new { |u| u.display_name_changed? }
28   validates_uniqueness_of :email, :case_sensitive => false, :if => Proc.new { |u| u.email_changed? }
29   validates_uniqueness_of :openid_url, :allow_nil => true
30   validates_length_of :pass_crypt, :within => 8..255
31   validates_length_of :display_name, :within => 3..255, :allow_nil => true
32   validates_email_format_of :email, :if => Proc.new { |u| u.email_changed? }
33   validates_email_format_of :new_email, :allow_blank => true, :if => Proc.new { |u| u.new_email_changed? }
34   validates_format_of :display_name, :with => /^[^\/;.,?]*$/, :if => Proc.new { |u| u.display_name_changed? }
35   validates_format_of :display_name, :with => /^\S/, :message => "has leading whitespace", :if => Proc.new { |u| u.display_name_changed? }
36   validates_format_of :display_name, :with => /\S$/, :message => "has trailing whitespace", :if => Proc.new { |u| u.display_name_changed? }
37   validates_numericality_of :home_lat, :allow_nil => true
38   validates_numericality_of :home_lon, :allow_nil => true
39   validates_numericality_of :home_zoom, :only_integer => true, :allow_nil => true
40   validates_inclusion_of :preferred_editor, :in => Editors::ALL_EDITORS, :allow_nil => true
41
42   after_initialize :set_creation_time
43   before_save :encrypt_password
44
45   file_column :image, :magick => { :geometry => "100x100>" }
46
47   def self.authenticate(options)
48     if options[:username] and options[:password]
49       user = where("email = ? OR display_name = ?", options[:username], options[:username]).first
50
51       if user.nil?
52         users = where("LOWER(email) = LOWER(?) OR LOWER(display_name) = LOWER(?)", options[:username], options[:username])
53
54         if users.count == 1
55           user = users.first
56         end
57       end
58
59       user = nil if user and user.pass_crypt != OSM::encrypt_password(options[:password], user.pass_salt)
60     elsif options[:token]
61       token = UserToken.find_by_token(options[:token])
62       user = token.user if token
63     end
64
65     if user and
66       ( user.status == "deleted" or
67         ( user.status == "pending" and not options[:pending] ) or
68         ( user.status == "suspended" and not options[:suspended] ) )
69       user = nil
70     end
71
72     token.update_attribute(:expiry, 1.week.from_now) if token and user
73
74     return user
75   end 
76
77   def to_xml
78     doc = OSM::API.new.get_xml_doc
79     doc.root << to_xml_node()
80     return doc
81   end
82
83   def to_xml_node
84     el1 = XML::Node.new 'user'
85     el1['display_name'] = self.display_name.to_s
86     el1['account_created'] = self.creation_time.xmlschema
87     if self.home_lat and self.home_lon
88       home = XML::Node.new 'home'
89       home['lat'] = self.home_lat.to_s
90       home['lon'] = self.home_lon.to_s
91       home['zoom'] = self.home_zoom.to_s
92       el1 << home
93     end
94     return el1
95   end
96
97   def languages
98     attribute_present?(:languages) ? read_attribute(:languages).split(/ *, */) : []
99   end
100
101   def languages=(languages)
102     write_attribute(:languages, languages.join(","))
103   end
104
105   def preferred_language
106     languages.find { |l| Language.exists?(:code => l) }
107   end
108
109   def preferred_language_from(array)
110     (languages & array.collect { |i| i.to_s }).first
111   end
112
113   def nearby(radius = NEARBY_RADIUS, num = NEARBY_USERS)
114     if self.home_lon and self.home_lat 
115       gc = OSM::GreatCircle.new(self.home_lat, self.home_lon)
116       bounds = gc.bounds(radius)
117       sql_for_distance = gc.sql_for_distance("home_lat", "home_lon")
118       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)
119     else
120       nearby = []
121     end
122     return nearby
123   end
124
125   def distance(nearby_user)
126     return OSM::GreatCircle.new(self.home_lat, self.home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
127   end
128
129   def is_friends_with?(new_friend)
130     res = false
131     @new_friend = new_friend
132     self.friends.each do |friend|
133       if friend.friend_user_id == @new_friend.id
134         return true
135       end
136     end
137     return false
138   end
139
140   ##
141   # returns true if a user is visible
142   def visible?
143     ["pending","active","confirmed"].include? self.status
144   end
145
146   ##
147   # returns true if a user is active
148   def active?
149     ["active","confirmed"].include? self.status
150   end
151
152   ##
153   # returns true if the user has the moderator role, false otherwise
154   def moderator?
155     has_role? 'moderator'
156   end
157
158   ##
159   # returns true if the user has the administrator role, false otherwise
160   def administrator?
161     has_role? 'administrator'
162   end
163
164   ##
165   # returns true if the user has the requested role
166   def has_role?(role)
167     roles.any? { |r| r.role == role }
168   end
169
170   ##
171   # returns the first active block which would require users to view 
172   # a message, or nil if there are none.
173   def blocked_on_view
174     active_blocks.detect { |b| b.needs_view? }
175   end
176
177   ##
178   # delete a user - leave the account but purge most personal data
179   def delete
180     self.display_name = "user_#{self.id}"
181     self.description = ""
182     self.home_lat = nil
183     self.home_lon = nil
184     self.image = nil
185     self.email_valid = false
186     self.new_email = nil
187     self.status = "deleted"
188     self.save
189   end
190
191   ##
192   # return a spam score for a user
193   def spam_score
194     changeset_score = self.changesets.limit(10).length * 50
195     trace_score = self.traces.limit(10).length * 50
196     diary_entry_score = self.diary_entries.inject(0) { |s,e| s += OSM.spam_score(e.body) }
197     diary_comment_score = self.diary_comments.inject(0) { |s,e| s += OSM.spam_score(e.body) }
198
199     score = OSM.spam_score(self.description) * 2
200     score += diary_entry_score / self.diary_entries.length if self.diary_entries.length > 0
201     score += diary_comment_score / self.diary_comments.length if self.diary_comments.length > 0
202     score -= changeset_score
203     score -= trace_score
204
205     return score.to_i
206   end
207
208   ##
209   # return an oauth access token for a specified application
210   def access_token(application_key)
211     return ClientApplication.find_by_key(application_key).access_token_for_user(self)
212   end
213
214 private
215
216   def set_creation_time
217     self.creation_time = Time.now.getutc unless self.attribute_present?(:creation_time)
218   end
219
220   def encrypt_password
221     if pass_crypt_confirmation
222       self.pass_salt = OSM::make_token(8)
223       self.pass_crypt = OSM::encrypt_password(pass_crypt, pass_salt)
224     end
225   end
226 end