]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
Adding a restriction to prevent more than 2000 nodes to be added to any way. Tests...
[rails.git] / lib / osm.rb
1 # The OSM module provides support functions for OSM.
2 module OSM
3
4   require 'time'
5   require 'rexml/parsers/sax2parser'
6   require 'rexml/text'
7   require 'xml/libxml'
8   require 'digest/md5'
9   require 'RMagick'
10
11   # The base class for API Errors.
12   class APIError < RuntimeError
13     def render_opts
14       { :text => "", :status => :internal_server_error }
15     end
16   end
17
18   # Raised when an API object is not found.
19   class APINotFoundError < APIError
20   end
21
22   # Raised when a precondition to an API action fails sanity check.
23   class APIPreconditionFailedError < APIError
24     def render_opts
25       { :text => "", :status => :precondition_failed }
26     end
27   end
28
29   # Raised when to delete an already-deleted object.
30   class APIAlreadyDeletedError < APIError
31     def render_opts
32       { :text => "", :status => :gone }
33     end
34   end
35
36   # Raised when the user logged in isn't the same as the changeset
37   class APIUserChangesetMismatchError < APIError
38     def render_opts
39       { :text => "The user doesn't own that changeset", :status => :conflict }
40     end
41   end
42
43   # Raised when the changeset provided is already closed
44   class APIChangesetAlreadyClosedError < APIError
45     def render_opts
46       { :text => "The supplied changeset has already been closed", :status => :conflict }
47     end
48   end
49   
50   # Raised when a change is expecting a changeset, but the changeset doesn't exist
51   class APIChangesetMissingError < APIError
52     def render_opts
53       { :text => "You need to supply a changeset to be able to make a change", :status => :conflict }
54     end
55   end
56
57   # Raised when a diff is uploaded containing many changeset IDs which don't match
58   # the changeset ID that the diff was uploaded to.
59   class APIChangesetMismatchError < APIError
60     def initialize(provided, allowed)
61       @provided, @allowed = provided, allowed
62     end
63     
64     def render_opts
65       { :text => "Changeset mismatch: Provided #{@provided} but only " +
66         "#{@allowed} is allowed.", :status => :conflict }
67     end
68   end
69
70   # Raised when bad XML is encountered which stops things parsing as
71   # they should.
72   class APIBadXMLError < APIError
73     def initialize(model, xml)
74       @model, @xml = model, xml
75     end
76
77     def render_opts
78       { :text => "Cannot parse valid #{@model} from xml string #{@xml}",
79         :status => :bad_request }
80     end
81   end
82
83   # Raised when the provided version is not equal to the latest in the db.
84   class APIVersionMismatchError < APIError
85     def initialize(provided, latest)
86       @provided, @latest = provided, latest
87     end
88
89     attr_reader :provided, :latest
90
91     def render_opts
92       { :text => "Version mismatch: Provided " + provided.to_s +
93       ", server had: " + latest.to_s, :status => :conflict }
94     end
95   end
96
97   # raised when a two tags have a duplicate key string in an element.
98   # this is now forbidden by the API.
99   class APIDuplicateTagsError < APIError
100     def initialize(type, id, tag_key)
101       @type, @id, @tag_key = type, id, tag_key
102     end
103
104     attr_reader :type, :id, :tag_key
105
106     def render_opts
107       { :text => "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}.",
108         :status => :bad_request }
109     end
110   end
111   
112   # Raised when a way has more than the configured number of way nodes.
113   # This prevents ways from being to long and difficult to work with
114   class APITooManyWayNodesError < APIError
115     def initialize(provided, max)
116       @provided, @max = provided, max
117     end
118     
119     attr_reader :provided, :max
120     
121     def render_opts
122       { :text => "You tried to add #{provided} nodes to the way, however only #{max} are allowed",
123       :status => :bad_request }
124     end
125   end
126
127   # Helper methods for going to/from mercator and lat/lng.
128   class Mercator
129     include Math
130
131     #init me with your bounding box and the size of your image
132     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
133       xsize = xsheet(max_lon) - xsheet(min_lon)
134       ysize = ysheet(max_lat) - ysheet(min_lat)
135       xscale = xsize / width
136       yscale = ysize / height
137       scale = [xscale, yscale].max
138
139       xpad = width * scale - xsize
140       ypad = height * scale - ysize
141
142       @width = width
143       @height = height
144
145       @tx = xsheet(min_lon) - xpad / 2
146       @ty = ysheet(min_lat) - ypad / 2
147
148       @bx = xsheet(max_lon) + xpad / 2
149       @by = ysheet(max_lat) + ypad / 2
150     end
151
152     #the following two functions will give you the x/y on the entire sheet
153
154     def ysheet(lat)
155       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
156     end
157
158     def xsheet(lon)
159       lon
160     end
161
162     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
163
164     def y(lat)
165       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
166     end
167
168     def x(lon)
169       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
170     end
171   end
172
173   class GreatCircle
174     include Math
175
176     # initialise with a base position
177     def initialize(lat, lon)
178       @lat = lat * PI / 180
179       @lon = lon * PI / 180
180     end
181
182     # get the distance from the base position to a given position
183     def distance(lat, lon)
184       lat = lat * PI / 180
185       lon = lon * PI / 180
186       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
187     end
188
189     # get the worst case bounds for a given radius from the base position
190     def bounds(radius)
191       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
192       lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
193       minlat = (@lat - latradius) * 180 / PI
194       maxlat = (@lat + latradius) * 180 / PI
195       minlon = (@lon - lonradius) * 180 / PI
196       maxlon = (@lon + lonradius) * 180 / PI
197       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
198     end
199   end
200
201   class GeoRSS
202     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
203       @doc = XML::Document.new
204       @doc.encoding = 'UTF-8' 
205
206       rss = XML::Node.new 'rss'
207       @doc.root = rss
208       rss['version'] = "2.0"
209       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
210       @channel = XML::Node.new 'channel'
211       rss << @channel
212       title = XML::Node.new 'title'
213       title <<  feed_title
214       @channel << title
215       description_el = XML::Node.new 'description'
216       @channel << description_el
217
218       description_el << feed_description
219       link = XML::Node.new 'link'
220       link << feed_url
221       @channel << link
222       image = XML::Node.new 'image'
223       @channel << image
224       url = XML::Node.new 'url'
225       url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
226       image << url
227       title = XML::Node.new 'title'
228       title << "OpenStreetMap"
229       image << title
230       width = XML::Node.new 'width'
231       width << '100'
232       image << width
233       height = XML::Node.new 'height'
234       height << '100'
235       image << height
236       link = XML::Node.new 'link'
237       link << feed_url
238       image << link
239     end
240
241     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)
242       item = XML::Node.new 'item'
243
244       title = XML::Node.new 'title'
245       item << title
246       title << title_text
247       link = XML::Node.new 'link'
248       link << url
249       item << link
250
251       guid = XML::Node.new 'guid'
252       guid << url
253       item << guid
254
255       description = XML::Node.new 'description'
256       description << description_text
257       item << description
258
259       author = XML::Node.new 'author'
260       author << author_text
261       item << author
262
263       pubDate = XML::Node.new 'pubDate'
264       pubDate << timestamp.to_s(:rfc822)
265       item << pubDate
266
267       if latitude
268         lat_el = XML::Node.new 'geo:lat'
269         lat_el << latitude.to_s
270         item << lat_el
271       end
272
273       if longitude
274         lon_el = XML::Node.new 'geo:long'
275         lon_el << longitude.to_s
276         item << lon_el
277       end
278
279       @channel << item
280     end
281
282     def to_s
283       return @doc.to_s
284     end
285   end
286
287   class API
288     def get_xml_doc
289       doc = XML::Document.new
290       doc.encoding = 'UTF-8' 
291       root = XML::Node.new 'osm'
292       root['version'] = API_VERSION
293       root['generator'] = GENERATOR
294       doc.root = root
295       return doc
296     end
297   end
298
299   def self.IPLocation(ip_address)
300     Timeout::timeout(4) do
301       Net::HTTP.start('api.hostip.info') do |http|
302         country = http.get("/country.php?ip=#{ip_address}").body
303         country = "GB" if country == "UK"
304         Net::HTTP.start('ws.geonames.org') do |http|
305           xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
306           xml.elements.each("geonames/country") do |ele|
307             minlon = ele.get_text("bBoxWest").to_s
308             minlat = ele.get_text("bBoxSouth").to_s
309             maxlon = ele.get_text("bBoxEast").to_s
310             maxlat = ele.get_text("bBoxNorth").to_s
311             return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
312           end
313         end
314       end
315     end
316
317     return nil
318   rescue Exception
319     return nil
320   end
321
322   # Construct a random token of a given length
323   def self.make_token(length = 30)
324     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
325     token = ''
326
327     length.times do
328       token += chars[(rand * chars.length).to_i].chr
329     end
330
331     return token
332   end
333
334   # Return an encrypted version of a password
335   def self.encrypt_password(password, salt)
336     return Digest::MD5.hexdigest(password) if salt.nil?
337     return Digest::MD5.hexdigest(salt + password)
338   end
339
340   # Return an SQL fragment to select a given area of the globe
341   def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
342     tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
343     minlat = (minlat * 10000000).round
344     minlon = (minlon * 10000000).round
345     maxlat = (maxlat * 10000000).round
346     maxlon = (maxlon * 10000000).round
347
348     return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
349   end
350
351
352 end