source: subversion/sites/rails_port_branches/api06/app/controllers/changeset_controller.rb @ 14227

Revision 14227, 16.6 KB checked in by edgemaster, 5 years ago (diff)

Rather than referring how to view a bbox history, just redirect to the global history.

Line 
1# The ChangesetController is the RESTful interface to Changeset objects
2
3class ChangesetController < ApplicationController
4  layout 'site'
5  require 'xml/libxml'
6
7  session :off, :except => [:list, :list_user, :list_bbox]
8  before_filter :authorize_web, :only => [:list, :list_user, :list_bbox]
9  before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
10  before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
11  before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
12  after_filter :compress_output
13
14  # Help methods for checking boundary sanity and area size
15  include MapBoundary
16
17  # Helper methods for checking consistency
18  include ConsistencyValidations
19
20  # Create a changeset from XML.
21  def create
22    if request.put?
23      cs = Changeset.from_xml(request.raw_post, true)
24
25      if cs
26        cs.user_id = @user.id
27        cs.save_with_tags!
28        render :text => cs.id.to_s, :content_type => "text/plain"
29      else
30        render :nothing => true, :status => :bad_request
31      end
32    else
33      render :nothing => true, :status => :method_not_allowed
34    end
35  end
36
37  ##
38  # Return XML giving the basic info about the changeset. Does not
39  # return anything about the nodes, ways and relations in the changeset.
40  def read
41    begin
42      changeset = Changeset.find(params[:id])
43      render :text => changeset.to_xml.to_s, :content_type => "text/xml"
44    rescue ActiveRecord::RecordNotFound
45      render :nothing => true, :status => :not_found
46    end
47  end
48 
49  ##
50  # marks a changeset as closed. this may be called multiple times
51  # on the same changeset, so is idempotent.
52  def close 
53    unless request.put?
54      render :nothing => true, :status => :method_not_allowed
55      return
56    end
57   
58    changeset = Changeset.find(params[:id])   
59    check_changeset_consistency(changeset, @user)
60
61    # to close the changeset, we'll just set its closed_at time to
62    # now. this might not be enough if there are concurrency issues,
63    # but we'll have to wait and see.
64    changeset.set_closed_time_now
65
66    changeset.save!
67    render :nothing => true
68  rescue ActiveRecord::RecordNotFound
69    render :nothing => true, :status => :not_found
70  rescue OSM::APIError => ex
71    render ex.render_opts
72  end
73
74  ##
75  # insert a (set of) points into a changeset bounding box. this can only
76  # increase the size of the bounding box. this is a hint that clients can
77  # set either before uploading a large number of changes, or changes that
78  # the client (but not the server) knows will affect areas further away.
79  def expand_bbox
80    # only allow POST requests, because although this method is
81    # idempotent, there is no "document" to PUT really...
82    if request.post?
83      cs = Changeset.find(params[:id])
84      check_changeset_consistency(cs, @user)
85
86      # keep an array of lons and lats
87      lon = Array.new
88      lat = Array.new
89
90      # the request is in pseudo-osm format... this is kind-of an
91      # abuse, maybe should change to some other format?
92      doc = XML::Parser.string(request.raw_post).parse
93      doc.find("//osm/node").each do |n|
94        lon << n['lon'].to_f * GeoRecord::SCALE
95        lat << n['lat'].to_f * GeoRecord::SCALE
96      end
97
98      # add the existing bounding box to the lon-lat array
99      lon << cs.min_lon unless cs.min_lon.nil?
100      lat << cs.min_lat unless cs.min_lat.nil?
101      lon << cs.max_lon unless cs.max_lon.nil?
102      lat << cs.max_lat unless cs.max_lat.nil?
103
104      # collapse the arrays to minimum and maximum
105      cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat = 
106        lon.min, lat.min, lon.max, lat.max
107
108      # save the larger bounding box and return the changeset, which
109      # will include the bigger bounding box.
110      cs.save!
111      render :text => cs.to_xml.to_s, :content_type => "text/xml"
112
113    else
114      render :nothing => true, :status => :method_not_allowed
115    end
116
117  rescue ActiveRecord::RecordNotFound
118    render :nothing => true, :status => :not_found
119  rescue OSM::APIError => ex
120    render ex.render_opts
121  end
122
123  ##
124  # Upload a diff in a single transaction.
125  #
126  # This means that each change within the diff must succeed, i.e: that
127  # each version number mentioned is still current. Otherwise the entire
128  # transaction *must* be rolled back.
129  #
130  # Furthermore, each element in the diff can only reference the current
131  # changeset.
132  #
133  # Returns: a diffResult document, as described in
134  # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
135  def upload
136    # only allow POST requests, as the upload method is most definitely
137    # not idempotent, as several uploads with placeholder IDs will have
138    # different side-effects.
139    # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
140    unless request.post?
141      render :nothing => true, :status => :method_not_allowed
142      return
143    end
144
145    changeset = Changeset.find(params[:id])
146    check_changeset_consistency(changeset, @user)
147   
148    diff_reader = DiffReader.new(request.raw_post, changeset)
149    Changeset.transaction do
150      result = diff_reader.commit
151      render :text => result.to_s, :content_type => "text/xml"
152    end
153   
154  rescue ActiveRecord::RecordNotFound
155    render :nothing => true, :status => :not_found
156  rescue OSM::APIError => ex
157    render ex.render_opts
158  end
159
160  ##
161  # download the changeset as an osmChange document.
162  #
163  # to make it easier to revert diffs it would be better if the osmChange
164  # format were reversible, i.e: contained both old and new versions of
165  # modified elements. but it doesn't at the moment...
166  #
167  # this method cannot order the database changes fully (i.e: timestamp and
168  # version number may be too coarse) so the resulting diff may not apply
169  # to a different database. however since changesets are not atomic this
170  # behaviour cannot be guaranteed anyway and is the result of a design
171  # choice.
172  def download
173    changeset = Changeset.find(params[:id])
174   
175    # get all the elements in the changeset and stick them in a big array.
176    elements = [changeset.old_nodes, 
177                changeset.old_ways, 
178                changeset.old_relations].flatten
179   
180    # sort the elements by timestamp and version number, as this is the
181    # almost sensible ordering available. this would be much nicer if
182    # global (SVN-style) versioning were used - then that would be
183    # unambiguous.
184    elements.sort! do |a, b| 
185      if (a.timestamp == b.timestamp)
186        a.version <=> b.version
187      else
188        a.timestamp <=> b.timestamp
189      end
190    end
191   
192    # create an osmChange document for the output
193    result = OSM::API.new.get_xml_doc
194    result.root.name = "osmChange"
195
196    # generate an output element for each operation. note: we avoid looking
197    # at the history because it is simpler - but it would be more correct to
198    # check these assertions.
199    elements.each do |elt|
200      result.root <<
201        if (elt.version == 1) 
202          # first version, so it must be newly-created.
203          created = XML::Node.new "create"
204          created << elt.to_xml_node
205        else
206          # get the previous version from the element history
207          prev_elt = elt.class.find(:first, :conditions => 
208                                    ['id = ? and version = ?',
209                                     elt.id, elt.version])
210          unless elt.visible
211            # if the element isn't visible then it must have been deleted, so
212            # output the *previous* XML
213            deleted = XML::Node.new "delete"
214            deleted << prev_elt.to_xml_node
215          else
216            # must be a modify, for which we don't need the previous version
217            # yet...
218            modified = XML::Node.new "modify"
219            modified << elt.to_xml_node
220          end
221        end
222    end
223
224    render :text => result.to_s, :content_type => "text/xml"
225           
226  rescue ActiveRecord::RecordNotFound
227    render :nothing => true, :status => :not_found
228  rescue OSM::APIError => ex
229    render ex.render_opts
230  end
231
232  ##
233  # query changesets by bounding box, time, user or open/closed status.
234  def query
235    # create the conditions that the user asked for. some or all of
236    # these may be nil.
237    conditions = conditions_bbox(params['bbox'])
238    conditions = cond_merge conditions, conditions_user(params['user'])
239    conditions = cond_merge conditions, conditions_time(params['time'])
240    conditions = cond_merge conditions, conditions_open(params['open'])
241    conditions = cond_merge conditions, conditions_closed(params['closed'])
242
243    # create the results document
244    results = OSM::API.new.get_xml_doc
245
246    # add all matching changesets to the XML results document
247    Changeset.find(:all, 
248                   :conditions => conditions, 
249                   :limit => 100,
250                   :order => 'created_at desc').each do |cs|
251      results.root << cs.to_xml_node
252    end
253
254    render :text => results.to_s, :content_type => "text/xml"
255
256  rescue ActiveRecord::RecordNotFound
257    render :nothing => true, :status => :not_found
258  rescue OSM::APIError => ex
259    render ex.render_opts
260  end
261 
262  ##
263  # updates a changeset's tags. none of the changeset's attributes are
264  # user-modifiable, so they will be ignored.
265  #
266  # changesets are not (yet?) versioned, so we don't have to deal with
267  # history tables here. changesets are locked to a single user, however.
268  #
269  # after succesful update, returns the XML of the changeset.
270  def update
271    # request *must* be a PUT.
272    unless request.put?
273      render :nothing => true, :status => :method_not_allowed
274      return
275    end
276   
277    changeset = Changeset.find(params[:id])
278    new_changeset = Changeset.from_xml(request.raw_post)
279
280    unless new_changeset.nil?
281      check_changeset_consistency(changeset, @user)
282      changeset.update_from(new_changeset, @user)
283      render :text => changeset.to_xml, :mime_type => "text/xml"
284    else
285     
286      render :nothing => true, :status => :bad_request
287    end
288     
289  rescue ActiveRecord::RecordNotFound
290    render :nothing => true, :status => :not_found
291  rescue OSM::APIError => ex
292    render ex.render_opts
293  end
294
295 
296 
297  ##
298  # list edits (open changesets) in reverse chronological order
299  def list
300    conditions = conditions_nonempty
301   
302   
303   # @changesets = Changeset.find(:all, :order => "closed_at DESC", :conditions => ['closed_at < ?', DateTime.now], :limit=> 20)
304   
305   
306   #@edit_pages, @edits = paginate(:changesets,
307   #                                :include => [:user, :changeset_tags],
308   #                                :conditions => conditions,
309   #                                :order => "changesets.created_at DESC",
310   #                                :per_page => 20)
311   #
312   
313   @edits =  Changeset.find(:all,
314                                   :order => "changesets.created_at DESC",
315                                   :conditions => conditions,
316                                   :limit => 20)
317   
318  end
319 
320  ##
321  # list edits (changesets) belonging to a user
322  def list_user
323    user = User.find_by_display_name(params[:display_name], :conditions => {:visible => true})
324   
325    if user
326      @display_name = user.display_name
327      if not user.data_public? and @user != user
328        @edits = nil
329        render
330      else
331        conditions = cond_merge conditions, ['user_id = ?', user.id]
332        conditions = cond_merge conditions, conditions_nonempty
333        @edit_pages, @edits = paginate(:changesets,
334                                        :include => [:user, :changeset_tags],
335                                        :conditions => conditions,
336                                        :order => "changesets.created_at DESC",
337                                        :per_page => 20)
338      end
339    else
340      @not_found_user = params[:display_name]
341      render :template => 'user/no_such_user', :status => :not_found
342    end
343  end
344 
345  ##
346  # list changesets in a bbox
347  def list_bbox
348    # support 'bbox' param or alternatively 'minlon', 'minlat' etc       
349    if params['bbox']
350       bbox = params['bbox']
351    elsif params['minlon'] and params['minlat'] and params['maxlon'] and params['maxlat']
352       bbox = params['minlon'] + ',' + params['minlat'] + ',' + params['maxlon'] + ',' + params['maxlat']
353    else
354      redirect_to :action => 'list'
355    end
356       
357    conditions = conditions_bbox(bbox);
358    conditions = cond_merge conditions, conditions_nonempty
359   
360    @edit_pages, @edits = paginate(:changesets,
361                                   :include => [:user, :changeset_tags],
362                                   :conditions => conditions,
363                                   :order => "changesets.created_at DESC",
364                                   :per_page => 20)
365                                   
366    @bbox = sanitise_boundaries(bbox.split(/,/)) unless bbox==nil
367  end
368 
369private
370  #------------------------------------------------------------
371  # utility functions below.
372  #------------------------------------------------------------ 
373
374  ##
375  # merge two conditions
376  def cond_merge(a, b)
377    if a and b
378      a_str = a.shift
379      b_str = b.shift
380      return [ a_str + " AND " + b_str ] + a + b
381    elsif a
382      return a
383    else b
384      return b
385    end
386  end
387
388  ##
389  # if a bounding box was specified then parse it and do some sanity
390  # checks. this is mostly the same as the map call, but without the
391  # area restriction.
392  def conditions_bbox(bbox)
393    unless bbox.nil?
394      raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
395      bbox = sanitise_boundaries(bbox.split(/,/))
396      raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
397      raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
398      return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
399              bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
400    else
401      return nil
402    end
403  end
404
405  ##
406  # restrict changesets to those by a particular user
407  def conditions_user(user)
408    unless user.nil?
409      # user input checking, we don't have any UIDs < 1
410      raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
411
412      u = User.find(user.to_i)
413      # should be able to get changesets of public users only, or
414      # our own changesets regardless of public-ness.
415      unless u.data_public?
416        # get optional user auth stuff so that users can see their own
417        # changesets if they're non-public
418        setup_user_auth
419       
420        raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
421      end
422      return ['user_id = ?', u.id]
423    else
424      return nil
425    end
426  end
427
428  ##
429  # restrict changes to those closed during a particular time period
430  def conditions_time(time) 
431    unless time.nil?
432      # if there is a range, i.e: comma separated, then the first is
433      # low, second is high - same as with bounding boxes.
434      if time.count(',') == 1
435        # check that we actually have 2 elements in the array
436        times = time.split(/,/)
437        raise OSM::APIBadUserInput.new("bad time range") if times.size != 2 
438
439        from, to = times.collect { |t| DateTime.parse(t) }
440        return ['closed_at >= ? and created_at <= ?', from, to]
441      else
442        # if there is no comma, assume its a lower limit on time
443        return ['closed_at >= ?', DateTime.parse(time)]
444      end
445    else
446      return nil
447    end
448    # stupid DateTime seems to throw both of these for bad parsing, so
449    # we have to catch both and ensure the correct code path is taken.
450  rescue ArgumentError => ex
451    raise OSM::APIBadUserInput.new(ex.message.to_s)
452  rescue RuntimeError => ex
453    raise OSM::APIBadUserInput.new(ex.message.to_s)
454  end
455
456  ##
457  # return changesets which are open (haven't been closed yet)
458  # we do this by seeing if the 'closed at' time is in the future. Also if we've
459  # hit the maximum number of changes then it counts as no longer open.
460  # if parameter 'open' is nill then open and closed changsets are returned
461  def conditions_open(open)
462    return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?', 
463                              DateTime.now, Changeset::MAX_ELEMENTS]
464  end
465 
466  ##
467  # query changesets which are closed
468  # ('closed at' time has passed or changes limit is hit)
469  def conditions_closed(closed)
470    return closed.nil? ? nil : ['closed_at < ? and num_changes > ?', 
471                              DateTime.now, Changeset::MAX_ELEMENTS]
472  end
473
474  ##
475  # eliminate empty changesets (where the bbox has not been set)
476  # this should be applied to all changeset list displays
477  def conditions_nonempty()
478    return ['min_lat IS NOT NULL']
479  end
480 
481end
Note: See TracBrowser for help on using the repository browser.