Added first attempt at bounding box support in changesets and tests for the same.
[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'
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   def self.from_xml(xml, create=false)
19     begin
20       p = XML::Parser.new
21       p.string = xml
22       doc = p.parse
23
24       doc.find('//osm/relation').each do |pt|
25         return Relation.from_xml_node(pt, create)
26       end
27     rescue
28       return nil
29     end
30   end
31
32   def self.from_xml_node(pt, create=false)
33     relation = Relation.new
34
35     if !create and pt['id'] != '0'
36       relation.id = pt['id'].to_i
37     end
38
39     relation.version = pt['version']
40     relation.changeset_id = pt['changeset']
41
42     if create
43       relation.timestamp = Time.now
44       relation.visible = true
45     else
46       if pt['timestamp']
47         relation.timestamp = Time.parse(pt['timestamp'])
48       end
49     end
50
51     pt.find('tag').each do |tag|
52       relation.add_tag_keyval(tag['k'], tag['v'])
53     end
54
55     pt.find('member').each do |member|
56       relation.add_member(member['type'], member['ref'], member['role'])
57     end
58
59     return relation
60   end
61
62   def to_xml
63     doc = OSM::API.new.get_xml_doc
64     doc.root << to_xml_node()
65     return doc
66   end
67
68   def to_xml_node(user_display_name_cache = nil)
69     el1 = XML::Node.new 'relation'
70     el1['id'] = self.id.to_s
71     el1['visible'] = self.visible.to_s
72     el1['timestamp'] = self.timestamp.xmlschema
73     el1['version'] = self.version.to_s
74     el1['changeset'] = self.changeset_id.to_s
75
76     user_display_name_cache = {} if user_display_name_cache.nil?
77     
78     if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
79       # use the cache if available
80     elsif self.changeset.user.data_public?
81       user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
82     else
83       user_display_name_cache[self.changeset.user_id] = nil
84     end
85
86     el1['user'] = user_display_name_cache[self.changeset.user_id] unless user_display_name_cache[self.changeset.user_id].nil?
87
88     self.relation_members.each do |member|
89       p=0
90       #if visible_members
91       #  # if there is a list of visible members then use that to weed out deleted segments
92       #  if visible_members[member.member_type][member.member_id]
93       #    p=1
94       #  end
95       #else
96         # otherwise, manually go to the db to check things
97         if member.member.visible?
98           p=1
99         end
100       #end
101       if p
102         e = XML::Node.new 'member'
103         e['type'] = member.member_type
104         e['ref'] = member.member_id.to_s 
105         e['role'] = member.member_role
106         el1 << e
107        end
108     end
109
110     self.relation_tags.each do |tag|
111       e = XML::Node.new 'tag'
112       e['k'] = tag.k
113       e['v'] = tag.v
114       el1 << e
115     end
116     return el1
117   end 
118
119   def self.find_for_nodes(ids, options = {})
120     if ids.empty?
121       return []
122     else
123       self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'node' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
124         return self.find(:all, options)
125       end
126     end
127   end
128
129   def self.find_for_ways(ids, options = {})
130     if ids.empty?
131       return []
132     else
133       self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'way' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
134         return self.find(:all, options)
135       end
136     end
137   end
138
139   def self.find_for_relations(ids, options = {})
140     if ids.empty?
141       return []
142     else
143       self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'relation' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
144         return self.find(:all, options)
145       end
146     end
147   end
148
149   # FIXME is this really needed?
150   def members
151     unless @members
152       @members = Array.new
153       self.relation_members.each do |member|
154         @members += [[member.member_type,member.member_id,member.member_role]]
155       end
156     end
157     @members
158   end
159
160   def tags
161     unless @tags
162       @tags = Hash.new
163       self.relation_tags.each do |tag|
164         @tags[tag.k] = tag.v
165       end
166     end
167     @tags
168   end
169
170   def members=(m)
171     @members = m
172   end
173
174   def tags=(t)
175     @tags = t
176   end
177
178   def add_member(type,id,role)
179     @members = Array.new unless @members
180     @members += [[type,id,role]]
181   end
182
183   def add_tag_keyval(k, v)
184     @tags = Hash.new unless @tags
185
186     # duplicate tags are now forbidden, so we can't allow values
187     # in the hash to be overwritten.
188     raise OSM::APIDuplicateTagsError.new if @tags.include? k
189
190     @tags[k] = v
191   end
192
193   def save_with_history!
194     Relation.transaction do
195       t = Time.now
196       self.version += 1
197       self.timestamp = t
198       self.save!
199
200       tags = self.tags
201       RelationTag.delete_all(['id = ?', self.id])
202       tags.each do |k,v|
203         tag = RelationTag.new
204         tag.k = k
205         tag.v = v
206         tag.id = self.id
207         tag.save!
208       end
209
210       members = self.members
211       RelationMember.delete_all(['id = ?', self.id])
212       members.each do |n|
213         mem = RelationMember.new
214         mem.id = self.id
215         mem.member_type = n[0];
216         mem.member_id = n[1];
217         mem.member_role = n[2];
218         mem.save!
219       end
220
221       old_relation = OldRelation.from_relation(self)
222       old_relation.timestamp = t
223       old_relation.save_with_dependencies!
224
225       # update the bbox of the changeset and save it too.
226       # FIXME: what is the bounding box of a relation?
227     end
228   end
229
230   def delete_with_history!(new_relation, user)
231     if self.visible
232       check_consistency(self, new_relation, user)
233       if RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id", :conditions => [ "visible = 1 AND member_type='relation' and member_id=? ", self.id ])
234         raise OSM::APIPreconditionFailedError.new
235       else
236         self.changeset_id = new_relation.changeset_id
237         self.tags = []
238         self.members = []
239         self.visible = false
240         save_with_history!
241       end
242     else
243       raise OSM::APIAlreadyDeletedError.new
244     end
245   end
246
247   def update_from(new_relation, user)
248     check_consistency(self, new_relation, user)
249     if !new_relation.preconditions_ok?
250       raise OSM::APIPreconditionFailedError.new
251     end
252     self.changeset_id = new_relation.changeset_id
253     self.tags = new_relation.tags
254     self.members = new_relation.members
255     self.visible = true
256     save_with_history!
257   end
258   
259   def create_with_history(user)
260     check_create_consistency(self, user)
261     if !self.preconditions_ok?
262       raise OSM::APIPreconditionFailedError.new
263     end
264     self.version = 0
265     self.visible = true
266     save_with_history!
267   end
268
269   def preconditions_ok?
270     # These are hastables that store an id in the index of all 
271     # the nodes/way/relations that have already been added.
272     # Once we know the id of the node/way/relation exists
273     # we check to see if it is already existing in the hashtable
274     # if it does, then we return false. Otherwise
275     # we add it to the relevant hash table, with the value true..
276     # Thus if you have nodes with the ids of 50 and 1 already in the
277     # relation, then the hash table nodes would contain:
278     # => {50=>true, 1=>true}
279     nodes = Hash.new
280     ways = Hash.new
281     relations = Hash.new
282     self.members.each do |m|
283       if (m[0] == "node")
284         n = Node.find(:first, :conditions => ["id = ?", m[1]])
285         unless n and n.visible 
286           return false
287         end
288         if nodes[m[1]]
289           return false
290         else
291           nodes[m[1]] = true
292         end
293       elsif (m[0] == "way")
294         w = Way.find(:first, :conditions => ["id = ?", m[1]])
295         unless w and w.visible and w.preconditions_ok?
296           return false
297         end
298         if ways[m[1]]
299           return false
300         else
301           ways[m[1]] = true
302         end
303       elsif (m[0] == "relation")
304         e = Relation.find(:first, :conditions => ["id = ?", m[1]])
305         unless e and e.visible and e.preconditions_ok?
306           return false
307         end
308         if relations[m[1]]
309           return false
310         else
311           relations[m[1]] = true
312         end
313       else
314         return false
315       end
316     end
317     return true
318   rescue
319     return false
320   end
321
322   # Temporary method to match interface to nodes
323   def tags_as_hash
324     return self.tags
325   end
326
327   ##
328   # if any members are referenced by placeholder IDs (i.e: negative) then
329   # this calling this method will fix them using the map from placeholders 
330   # to IDs +id_map+. 
331   def fix_placeholders!(id_map)
332     self.members.map! do |type, id, role|
333       old_id = id.to_i
334       if old_id < 0
335         new_id = id_map[type.to_sym][old_id]
336         raise "invalid placeholder" if new_id.nil?
337         [type, new_id, role]
338       else
339         [type, id, role]
340       end
341     end
342   end
343
344 end