]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
Link to the Markdown spec
[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
10   if defined?(SystemTimer)
11     Timer = SystemTimer
12   else
13     require 'timeout'
14     Timer = Timeout
15   end
16
17   # The base class for API Errors.
18   class APIError < RuntimeError
19     def status
20       :internal_server_error
21     end
22
23     def to_s
24       "Generic API Error"
25     end
26   end
27
28   # Raised when an API object is not found.
29   class APINotFoundError < APIError
30     def status
31       :not_found
32     end
33
34     def to_s
35       "Object not found"
36     end
37   end
38
39   # Raised when a precondition to an API action fails sanity check.
40   class APIPreconditionFailedError < APIError
41     def initialize(message = "")
42       @message = message
43     end
44
45     def status
46       :precondition_failed
47     end
48
49     def to_s
50       "Precondition failed: #{@message}"
51     end
52   end
53
54   # Raised when to delete an already-deleted object.
55   class APIAlreadyDeletedError < APIError
56     def initialize(object = "object", object_id = "")
57       @object, @object_id = object, object_id
58     end
59
60     attr_reader :object, :object_id
61
62     def status
63       :gone
64     end
65
66     def to_s
67       "The #{object} with the id #{object_id} has already been deleted"
68     end
69   end
70
71   # Raised when the user logged in isn't the same as the changeset
72   class APIUserChangesetMismatchError < APIError
73     def status
74       :conflict
75     end
76
77     def to_s
78       "The user doesn't own that changeset"
79     end
80   end
81
82   # Raised when the changeset provided is already closed
83   class APIChangesetAlreadyClosedError < APIError
84     def initialize(changeset)
85       @changeset = changeset
86     end
87
88     attr_reader :changeset
89
90     def status
91       :conflict
92     end
93
94     def to_s
95       "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
96     end
97   end
98
99   # Raised when a change is expecting a changeset, but the changeset doesn't exist
100   class APIChangesetMissingError < APIError
101     def status
102       :conflict
103     end
104
105     def to_s
106       "You need to supply a changeset to be able to make a change"
107     end
108   end
109
110   # Raised when a diff is uploaded containing many changeset IDs which don't match
111   # the changeset ID that the diff was uploaded to.
112   class APIChangesetMismatchError < APIError
113     def initialize(provided, allowed)
114       @provided, @allowed = provided, allowed
115     end
116
117     def status
118       :conflict
119     end
120
121     def to_s
122       "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
123     end
124   end
125
126   # Raised when a diff upload has an unknown action. You can only have create,
127   # modify, or delete
128   class APIChangesetActionInvalid < APIError
129     def initialize(provided)
130       @provided = provided
131     end
132
133     def status
134       :bad_request
135     end
136
137     def to_s
138       "Unknown action #{@provided}, choices are create, modify, delete"
139     end
140   end
141
142   # Raised when bad XML is encountered which stops things parsing as
143   # they should.
144   class APIBadXMLError < APIError
145     def initialize(model, xml, message="")
146       @model, @xml, @message = model, xml, message
147     end
148
149     def status
150       :bad_request
151     end
152
153     def to_s
154       "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
155     end
156   end
157
158   # Raised when the provided version is not equal to the latest in the db.
159   class APIVersionMismatchError < APIError
160     def initialize(id, type, provided, latest)
161       @id, @type, @provided, @latest = id, type, provided, latest
162     end
163
164     attr_reader :provided, :latest, :id, :type
165
166     def status
167       :conflict
168     end
169
170     def to_s
171       "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
172     end
173   end
174
175   # raised when a two tags have a duplicate key string in an element.
176   # this is now forbidden by the API.
177   class APIDuplicateTagsError < APIError
178     def initialize(type, id, tag_key)
179       @type, @id, @tag_key = type, id, tag_key
180     end
181
182     attr_reader :type, :id, :tag_key
183
184     def status
185       :bad_request
186     end
187
188     def to_s
189       "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
190     end
191   end
192
193   # Raised when a way has more than the configured number of way nodes.
194   # This prevents ways from being to long and difficult to work with
195   class APITooManyWayNodesError < APIError
196     def initialize(id, provided, max)
197       @id, @provided, @max = id, provided, max
198     end
199
200     attr_reader :id, :provided, :max
201
202     def status
203       :bad_request
204     end
205
206     def to_s
207       "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
208     end
209   end
210
211   ##
212   # raised when user input couldn't be parsed
213   class APIBadUserInput < APIError
214     def initialize(message)
215       @message = message
216     end
217
218     def status
219       :bad_request
220     end
221
222     def to_s
223       @message
224     end
225   end
226
227   ##
228   # raised when bounding box is invalid
229   class APIBadBoundingBox < APIError
230     def initialize(message)
231       @message = message
232     end
233
234     def status
235       :bad_request
236     end
237
238     def to_s
239       @message
240     end
241   end
242
243   ##
244   # raised when an API call is made using a method not supported on that URI
245   class APIBadMethodError < APIError
246     def initialize(supported_method)
247       @supported_method = supported_method
248     end
249
250     def status
251       :method_not_allowed
252     end
253
254     def to_s
255       "Only method #{@supported_method} is supported on this URI"
256     end
257   end
258
259   ##
260   # raised when an API call takes too long
261   class APITimeoutError < APIError
262     def status
263       :request_timeout
264     end
265
266     def to_s
267       "Request timed out"
268     end
269   end
270
271   # Helper methods for going to/from mercator and lat/lng.
272   class Mercator
273     include Math
274
275     #init me with your bounding box and the size of your image
276     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
277       xsize = xsheet(max_lon) - xsheet(min_lon)
278       ysize = ysheet(max_lat) - ysheet(min_lat)
279       xscale = xsize / width
280       yscale = ysize / height
281       scale = [xscale, yscale].max
282
283       xpad = width * scale - xsize
284       ypad = height * scale - ysize
285
286       @width = width
287       @height = height
288
289       @tx = xsheet(min_lon) - xpad / 2
290       @ty = ysheet(min_lat) - ypad / 2
291
292       @bx = xsheet(max_lon) + xpad / 2
293       @by = ysheet(max_lat) + ypad / 2
294     end
295
296     #the following two functions will give you the x/y on the entire sheet
297
298     def ysheet(lat)
299       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
300     end
301
302     def xsheet(lon)
303       lon
304     end
305
306     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
307
308     def y(lat)
309       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
310     end
311
312     def x(lon)
313       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
314     end
315   end
316
317   class GreatCircle
318     include Math
319
320     # initialise with a base position
321     def initialize(lat, lon)
322       @lat = lat * PI / 180
323       @lon = lon * PI / 180
324     end
325
326     # get the distance from the base position to a given position
327     def distance(lat, lon)
328       lat = lat * PI / 180
329       lon = lon * PI / 180
330       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
331     end
332
333     # get the worst case bounds for a given radius from the base position
334     def bounds(radius)
335       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
336
337       begin
338         lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
339       rescue Errno::EDOM
340         lonradius = PI
341       end
342
343       minlat = (@lat - latradius) * 180 / PI
344       maxlat = (@lat + latradius) * 180 / PI
345       minlon = (@lon - lonradius) * 180 / PI
346       maxlon = (@lon + lonradius) * 180 / PI
347
348       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
349     end
350
351     # get the SQL to use to calculate distance
352     def sql_for_distance(lat_field, lon_field)
353       "6372.795 * 2 * asin(sqrt(power(sin((radians(#{lat_field}) - #{@lat}) / 2), 2) + cos(#{@lat}) * cos(radians(#{lat_field})) * power(sin((radians(#{lon_field}) - #{@lon})/2), 2)))"
354     end
355   end
356
357   class GeoRSS
358     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
359       @doc = XML::Document.new
360       @doc.encoding = XML::Encoding::UTF_8
361
362       rss = XML::Node.new 'rss'
363       @doc.root = rss
364       rss['version'] = "2.0"
365       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
366       @channel = XML::Node.new 'channel'
367       rss << @channel
368       title = XML::Node.new 'title'
369       title <<  feed_title
370       @channel << title
371       description_el = XML::Node.new 'description'
372       @channel << description_el
373
374       description_el << feed_description
375       link = XML::Node.new 'link'
376       link << feed_url
377       @channel << link
378       image = XML::Node.new 'image'
379       @channel << image
380       url = XML::Node.new 'url'
381       url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
382       image << url
383       title = XML::Node.new 'title'
384       title << "OpenStreetMap"
385       image << title
386       width = XML::Node.new 'width'
387       width << '100'
388       image << width
389       height = XML::Node.new 'height'
390       height << '100'
391       image << height
392       link = XML::Node.new 'link'
393       link << feed_url
394       image << link
395     end
396
397     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)
398       item = XML::Node.new 'item'
399
400       title = XML::Node.new 'title'
401       item << title
402       title << title_text
403       link = XML::Node.new 'link'
404       link << url
405       item << link
406
407       guid = XML::Node.new 'guid'
408       guid << url
409       item << guid
410
411       description = XML::Node.new 'description'
412       description << description_text
413       item << description
414
415       author = XML::Node.new 'author'
416       author << author_text
417       item << author
418
419       pubDate = XML::Node.new 'pubDate'
420       pubDate << timestamp.to_s(:rfc822)
421       item << pubDate
422
423       if latitude
424         lat_el = XML::Node.new 'geo:lat'
425         lat_el << latitude.to_s
426         item << lat_el
427       end
428
429       if longitude
430         lon_el = XML::Node.new 'geo:long'
431         lon_el << longitude.to_s
432         item << lon_el
433       end
434
435       @channel << item
436     end
437
438     def to_s
439       return @doc.to_s
440     end
441   end
442
443   class API
444     def get_xml_doc
445       doc = XML::Document.new
446       doc.encoding = XML::Encoding::UTF_8
447       root = XML::Node.new 'osm'
448       root['version'] = API_VERSION.to_s
449       root['generator'] = GENERATOR
450       doc.root = root
451       return doc
452     end
453   end
454
455   def self.IPToCountry(ip_address)
456     Timer.timeout(4) do
457       ipinfo = Quova::IpInfo.new(ip_address)
458
459       if ipinfo.status == Quova::Success then
460         country = ipinfo.country_code
461       else
462         Net::HTTP.start('api.hostip.info') do |http|
463           country = http.get("/country.php?ip=#{ip_address}").body
464           country = "GB" if country == "UK"
465         end
466       end
467       
468       return country.upcase
469     end
470
471     return nil
472   rescue Exception
473     return nil
474   end
475
476   def self.IPLocation(ip_address)
477     code = OSM.IPToCountry(ip_address)
478
479     if code and country = Country.find_by_code(code)
480       return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
481     end
482
483     return nil
484   end
485
486   # Construct a random token of a given length
487   def self.make_token(length = 30)
488     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
489     token = ''
490
491     length.times do
492       token += chars[(rand * chars.length).to_i].chr
493     end
494
495     return token
496   end
497
498   # Return an encrypted version of a password
499   def self.encrypt_password(password, salt)
500     return Digest::MD5.hexdigest(password) if salt.nil?
501     return Digest::MD5.hexdigest(salt + password)
502   end
503
504   # Return an SQL fragment to select a given area of the globe
505   def self.sql_for_area(bbox, prefix = nil)
506     tilesql = QuadTile.sql_for_area(bbox, prefix)
507     bbox = bbox.to_scaled
508
509     return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
510                       "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
511   end
512
513   def self.legal_text_for_country(country_code)
514     file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
515     file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
516     YAML::load_file(file_name)
517   end
518 end