moving the check consistency to it's own file so that checks will be able to be loade...
[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.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     @tags[k] = v
186   end
187
188   def save_with_history!
189     Relation.transaction do
190       t = Time.now
191       self.version += 1
192       self.timestamp = t
193       self.save!
194
195       tags = self.tags
196       RelationTag.delete_all(['id = ?', self.id])
197       tags.each do |k,v|
198         tag = RelationTag.new
199         tag.k = k
200         tag.v = v
201         tag.id = self.id
202         tag.save!
203       end
204
205       members = self.members
206       RelationMember.delete_all(['id = ?', self.id])
207       members.each do |n|
208         mem = RelationMember.new
209         mem.id = self.id
210         mem.member_type = n[0];
211         mem.member_id = n[1];
212         mem.member_role = n[2];
213         mem.save!
214       end
215
216       old_relation = OldRelation.from_relation(self)
217       old_relation.timestamp = t
218       old_relation.save_with_dependencies!
219     end
220   end
221
222   def delete_with_history(new_relation, user)
223     if self.visible
224       check_consistency(self, new_relation, user)
225       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 ])
226         raise OSM::APIPreconditionFailedError.new
227       else
228         #self.user_id = user.id
229         # FIXME we need to deal with changeset here, which is probably already dealt with
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     else
237       raise OSM::APIAlreadyDeletedError.new
238     end
239   end
240
241   def update_from(new_relation, user)
242     check_consistency(self, new_relation, user)
243     if !new_relation.preconditions_ok?
244       raise OSM::APIPreconditionFailedError.new
245     end
246     # FIXME need to deal with changeset etc
247     #self.user_id = user.id
248     self.changeset_id = new_relation.changeset_id
249     self.tags = new_relation.tags
250     self.members = new_relation.members
251     self.visible = true
252     save_with_history!
253   end
254
255   def preconditions_ok?
256     # These are hastables that store an id in the index of all 
257     # the nodes/way/relations that have already been added.
258     # Once we know the id of the node/way/relation exists
259     # we check to see if it is already existing in the hashtable
260     # if it does, then we return false. Otherwise
261     # we add it to the relevant hash table, with the value true..
262     # Thus if you have nodes with the ids of 50 and 1 already in the
263     # relation, then the hash table nodes would contain:
264     # => {50=>true, 1=>true}
265     nodes = Hash.new
266     ways = Hash.new
267     relations = Hash.new
268     self.members.each do |m|
269       if (m[0] == "node")
270         n = Node.find(:first, :conditions => ["id = ?", m[1]])
271         unless n and n.visible 
272           return false
273         end
274         if nodes[m[1]]
275           return false
276         else
277           nodes[m[1]] = true
278         end
279       elsif (m[0] == "way")
280         w = Way.find(:first, :conditions => ["id = ?", m[1]])
281         unless w and w.visible and w.preconditions_ok?
282           return false
283         end
284         if ways[m[1]]
285           return false
286         else
287           ways[m[1]] = true
288         end
289       elsif (m[0] == "relation")
290         e = Relation.find(:first, :conditions => ["id = ?", m[1]])
291         unless e and e.visible and e.preconditions_ok?
292           return false
293         end
294         if relations[m[1]]
295           return false
296         else
297           relations[m[1]] = true
298         end
299       else
300         return false
301       end
302     end
303     return true
304   rescue
305     return false
306   end
307
308   # Temporary method to match interface to nodes
309   def tags_as_hash
310     return self.tags
311   end
312 end