]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
removed comments which apparently no-one bothers to read anyway. since no-one reads...
[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) and (num_changes <= MAX_ELEMENTS))
46   end
47
48   def set_closed_time_now
49     unless is_open?
50       self.closed_at = Time.now
51     end
52   end
53   
54   def self.from_xml(xml, create=false)
55     begin
56       p = XML::Parser.new
57       p.string = xml
58       doc = p.parse
59
60       cs = Changeset.new
61
62       doc.find('//osm/changeset').each do |pt|
63         if create
64           cs.created_at = Time.now
65           # initial close time is 1h ahead, but will be increased on each
66           # modification.
67           cs.closed_at = Time.now + IDLE_TIMEOUT
68           # initially we have no changes in a changeset
69           cs.num_changes = 0
70         end
71
72         pt.find('tag').each do |tag|
73           cs.add_tag_keyval(tag['k'], tag['v'])
74         end
75       end
76     rescue Exception => ex
77       cs = nil
78     end
79
80     return cs
81   end
82
83   ##
84   # returns the bounding box of the changeset. it is possible that some
85   # or all of the values will be nil, indicating that they are undefined.
86   def bbox
87     @bbox ||= [ min_lon, min_lat, max_lon, max_lat ]
88   end
89
90   ##
91   # expand the bounding box to include the given bounding box. also, 
92   # expand a little bit more in the direction of the expansion, so that
93   # further expansions may be unnecessary. this is an optimisation 
94   # suggested on the wiki page by kleptog.
95   def update_bbox!(array)
96     # ensure that bbox is cached and has no nils in it. if there are any
97     # nils, just use the bounding box update to write over them.
98     @bbox = bbox.zip(array).collect { |a, b| a.nil? ? b : a }
99
100     # FIXME - this looks nasty and violates DRY... is there any prettier 
101     # way to do this? 
102     @bbox[0] = array[0] + EXPAND * (@bbox[0] - @bbox[2]) if array[0] < @bbox[0]
103     @bbox[1] = array[1] + EXPAND * (@bbox[1] - @bbox[3]) if array[1] < @bbox[1]
104     @bbox[2] = array[2] + EXPAND * (@bbox[2] - @bbox[0]) if array[2] > @bbox[2]
105     @bbox[3] = array[3] + EXPAND * (@bbox[3] - @bbox[1]) if array[3] > @bbox[3]
106
107     # update active record. rails 2.1's dirty handling should take care of
108     # whether this object needs saving or not.
109     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox
110   end
111
112   ##
113   # the number of elements is also passed in so that we can ensure that
114   # a single changeset doesn't contain too many elements. this, of course,
115   # destroys the optimisation described in the bbox method above.
116   def add_changes!(elements)
117     self.num_changes += elements
118   end
119
120   def tags_as_hash
121     return tags
122   end
123
124   def tags
125     unless @tags
126       @tags = {}
127       self.changeset_tags.each do |tag|
128         @tags[tag.k] = tag.v
129       end
130     end
131     @tags
132   end
133
134   def tags=(t)
135     @tags = t
136   end
137
138   def add_tag_keyval(k, v)
139     @tags = Hash.new unless @tags
140     @tags[k] = v
141   end
142
143   def save_with_tags!
144     t = Time.now
145
146     # do the changeset update and the changeset tags update in the
147     # same transaction to ensure consistency.
148     Changeset.transaction do
149       # set the auto-close time to be one hour in the future unless
150       # that would make it more than 24h long, in which case clip to
151       # 24h, as this has been decided is a reasonable time limit.
152       if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
153         self.closed_at = created_at + MAX_TIME_OPEN
154       else
155         self.closed_at = Time.now + IDLE_TIMEOUT
156       end
157       self.save!
158
159       tags = self.tags
160       ChangesetTag.delete_all(['id = ?', self.id])
161
162       tags.each do |k,v|
163         tag = ChangesetTag.new
164         tag.k = k
165         tag.v = v
166         tag.id = self.id
167         tag.save!
168       end
169     end
170   end
171   
172   def to_xml
173     doc = OSM::API.new.get_xml_doc
174     doc.root << to_xml_node()
175     return doc
176   end
177   
178   def to_xml_node(user_display_name_cache = nil)
179     el1 = XML::Node.new 'changeset'
180     el1['id'] = self.id.to_s
181
182     user_display_name_cache = {} if user_display_name_cache.nil?
183
184     if user_display_name_cache and user_display_name_cache.key?(self.user_id)
185       # use the cache if available
186     elsif self.user.data_public?
187       user_display_name_cache[self.user_id] = self.user.display_name
188     else
189       user_display_name_cache[self.user_id] = nil
190     end
191
192     el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
193     el1['uid'] = self.user_id.to_s if self.user.data_public?
194
195     self.tags.each do |k,v|
196       el2 = XML::Node.new('tag')
197       el2['k'] = k.to_s
198       el2['v'] = v.to_s
199       el1 << el2
200     end
201     
202     el1['created_at'] = self.created_at.xmlschema
203     el1['closed_at'] = self.closed_at.xmlschema unless is_open?
204     el1['open'] = is_open?.to_s
205
206     el1['min_lon'] = (bbox[0].to_f / GeoRecord::SCALE).to_s unless bbox[0].nil?
207     el1['min_lat'] = (bbox[1].to_f / GeoRecord::SCALE).to_s unless bbox[1].nil?
208     el1['max_lon'] = (bbox[2].to_f / GeoRecord::SCALE).to_s unless bbox[2].nil?
209     el1['max_lat'] = (bbox[3].to_f / GeoRecord::SCALE).to_s unless bbox[3].nil?
210     
211     # NOTE: changesets don't include the XML of the changes within them,
212     # they are just structures for tagging. to get the osmChange of a
213     # changeset, see the download method of the controller.
214
215     return el1
216   end
217
218   ##
219   # update this instance from another instance given and the user who is
220   # doing the updating. note that this method is not for updating the
221   # bounding box, only the tags of the changeset.
222   def update_from(other, user)
223     # ensure that only the user who opened the changeset may modify it.
224     unless user.id == self.user_id 
225       raise OSM::APIUserChangesetMismatchError 
226     end
227     
228     # can't change a closed changeset
229     unless is_open?
230       raise OSM::APIChangesetAlreadyClosedError.new(self)
231     end
232
233     # copy the other's tags
234     self.tags = other.tags
235
236     save_with_tags!
237   end
238 end