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