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
47 { :text => "The object has already been deleted", :status => :gone, :content_type => "text/plain" }
51 # Raised when the user logged in isn't the same as the changeset
52 class APIUserChangesetMismatchError < APIError
54 { :text => "The user doesn't own that changeset", :status => :conflict, :content_type => "text/plain" }
58 # Raised when the changeset provided is already closed
59 class APIChangesetAlreadyClosedError < APIError
60 def initialize(changeset)
61 @changeset = changeset
64 attr_reader :changeset
67 { :text => "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}.", :status => :conflict, :content_type => "text/plain" }
71 # Raised when a change is expecting a changeset, but the changeset doesn't exist
72 class APIChangesetMissingError < APIError
74 { :text => "You need to supply a changeset to be able to make a change", :status => :conflict, :content_type => "text/plain" }
78 "You need to supply a changeset to be able to make a change"
82 # Raised when a diff is uploaded containing many changeset IDs which don't match
83 # the changeset ID that the diff was uploaded to.
84 class APIChangesetMismatchError < APIError
85 def initialize(provided, allowed)
86 @provided, @allowed = provided, allowed
90 { :text => "Changeset mismatch: Provided #{@provided} but only " +
91 "#{@allowed} is allowed.", :status => :conflict, :content_type => "text/plain" }
95 # Raised when a diff upload has an unknown action. You can only have create,
97 class APIChangesetActionInvalid < APIError
98 def initialize(provided)
103 { :text => "Unknown action #{@provided}, choices are create, modify, delete.",
104 :status => :bad_request, :content_type => "text/plain" }
108 # Raised when bad XML is encountered which stops things parsing as
110 class APIBadXMLError < APIError
111 def initialize(model, xml, message="")
112 @model, @xml, @message = model, xml, message
116 { :text => "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}",
117 :status => :bad_request, :content_type => "text/plain" }
121 # Raised when the provided version is not equal to the latest in the db.
122 class APIVersionMismatchError < APIError
123 def initialize(id, type, provided, latest)
124 @id, @type, @provided, @latest = id, type, provided, latest
127 attr_reader :provided, :latest, :id, :type
130 { :text => "Version mismatch: Provided " + provided.to_s +
131 ", server had: " + latest.to_s + " of " + type + " " + id.to_s,
132 :status => :conflict, :content_type => "text/plain" }
136 "Version mismatch: Provided " + provided.to_s + ", server had: " + latest.to_s + " of " + type + " " + id.to_s
140 # raised when a two tags have a duplicate key string in an element.
141 # this is now forbidden by the API.
142 class APIDuplicateTagsError < APIError
143 def initialize(type, id, tag_key)
144 @type, @id, @tag_key = type, id, tag_key
147 attr_reader :type, :id, :tag_key
150 { :text => "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}.",
151 :status => :bad_request, :content_type => "text/plain" }
155 # Raised when a way has more than the configured number of way nodes.
156 # This prevents ways from being to long and difficult to work with
157 class APITooManyWayNodesError < APIError
158 def initialize(provided, max)
159 @provided, @max = provided, max
162 attr_reader :provided, :max
165 { :text => "You tried to add #{provided} nodes to the way, however only #{max} are allowed",
166 :status => :bad_request, :content_type => "text/plain" }
171 # raised when user input couldn't be parsed
172 class APIBadUserInput < APIError
173 def initialize(message)
178 { :text => @message, :content_type => "text/plain", :status => :bad_request }
182 # Helper methods for going to/from mercator and lat/lng.
186 #init me with your bounding box and the size of your image
187 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
188 xsize = xsheet(max_lon) - xsheet(min_lon)
189 ysize = ysheet(max_lat) - ysheet(min_lat)
190 xscale = xsize / width
191 yscale = ysize / height
192 scale = [xscale, yscale].max
194 xpad = width * scale - xsize
195 ypad = height * scale - ysize
200 @tx = xsheet(min_lon) - xpad / 2
201 @ty = ysheet(min_lat) - ypad / 2
203 @bx = xsheet(max_lon) + xpad / 2
204 @by = ysheet(max_lat) + ypad / 2
207 #the following two functions will give you the x/y on the entire sheet
210 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
217 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
220 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
224 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
231 # initialise with a base position
232 def initialize(lat, lon)
233 @lat = lat * PI / 180
234 @lon = lon * PI / 180
237 # get the distance from the base position to a given position
238 def distance(lat, lon)
241 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
244 # get the worst case bounds for a given radius from the base position
246 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
247 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
248 minlat = (@lat - latradius) * 180 / PI
249 maxlat = (@lat + latradius) * 180 / PI
250 minlon = (@lon - lonradius) * 180 / PI
251 maxlon = (@lon + lonradius) * 180 / PI
252 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
257 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
258 @doc = XML::Document.new
259 @doc.encoding = XML::Encoding::UTF_8
261 rss = XML::Node.new 'rss'
263 rss['version'] = "2.0"
264 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
265 @channel = XML::Node.new 'channel'
267 title = XML::Node.new 'title'
270 description_el = XML::Node.new 'description'
271 @channel << description_el
273 description_el << feed_description
274 link = XML::Node.new 'link'
277 image = XML::Node.new 'image'
279 url = XML::Node.new 'url'
280 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
282 title = XML::Node.new 'title'
283 title << "OpenStreetMap"
285 width = XML::Node.new 'width'
288 height = XML::Node.new 'height'
291 link = XML::Node.new 'link'
296 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)
297 item = XML::Node.new 'item'
299 title = XML::Node.new 'title'
302 link = XML::Node.new 'link'
306 guid = XML::Node.new 'guid'
310 description = XML::Node.new 'description'
311 description << description_text
314 author = XML::Node.new 'author'
315 author << author_text
318 pubDate = XML::Node.new 'pubDate'
319 pubDate << timestamp.to_s(:rfc822)
323 lat_el = XML::Node.new 'geo:lat'
324 lat_el << latitude.to_s
329 lon_el = XML::Node.new 'geo:long'
330 lon_el << longitude.to_s
344 doc = XML::Document.new
345 doc.encoding = XML::Encoding::UTF_8
346 root = XML::Node.new 'osm'
347 root['version'] = API_VERSION
348 root['generator'] = GENERATOR
354 def self.IPLocation(ip_address)
355 Timeout::timeout(4) do
356 Net::HTTP.start('api.hostip.info') do |http|
357 country = http.get("/country.php?ip=#{ip_address}").body
358 country = "GB" if country == "UK"
359 Net::HTTP.start('ws.geonames.org') do |http|
360 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
361 xml.elements.each("geonames/country") do |ele|
362 minlon = ele.get_text("bBoxWest").to_s
363 minlat = ele.get_text("bBoxSouth").to_s
364 maxlon = ele.get_text("bBoxEast").to_s
365 maxlat = ele.get_text("bBoxNorth").to_s
366 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
377 # Construct a random token of a given length
378 def self.make_token(length = 30)
379 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
383 token += chars[(rand * chars.length).to_i].chr
389 # Return an encrypted version of a password
390 def self.encrypt_password(password, salt)
391 return Digest::MD5.hexdigest(password) if salt.nil?
392 return Digest::MD5.hexdigest(salt + password)
395 # Return an SQL fragment to select a given area of the globe
396 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
397 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
398 minlat = (minlat * 10000000).round
399 minlon = (minlon * 10000000).round
400 maxlat = (maxlat * 10000000).round
401 maxlon = (maxlon * 10000000).round
403 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"