1 # The OSM module provides support functions for OSM.
5 require 'rexml/parsers/sax2parser'
12 # The base class for API Errors.
13 class APIError < RuntimeError
15 :internal_server_error
23 # Raised when an API object is not found.
24 class APINotFoundError < APIError
34 # Raised when a precondition to an API action fails sanity check.
35 class APIPreconditionFailedError < APIError
36 def initialize(message = "")
45 "Precondition failed: #{@message}"
49 # Raised when to delete an already-deleted object.
50 class APIAlreadyDeletedError < APIError
51 def initialize(object = "object", object_id = "")
52 @object, @object_id = object, object_id
55 attr_reader :object, :object_id
62 "The #{object} with the id #{object_id} has already been deleted"
66 # Raised when the user logged in isn't the same as the changeset
67 class APIUserChangesetMismatchError < APIError
73 "The user doesn't own that changeset"
77 # Raised when the changeset provided is already closed
78 class APIChangesetAlreadyClosedError < APIError
79 def initialize(changeset)
80 @changeset = changeset
83 attr_reader :changeset
90 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
94 # Raised when a change is expecting a changeset, but the changeset doesn't exist
95 class APIChangesetMissingError < APIError
101 "You need to supply a changeset to be able to make a change"
105 # Raised when a diff is uploaded containing many changeset IDs which don't match
106 # the changeset ID that the diff was uploaded to.
107 class APIChangesetMismatchError < APIError
108 def initialize(provided, allowed)
109 @provided, @allowed = provided, allowed
117 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
121 # Raised when a diff upload has an unknown action. You can only have create,
123 class APIChangesetActionInvalid < APIError
124 def initialize(provided)
133 "Unknown action #{@provided}, choices are create, modify, delete"
137 # Raised when bad XML is encountered which stops things parsing as
139 class APIBadXMLError < APIError
140 def initialize(model, xml, message="")
141 @model, @xml, @message = model, xml, message
149 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
153 # Raised when the provided version is not equal to the latest in the db.
154 class APIVersionMismatchError < APIError
155 def initialize(id, type, provided, latest)
156 @id, @type, @provided, @latest = id, type, provided, latest
159 attr_reader :provided, :latest, :id, :type
166 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
170 # raised when a two tags have a duplicate key string in an element.
171 # this is now forbidden by the API.
172 class APIDuplicateTagsError < APIError
173 def initialize(type, id, tag_key)
174 @type, @id, @tag_key = type, id, tag_key
177 attr_reader :type, :id, :tag_key
184 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
188 # Raised when a way has more than the configured number of way nodes.
189 # This prevents ways from being to long and difficult to work with
190 class APITooManyWayNodesError < APIError
191 def initialize(id, provided, max)
192 @id, @provided, @max = id, provided, max
195 attr_reader :id, :provided, :max
202 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
207 # raised when user input couldn't be parsed
208 class APIBadUserInput < APIError
209 def initialize(message)
223 # raised when bounding box is invalid
224 class APIBadBoundingBox < APIError
225 def initialize(message)
239 # raised when an API call is made using a method not supported on that URI
240 class APIBadMethodError < APIError
241 def initialize(supported_method)
242 @supported_method = supported_method
250 "Only method #{@supported_method} is supported on this URI"
255 # raised when an API call takes too long
256 class APITimeoutError < APIError
266 # Helper methods for going to/from mercator and lat/lng.
270 #init me with your bounding box and the size of your image
271 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
272 xsize = xsheet(max_lon) - xsheet(min_lon)
273 ysize = ysheet(max_lat) - ysheet(min_lat)
274 xscale = xsize / width
275 yscale = ysize / height
276 scale = [xscale, yscale].max
278 xpad = width * scale - xsize
279 ypad = height * scale - ysize
284 @tx = xsheet(min_lon) - xpad / 2
285 @ty = ysheet(min_lat) - ypad / 2
287 @bx = xsheet(max_lon) + xpad / 2
288 @by = ysheet(max_lat) + ypad / 2
291 #the following two functions will give you the x/y on the entire sheet
294 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
301 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
304 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
308 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
315 # initialise with a base position
316 def initialize(lat, lon)
317 @lat = lat * PI / 180
318 @lon = lon * PI / 180
321 # get the distance from the base position to a given position
322 def distance(lat, lon)
325 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
328 # get the worst case bounds for a given radius from the base position
330 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
333 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
338 minlat = (@lat - latradius) * 180 / PI
339 maxlat = (@lat + latradius) * 180 / PI
340 minlon = (@lon - lonradius) * 180 / PI
341 maxlon = (@lon + lonradius) * 180 / PI
343 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
346 # get the SQL to use to calculate distance
347 def sql_for_distance(lat_field, lon_field)
348 "6372.795 * 2 * asin(sqrt(power(sin((radians(#{lat_field}) - #{@lat}) / 2), 2) + cos(#{@lat}) * cos(radians(#{lat_field})) * power(sin((radians(#{lon_field}) - #{@lon})/2), 2)))"
353 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
354 @doc = XML::Document.new
355 @doc.encoding = XML::Encoding::UTF_8
357 rss = XML::Node.new 'rss'
359 rss['version'] = "2.0"
360 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
361 @channel = XML::Node.new 'channel'
363 title = XML::Node.new 'title'
366 description_el = XML::Node.new 'description'
367 @channel << description_el
369 description_el << feed_description
370 link = XML::Node.new 'link'
373 image = XML::Node.new 'image'
375 url = XML::Node.new 'url'
376 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
378 title = XML::Node.new 'title'
379 title << "OpenStreetMap"
381 width = XML::Node.new 'width'
384 height = XML::Node.new 'height'
387 link = XML::Node.new 'link'
392 def add(latitude=0, longitude=0, title_text='dummy title', author_text='anonymous', url='http://www.example.com/', description_text='dummy description', timestamp=DateTime.now)
393 item = XML::Node.new 'item'
395 title = XML::Node.new 'title'
398 link = XML::Node.new 'link'
402 guid = XML::Node.new 'guid'
406 description = XML::Node.new 'description'
407 description << description_text
410 author = XML::Node.new 'author'
411 author << author_text
414 pubDate = XML::Node.new 'pubDate'
415 pubDate << timestamp.to_s(:rfc822)
419 lat_el = XML::Node.new 'geo:lat'
420 lat_el << latitude.to_s
425 lon_el = XML::Node.new 'geo:long'
426 lon_el << longitude.to_s
440 doc = XML::Document.new
441 doc.encoding = XML::Encoding::UTF_8
442 root = XML::Node.new 'osm'
443 root['version'] = API_VERSION
444 root['generator'] = GENERATOR
450 def self.IPToCountry(ip_address)
451 Timeout::timeout(4) do
452 ipinfo = Quova::IpInfo.new(ip_address)
454 if ipinfo.status == Quova::Success then
455 country = ipinfo.country_code
457 Net::HTTP.start('api.hostip.info') do |http|
458 country = http.get("/country.php?ip=#{ip_address}").body
459 country = "GB" if country == "UK"
463 return country.upcase
471 def self.IPLocation(ip_address)
472 code = OSM.IPToCountry(ip_address)
474 if code and country = Country.find_by_code(code)
475 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
481 # Construct a random token of a given length
482 def self.make_token(length = 30)
483 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
487 token += chars[(rand * chars.length).to_i].chr
493 # Return an encrypted version of a password
494 def self.encrypt_password(password, salt)
495 return Digest::MD5.hexdigest(password) if salt.nil?
496 return Digest::MD5.hexdigest(salt + password)
499 # Return an SQL fragment to select a given area of the globe
500 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
501 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
503 minlat = (minlat * 10000000).round
504 minlon = (minlon * 10000000).round
505 maxlat = (maxlat * 10000000).round
506 maxlon = (maxlon * 10000000).round
508 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
511 # Return a spam score for a chunk of text
512 def self.spam_score(text)
516 doc = Nokogiri::HTML(text)
518 if doc.content.length > 0
519 doc.xpath("//a").each do |link|
521 link_size += link.content.length
524 link_proportion = link_size.to_f / doc.content.length.to_f
529 return [link_proportion - 0.2, 0.0].max * 200 + link_count * 20
532 def self.legal_text_for_country(country_code)
533 file_name = File.join(RAILS_ROOT, "config", "legales", country_code.to_s + ".yml")
534 file_name = File.join(RAILS_ROOT, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
535 YAML::load_file(file_name)