1 class User < ActiveRecord::Base
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
22 has_many :client_applications
23 has_many :oauth_tokens, -> { order(:authorized_at => :desc).preload(:client_application) }, :class_name => "OauthToken"
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
29 has_many :roles, :class_name => "UserRole"
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
37 scope :visible, -> { where(:status => %w[pending active confirmed]) }
38 scope :active, -> { where(:status => %w[active confirmed]) }
39 scope :identifiable, -> { where(:data_public => true) }
41 has_attached_file :image,
42 :default_url => "/assets/:class/:attachment/:style.png",
43 :styles => { :large => "100x100>", :small => "50x50>" }
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 }
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? }
69 after_initialize :set_defaults
70 before_save :encrypt_password
71 after_save :spam_check
73 def self.authenticate(options)
74 if options[:username] && options[:password]
75 user = find_by("email = ? OR display_name = ?", options[:username], options[:username])
78 users = where("LOWER(email) = LOWER(?) OR LOWER(display_name) = LOWER(?)", options[:username], options[:username])
80 user = users.first if users.count == 1
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])
92 token = UserToken.find_by(:token => options[:token])
93 user = token.user if token
97 (user.status == "deleted" ||
98 (user.status == "pending" && !options[:pending]) ||
99 (user.status == "suspended" && !options[:suspended]))
103 token.update(:expiry => 1.week.from_now) if token && user
109 doc = OSM::API.new.get_xml_doc
110 doc.root << 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
129 RichText.new(self[:description_format], self[:description])
133 attribute_present?(:languages) ? self[:languages].split(/ *[, ] */) : []
136 def languages=(languages)
137 self[:languages] = languages.join(",")
140 def preferred_language
141 languages.find { |l| Language.exists?(:code => l) }
144 def preferred_languages
145 @locales ||= Locale.list(languages)
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)
159 def distance(nearby_user)
160 OSM::GreatCircle.new(home_lat, home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
163 def is_friends_with?(new_friend)
164 friends.where(:friend_user_id => new_friend.id).exists?
168 # returns true if a user is visible
170 %w[pending active confirmed].include? status
174 # returns true if a user is active
176 %w[active confirmed].include? status
180 # returns true if the user has the moderator role, false otherwise
182 has_role? "moderator"
186 # returns true if the user has the administrator role, false otherwise
188 has_role? "administrator"
192 # returns true if the user has the requested role
194 roles.any? { |r| r.role == role }
198 # returns the first active block which would require users to view
199 # a message, or nil if there are none.
201 blocks.active.detect(&:needs_view?)
205 # delete a user - leave the account but purge most personal data
207 self.display_name = "user_#{id}"
208 self.description = ""
212 self.email_valid = false
214 self.auth_provider = nil
216 self.status = "deleted"
221 # return a spam score for a user
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 }
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
239 # perform a spam check on a user
241 if status == "active" && spam_score > SPAM_THRESHOLD
242 update(:status => "suspended")
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)
255 self.creation_time = Time.now.getutc unless attribute_present?(:creation_time)
259 if pass_crypt_confirmation
260 self.pass_crypt, self.pass_salt = PasswordHash.create(pass_crypt)
261 self.pass_crypt_confirmation = nil