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