1 # The OSM module provides support functions for OSM.
5 require 'rexml/parsers/sax2parser'
12 if defined?(SystemTimer)
19 # The base class for API Errors.
20 class APIError < RuntimeError
22 :internal_server_error
30 # Raised when an API object is not found.
31 class APINotFoundError < APIError
41 # Raised when a precondition to an API action fails sanity check.
42 class APIPreconditionFailedError < APIError
43 def initialize(message = "")
52 "Precondition failed: #{@message}"
56 # Raised when to delete an already-deleted object.
57 class APIAlreadyDeletedError < APIError
58 def initialize(object = "object", object_id = "")
59 @object, @object_id = object, object_id
62 attr_reader :object, :object_id
69 "The #{object} with the id #{object_id} has already been deleted"
73 # Raised when the user logged in isn't the same as the changeset
74 class APIUserChangesetMismatchError < APIError
80 "The user doesn't own that changeset"
84 # Raised when the changeset provided is already closed
85 class APIChangesetAlreadyClosedError < APIError
86 def initialize(changeset)
87 @changeset = changeset
90 attr_reader :changeset
97 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
101 # Raised when a change is expecting a changeset, but the changeset doesn't exist
102 class APIChangesetMissingError < APIError
108 "You need to supply a changeset to be able to make a change"
112 # Raised when a diff is uploaded containing many changeset IDs which don't match
113 # the changeset ID that the diff was uploaded to.
114 class APIChangesetMismatchError < APIError
115 def initialize(provided, allowed)
116 @provided, @allowed = provided, allowed
124 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
128 # Raised when a diff upload has an unknown action. You can only have create,
130 class APIChangesetActionInvalid < APIError
131 def initialize(provided)
140 "Unknown action #{@provided}, choices are create, modify, delete"
144 # Raised when bad XML is encountered which stops things parsing as
146 class APIBadXMLError < APIError
147 def initialize(model, xml, message="")
148 @model, @xml, @message = model, xml, message
156 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
160 # Raised when the provided version is not equal to the latest in the db.
161 class APIVersionMismatchError < APIError
162 def initialize(id, type, provided, latest)
163 @id, @type, @provided, @latest = id, type, provided, latest
166 attr_reader :provided, :latest, :id, :type
173 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
177 # raised when a two tags have a duplicate key string in an element.
178 # this is now forbidden by the API.
179 class APIDuplicateTagsError < APIError
180 def initialize(type, id, tag_key)
181 @type, @id, @tag_key = type, id, tag_key
184 attr_reader :type, :id, :tag_key
191 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
195 # Raised when a way has more than the configured number of way nodes.
196 # This prevents ways from being to long and difficult to work with
197 class APITooManyWayNodesError < APIError
198 def initialize(id, provided, max)
199 @id, @provided, @max = id, provided, max
202 attr_reader :id, :provided, :max
209 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
214 # raised when user input couldn't be parsed
215 class APIBadUserInput < APIError
216 def initialize(message)
230 # raised when bounding box is invalid
231 class APIBadBoundingBox < APIError
232 def initialize(message)
246 # raised when an API call is made using a method not supported on that URI
247 class APIBadMethodError < APIError
248 def initialize(supported_method)
249 @supported_method = supported_method
257 "Only method #{@supported_method} is supported on this URI"
262 # raised when an API call takes too long
263 class APITimeoutError < APIError
273 # Helper methods for going to/from mercator and lat/lng.
277 #init me with your bounding box and the size of your image
278 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
279 xsize = xsheet(max_lon) - xsheet(min_lon)
280 ysize = ysheet(max_lat) - ysheet(min_lat)
281 xscale = xsize / width
282 yscale = ysize / height
283 scale = [xscale, yscale].max
285 xpad = width * scale - xsize
286 ypad = height * scale - ysize
291 @tx = xsheet(min_lon) - xpad / 2
292 @ty = ysheet(min_lat) - ypad / 2
294 @bx = xsheet(max_lon) + xpad / 2
295 @by = ysheet(max_lat) + ypad / 2
298 #the following two functions will give you the x/y on the entire sheet
301 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
308 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
311 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
315 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
322 # initialise with a base position
323 def initialize(lat, lon)
324 @lat = lat * PI / 180
325 @lon = lon * PI / 180
328 # get the distance from the base position to a given position
329 def distance(lat, lon)
332 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
335 # get the worst case bounds for a given radius from the base position
337 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
340 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
345 minlat = (@lat - latradius) * 180 / PI
346 maxlat = (@lat + latradius) * 180 / PI
347 minlon = (@lon - lonradius) * 180 / PI
348 maxlon = (@lon + lonradius) * 180 / PI
350 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
353 # get the SQL to use to calculate distance
354 def sql_for_distance(lat_field, lon_field)
355 "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)))"
360 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
361 @doc = XML::Document.new
362 @doc.encoding = XML::Encoding::UTF_8
364 rss = XML::Node.new 'rss'
366 rss['version'] = "2.0"
367 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
368 @channel = XML::Node.new 'channel'
370 title = XML::Node.new 'title'
373 description_el = XML::Node.new 'description'
374 @channel << description_el
376 description_el << feed_description
377 link = XML::Node.new 'link'
380 image = XML::Node.new 'image'
382 url = XML::Node.new 'url'
383 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
385 title = XML::Node.new 'title'
386 title << "OpenStreetMap"
388 width = XML::Node.new 'width'
391 height = XML::Node.new 'height'
394 link = XML::Node.new 'link'
399 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)
400 item = XML::Node.new 'item'
402 title = XML::Node.new 'title'
405 link = XML::Node.new 'link'
409 guid = XML::Node.new 'guid'
413 description = XML::Node.new 'description'
414 description << description_text
417 author = XML::Node.new 'author'
418 author << author_text
421 pubDate = XML::Node.new 'pubDate'
422 pubDate << timestamp.to_s(:rfc822)
426 lat_el = XML::Node.new 'geo:lat'
427 lat_el << latitude.to_s
432 lon_el = XML::Node.new 'geo:long'
433 lon_el << longitude.to_s
447 doc = XML::Document.new
448 doc.encoding = XML::Encoding::UTF_8
449 root = XML::Node.new 'osm'
450 root['version'] = API_VERSION.to_s
451 root['generator'] = GENERATOR
457 def self.IPToCountry(ip_address)
459 ipinfo = Quova::IpInfo.new(ip_address)
461 if ipinfo.status == Quova::Success then
462 country = ipinfo.country_code
464 Net::HTTP.start('api.hostip.info') do |http|
465 country = http.get("/country.php?ip=#{ip_address}").body
466 country = "GB" if country == "UK"
470 return country.upcase
478 def self.IPLocation(ip_address)
479 code = OSM.IPToCountry(ip_address)
481 if code and country = Country.find_by_code(code)
482 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
488 # Construct a random token of a given length
489 def self.make_token(length = 30)
490 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
494 token += chars[(rand * chars.length).to_i].chr
500 # Return an encrypted version of a password
501 def self.encrypt_password(password, salt)
502 return Digest::MD5.hexdigest(password) if salt.nil?
503 return Digest::MD5.hexdigest(salt + password)
506 # Return an SQL fragment to select a given area of the globe
507 def self.sql_for_area(bbox, prefix = nil)
508 tilesql = QuadTile.sql_for_area(bbox, prefix)
509 bbox = bbox.to_scaled
511 return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
512 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
515 # Return a spam score for a chunk of text
516 def self.spam_score(text)
520 doc = Nokogiri::HTML(text)
522 if doc.content.length > 0
523 doc.xpath("//a").each do |link|
525 link_size += link.content.length
528 link_proportion = link_size.to_f / doc.content.length.to_f
533 return [link_proportion - 0.2, 0.0].max * 200 + link_count * 20
536 def self.legal_text_for_country(country_code)
537 file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
538 file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
539 YAML::load_file(file_name)