]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
Implemented changeset tags updating via the update method.
[rails.git] / app / controllers / changeset_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 class ChangesetController < ApplicationController
4   require 'xml/libxml'
5   require 'diff_reader'
6
7   before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
8   before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
9   before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
10   after_filter :compress_output
11
12   # Help methods for checking boundary sanity and area size
13   include MapBoundary
14
15   # Create a changeset from XML.
16   def create
17     if request.put?
18       cs = Changeset.from_xml(request.raw_post, true)
19
20       if cs
21         cs.user_id = @user.id
22         cs.save_with_tags!
23         render :text => cs.id.to_s, :content_type => "text/plain"
24       else
25         render :nothing => true, :status => :bad_request
26       end
27     else
28       render :nothing => true, :status => :method_not_allowed
29     end
30   end
31
32   def read
33     begin
34       changeset = Changeset.find(params[:id])
35       render :text => changeset.to_xml.to_s, :content_type => "text/xml"
36     rescue ActiveRecord::RecordNotFound
37       render :nothing => true, :status => :not_found
38     end
39   end
40   
41   def close 
42     begin
43       unless request.put?
44         render :nothing => true, :status => :method_not_allowed
45         return
46       end
47
48       changeset = Changeset.find(params[:id])
49
50       unless @user.id == changeset.user_id 
51         raise OSM::APIUserChangesetMismatchError 
52       end
53
54       changeset.open = false
55       changeset.save!
56       render :nothing => true
57     rescue ActiveRecord::RecordNotFound
58       render :nothing => true, :status => :not_found
59     end
60   end
61
62   ##
63   # insert a (set of) points into a changeset bounding box. this can only
64   # increase the size of the bounding box. this is a hint that clients can
65   # set either before uploading a large number of changes, or changes that
66   # the client (but not the server) knows will affect areas further away.
67   def include
68     # only allow POST requests, because although this method is
69     # idempotent, there is no "document" to PUT really...
70     if request.post?
71       cs = Changeset.find(params[:id])
72
73       # check user credentials - only the user who opened a changeset
74       # may alter it.
75       unless @user.id == cs.user_id 
76         raise OSM::APIUserChangesetMismatchError 
77       end
78
79       # keep an array of lons and lats
80       lon = Array.new
81       lat = Array.new
82
83       # the request is in pseudo-osm format... this is kind-of an
84       # abuse, maybe should change to some other format?
85       doc = XML::Parser.string(request.raw_post).parse
86       doc.find("//osm/node").each do |n|
87         lon << n['lon'].to_f * GeoRecord::SCALE
88         lat << n['lat'].to_f * GeoRecord::SCALE
89       end
90
91       # add the existing bounding box to the lon-lat array
92       lon << cs.min_lon unless cs.min_lon.nil?
93       lat << cs.min_lat unless cs.min_lat.nil?
94       lon << cs.max_lon unless cs.max_lon.nil?
95       lat << cs.max_lat unless cs.max_lat.nil?
96
97       # collapse the arrays to minimum and maximum
98       cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat = 
99         lon.min, lat.min, lon.max, lat.max
100
101       # save the larger bounding box and return the changeset, which
102       # will include the bigger bounding box.
103       cs.save!
104       render :text => cs.to_xml.to_s, :content_type => "text/xml"
105
106     else
107       render :nothing => true, :status => :method_not_allowed
108     end
109
110   rescue ActiveRecord::RecordNotFound
111     render :nothing => true, :status => :not_found
112   rescue OSM::APIError => ex
113     render ex.render_opts
114   end
115
116   ##
117   # Upload a diff in a single transaction.
118   #
119   # This means that each change within the diff must succeed, i.e: that
120   # each version number mentioned is still current. Otherwise the entire
121   # transaction *must* be rolled back.
122   #
123   # Furthermore, each element in the diff can only reference the current
124   # changeset.
125   #
126   # Returns: a diffResult document, as described in 
127   # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
128   def upload
129     # only allow POST requests, as the upload method is most definitely
130     # not idempotent, as several uploads with placeholder IDs will have
131     # different side-effects.
132     # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
133     unless request.post?
134       render :nothing => true, :status => :method_not_allowed
135       return
136     end
137
138     changeset = Changeset.find(params[:id])
139
140     # access control - only the user who created a changeset may
141     # upload to it.
142     unless @user.id == changeset.user_id 
143       raise OSM::APIUserChangesetMismatchError 
144     end
145     
146     diff_reader = DiffReader.new(request.raw_post, changeset)
147     Changeset.transaction do
148       result = diff_reader.commit
149       render :text => result.to_s, :content_type => "text/xml"
150     end
151     
152   rescue ActiveRecord::RecordNotFound
153     render :nothing => true, :status => :not_found
154   rescue OSM::APIError => ex
155     render ex.render_opts
156   end
157
158   ##
159   # download the changeset as an osmChange document.
160   #
161   # to make it easier to revert diffs it would be better if the osmChange
162   # format were reversible, i.e: contained both old and new versions of 
163   # modified elements. but it doesn't at the moment...
164   #
165   # this method cannot order the database changes fully (i.e: timestamp and
166   # version number may be too coarse) so the resulting diff may not apply
167   # to a different database. however since changesets are not atomic this 
168   # behaviour cannot be guaranteed anyway and is the result of a design
169   # choice.
170   def download
171     changeset = Changeset.find(params[:id])
172     
173     # get all the elements in the changeset and stick them in a big array.
174     elements = [changeset.old_nodes, 
175                 changeset.old_ways, 
176                 changeset.old_relations].flatten
177     
178     # sort the elements by timestamp and version number, as this is the 
179     # almost sensible ordering available. this would be much nicer if 
180     # global (SVN-style) versioning were used - then that would be 
181     # unambiguous.
182     elements.sort! do |a, b| 
183       if (a.timestamp == b.timestamp)
184         a.version <=> b.version
185       else
186         a.timestamp <=> b.timestamp 
187       end
188     end
189     
190     # create an osmChange document for the output
191     result = OSM::API.new.get_xml_doc
192     result.root.name = "osmChange"
193
194     # generate an output element for each operation. note: we avoid looking
195     # at the history because it is simpler - but it would be more correct to 
196     # check these assertions.
197     elements.each do |elt|
198       result.root <<
199         if (elt.version == 1) 
200           # first version, so it must be newly-created.
201           created = XML::Node.new "create"
202           created << elt.to_xml_node
203         else
204           # get the previous version from the element history
205           prev_elt = elt.class.find(:first, :conditions => 
206                                     ['id = ? and version = ?',
207                                      elt.id, elt.version])
208           unless elt.visible
209             # if the element isn't visible then it must have been deleted, so
210             # output the *previous* XML
211             deleted = XML::Node.new "delete"
212             deleted << prev_elt.to_xml_node
213           else
214             # must be a modify, for which we don't need the previous version
215             # yet...
216             modified = XML::Node.new "modify"
217             modified << elt.to_xml_node
218           end
219         end
220     end
221
222     render :text => result.to_s, :content_type => "text/xml"
223             
224   rescue ActiveRecord::RecordNotFound
225     render :nothing => true, :status => :not_found
226   rescue OSM::APIError => ex
227     render ex.render_opts
228   end
229
230   ##
231   # query changesets by bounding box, time, user or open/closed status.
232   def query
233     # create the conditions that the user asked for. some or all of
234     # these may be nil.
235     conditions = conditions_bbox(params['bbox'])
236     cond_merge conditions, conditions_user(params['user'])
237     cond_merge conditions, conditions_time(params['time'])
238     cond_merge conditions, conditions_open(params['open'])
239
240     # create the results document
241     results = OSM::API.new.get_xml_doc
242
243     # add all matching changesets to the XML results document
244     Changeset.find(:all, 
245                    :conditions => conditions, 
246                    :limit => 100,
247                    :order => 'created_at desc').each do |cs|
248       results.root << cs.to_xml_node
249     end
250
251     render :text => results.to_s, :content_type => "text/xml"
252
253   rescue ActiveRecord::RecordNotFound
254     render :nothing => true, :status => :not_found
255   rescue OSM::APIError => ex
256     render ex.render_opts
257   rescue String => s
258     render :text => s, :content_type => "text/plain", :status => :bad_request
259   end
260   
261   ##
262   # updates a changeset's tags. none of the changeset's attributes are
263   # user-modifiable, so they will be ignored.
264   #
265   # changesets are not (yet?) versioned, so we don't have to deal with
266   # history tables here. changesets are locked to a single user, however.
267   #
268   # after succesful update, returns the XML of the changeset.
269   def update
270     # request *must* be a PUT.
271     unless request.put?
272       render :nothing => true, :status => :method_not_allowed
273       return
274     end
275     
276     changeset = Changeset.find(params[:id])
277     new_changeset = Changeset.from_xml(request.raw_post)
278
279     unless new_changeset.nil?
280       changeset.update_from(new_changeset, @user)
281       render :text => changeset.to_xml, :mime_type => "text/xml"
282     else
283       
284       render :nothing => true, :status => :bad_request
285     end
286       
287   rescue ActiveRecord::RecordNotFound
288     render :nothing => true, :status => :not_found
289   rescue OSM::APIError => ex
290     render ex.render_opts
291   end
292
293   #------------------------------------------------------------
294   # utility functions below.
295   #------------------------------------------------------------  
296
297   ##
298   # merge two conditions
299   def cond_merge(a, b)
300     if a and b
301       a_str = a.shift
302       b_str = b.shift
303       return [ a_str + " and " + b_str ] + a + b
304     elsif a 
305       return a
306     else b
307       return b
308     end
309   end
310
311   ##
312   # if a bounding box was specified then parse it and do some sanity 
313   # checks. this is mostly the same as the map call, but without the 
314   # area restriction.
315   def conditions_bbox(bbox)
316     unless bbox.nil?
317       raise "Bounding box should be min_lon,min_lat,max_lon,max_lat" unless bbox.count(',') == 3
318       bbox = sanitise_boundaries(bbox.split(/,/))
319       raise "Minimum longitude should be less than maximum." unless bbox[0] <= bbox[2]
320       raise "Minimum latitude should be less than maximum." unless bbox[1] <= bbox[3]
321       return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
322               bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
323     else
324       return nil
325     end
326   end
327
328   ##
329   # restrict changesets to those by a particular user
330   def conditions_user(user)
331     unless user.nil?
332       u = User.find(user.to_i)
333       raise OSM::APINotFoundError unless u.data_public?
334       return ['user_id = ?', u.id]
335     else
336       return nil
337     end
338   end
339
340   ##
341   # restrict changes to those during a particular time period
342   def conditions_time(time) 
343     unless time.nil?
344       # if there is a range, i.e: comma separated, then the first is 
345       # low, second is high - same as with bounding boxes.
346       if time.count(',') == 1
347         from, to = time.split(/,/).collect { |t| Date.parse(t) }
348         return ['created_at > ? and created_at < ?', from, to]
349       else
350         # if there is no comma, assume its a lower limit on time
351         return ['created_at > ?', Date.parse(time)]
352       end
353     else
354       return nil
355     end
356   rescue ArgumentError => ex
357     raise ex.message.to_s
358   end
359
360   ##
361   # restrict changes to those which are open
362   def conditions_open(open)
363     return open.nil? ? nil : ['open = ?', true]
364   end
365
366 end