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