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