]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Replace deprecated reset method with restore method
[rails.git] / app / models / changeset.rb
1 class Changeset < ActiveRecord::Base
2   require 'xml/libxml'
3
4   belongs_to :user, :counter_cache => true
5
6   has_many :changeset_tags
7
8   has_many :nodes
9   has_many :ways
10   has_many :relations
11   has_many :old_nodes
12   has_many :old_ways
13   has_many :old_relations
14   
15   has_many :comments, -> { where(:visible => true).order(:created_at) }, :class_name => "ChangesetComment"
16   has_and_belongs_to_many :subscribers, :class_name => 'User', :join_table => 'changesets_subscribers', :association_foreign_key => 'subscriber_id'
17
18   validates_presence_of :id, :on => :update
19   validates_presence_of :user_id, :created_at, :closed_at, :num_changes
20   validates_uniqueness_of :id
21   validates_numericality_of :id, :on => :update, :integer_only => true
22   validates_numericality_of :min_lat, :max_lat, :min_lon, :max_lat, :allow_nil => true, :integer_only => true
23   validates_numericality_of :user_id,  :integer_only => true
24   validates_numericality_of :num_changes, :integer_only => true, :greater_than_or_equal_to => 0
25
26   before_save :update_closed_at
27
28   # over-expansion factor to use when updating the bounding box
29   EXPAND = 0.1
30
31   # maximum number of elements allowed in a changeset
32   MAX_ELEMENTS = 50000
33
34   # maximum time a changeset is allowed to be open for.
35   MAX_TIME_OPEN = 1.day
36
37   # idle timeout increment, one hour seems reasonable.
38   IDLE_TIMEOUT = 1.hour
39
40   # Use a method like this, so that we can easily change how we
41   # determine whether a changeset is open, without breaking code in at
42   # least 6 controllers
43   def is_open?
44     # a changeset is open (that is, it will accept further changes) when
45     # it has not yet run out of time and its capacity is small enough.
46     # note that this may not be a hard limit - due to timing changes and
47     # concurrency it is possible that some changesets may be slightly
48     # longer than strictly allowed or have slightly more changes in them.
49     return ((closed_at > Time.now.getutc) and (num_changes <= MAX_ELEMENTS))
50   end
51
52   def set_closed_time_now
53     if is_open?
54       self.closed_at = Time.now.getutc
55     end
56   end
57
58   def self.from_xml(xml, create=false)
59     begin
60       p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
61       doc = p.parse
62
63       doc.find('//osm/changeset').each do |pt|
64         return Changeset.from_xml_node(pt, create)
65       end
66       raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
67     rescue LibXML::XML::Error, ArgumentError => ex
68       raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
69     end
70   end
71
72   def self.from_xml_node(pt, create=false)
73     cs = Changeset.new
74     if create
75       cs.created_at = Time.now.getutc
76       # initial close time is 1h ahead, but will be increased on each
77       # modification.
78       cs.closed_at = cs.created_at + IDLE_TIMEOUT
79       # initially we have no changes in a changeset
80       cs.num_changes = 0
81     end
82
83     pt.find('tag').each do |tag|
84       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag['k'].nil?
85       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag['v'].nil?
86       cs.add_tag_keyval(tag['k'], tag['v'])
87     end
88
89     return cs
90   end
91
92   ##
93   # returns the bounding box of the changeset. it is possible that some
94   # or all of the values will be nil, indicating that they are undefined.
95   def bbox
96     @bbox ||= BoundingBox.new(min_lon, min_lat, max_lon, max_lat)
97   end
98
99   def has_valid_bbox?
100     bbox.complete?
101   end
102
103   ##
104   # expand the bounding box to include the given bounding box. also,
105   # expand a little bit more in the direction of the expansion, so that
106   # further expansions may be unnecessary. this is an optimisation
107   # suggested on the wiki page by kleptog.
108   def update_bbox!(bbox_update)
109     bbox.expand!(bbox_update, EXPAND)
110       
111     # update active record. rails 2.1's dirty handling should take care of
112     # whether this object needs saving or not.
113     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox.to_a if bbox.complete?
114   end
115
116   ##
117   # the number of elements is also passed in so that we can ensure that
118   # a single changeset doesn't contain too many elements. this, of course,
119   # destroys the optimisation described in the bbox method above.
120   def add_changes!(elements)
121     self.num_changes += elements
122   end
123
124   def tags_as_hash
125     return tags
126   end
127
128   def tags
129     unless @tags
130       @tags = {}
131       self.changeset_tags.each do |tag|
132         @tags[tag.k] = tag.v
133       end
134     end
135     @tags
136   end
137
138   def tags=(t)
139     @tags = t
140   end
141
142   def add_tag_keyval(k, v)
143     @tags = Hash.new unless @tags
144
145     # duplicate tags are now forbidden, so we can't allow values
146     # in the hash to be overwritten.
147     raise OSM::APIDuplicateTagsError.new("changeset", self.id, k) if @tags.include? k
148
149     @tags[k] = v
150   end
151
152   def save_with_tags!
153     # do the changeset update and the changeset tags update in the
154     # same transaction to ensure consistency.
155     Changeset.transaction do
156       self.save!
157
158       tags = self.tags
159       ChangesetTag.delete_all(:changeset_id => self.id)
160
161       tags.each do |k,v|
162         tag = ChangesetTag.new
163         tag.changeset_id = self.id
164         tag.k = k
165         tag.v = v
166         tag.save!
167       end
168     end
169   end
170
171   ##
172   # set the auto-close time to be one hour in the future unless
173   # that would make it more than 24h long, in which case clip to
174   # 24h, as this has been decided is a reasonable time limit.
175   def update_closed_at
176     if self.is_open?
177       if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
178         self.closed_at = created_at + MAX_TIME_OPEN
179       else
180         self.closed_at = Time.now.getutc + IDLE_TIMEOUT
181       end
182     end
183   end
184
185   def to_xml(include_discussion = false)
186     doc = OSM::API.new.get_xml_doc
187     doc.root << to_xml_node(nil, include_discussion)
188     return doc
189   end
190
191   def to_xml_node(user_display_name_cache = nil, include_discussion = false)
192     el1 = XML::Node.new 'changeset'
193     el1['id'] = self.id.to_s
194
195     user_display_name_cache = {} if user_display_name_cache.nil?
196
197     if user_display_name_cache and user_display_name_cache.key?(self.user_id)
198       # use the cache if available
199     elsif self.user.data_public?
200       user_display_name_cache[self.user_id] = self.user.display_name
201     else
202       user_display_name_cache[self.user_id] = nil
203     end
204
205     el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
206     el1['uid'] = self.user_id.to_s if self.user.data_public?
207
208     self.tags.each do |k,v|
209       el2 = XML::Node.new('tag')
210       el2['k'] = k.to_s
211       el2['v'] = v.to_s
212       el1 << el2
213     end
214
215     el1['created_at'] = self.created_at.xmlschema
216     el1['closed_at'] = self.closed_at.xmlschema unless is_open?
217     el1['open'] = is_open?.to_s
218
219     if bbox.complete?
220       bbox.to_unscaled.add_bounds_to(el1, '_')
221     end
222
223     el1['comments_count'] = self.comments.count.to_s
224
225     if include_discussion
226       el2 = XML::Node.new('discussion')
227       self.comments.includes(:author).each do |comment|
228         el3 = XML::Node.new('comment')
229         el3['date'] = comment.created_at.xmlschema
230         el3['uid'] = comment.author.id.to_s if comment.author.data_public?
231         el3['user'] = comment.author.display_name.to_s if comment.author.data_public?
232         el4 = XML::Node.new('text')
233         el4.content = comment.body.to_s
234         el3 << el4
235         el2 << el3
236       end
237       el1 << el2
238     end
239
240     # NOTE: changesets don't include the XML of the changes within them,
241     # they are just structures for tagging. to get the osmChange of a
242     # changeset, see the download method of the controller.
243
244     return el1
245   end
246
247   ##
248   # update this instance from another instance given and the user who is
249   # doing the updating. note that this method is not for updating the
250   # bounding box, only the tags of the changeset.
251   def update_from(other, user)
252     # ensure that only the user who opened the changeset may modify it.
253     unless user.id == self.user_id
254       raise OSM::APIUserChangesetMismatchError.new
255     end
256
257     # can't change a closed changeset
258     unless is_open?
259       raise OSM::APIChangesetAlreadyClosedError.new(self)
260     end
261
262     # copy the other's tags
263     self.tags = other.tags
264
265     save_with_tags!
266   end
267 end