1 # The OSM module provides support functions for OSM.
5 require 'rexml/parsers/sax2parser'
10 if defined?(SystemTimer)
17 # The base class for API Errors.
18 class APIError < RuntimeError
20 :internal_server_error
28 # Raised when an API object is not found.
29 class APINotFoundError < APIError
39 # Raised when a precondition to an API action fails sanity check.
40 class APIPreconditionFailedError < APIError
41 def initialize(message = "")
50 "Precondition failed: #{@message}"
54 # Raised when to delete an already-deleted object.
55 class APIAlreadyDeletedError < APIError
56 def initialize(object = "object", object_id = "")
57 @object, @object_id = object, object_id
60 attr_reader :object, :object_id
67 "The #{object} with the id #{object_id} has already been deleted"
71 # Raised when the user logged in isn't the same as the changeset
72 class APIUserChangesetMismatchError < APIError
78 "The user doesn't own that changeset"
82 # Raised when the changeset provided is already closed
83 class APIChangesetAlreadyClosedError < APIError
84 def initialize(changeset)
85 @changeset = changeset
88 attr_reader :changeset
95 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
99 # Raised when a change is expecting a changeset, but the changeset doesn't exist
100 class APIChangesetMissingError < APIError
106 "You need to supply a changeset to be able to make a change"
110 # Raised when a diff is uploaded containing many changeset IDs which don't match
111 # the changeset ID that the diff was uploaded to.
112 class APIChangesetMismatchError < APIError
113 def initialize(provided, allowed)
114 @provided, @allowed = provided, allowed
122 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
126 # Raised when a diff upload has an unknown action. You can only have create,
128 class APIChangesetActionInvalid < APIError
129 def initialize(provided)
138 "Unknown action #{@provided}, choices are create, modify, delete"
142 # Raised when bad XML is encountered which stops things parsing as
144 class APIBadXMLError < APIError
145 def initialize(model, xml, message="")
146 @model, @xml, @message = model, xml, message
154 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
158 # Raised when the provided version is not equal to the latest in the db.
159 class APIVersionMismatchError < APIError
160 def initialize(id, type, provided, latest)
161 @id, @type, @provided, @latest = id, type, provided, latest
164 attr_reader :provided, :latest, :id, :type
171 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
175 # raised when a two tags have a duplicate key string in an element.
176 # this is now forbidden by the API.
177 class APIDuplicateTagsError < APIError
178 def initialize(type, id, tag_key)
179 @type, @id, @tag_key = type, id, tag_key
182 attr_reader :type, :id, :tag_key
189 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
193 # Raised when a way has more than the configured number of way nodes.
194 # This prevents ways from being to long and difficult to work with
195 class APITooManyWayNodesError < APIError
196 def initialize(id, provided, max)
197 @id, @provided, @max = id, provided, max
200 attr_reader :id, :provided, :max
207 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
212 # raised when user input couldn't be parsed
213 class APIBadUserInput < APIError
214 def initialize(message)
228 # raised when bounding box is invalid
229 class APIBadBoundingBox < APIError
230 def initialize(message)
244 # raised when an API call is made using a method not supported on that URI
245 class APIBadMethodError < APIError
246 def initialize(supported_method)
247 @supported_method = supported_method
255 "Only method #{@supported_method} is supported on this URI"
260 # raised when an API call takes too long
261 class APITimeoutError < APIError
272 # raised when someone tries to redact a current version of
273 # an element - only historical versions can be redacted.
274 class APICannotRedactError < APIError
280 "Cannot redact current version of element, only historical versions may be redacted."
284 # Raised when the note provided is already closed
285 class APINoteAlreadyClosedError < APIError
297 "The note #{@note.id} was closed at #{@note.closed_at}"
301 # Helper methods for going to/from mercator and lat/lng.
305 #init me with your bounding box and the size of your image
306 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
307 xsize = xsheet(max_lon) - xsheet(min_lon)
308 ysize = ysheet(max_lat) - ysheet(min_lat)
309 xscale = xsize / width
310 yscale = ysize / height
311 scale = [xscale, yscale].max
313 xpad = width * scale - xsize
314 ypad = height * scale - ysize
319 @tx = xsheet(min_lon) - xpad / 2
320 @ty = ysheet(min_lat) - ypad / 2
322 @bx = xsheet(max_lon) + xpad / 2
323 @by = ysheet(max_lat) + ypad / 2
326 #the following two functions will give you the x/y on the entire sheet
329 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
336 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
339 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
343 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
350 # initialise with a base position
351 def initialize(lat, lon)
352 @lat = lat * PI / 180
353 @lon = lon * PI / 180
356 # get the distance from the base position to a given position
357 def distance(lat, lon)
360 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
363 # get the worst case bounds for a given radius from the base position
365 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
368 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
373 minlat = (@lat - latradius) * 180 / PI
374 maxlat = (@lat + latradius) * 180 / PI
375 minlon = (@lon - lonradius) * 180 / PI
376 maxlon = (@lon + lonradius) * 180 / PI
378 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
381 # get the SQL to use to calculate distance
382 def sql_for_distance(lat_field, lon_field)
383 "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)))"
388 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
389 @doc = XML::Document.new
390 @doc.encoding = XML::Encoding::UTF_8
392 rss = XML::Node.new 'rss'
394 rss['version'] = "2.0"
395 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
396 @channel = XML::Node.new 'channel'
398 title = XML::Node.new 'title'
401 description_el = XML::Node.new 'description'
402 @channel << description_el
404 description_el << feed_description
405 link = XML::Node.new 'link'
408 image = XML::Node.new 'image'
410 url = XML::Node.new 'url'
411 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
413 title = XML::Node.new 'title'
414 title << "OpenStreetMap"
416 width = XML::Node.new 'width'
419 height = XML::Node.new 'height'
422 link = XML::Node.new 'link'
427 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)
428 item = XML::Node.new 'item'
430 title = XML::Node.new 'title'
433 link = XML::Node.new 'link'
437 guid = XML::Node.new 'guid'
441 description = XML::Node.new 'description'
442 description << description_text
445 author = XML::Node.new 'author'
446 author << author_text
449 pubDate = XML::Node.new 'pubDate'
450 pubDate << timestamp.to_s(:rfc822)
454 lat_el = XML::Node.new 'geo:lat'
455 lat_el << latitude.to_s
460 lon_el = XML::Node.new 'geo:long'
461 lon_el << longitude.to_s
475 doc = XML::Document.new
476 doc.encoding = XML::Encoding::UTF_8
477 root = XML::Node.new 'osm'
478 root['version'] = API_VERSION.to_s
479 root['generator'] = GENERATOR
480 root['copyright'] = COPYRIGHT_OWNER
481 root['attribution'] = ATTRIBUTION_URL
482 root['license'] = LICENSE_URL
488 def self.IPToCountry(ip_address)
490 ipinfo = Quova::IpInfo.new(ip_address)
492 if ipinfo.status == Quova::Success then
493 country = ipinfo.country_code
495 Net::HTTP.start('api.hostip.info') do |http|
496 country = http.get("/country.php?ip=#{ip_address}").body
497 country = "GB" if country == "UK"
501 return country.upcase
509 def self.IPLocation(ip_address)
510 code = OSM.IPToCountry(ip_address)
512 if code and country = Country.find_by_code(code)
513 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
519 # Construct a random token of a given length
520 def self.make_token(length = 30)
521 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
525 token += chars[(rand * chars.length).to_i].chr
531 # Return an encrypted version of a password
532 def self.encrypt_password(password, salt)
533 return Digest::MD5.hexdigest(password) if salt.nil?
534 return Digest::MD5.hexdigest(salt + password)
537 # Return an SQL fragment to select a given area of the globe
538 def self.sql_for_area(bbox, prefix = nil)
539 tilesql = QuadTile.sql_for_area(bbox, prefix)
540 bbox = bbox.to_scaled
542 return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
543 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
546 def self.legal_text_for_country(country_code)
547 file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
548 file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
549 YAML::load_file(file_name)