]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
Ignore the bits in tmp/
[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 a diff upload has an unknown action. You can only have create,
71   # modify, or delete
72   class APIChangesetActionInvalid < APIError
73     def initialize(provided)
74       @provided = provided
75     end
76     
77     def render_opts
78       { :text => "Unknown action #{@provided}, choices are create, modify, delete.",
79       :status => :bad_request }
80     end
81   end
82
83   # Raised when bad XML is encountered which stops things parsing as
84   # they should.
85   class APIBadXMLError < APIError
86     def initialize(model, xml)
87       @model, @xml = model, xml
88     end
89
90     def render_opts
91       { :text => "Cannot parse valid #{@model} from xml string #{@xml}",
92         :status => :bad_request }
93     end
94   end
95
96   # Raised when the provided version is not equal to the latest in the db.
97   class APIVersionMismatchError < APIError
98     def initialize(id, type, provided, latest)
99       @id, @type, @provided, @latest = id, type, provided, latest
100     end
101
102     attr_reader :provided, :latest, :id, :type
103
104     def render_opts
105       { :text => "Version mismatch: Provided " + provided.to_s +
106         ", server had: " + latest.to_s + " of " + type + " " + id.to_s, 
107         :status => :conflict }
108     end
109   end
110
111   # raised when a two tags have a duplicate key string in an element.
112   # this is now forbidden by the API.
113   class APIDuplicateTagsError < APIError
114     def initialize(type, id, tag_key)
115       @type, @id, @tag_key = type, id, tag_key
116     end
117
118     attr_reader :type, :id, :tag_key
119
120     def render_opts
121       { :text => "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}.",
122         :status => :bad_request }
123     end
124   end
125   
126   # Raised when a way has more than the configured number of way nodes.
127   # This prevents ways from being to long and difficult to work with
128   class APITooManyWayNodesError < APIError
129     def initialize(provided, max)
130       @provided, @max = provided, max
131     end
132     
133     attr_reader :provided, :max
134     
135     def render_opts
136       { :text => "You tried to add #{provided} nodes to the way, however only #{max} are allowed",
137       :status => :bad_request }
138     end
139   end
140
141   # Helper methods for going to/from mercator and lat/lng.
142   class Mercator
143     include Math
144
145     #init me with your bounding box and the size of your image
146     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
147       xsize = xsheet(max_lon) - xsheet(min_lon)
148       ysize = ysheet(max_lat) - ysheet(min_lat)
149       xscale = xsize / width
150       yscale = ysize / height
151       scale = [xscale, yscale].max
152
153       xpad = width * scale - xsize
154       ypad = height * scale - ysize
155
156       @width = width
157       @height = height
158
159       @tx = xsheet(min_lon) - xpad / 2
160       @ty = ysheet(min_lat) - ypad / 2
161
162       @bx = xsheet(max_lon) + xpad / 2
163       @by = ysheet(max_lat) + ypad / 2
164     end
165
166     #the following two functions will give you the x/y on the entire sheet
167
168     def ysheet(lat)
169       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
170     end
171
172     def xsheet(lon)
173       lon
174     end
175
176     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
177
178     def y(lat)
179       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
180     end
181
182     def x(lon)
183       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
184     end
185   end
186
187   class GreatCircle
188     include Math
189
190     # initialise with a base position
191     def initialize(lat, lon)
192       @lat = lat * PI / 180
193       @lon = lon * PI / 180
194     end
195
196     # get the distance from the base position to a given position
197     def distance(lat, lon)
198       lat = lat * PI / 180
199       lon = lon * PI / 180
200       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
201     end
202
203     # get the worst case bounds for a given radius from the base position
204     def bounds(radius)
205       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
206       lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
207       minlat = (@lat - latradius) * 180 / PI
208       maxlat = (@lat + latradius) * 180 / PI
209       minlon = (@lon - lonradius) * 180 / PI
210       maxlon = (@lon + lonradius) * 180 / PI
211       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
212     end
213   end
214
215   class GeoRSS
216     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
217       @doc = XML::Document.new
218       @doc.encoding = 'UTF-8' 
219
220       rss = XML::Node.new 'rss'
221       @doc.root = rss
222       rss['version'] = "2.0"
223       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
224       @channel = XML::Node.new 'channel'
225       rss << @channel
226       title = XML::Node.new 'title'
227       title <<  feed_title
228       @channel << title
229       description_el = XML::Node.new 'description'
230       @channel << description_el
231
232       description_el << feed_description
233       link = XML::Node.new 'link'
234       link << feed_url
235       @channel << link
236       image = XML::Node.new 'image'
237       @channel << image
238       url = XML::Node.new 'url'
239       url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
240       image << url
241       title = XML::Node.new 'title'
242       title << "OpenStreetMap"
243       image << title
244       width = XML::Node.new 'width'
245       width << '100'
246       image << width
247       height = XML::Node.new 'height'
248       height << '100'
249       image << height
250       link = XML::Node.new 'link'
251       link << feed_url
252       image << link
253     end
254
255     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)
256       item = XML::Node.new 'item'
257
258       title = XML::Node.new 'title'
259       item << title
260       title << title_text
261       link = XML::Node.new 'link'
262       link << url
263       item << link
264
265       guid = XML::Node.new 'guid'
266       guid << url
267       item << guid
268
269       description = XML::Node.new 'description'
270       description << description_text
271       item << description
272
273       author = XML::Node.new 'author'
274       author << author_text
275       item << author
276
277       pubDate = XML::Node.new 'pubDate'
278       pubDate << timestamp.to_s(:rfc822)
279       item << pubDate
280
281       if latitude
282         lat_el = XML::Node.new 'geo:lat'
283         lat_el << latitude.to_s
284         item << lat_el
285       end
286
287       if longitude
288         lon_el = XML::Node.new 'geo:long'
289         lon_el << longitude.to_s
290         item << lon_el
291       end
292
293       @channel << item
294     end
295
296     def to_s
297       return @doc.to_s
298     end
299   end
300
301   class API
302     def get_xml_doc
303       doc = XML::Document.new
304       doc.encoding = 'UTF-8' 
305       root = XML::Node.new 'osm'
306       root['version'] = API_VERSION
307       root['generator'] = GENERATOR
308       doc.root = root
309       return doc
310     end
311   end
312
313   def self.IPLocation(ip_address)
314     Timeout::timeout(4) do
315       Net::HTTP.start('api.hostip.info') do |http|
316         country = http.get("/country.php?ip=#{ip_address}").body
317         country = "GB" if country == "UK"
318         Net::HTTP.start('ws.geonames.org') do |http|
319           xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
320           xml.elements.each("geonames/country") do |ele|
321             minlon = ele.get_text("bBoxWest").to_s
322             minlat = ele.get_text("bBoxSouth").to_s
323             maxlon = ele.get_text("bBoxEast").to_s
324             maxlat = ele.get_text("bBoxNorth").to_s
325             return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
326           end
327         end
328       end
329     end
330
331     return nil
332   rescue Exception
333     return nil
334   end
335
336   # Construct a random token of a given length
337   def self.make_token(length = 30)
338     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
339     token = ''
340
341     length.times do
342       token += chars[(rand * chars.length).to_i].chr
343     end
344
345     return token
346   end
347
348   # Return an encrypted version of a password
349   def self.encrypt_password(password, salt)
350     return Digest::MD5.hexdigest(password) if salt.nil?
351     return Digest::MD5.hexdigest(salt + password)
352   end
353
354   # Return an SQL fragment to select a given area of the globe
355   def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
356     tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
357     minlat = (minlat * 10000000).round
358     minlon = (minlon * 10000000).round
359     maxlat = (maxlat * 10000000).round
360     maxlon = (maxlon * 10000000).round
361
362     return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
363   end
364
365
366 end