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