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