]> git.openstreetmap.org Git - rails.git/blob - app/models/relation.rb
Enable the donation drive message
[rails.git] / app / models / relation.rb
1 class Relation < ActiveRecord::Base
2   require 'xml/libxml'
3   
4   include ConsistencyValidations
5   
6   set_table_name 'current_relations'
7
8   belongs_to :changeset
9
10   has_many :old_relations, :order => 'version'
11
12   has_many :relation_members, :order => 'sequence_id'
13   has_many :relation_tags
14
15   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
16   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
17
18   validates_presence_of :id, :on => :update
19   validates_presence_of :timestamp,:version,  :changeset_id 
20   validates_uniqueness_of :id
21   validates_inclusion_of :visible, :in => [ true, false ]
22   validates_numericality_of :id, :on => :update, :integer_only => true
23   validates_numericality_of :changeset_id, :version, :integer_only => true
24   validates_associated :changeset
25   
26   scope :visible, where(:visible => true)
27   scope :invisible, where(:visible => false)
28   scope :nodes, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids }) }
29   scope :ways, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids }) }
30   scope :relations, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids }) }
31
32   TYPES = ["node", "way", "relation"]
33
34   def self.from_xml(xml, create=false)
35     begin
36       p = XML::Parser.string(xml)
37       doc = p.parse
38
39       doc.find('//osm/relation').each do |pt|
40         return Relation.from_xml_node(pt, create)
41       end
42       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
43     rescue LibXML::XML::Error, ArgumentError => ex
44       raise OSM::APIBadXMLError.new("relation", xml, ex.message)
45     end
46   end
47
48   def self.from_xml_node(pt, create=false)
49     relation = Relation.new
50
51     raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create or not pt['version'].nil?
52     relation.version = pt['version']
53     raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil?
54     relation.changeset_id = pt['changeset']
55     
56     unless create
57       raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt['id'].nil?
58       relation.id = pt['id'].to_i
59       # .to_i will return 0 if there is no number that can be parsed. 
60       # We want to make sure that there is no id with zero anyway
61       raise OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
62     end
63     
64     # We don't care about the timestamp nor the visibility as these are either
65     # set explicitly or implicit in the action. The visibility is set to true, 
66     # and manually set to false before the actual delete.
67     relation.visible = true
68
69     pt.find('tag').each do |tag|
70       raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag['k'].nil?
71       raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag['v'].nil?
72       relation.add_tag_keyval(tag['k'], tag['v'])
73     end
74
75     pt.find('member').each do |member|
76       #member_type = 
77       logger.debug "each member"
78       raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
79       logger.debug "after raise"
80       #member_ref = member['ref']
81       #member_role
82       member['role'] ||= "" # Allow  the upload to not include this, in which case we default to an empty string.
83       logger.debug member['role']
84       relation.add_member(member['type'].classify, member['ref'], member['role'])
85     end
86     raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
87
88     return relation
89   end
90
91   def to_xml
92     doc = OSM::API.new.get_xml_doc
93     doc.root << to_xml_node()
94     return doc
95   end
96
97   def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
98     el1 = XML::Node.new 'relation'
99     el1['id'] = self.id.to_s
100     el1['visible'] = self.visible.to_s
101     el1['timestamp'] = self.timestamp.xmlschema
102     el1['version'] = self.version.to_s
103     el1['changeset'] = self.changeset_id.to_s
104
105     if changeset_cache.key?(self.changeset_id)
106       # use the cache if available
107     else
108       changeset_cache[self.changeset_id] = self.changeset.user_id
109     end
110
111     user_id = changeset_cache[self.changeset_id]
112
113     if user_display_name_cache.key?(user_id)
114       # use the cache if available
115     elsif self.changeset.user.data_public?
116       user_display_name_cache[user_id] = self.changeset.user.display_name
117     else
118       user_display_name_cache[user_id] = nil
119     end
120
121     if not user_display_name_cache[user_id].nil?
122       el1['user'] = user_display_name_cache[user_id]
123       el1['uid'] = user_id.to_s
124     end
125
126     self.relation_members.each do |member|
127       p=0
128       if visible_members
129         # if there is a list of visible members then use that to weed out deleted segments
130         if visible_members[member.member_type][member.member_id]
131           p=1
132         end
133       else
134         # otherwise, manually go to the db to check things
135         if member.member.visible?
136           p=1
137         end
138       end
139       if p
140         e = XML::Node.new 'member'
141         e['type'] = member.member_type.downcase
142         e['ref'] = member.member_id.to_s 
143         e['role'] = member.member_role
144         el1 << e
145        end
146     end
147
148     self.relation_tags.each do |tag|
149       e = XML::Node.new 'tag'
150       e['k'] = tag.k
151       e['v'] = tag.v
152       el1 << e
153     end
154     return el1
155   end 
156
157   # FIXME is this really needed?
158   def members
159     unless @members
160       @members = Array.new
161       self.relation_members.each do |member|
162         @members += [[member.member_type,member.member_id,member.member_role]]
163       end
164     end
165     @members
166   end
167
168   def tags
169     unless @tags
170       @tags = Hash.new
171       self.relation_tags.each do |tag|
172         @tags[tag.k] = tag.v
173       end
174     end
175     @tags
176   end
177
178   def members=(m)
179     @members = m
180   end
181
182   def tags=(t)
183     @tags = t
184   end
185
186   def add_member(type,id,role)
187     @members = Array.new unless @members
188     @members += [[type,id.to_i,role]]
189   end
190
191   def add_tag_keyval(k, v)
192     @tags = Hash.new unless @tags
193
194     # duplicate tags are now forbidden, so we can't allow values
195     # in the hash to be overwritten.
196     raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
197
198     @tags[k] = v
199   end
200
201   ##
202   # updates the changeset bounding box to contain the bounding box of 
203   # the element with given +type+ and +id+. this only works with nodes
204   # and ways at the moment, as they're the only elements to respond to
205   # the :bbox call.
206   def update_changeset_element(type, id)
207     element = Kernel.const_get(type.capitalize).find(id)
208     changeset.update_bbox! element.bbox
209   end    
210
211   def delete_with_history!(new_relation, user)
212     unless self.visible
213       raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
214     end
215
216     # need to start the transaction here, so that the database can 
217     # provide repeatable reads for the used-by checks. this means it
218     # shouldn't be possible to get race conditions.
219     Relation.transaction do
220       self.lock!
221       check_consistency(self, new_relation, user)
222       # This will check to see if this relation is used by another relation
223       rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, self.id).first
224       raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
225
226       self.changeset_id = new_relation.changeset_id
227       self.tags = {}
228       self.members = []
229       self.visible = false
230       save_with_history!
231     end
232   end
233
234   def update_from(new_relation, user)
235     Relation.transaction do
236       self.lock!
237       check_consistency(self, new_relation, user)
238       unless new_relation.preconditions_ok?(self.members)
239         raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
240       end
241       self.changeset_id = new_relation.changeset_id
242       self.changeset = new_relation.changeset
243       self.tags = new_relation.tags
244       self.members = new_relation.members
245       self.visible = true
246       save_with_history!
247     end
248   end
249   
250   def create_with_history(user)
251     check_create_consistency(self, user)
252     unless self.preconditions_ok?
253       raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
254     end
255     self.version = 0
256     self.visible = true
257     save_with_history!
258   end
259
260   def preconditions_ok?(good_members = [])
261     # These are hastables that store an id in the index of all 
262     # the nodes/way/relations that have already been added.
263     # If the member is valid and visible then we add it to the 
264     # relevant hash table, with the value true as a cache.
265     # Thus if you have nodes with the ids of 50 and 1 already in the
266     # relation, then the hash table nodes would contain:
267     # => {50=>true, 1=>true}
268     elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
269
270     # pre-set all existing members to good
271     good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
272
273     self.members.each do |m|
274       # find the hash for the element type or die
275       hash = elements[m[0].downcase.to_sym] or return false
276       # unless its in the cache already
277       unless hash.key? m[1]
278         # use reflection to look up the appropriate class
279         model = Kernel.const_get(m[0].capitalize)
280         # get the element with that ID
281         element = model.where(:id => m[1]).first
282
283         # and check that it is OK to use.
284         unless element and element.visible? and element.preconditions_ok?
285           raise OSM::APIPreconditionFailedError.new("Relation with id #{self.id} cannot be saved due to #{m[0]} with id #{m[1]}")
286         end
287         hash[m[1]] = true
288       end
289     end
290
291     return true
292   end
293
294   # Temporary method to match interface to nodes
295   def tags_as_hash
296     return self.tags
297   end
298
299   ##
300   # if any members are referenced by placeholder IDs (i.e: negative) then
301   # this calling this method will fix them using the map from placeholders 
302   # to IDs +id_map+. 
303   def fix_placeholders!(id_map, placeholder_id = nil)
304     self.members.map! do |type, id, role|
305       old_id = id.to_i
306       if old_id < 0
307         new_id = id_map[type.downcase.to_sym][old_id]
308         raise OSM::APIBadUserInput.new("Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}.") if new_id.nil?
309         [type, new_id, role]
310       else
311         [type, id, role]
312       end
313     end
314   end
315
316   private
317   
318   def save_with_history!
319     Relation.transaction do
320       # have to be a little bit clever here - to detect if any tags
321       # changed then we have to monitor their before and after state.
322       tags_changed = false
323
324       t = Time.now.getutc
325       self.version += 1
326       self.timestamp = t
327       self.save!
328
329       tags = self.tags.clone
330       self.relation_tags.each do |old_tag|
331         key = old_tag.k
332         # if we can match the tags we currently have to the list
333         # of old tags, then we never set the tags_changed flag. but
334         # if any are different then set the flag and do the DB 
335         # update.
336         if tags.has_key? key 
337           tags_changed |= (old_tag.v != tags[key])
338
339           # remove from the map, so that we can expect an empty map
340           # at the end if there are no new tags
341           tags.delete key
342
343         else
344           # this means a tag was deleted
345           tags_changed = true
346         end
347       end
348       # if there are left-over tags then they are new and will have to
349       # be added.
350       tags_changed |= (not tags.empty?)
351       RelationTag.delete_all(:relation_id => self.id)
352       self.tags.each do |k,v|
353         tag = RelationTag.new
354         tag.relation_id = self.id
355         tag.k = k
356         tag.v = v
357         tag.save!
358       end
359       
360       # same pattern as before, but this time we're collecting the
361       # changed members in an array, as the bounding box updates for
362       # elements are per-element, not blanked on/off like for tags.
363       changed_members = Array.new
364       members = self.members.clone
365       self.relation_members.each do |old_member|
366         key = [old_member.member_type, old_member.member_id, old_member.member_role]
367         i = members.index key
368         if i.nil?
369           changed_members << key
370         else
371           members.delete_at i
372         end
373       end
374       # any remaining members must be new additions
375       changed_members += members
376
377       # update the members. first delete all the old members, as the new
378       # members may be in a different order and i don't feel like implementing
379       # a longest common subsequence algorithm to optimise this.
380       members = self.members
381       RelationMember.delete_all(:relation_id => self.id)
382       members.each_with_index do |m,i|
383         mem = RelationMember.new
384         mem.relation_id = self.id
385         mem.sequence_id = i
386         mem.member_type = m[0]
387         mem.member_id = m[1]
388         mem.member_role = m[2]
389         mem.save!
390       end
391
392       old_relation = OldRelation.from_relation(self)
393       old_relation.timestamp = t
394       old_relation.save_with_dependencies!
395
396       # update the bbox of the changeset and save it too.
397       # discussion on the mailing list gave the following definition for
398       # the bounding box update procedure of a relation:
399       #
400       # adding or removing nodes or ways from a relation causes them to be
401       # added to the changeset bounding box. adding a relation member or
402       # changing tag values causes all node and way members to be added to the
403       # bounding box. this is similar to how the map call does things and is
404       # reasonable on the assumption that adding or removing members doesn't
405       # materially change the rest of the relation.
406       any_relations = 
407         changed_members.collect { |id,type| type == "relation" }.
408         inject(false) { |b,s| b or s }
409
410       update_members = if tags_changed or any_relations
411                          # add all non-relation bounding boxes to the changeset
412                          # FIXME: check for tag changes along with element deletions and
413                          # make sure that the deleted element's bounding box is hit.
414                          self.members
415                        else 
416                          changed_members
417                        end
418       update_members.each do |type, id, role|
419         if type != "Relation"
420           update_changeset_element(type, id)
421         end
422       end
423
424       # tell the changeset we updated one element only
425       changeset.add_changes! 1
426
427       # save the (maybe updated) changeset bounding box
428       changeset.save!
429     end
430   end
431
432 end