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