1 # The OSM module provides support functions for OSM.
4 require "rexml/parsers/sax2parser"
8 if defined?(SystemTimer)
15 # The base class for API Errors.
16 class APIError < RuntimeError
18 :internal_server_error
26 # Raised when access is denied.
27 class APIAccessDenied < RuntimeError
37 # Raised when an API object is not found.
38 class APINotFoundError < APIError
48 # Raised when a precondition to an API action fails sanity check.
49 class APIPreconditionFailedError < APIError
50 def initialize(message = "")
59 "Precondition failed: #{@message}"
63 # Raised when to delete an already-deleted object.
64 class APIAlreadyDeletedError < APIError
65 def initialize(object = "object", object_id = "")
67 @object_id = object_id
70 attr_reader :object, :object_id
77 "The #{object} with the id #{object_id} has already been deleted"
81 # Raised when the user logged in isn't the same as the changeset
82 class APIUserChangesetMismatchError < APIError
88 "The user doesn't own that changeset"
92 # Raised when the changeset provided is already closed
93 class APIChangesetAlreadyClosedError < APIError
94 def initialize(changeset)
95 @changeset = changeset
98 attr_reader :changeset
105 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
109 # Raised when the changeset provided is not yet closed
110 class APIChangesetNotYetClosedError < APIError
111 def initialize(changeset)
112 @changeset = changeset
115 attr_reader :changeset
122 "The changeset #{@changeset.id} is not yet closed."
126 # Raised when a user is already subscribed to the changeset
127 class APIChangesetAlreadySubscribedError < APIError
128 def initialize(changeset)
129 @changeset = changeset
132 attr_reader :changeset
139 "You are already subscribed to changeset #{@changeset.id}."
143 # Raised when a user is not subscribed to the changeset
144 class APIChangesetNotSubscribedError < APIError
145 def initialize(changeset)
146 @changeset = changeset
149 attr_reader :changeset
156 "You are not subscribed to changeset #{@changeset.id}."
160 # Raised when a change is expecting a changeset, but the changeset doesn't exist
161 class APIChangesetMissingError < APIError
167 "You need to supply a changeset to be able to make a change"
171 # Raised when a diff is uploaded containing many changeset IDs which don't match
172 # the changeset ID that the diff was uploaded to.
173 class APIChangesetMismatchError < APIError
174 def initialize(provided, allowed)
184 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
188 # Raised when a diff upload has an unknown action. You can only have create,
190 class APIChangesetActionInvalid < APIError
191 def initialize(provided)
200 "Unknown action #{@provided}, choices are create, modify, delete"
204 # Raised when bad XML is encountered which stops things parsing as
206 class APIBadXMLError < APIError
207 def initialize(model, xml, message = "")
218 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
222 # Raised when the provided version is not equal to the latest in the db.
223 class APIVersionMismatchError < APIError
224 def initialize(id, type, provided, latest)
231 attr_reader :provided, :latest, :id, :type
238 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
242 # raised when a two tags have a duplicate key string in an element.
243 # this is now forbidden by the API.
244 class APIDuplicateTagsError < APIError
245 def initialize(type, id, tag_key)
251 attr_reader :type, :id, :tag_key
258 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
262 # Raised when a way has more than the configured number of way nodes.
263 # This prevents ways from being to long and difficult to work with
264 class APITooManyWayNodesError < APIError
265 def initialize(id, provided, max)
271 attr_reader :id, :provided, :max
278 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
283 # raised when user input couldn't be parsed
284 class APIBadUserInput < APIError
285 def initialize(message)
299 # raised when bounding box is invalid
300 class APIBadBoundingBox < APIError
301 def initialize(message)
315 # raised when an API call is made using a method not supported on that URI
316 class APIBadMethodError < APIError
317 def initialize(supported_method)
318 @supported_method = supported_method
326 "Only method #{@supported_method} is supported on this URI"
331 # raised when an API call takes too long
332 class APITimeoutError < APIError
343 # raised when someone tries to redact a current version of
344 # an element - only historical versions can be redacted.
345 class APICannotRedactError < APIError
351 "Cannot redact current version of element, only historical versions may be redacted."
355 # Raised when the note provided is already closed
356 class APINoteAlreadyClosedError < APIError
368 "The note #{@note.id} was closed at #{@note.closed_at}"
372 # Raised when the note provided is already open
373 class APINoteAlreadyOpenError < APIError
385 "The note #{@note.id} is already open"
389 # raised when a two preferences have a duplicate key string.
390 class APIDuplicatePreferenceError < APIError
402 "Duplicate preferences with key #{@key}"
406 # Helper methods for going to/from mercator and lat/lng.
410 # init me with your bounding box and the size of your image
411 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
412 xsize = xsheet(max_lon) - xsheet(min_lon)
413 ysize = ysheet(max_lat) - ysheet(min_lat)
414 xscale = xsize / width
415 yscale = ysize / height
416 scale = [xscale, yscale].max
418 xpad = width * scale - xsize
419 ypad = height * scale - ysize
424 @tx = xsheet(min_lon) - xpad / 2
425 @ty = ysheet(min_lat) - ypad / 2
427 @bx = xsheet(max_lon) + xpad / 2
428 @by = ysheet(max_lat) + ypad / 2
431 # the following two functions will give you the x/y on the entire sheet
434 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
441 # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
444 @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
448 ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
455 # initialise with a base position
456 def initialize(lat, lon)
457 @lat = lat * PI / 180
458 @lon = lon * PI / 180
461 # get the distance from the base position to a given position
462 def distance(lat, lon)
465 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2)**2 + cos(@lat) * cos(lat) * sin((lon - @lon) / 2)**2))
468 # get the worst case bounds for a given radius from the base position
470 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
473 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2 / cos(@lat)**2))
474 rescue Errno::EDOM, Math::DomainError
478 minlat = [(@lat - latradius) * 180 / PI, -90].max
479 maxlat = [(@lat + latradius) * 180 / PI, 90].min
480 minlon = [(@lon - lonradius) * 180 / PI, -180].max
481 maxlon = [(@lon + lonradius) * 180 / PI, 180].min
483 BoundingBox.new(minlon, minlat, maxlon, maxlat)
486 # get the SQL to use to calculate distance
487 def sql_for_distance(lat_field, lon_field)
488 "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)))"
494 doc = XML::Document.new
495 doc.encoding = XML::Encoding::UTF_8
496 root = XML::Node.new "osm"
497 xml_root_attributes.each do |k, v|
504 def xml_root_attributes
505 { "version" => Settings.api_version,
506 "generator" => Settings.generator,
507 "copyright" => Settings.copyright_owner,
508 "attribution" => Settings.attribution_url,
509 "license" => Settings.license_url }
513 def self.ip_to_country(ip_address)
514 ipinfo = maxmind_database.lookup(ip_address) if Settings.key?(:maxmind_database)
517 country = ipinfo.country.iso_code
519 country = http_client.get("https://api.hostip.info/country.php?ip=#{ip_address}").body
520 country = "GB" if country == "UK"
528 def self.ip_location(ip_address)
529 code = OSM.ip_to_country(ip_address)
531 if code && country = Country.find(code)
532 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
538 # Parse a float, raising a specified exception on failure
539 def self.parse_float(str, klass, *args)
542 raise klass.new(*args)
545 # Construct a random token of a given length
546 def self.make_token(length = 30)
547 chars = "abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
551 token += chars[(rand * chars.length).to_i].chr
557 # Return an SQL fragment to select a given area of the globe
558 def self.sql_for_area(bbox, prefix = nil)
559 tilesql = QuadTile.sql_for_area(bbox, prefix)
560 bbox = bbox.to_scaled
562 "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " \
563 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
566 # Return the terms and conditions text for a given country
567 def self.legal_text_for_country(country_code)
568 file_name = Rails.root.join("config", "legales", country_code.to_s + ".yml")
569 file_name = Rails.root.join("config", "legales", Settings.default_legale + ".yml") unless File.exist? file_name
570 YAML.load_file(file_name)
573 # Return the HTTP client to use
575 @http_client ||= Faraday.new
578 # Return the MaxMindDB database handle
579 def self.maxmind_database
580 @maxmind_database ||= MaxMindDB.new(Settings.maxmind_database) if Settings.key?(:maxmind_database)