]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
Add a description meta tag for the all web pages. Wording probably needs to be improved.
[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   # Helper methods for going to/from mercator and lat/lng.
113   class Mercator
114     include Math
115
116     #init me with your bounding box and the size of your image
117     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
118       xsize = xsheet(max_lon) - xsheet(min_lon)
119       ysize = ysheet(max_lat) - ysheet(min_lat)
120       xscale = xsize / width
121       yscale = ysize / height
122       scale = [xscale, yscale].max
123
124       xpad = width * scale - xsize
125       ypad = height * scale - ysize
126
127       @width = width
128       @height = height
129
130       @tx = xsheet(min_lon) - xpad / 2
131       @ty = ysheet(min_lat) - ypad / 2
132
133       @bx = xsheet(max_lon) + xpad / 2
134       @by = ysheet(max_lat) + ypad / 2
135     end
136
137     #the following two functions will give you the x/y on the entire sheet
138
139     def ysheet(lat)
140       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
141     end
142
143     def xsheet(lon)
144       lon
145     end
146
147     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
148
149     def y(lat)
150       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
151     end
152
153     def x(lon)
154       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
155     end
156   end
157
158   class GreatCircle
159     include Math
160
161     # initialise with a base position
162     def initialize(lat, lon)
163       @lat = lat * PI / 180
164       @lon = lon * PI / 180
165     end
166
167     # get the distance from the base position to a given position
168     def distance(lat, lon)
169       lat = lat * PI / 180
170       lon = lon * PI / 180
171       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
172     end
173
174     # get the worst case bounds for a given radius from the base position
175     def bounds(radius)
176       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
177       lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
178       minlat = (@lat - latradius) * 180 / PI
179       maxlat = (@lat + latradius) * 180 / PI
180       minlon = (@lon - lonradius) * 180 / PI
181       maxlon = (@lon + lonradius) * 180 / PI
182       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
183     end
184   end
185
186   class GeoRSS
187     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
188       @doc = XML::Document.new
189       @doc.encoding = 'UTF-8' 
190
191       rss = XML::Node.new 'rss'
192       @doc.root = rss
193       rss['version'] = "2.0"
194       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
195       @channel = XML::Node.new 'channel'
196       rss << @channel
197       title = XML::Node.new 'title'
198       title <<  feed_title
199       @channel << title
200       description_el = XML::Node.new 'description'
201       @channel << description_el
202
203       description_el << feed_description
204       link = XML::Node.new 'link'
205       link << feed_url
206       @channel << link
207       image = XML::Node.new 'image'
208       @channel << image
209       url = XML::Node.new 'url'
210       url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
211       image << url
212       title = XML::Node.new 'title'
213       title << "OpenStreetMap"
214       image << title
215       width = XML::Node.new 'width'
216       width << '100'
217       image << width
218       height = XML::Node.new 'height'
219       height << '100'
220       image << height
221       link = XML::Node.new 'link'
222       link << feed_url
223       image << link
224     end
225
226     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)
227       item = XML::Node.new 'item'
228
229       title = XML::Node.new 'title'
230       item << title
231       title << title_text
232       link = XML::Node.new 'link'
233       link << url
234       item << link
235
236       guid = XML::Node.new 'guid'
237       guid << url
238       item << guid
239
240       description = XML::Node.new 'description'
241       description << description_text
242       item << description
243
244       author = XML::Node.new 'author'
245       author << author_text
246       item << author
247
248       pubDate = XML::Node.new 'pubDate'
249       pubDate << timestamp.to_s(:rfc822)
250       item << pubDate
251
252       if latitude
253         lat_el = XML::Node.new 'geo:lat'
254         lat_el << latitude.to_s
255         item << lat_el
256       end
257
258       if longitude
259         lon_el = XML::Node.new 'geo:long'
260         lon_el << longitude.to_s
261         item << lon_el
262       end
263
264       @channel << item
265     end
266
267     def to_s
268       return @doc.to_s
269     end
270   end
271
272   class API
273     def get_xml_doc
274       doc = XML::Document.new
275       doc.encoding = 'UTF-8' 
276       root = XML::Node.new 'osm'
277       root['version'] = API_VERSION
278       root['generator'] = GENERATOR
279       doc.root = root
280       return doc
281     end
282   end
283
284   def self.IPLocation(ip_address)
285     Timeout::timeout(4) do
286       Net::HTTP.start('api.hostip.info') do |http|
287         country = http.get("/country.php?ip=#{ip_address}").body
288         country = "GB" if country == "UK"
289         Net::HTTP.start('ws.geonames.org') do |http|
290           xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
291           xml.elements.each("geonames/country") do |ele|
292             minlon = ele.get_text("bBoxWest").to_s
293             minlat = ele.get_text("bBoxSouth").to_s
294             maxlon = ele.get_text("bBoxEast").to_s
295             maxlat = ele.get_text("bBoxNorth").to_s
296             return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
297           end
298         end
299       end
300     end
301
302     return nil
303   rescue Exception
304     return nil
305   end
306
307   # Construct a random token of a given length
308   def self.make_token(length = 30)
309     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
310     token = ''
311
312     length.times do
313       token += chars[(rand * chars.length).to_i].chr
314     end
315
316     return token
317   end
318
319   # Return an encrypted version of a password
320   def self.encrypt_password(password, salt)
321     return Digest::MD5.hexdigest(password) if salt.nil?
322     return Digest::MD5.hexdigest(salt + password)
323   end
324
325   # Return an SQL fragment to select a given area of the globe
326   def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
327     tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
328     minlat = (minlat * 10000000).round
329     minlon = (minlon * 10000000).round
330     maxlat = (maxlat * 10000000).round
331     maxlon = (maxlon * 10000000).round
332
333     return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
334   end
335
336
337 end