1 # The OSM module provides support functions for OSM.
5 require 'rexml/parsers/sax2parser'
11 # The base class for API Errors.
12 class APIError < RuntimeError
14 { :text => "Generic API Error", :status => :internal_server_error, :content_type => "text/plain" }
22 # Raised when an API object is not found.
23 class APINotFoundError < APIError
25 { :text => "The API wasn't found", :status => :not_found, :content_type => "text/plain" }
29 # Raised when a precondition to an API action fails sanity check.
30 class APIPreconditionFailedError < APIError
31 def initialize(message = "")
36 { :text => "Precondition failed: #{@message}", :status => :precondition_failed, :content_type => "text/plain" }
40 "Precondition failed: #{@message}"
44 # Raised when to delete an already-deleted object.
45 class APIAlreadyDeletedError < APIError
46 def initialize(object = "object", object_id = "")
47 @object, @object_id = object, object_id
50 attr_reader :object, :object_id
53 { :text => "The #{object} with the id #{object_id} has already been deleted", :status => :gone, :content_type => "text/plain" }
57 # Raised when the user logged in isn't the same as the changeset
58 class APIUserChangesetMismatchError < APIError
60 { :text => "The user doesn't own that changeset", :status => :conflict, :content_type => "text/plain" }
64 # Raised when the changeset provided is already closed
65 class APIChangesetAlreadyClosedError < APIError
66 def initialize(changeset)
67 @changeset = changeset
70 attr_reader :changeset
73 { :text => "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}.", :status => :conflict, :content_type => "text/plain" }
77 # Raised when a change is expecting a changeset, but the changeset doesn't exist
78 class APIChangesetMissingError < APIError
80 { :text => "You need to supply a changeset to be able to make a change", :status => :conflict, :content_type => "text/plain" }
84 "You need to supply a changeset to be able to make a change"
88 # Raised when a diff is uploaded containing many changeset IDs which don't match
89 # the changeset ID that the diff was uploaded to.
90 class APIChangesetMismatchError < APIError
91 def initialize(provided, allowed)
92 @provided, @allowed = provided, allowed
96 { :text => "Changeset mismatch: Provided #{@provided} but only " +
97 "#{@allowed} is allowed.", :status => :conflict, :content_type => "text/plain" }
101 # Raised when a diff upload has an unknown action. You can only have create,
103 class APIChangesetActionInvalid < APIError
104 def initialize(provided)
109 { :text => "Unknown action #{@provided}, choices are create, modify, delete.",
110 :status => :bad_request, :content_type => "text/plain" }
114 # Raised when bad XML is encountered which stops things parsing as
116 class APIBadXMLError < APIError
117 def initialize(model, xml, message="")
118 @model, @xml, @message = model, xml, message
122 { :text => "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}",
123 :status => :bad_request, :content_type => "text/plain" }
127 # Raised when the provided version is not equal to the latest in the db.
128 class APIVersionMismatchError < APIError
129 def initialize(id, type, provided, latest)
130 @id, @type, @provided, @latest = id, type, provided, latest
133 attr_reader :provided, :latest, :id, :type
136 { :text => "Version mismatch: Provided " + provided.to_s +
137 ", server had: " + latest.to_s + " of " + type + " " + id.to_s,
138 :status => :conflict, :content_type => "text/plain" }
142 "Version mismatch: Provided " + provided.to_s + ", server had: " + latest.to_s + " of " + type + " " + id.to_s
146 # raised when a two tags have a duplicate key string in an element.
147 # this is now forbidden by the API.
148 class APIDuplicateTagsError < APIError
149 def initialize(type, id, tag_key)
150 @type, @id, @tag_key = type, id, tag_key
153 attr_reader :type, :id, :tag_key
156 { :text => "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}.",
157 :status => :bad_request, :content_type => "text/plain" }
161 # Raised when a way has more than the configured number of way nodes.
162 # This prevents ways from being to long and difficult to work with
163 class APITooManyWayNodesError < APIError
164 def initialize(provided, max)
165 @provided, @max = provided, max
168 attr_reader :provided, :max
171 { :text => "You tried to add #{provided} nodes to the way, however only #{max} are allowed",
172 :status => :bad_request, :content_type => "text/plain" }
177 # raised when user input couldn't be parsed
178 class APIBadUserInput < APIError
179 def initialize(message)
184 { :text => @message, :content_type => "text/plain", :status => :bad_request }
189 # raised when an API call is made using a method not supported on that URI
190 class APIBadMethodError < APIError
191 def initialize(supported_method)
192 @supported_method = supported_method
196 { :text => "Only method #{@supported_method} is supported on this URI.", :status => :method_not_allowed }
201 # raised when an API call takes too long
202 class APITimeoutError < APIError
204 { :text => "Request timed out", :status => :request_timeout }
212 # Helper methods for going to/from mercator and lat/lng.
216 #init me with your bounding box and the size of your image
217 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
218 xsize = xsheet(max_lon) - xsheet(min_lon)
219 ysize = ysheet(max_lat) - ysheet(min_lat)
220 xscale = xsize / width
221 yscale = ysize / height
222 scale = [xscale, yscale].max
224 xpad = width * scale - xsize
225 ypad = height * scale - ysize
230 @tx = xsheet(min_lon) - xpad / 2
231 @ty = ysheet(min_lat) - ypad / 2
233 @bx = xsheet(max_lon) + xpad / 2
234 @by = ysheet(max_lat) + ypad / 2
237 #the following two functions will give you the x/y on the entire sheet
240 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
247 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
250 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
254 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
261 # initialise with a base position
262 def initialize(lat, lon)
263 @lat = lat * PI / 180
264 @lon = lon * PI / 180
267 # get the distance from the base position to a given position
268 def distance(lat, lon)
271 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
274 # get the worst case bounds for a given radius from the base position
276 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
277 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
278 minlat = (@lat - latradius) * 180 / PI
279 maxlat = (@lat + latradius) * 180 / PI
280 minlon = (@lon - lonradius) * 180 / PI
281 maxlon = (@lon + lonradius) * 180 / PI
282 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
287 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
288 @doc = XML::Document.new
289 @doc.encoding = XML::Encoding::UTF_8
291 rss = XML::Node.new 'rss'
293 rss['version'] = "2.0"
294 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
295 @channel = XML::Node.new 'channel'
297 title = XML::Node.new 'title'
300 description_el = XML::Node.new 'description'
301 @channel << description_el
303 description_el << feed_description
304 link = XML::Node.new 'link'
307 image = XML::Node.new 'image'
309 url = XML::Node.new 'url'
310 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
312 title = XML::Node.new 'title'
313 title << "OpenStreetMap"
315 width = XML::Node.new 'width'
318 height = XML::Node.new 'height'
321 link = XML::Node.new 'link'
326 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)
327 item = XML::Node.new 'item'
329 title = XML::Node.new 'title'
332 link = XML::Node.new 'link'
336 guid = XML::Node.new 'guid'
340 description = XML::Node.new 'description'
341 description << description_text
344 author = XML::Node.new 'author'
345 author << author_text
348 pubDate = XML::Node.new 'pubDate'
349 pubDate << timestamp.to_s(:rfc822)
353 lat_el = XML::Node.new 'geo:lat'
354 lat_el << latitude.to_s
359 lon_el = XML::Node.new 'geo:long'
360 lon_el << longitude.to_s
374 doc = XML::Document.new
375 doc.encoding = XML::Encoding::UTF_8
376 root = XML::Node.new 'osm'
377 root['version'] = API_VERSION
378 root['generator'] = GENERATOR
384 def self.IPLocation(ip_address)
385 Timeout::timeout(4) do
386 Net::HTTP.start('api.hostip.info') do |http|
387 country = http.get("/country.php?ip=#{ip_address}").body
388 country = "GB" if country == "UK"
389 country = Country.find_by_code(country)
390 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
399 # Construct a random token of a given length
400 def self.make_token(length = 30)
401 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
405 token += chars[(rand * chars.length).to_i].chr
411 # Return an encrypted version of a password
412 def self.encrypt_password(password, salt)
413 return Digest::MD5.hexdigest(password) if salt.nil?
414 return Digest::MD5.hexdigest(salt + password)
417 # Return an SQL fragment to select a given area of the globe
418 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
419 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
420 minlat = (minlat * 10000000).round
421 minlon = (minlon * 10000000).round
422 maxlat = (maxlat * 10000000).round
423 maxlon = (maxlon * 10000000).round
425 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"