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