]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
moving the check consistency to it's own file so that checks will be able to be loade...
[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 the provided version is not equal to the latest in the db.
58   class APIVersionMismatchError < APIError
59     def initialize(provided, latest)
60       @provided, @latest = provided, latest
61     end
62
63     attr_reader :provided, :latest
64
65     def render_opts
66       { :text => "Version mismatch: Provided " + provided.to_s +
67       ", server had: " + latest.to_s, :status => :conflict }
68     end
69   end
70
71   # Helper methods for going to/from mercator and lat/lng.
72   class Mercator
73     include Math
74
75     #init me with your bounding box and the size of your image
76     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
77       xsize = xsheet(max_lon) - xsheet(min_lon)
78       ysize = ysheet(max_lat) - ysheet(min_lat)
79       xscale = xsize / width
80       yscale = ysize / height
81       scale = [xscale, yscale].max
82
83       xpad = width * scale - xsize
84       ypad = height * scale - ysize
85
86       @width = width
87       @height = height
88
89       @tx = xsheet(min_lon) - xpad / 2
90       @ty = ysheet(min_lat) - ypad / 2
91
92       @bx = xsheet(max_lon) + xpad / 2
93       @by = ysheet(max_lat) + ypad / 2
94     end
95
96     #the following two functions will give you the x/y on the entire sheet
97
98     def ysheet(lat)
99       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
100     end
101
102     def xsheet(lon)
103       lon
104     end
105
106     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
107
108     def y(lat)
109       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
110     end
111
112     def x(lon)
113       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
114     end
115   end
116
117   class GreatCircle
118     include Math
119
120     # initialise with a base position
121     def initialize(lat, lon)
122       @lat = lat * PI / 180
123       @lon = lon * PI / 180
124     end
125
126     # get the distance from the base position to a given position
127     def distance(lat, lon)
128       lat = lat * PI / 180
129       lon = lon * PI / 180
130       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
131     end
132
133     # get the worst case bounds for a given radius from the base position
134     def bounds(radius)
135       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
136       lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
137       minlat = (@lat - latradius) * 180 / PI
138       maxlat = (@lat + latradius) * 180 / PI
139       minlon = (@lon - lonradius) * 180 / PI
140       maxlon = (@lon + lonradius) * 180 / PI
141       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
142     end
143   end
144
145   class GeoRSS
146     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
147       @doc = XML::Document.new
148       @doc.encoding = 'UTF-8' 
149
150       rss = XML::Node.new 'rss'
151       @doc.root = rss
152       rss['version'] = "2.0"
153       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
154       @channel = XML::Node.new 'channel'
155       rss << @channel
156       title = XML::Node.new 'title'
157       title <<  feed_title
158       @channel << title
159       description_el = XML::Node.new 'description'
160       @channel << description_el
161
162       description_el << feed_description
163       link = XML::Node.new 'link'
164       link << feed_url
165       @channel << link
166       image = XML::Node.new 'image'
167       @channel << image
168       url = XML::Node.new 'url'
169       url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
170       image << url
171       title = XML::Node.new 'title'
172       title << "OpenStreetMap"
173       image << title
174       width = XML::Node.new 'width'
175       width << '100'
176       image << width
177       height = XML::Node.new 'height'
178       height << '100'
179       image << height
180       link = XML::Node.new 'link'
181       link << feed_url
182       image << link
183     end
184
185     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)
186       item = XML::Node.new 'item'
187
188       title = XML::Node.new 'title'
189       item << title
190       title << title_text
191       link = XML::Node.new 'link'
192       link << url
193       item << link
194
195       guid = XML::Node.new 'guid'
196       guid << url
197       item << guid
198
199       description = XML::Node.new 'description'
200       description << description_text
201       item << description
202
203       author = XML::Node.new 'author'
204       author << author_text
205       item << author
206
207       pubDate = XML::Node.new 'pubDate'
208       pubDate << timestamp.to_s(:rfc822)
209       item << pubDate
210
211       if latitude
212         lat_el = XML::Node.new 'geo:lat'
213         lat_el << latitude.to_s
214         item << lat_el
215       end
216
217       if longitude
218         lon_el = XML::Node.new 'geo:long'
219         lon_el << longitude.to_s
220         item << lon_el
221       end
222
223       @channel << item
224     end
225
226     def to_s
227       return @doc.to_s
228     end
229   end
230
231   class API
232     def get_xml_doc
233       doc = XML::Document.new
234       doc.encoding = 'UTF-8' 
235       root = XML::Node.new 'osm'
236       root['version'] = API_VERSION
237       root['generator'] = 'OpenStreetMap server'
238       doc.root = root
239       return doc
240     end
241   end
242
243   def self.IPLocation(ip_address)
244     Timeout::timeout(4) do
245       Net::HTTP.start('api.hostip.info') do |http|
246         country = http.get("/country.php?ip=#{ip_address}").body
247         country = "GB" if country == "UK"
248         Net::HTTP.start('ws.geonames.org') do |http|
249           xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
250           xml.elements.each("geonames/country") do |ele|
251             minlon = ele.get_text("bBoxWest").to_s
252             minlat = ele.get_text("bBoxSouth").to_s
253             maxlon = ele.get_text("bBoxEast").to_s
254             maxlat = ele.get_text("bBoxNorth").to_s
255             return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
256           end
257         end
258       end
259     end
260
261     return nil
262   rescue Exception
263     return nil
264   end
265
266   # Construct a random token of a given length
267   def self.make_token(length = 30)
268     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
269     token = ''
270
271     length.times do
272       token += chars[(rand * chars.length).to_i].chr
273     end
274
275     return token
276   end
277
278   # Return an encrypted version of a password
279   def self.encrypt_password(password, salt)
280     return Digest::MD5.hexdigest(password) if salt.nil?
281     return Digest::MD5.hexdigest(salt + password)
282   end
283
284   # Return an SQL fragment to select a given area of the globe
285   def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
286     tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
287     minlat = (minlat * 10000000).round
288     minlon = (minlon * 10000000).round
289     maxlat = (maxlat * 10000000).round
290     maxlon = (maxlon * 10000000).round
291
292     return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
293   end
294
295
296 end