]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Put back missing divider. Closes #1939.
[rails.git] / app / models / changeset.rb
1 class Changeset < ActiveRecord::Base
2   require 'xml/libxml'
3
4   belongs_to :user
5
6   has_many :changeset_tags, :foreign_key => 'id'
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   validates_presence_of :id, :on => :update
16   validates_presence_of :user_id, :created_at, :closed_at, :num_changes
17   validates_uniqueness_of :id
18   validates_numericality_of :id, :on => :update, :integer_only => true
19   validates_numericality_of :min_lat, :max_lat, :min_lon, :max_lat, :allow_nil => true, :integer_only => true
20   validates_numericality_of :user_id,  :integer_only => true
21   validates_numericality_of :num_changes, :integer_only => true, :greater_than_or_equal_to => 0
22   validates_associated :user
23
24   # over-expansion factor to use when updating the bounding box
25   EXPAND = 0.1
26
27   # maximum number of elements allowed in a changeset
28   MAX_ELEMENTS = 50000
29
30   # maximum time a changeset is allowed to be open for.
31   MAX_TIME_OPEN = 1.day
32
33   # idle timeout increment, one hour seems reasonable.
34   IDLE_TIMEOUT = 1.hour
35
36   # Use a method like this, so that we can easily change how we
37   # determine whether a changeset is open, without breaking code in at 
38   # least 6 controllers
39   def is_open?
40     # a changeset is open (that is, it will accept further changes) when
41     # it has not yet run out of time and its capacity is small enough.
42     # note that this may not be a hard limit - due to timing changes and
43     # concurrency it is possible that some changesets may be slightly 
44     # longer than strictly allowed or have slightly more changes in them.
45     return ((closed_at > Time.now.getutc) and (num_changes <= MAX_ELEMENTS))
46   end
47
48   def set_closed_time_now
49     if is_open?
50       self.closed_at = Time.now.getutc
51     end
52   end
53   
54   def self.from_xml(xml, create=false)
55     begin
56       p = XML::Parser.string(xml)
57       doc = p.parse
58
59       cs = Changeset.new
60
61       doc.find('//osm/changeset').each do |pt|
62         if create
63           cs.created_at = Time.now.getutc
64           # initial close time is 1h ahead, but will be increased on each
65           # modification.
66           cs.closed_at = cs.created_at + IDLE_TIMEOUT
67           # initially we have no changes in a changeset
68           cs.num_changes = 0
69         end
70
71         pt.find('tag').each do |tag|
72           cs.add_tag_keyval(tag['k'], tag['v'])
73         end
74       end
75     rescue Exception => ex
76       cs = nil
77     end
78
79     return cs
80   end
81
82   ##
83   # returns the bounding box of the changeset. it is possible that some
84   # or all of the values will be nil, indicating that they are undefined.
85   def bbox
86     @bbox ||= [ min_lon, min_lat, max_lon, max_lat ]
87   end
88   
89   def has_valid_bbox?
90     not bbox.include? nil
91   end
92   
93   ##
94   # returns area of the changset bbox as a rough comparitive quantity for use of changset displays
95   def area
96      if has_valid_bbox?
97              (max_lon - min_lon) * (max_lat - min_lat)
98      else
99              0
100      end
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!(array)
109     # ensure that bbox is cached and has no nils in it. if there are any
110     # nils, just use the bounding box update to write over them.
111     @bbox = bbox.zip(array).collect { |a, b| a.nil? ? b : a }
112
113     # FIXME - this looks nasty and violates DRY... is there any prettier 
114     # way to do this? 
115     @bbox[0] = array[0] + EXPAND * (@bbox[0] - @bbox[2]) if array[0] < @bbox[0]
116     @bbox[1] = array[1] + EXPAND * (@bbox[1] - @bbox[3]) if array[1] < @bbox[1]
117     @bbox[2] = array[2] + EXPAND * (@bbox[2] - @bbox[0]) if array[2] > @bbox[2]
118     @bbox[3] = array[3] + EXPAND * (@bbox[3] - @bbox[1]) if array[3] > @bbox[3]
119
120     # update active record. rails 2.1's dirty handling should take care of
121     # whether this object needs saving or not.
122     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox
123   end
124
125   ##
126   # the number of elements is also passed in so that we can ensure that
127   # a single changeset doesn't contain too many elements. this, of course,
128   # destroys the optimisation described in the bbox method above.
129   def add_changes!(elements)
130     self.num_changes += elements
131   end
132
133   def tags_as_hash
134     return tags
135   end
136
137   def tags
138     unless @tags
139       @tags = {}
140       self.changeset_tags.each do |tag|
141         @tags[tag.k] = tag.v
142       end
143     end
144     @tags
145   end
146
147   def tags=(t)
148     @tags = t
149   end
150
151   def add_tag_keyval(k, v)
152     @tags = Hash.new unless @tags
153     @tags[k] = v
154   end
155
156   def save_with_tags!
157     # do the changeset update and the changeset tags update in the
158     # same transaction to ensure consistency.
159     Changeset.transaction do
160       self.save!
161
162       tags = self.tags
163       ChangesetTag.delete_all(['id = ?', self.id])
164
165       tags.each do |k,v|
166         tag = ChangesetTag.new
167         tag.k = k
168         tag.v = v
169         tag.id = self.id
170         tag.save!
171       end
172     end
173   end
174
175   ##
176   # set the auto-close time to be one hour in the future unless
177   # that would make it more than 24h long, in which case clip to
178   # 24h, as this has been decided is a reasonable time limit.
179   def before_save
180     if self.is_open?
181       if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
182         self.closed_at = created_at + MAX_TIME_OPEN
183       else
184         self.closed_at = Time.now.getutc + IDLE_TIMEOUT
185       end
186     end
187   end
188   
189   def to_xml
190     doc = OSM::API.new.get_xml_doc
191     doc.root << to_xml_node()
192     return doc
193   end
194   
195   def to_xml_node(user_display_name_cache = nil)
196     el1 = XML::Node.new 'changeset'
197     el1['id'] = self.id.to_s
198
199     user_display_name_cache = {} if user_display_name_cache.nil?
200
201     if user_display_name_cache and user_display_name_cache.key?(self.user_id)
202       # use the cache if available
203     elsif self.user.data_public?
204       user_display_name_cache[self.user_id] = self.user.display_name
205     else
206       user_display_name_cache[self.user_id] = nil
207     end
208
209     el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
210     el1['uid'] = self.user_id.to_s if self.user.data_public?
211
212     self.tags.each do |k,v|
213       el2 = XML::Node.new('tag')
214       el2['k'] = k.to_s
215       el2['v'] = v.to_s
216       el1 << el2
217     end
218     
219     el1['created_at'] = self.created_at.xmlschema
220     el1['closed_at'] = self.closed_at.xmlschema unless is_open?
221     el1['open'] = is_open?.to_s
222
223     el1['min_lon'] = (bbox[0].to_f / GeoRecord::SCALE).to_s unless bbox[0].nil?
224     el1['min_lat'] = (bbox[1].to_f / GeoRecord::SCALE).to_s unless bbox[1].nil?
225     el1['max_lon'] = (bbox[2].to_f / GeoRecord::SCALE).to_s unless bbox[2].nil?
226     el1['max_lat'] = (bbox[3].to_f / GeoRecord::SCALE).to_s unless bbox[3].nil?
227     
228     # NOTE: changesets don't include the XML of the changes within them,
229     # they are just structures for tagging. to get the osmChange of a
230     # changeset, see the download method of the controller.
231
232     return el1
233   end
234
235   ##
236   # update this instance from another instance given and the user who is
237   # doing the updating. note that this method is not for updating the
238   # bounding box, only the tags of the changeset.
239   def update_from(other, user)
240     # ensure that only the user who opened the changeset may modify it.
241     unless user.id == self.user_id 
242       raise OSM::APIUserChangesetMismatchError.new
243     end
244     
245     # can't change a closed changeset
246     unless is_open?
247       raise OSM::APIChangesetAlreadyClosedError.new(self)
248     end
249
250     # copy the other's tags
251     self.tags = other.tags
252
253     save_with_tags!
254   end
255 end