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