1 # frozen_string_literal: true
 
   3 # The OSM module provides support functions for OSM.
 
   6   require "rexml/parsers/sax2parser"
 
   9   # The base class for API Errors.
 
  10   class APIError < RuntimeError
 
  11     def initialize(message = "Generic API Error")
 
  16       :internal_server_error
 
  20   # Raised when access is denied.
 
  21   class APIAccessDenied < APIError
 
  23       super("Access denied")
 
  31   # Raised when an API object is not found.
 
  32   class APINotFoundError < APIError
 
  34       super("Object not found")
 
  42   # Raised when a precondition to an API action fails sanity check.
 
  43   class APIPreconditionFailedError < APIError
 
  44     def initialize(message = "")
 
  45       super("Precondition failed: #{message}")
 
  53   # Raised when to delete an already-deleted object.
 
  54   class APIAlreadyDeletedError < APIError
 
  55     def initialize(type = "object", id = "")
 
  59       super("The #{type} with the id #{id} has already been deleted")
 
  62     attr_reader :type, :id
 
  69   # Raised when the user logged in isn't the same as the changeset
 
  70   class APIUserChangesetMismatchError < APIError
 
  72       super("The user doesn't own that changeset")
 
  80   # Raised when the changeset provided is already closed
 
  81   class APIChangesetAlreadyClosedError < APIError
 
  82     def initialize(changeset)
 
  83       @changeset = changeset
 
  85       super("The changeset #{changeset.id} was closed at #{changeset.closed_at}")
 
  88     attr_reader :changeset
 
  95   # Raised when the changeset provided is not yet closed
 
  96   class APIChangesetNotYetClosedError < APIError
 
  97     def initialize(changeset)
 
  98       @changeset = changeset
 
 100       super("The changeset #{changeset.id} is not yet closed.")
 
 103     attr_reader :changeset
 
 110   # Raised when a user is already subscribed to the changeset
 
 111   class APIChangesetAlreadySubscribedError < APIError
 
 112     def initialize(changeset)
 
 113       @changeset = changeset
 
 115       super("You are already subscribed to changeset #{changeset.id}.")
 
 118     attr_reader :changeset
 
 125   # Raised when a user is not subscribed to the changeset
 
 126   class APIChangesetNotSubscribedError < APIError
 
 127     def initialize(changeset)
 
 128       @changeset = changeset
 
 130       super("You are not subscribed to changeset #{changeset.id}.")
 
 133     attr_reader :changeset
 
 140   # Raised when a change is expecting a changeset, but the changeset doesn't exist
 
 141   class APIChangesetMissingError < APIError
 
 143       super("You need to supply a changeset to be able to make a change")
 
 151   # Raised when a diff is uploaded containing many changeset IDs which don't match
 
 152   # the changeset ID that the diff was uploaded to.
 
 153   class APIChangesetMismatchError < APIError
 
 154     def initialize(provided, allowed)
 
 155       super("Changeset mismatch: Provided #{provided} but only #{allowed} is allowed")
 
 163   # Raised when a diff upload has an unknown action. You can only have create,
 
 165   class APIChangesetActionInvalid < APIError
 
 166     def initialize(provided)
 
 167       super("Unknown action #{provided}, choices are create, modify, delete")
 
 175   # Raised when bad XML is encountered which stops things parsing as
 
 177   class APIBadXMLError < APIError
 
 178     def initialize(model, xml, message = "")
 
 179       super("Cannot parse valid #{model} from xml string #{xml}. #{message}")
 
 187   # Raised when the provided version is not equal to the latest in the db.
 
 188   class APIVersionMismatchError < APIError
 
 189     def initialize(id, type, provided, latest)
 
 195       super("Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}")
 
 198     attr_reader :provided, :latest, :id, :type
 
 205   # raised when a two tags have a duplicate key string in an element.
 
 206   # this is now forbidden by the API.
 
 207   class APIDuplicateTagsError < APIError
 
 208     def initialize(type, id, tag_key)
 
 213       super("Element #{type}/#{id} has duplicate tags with key #{tag_key}")
 
 216     attr_reader :type, :id, :tag_key
 
 223   # Raised when a way has more than the configured number of way nodes.
 
 224   # This prevents ways from being to long and difficult to work with
 
 225   class APITooManyWayNodesError < APIError
 
 226     def initialize(id, provided, max)
 
 227       super("You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed")
 
 234     attr_reader :id, :provided, :max
 
 241   # Raised when a relation has more than the configured number of relation members.
 
 242   # This prevents relations from being too complex and difficult to work with
 
 243   class APITooManyRelationMembersError < APIError
 
 244     def initialize(id, provided, max)
 
 245       super("You tried to add #{provided} members to relation #{id}, however only #{max} are allowed")
 
 252     attr_reader :id, :provided, :max
 
 260   # raised when user input couldn't be parsed
 
 261   class APIBadUserInput < APIError
 
 268   # raised when bounding box is invalid
 
 269   class APIBadBoundingBox < APIError
 
 276   # raised when an API call is made using a method not supported on that URI
 
 277   class APIBadMethodError < APIError
 
 278     def initialize(supported_method)
 
 279       super("Only method #{supported_method} is supported on this URI")
 
 288   # raised when an API call takes too long
 
 289   class APITimeoutError < APIError
 
 291       super("Request timed out")
 
 300   # raised when someone tries to redact a current version of
 
 301   # an element - only historical versions can be redacted.
 
 302   class APICannotRedactError < APIError
 
 304       super("Cannot redact current version of element, only historical versions may be redacted.")
 
 312   # Raised when the note provided is already closed
 
 313   class APINoteAlreadyClosedError < APIError
 
 317       super("The note #{note.id} was closed at #{note.closed_at}")
 
 327   # Raised when the note provided is already open
 
 328   class APINoteAlreadyOpenError < APIError
 
 332       super("The note #{note.id} is already open")
 
 342   # raised when a two preferences have a duplicate key string.
 
 343   class APIDuplicatePreferenceError < APIError
 
 347       super("Duplicate preferences with key #{key}")
 
 357   # Raised when a rate limit is exceeded
 
 358   class APIRateLimitExceeded < APIError
 
 360       super("Rate limit exceeded")
 
 368   # Raised when a size limit is exceeded
 
 369   class APISizeLimitExceeded < APIError
 
 371       super("Size limit exceeded")
 
 379   # Helper methods for going to/from mercator and lat/lng.
 
 383     # init me with your bounding box and the size of your image
 
 384     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
 
 385       xsize = xsheet(max_lon) - xsheet(min_lon)
 
 386       ysize = ysheet(max_lat) - ysheet(min_lat)
 
 387       xscale = xsize / width
 
 388       yscale = ysize / height
 
 389       scale = [xscale, yscale].max
 
 391       xpad = (width * scale) - xsize
 
 392       ypad = (height * scale) - ysize
 
 397       @tx = xsheet(min_lon) - (xpad / 2)
 
 398       @ty = ysheet(min_lat) - (ypad / 2)
 
 400       @bx = xsheet(max_lon) + (xpad / 2)
 
 401       @by = ysheet(max_lat) + (ypad / 2)
 
 404     # the following two functions will give you the x/y on the entire sheet
 
 407       log(tan((PI / 4) + (lat * PI / 180 / 2))) / (PI / 180)
 
 414     # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
 
 415     # If the bbox has no extent, return the centre of the image to avoid dividing by zero.
 
 418       return @height / 2 if (@by - @ty).zero?
 
 420       @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
 
 424       return @width / 2 if (@bx - @tx).zero?
 
 426       ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
 
 433     # initialise with a base position
 
 434     def initialize(lat, lon)
 
 435       @lat = lat * PI / 180
 
 436       @lon = lon * PI / 180
 
 439     # get the distance from the base position to a given position
 
 440     def distance(lat, lon)
 
 443       6372.795 * 2 * asin(sqrt((sin((lat - @lat) / 2)**2) + (cos(@lat) * cos(lat) * (sin((lon - @lon) / 2)**2))))
 
 446     # get the worst case bounds for a given radius from the base position
 
 448       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
 
 451         lonradius = 2 * asin(sqrt((sin(radius / 6372.795 / 2)**2) / (cos(@lat)**2)))
 
 452       rescue Errno::EDOM, Math::DomainError
 
 456       minlat = [(@lat - latradius) * 180 / PI, -90].max
 
 457       maxlat = [(@lat + latradius) * 180 / PI, 90].min
 
 458       minlon = [(@lon - lonradius) * 180 / PI, -180].max
 
 459       maxlon = [(@lon + lonradius) * 180 / PI, 180].min
 
 461       BoundingBox.new(minlon, minlat, maxlon, maxlat)
 
 464     # get the SQL to use to calculate distance
 
 465     def sql_for_distance(lat_field, lon_field)
 
 466       "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)))"
 
 472       doc = LibXML::XML::Document.new
 
 473       doc.encoding = LibXML::XML::Encoding::UTF_8
 
 474       root = LibXML::XML::Node.new "osm"
 
 475       xml_root_attributes.each do |k, v|
 
 482     def xml_root_attributes
 
 483       { "version" => Settings.api_version,
 
 484         "generator" => Settings.generator,
 
 485         "copyright" => Settings.copyright_owner,
 
 486         "attribution" => Settings.attribution_url,
 
 487         "license" => Settings.license_url }
 
 491   def self.ip_to_country(ip_address)
 
 492     ipinfo = maxmind_database.lookup(ip_address) if Settings.key?(:maxmind_database)
 
 494     return ipinfo.country.iso_code if ipinfo&.found?
 
 499   def self.ip_location(ip_address)
 
 500     code = OSM.ip_to_country(ip_address)
 
 502     if code && country = Country.find(code)
 
 503       return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
 
 509   # Parse a float, raising a specified exception on failure
 
 510   def self.parse_float(str, klass, *)
 
 516   # Construct a random token of a given length
 
 517   def self.make_token(length = 24)
 
 518     SecureRandom.urlsafe_base64(length)
 
 521   # Return an SQL fragment to select a given area of the globe
 
 522   def self.sql_for_area(bbox, prefix = nil)
 
 523     tilesql = QuadTile.sql_for_area(bbox, prefix)
 
 524     bbox = bbox.to_scaled
 
 526     "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " \
 
 527       "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
 
 530   # Return the terms and conditions text for a given country
 
 531   def self.legal_text_for_country(country_code)
 
 532     file_name = Rails.root.join("config", "legales", "#{country_code}.yml")
 
 533     file_name = Rails.root.join("config", "legales", "#{Settings.default_legale}.yml") unless File.exist? file_name
 
 534     YAML.load_file(file_name).transform_values!(&:html_safe)
 
 537   # Return the HTTP client to use
 
 539     @http_client ||= Faraday.new(:request => { :timeout => 15 },
 
 540                                  :headers => { :user_agent => Settings.server_url })
 
 543   # Return the MaxMindDB database handle
 
 544   def self.maxmind_database
 
 545     @maxmind_database ||= MaxMindDB.new(Settings.maxmind_database) if Settings.key?(:maxmind_database)