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