moving the conistency checks for updates and deletes to library, hopefully got the...
[rails.git] / app / models / relation.rb
1 class Relation < ActiveRecord::Base
2   require 'xml/libxml'
3   
4   set_table_name 'current_relations'
5
6   belongs_to :changeset
7
8   has_many :old_relations, :foreign_key => 'id', :order => 'version'
9
10   has_many :relation_members, :foreign_key => 'id'
11   has_many :relation_tags, :foreign_key => 'id'
12
13   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
14   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
15
16   def self.from_xml(xml, create=false)
17     begin
18       p = XML::Parser.new
19       p.string = xml
20       doc = p.parse
21
22       doc.find('//osm/relation').each do |pt|
23         return Relation.from_xml_node(pt, create)
24       end
25     rescue
26       return nil
27     end
28   end
29
30   def self.from_xml_node(pt, create=false)
31     relation = Relation.new
32
33     if !create and pt['id'] != '0'
34       relation.id = pt['id'].to_i
35     end
36
37     relation.version = pt['version']
38     relation.changeset_id = pt['changeset']
39
40     if create
41       relation.timestamp = Time.now
42       relation.visible = true
43     else
44       if pt['timestamp']
45         relation.timestamp = Time.parse(pt['timestamp'])
46       end
47     end
48
49     pt.find('tag').each do |tag|
50       relation.add_tag_keyval(tag['k'], tag['v'])
51     end
52
53     pt.find('member').each do |member|
54       relation.add_member(member['type'], member['ref'], member['role'])
55     end
56
57     return relation
58   end
59
60   def to_xml
61     doc = OSM::API.new.get_xml_doc
62     doc.root << to_xml_node()
63     return doc
64   end
65
66   def to_xml_node(user_display_name_cache = nil)
67     el1 = XML::Node.new 'relation'
68     el1['id'] = self.id.to_s
69     el1['visible'] = self.visible.to_s
70     el1['timestamp'] = self.timestamp.xmlschema
71     el1['version'] = self.version.to_s
72     el1['changeset'] = self.changeset_id.to_s
73
74     user_display_name_cache = {} if user_display_name_cache.nil?
75     
76     if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
77       # use the cache if available
78     elsif self.user.data_public?
79       user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
80     else
81       user_display_name_cache[self.changeset.user_id] = nil
82     end
83
84     el1['user'] = user_display_name_cache[self.changeset.user_id] unless user_display_name_cache[self.changeset.user_id].nil?
85
86     self.relation_members.each do |member|
87       p=0
88       #if visible_members
89       #  # if there is a list of visible members then use that to weed out deleted segments
90       #  if visible_members[member.member_type][member.member_id]
91       #    p=1
92       #  end
93       #else
94         # otherwise, manually go to the db to check things
95         if member.member.visible?
96           p=1
97         end
98       #end
99       if p
100         e = XML::Node.new 'member'
101         e['type'] = member.member_type
102         e['ref'] = member.member_id.to_s 
103         e['role'] = member.member_role
104         el1 << e
105        end
106     end
107
108     self.relation_tags.each do |tag|
109       e = XML::Node.new 'tag'
110       e['k'] = tag.k
111       e['v'] = tag.v
112       el1 << e
113     end
114     return el1
115   end 
116
117   def self.find_for_nodes(ids, options = {})
118     if ids.empty?
119       return []
120     else
121       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
122         return self.find(:all, options)
123       end
124     end
125   end
126
127   def self.find_for_ways(ids, options = {})
128     if ids.empty?
129       return []
130     else
131       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
132         return self.find(:all, options)
133       end
134     end
135   end
136
137   def self.find_for_relations(ids, options = {})
138     if ids.empty?
139       return []
140     else
141       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
142         return self.find(:all, options)
143       end
144     end
145   end
146
147   # FIXME is this really needed?
148   def members
149     unless @members
150       @members = Array.new
151       self.relation_members.each do |member|
152         @members += [[member.member_type,member.member_id,member.member_role]]
153       end
154     end
155     @members
156   end
157
158   def tags
159     unless @tags
160       @tags = Hash.new
161       self.relation_tags.each do |tag|
162         @tags[tag.k] = tag.v
163       end
164     end
165     @tags
166   end
167
168   def members=(m)
169     @members = m
170   end
171
172   def tags=(t)
173     @tags = t
174   end
175
176   def add_member(type,id,role)
177     @members = Array.new unless @members
178     @members += [[type,id,role]]
179   end
180
181   def add_tag_keyval(k, v)
182     @tags = Hash.new unless @tags
183     @tags[k] = v
184   end
185
186   def save_with_history!
187     Relation.transaction do
188       t = Time.now
189       self.version += 1
190       self.timestamp = t
191       self.save!
192
193       tags = self.tags
194       RelationTag.delete_all(['id = ?', self.id])
195       tags.each do |k,v|
196         tag = RelationTag.new
197         tag.k = k
198         tag.v = v
199         tag.id = self.id
200         tag.save!
201       end
202
203       members = self.members
204       RelationMember.delete_all(['id = ?', self.id])
205       members.each do |n|
206         mem = RelationMember.new
207         mem.id = self.id
208         mem.member_type = n[0];
209         mem.member_id = n[1];
210         mem.member_role = n[2];
211         mem.save!
212       end
213
214       old_relation = OldRelation.from_relation(self)
215       old_relation.timestamp = t
216       old_relation.save_with_dependencies!
217     end
218   end
219
220   def delete_with_history(new_relation, user)
221     if self.visible
222       check_consistency(self, new_relation, user)
223       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 ])
224         raise OSM::APIPreconditionFailedError.new
225       else
226         #self.user_id = user.id
227         # FIXME we need to deal with changeset here, which is probably already dealt with
228         self.changeset_id = new_relation.changeset_id
229         self.tags = []
230         self.members = []
231         self.visible = false
232         save_with_history!
233       end
234     else
235       raise OSM::APIAlreadyDeletedError.new
236     end
237   end
238
239   def update_from(new_relation, user)
240     check_consistency(self, new_relation, user)
241     if !new_relation.preconditions_ok?
242       raise OSM::APIPreconditionFailedError.new
243     end
244     # FIXME need to deal with changeset etc
245     #self.user_id = user.id
246     self.changeset_id = new_relation.changeset_id
247     self.tags = new_relation.tags
248     self.members = new_relation.members
249     self.visible = true
250     save_with_history!
251   end
252
253   def preconditions_ok?
254     # These are hastables that store an id in the index of all 
255     # the nodes/way/relations that have already been added.
256     # Once we know the id of the node/way/relation exists
257     # we check to see if it is already existing in the hashtable
258     # if it does, then we return false. Otherwise
259     # we add it to the relevant hash table, with the value true..
260     # Thus if you have nodes with the ids of 50 and 1 already in the
261     # relation, then the hash table nodes would contain:
262     # => {50=>true, 1=>true}
263     nodes = Hash.new
264     ways = Hash.new
265     relations = Hash.new
266     self.members.each do |m|
267       if (m[0] == "node")
268         n = Node.find(:first, :conditions => ["id = ?", m[1]])
269         unless n and n.visible 
270           return false
271         end
272         if nodes[m[1]]
273           return false
274         else
275           nodes[m[1]] = true
276         end
277       elsif (m[0] == "way")
278         w = Way.find(:first, :conditions => ["id = ?", m[1]])
279         unless w and w.visible and w.preconditions_ok?
280           return false
281         end
282         if ways[m[1]]
283           return false
284         else
285           ways[m[1]] = true
286         end
287       elsif (m[0] == "relation")
288         e = Relation.find(:first, :conditions => ["id = ?", m[1]])
289         unless e and e.visible and e.preconditions_ok?
290           return false
291         end
292         if relations[m[1]]
293           return false
294         else
295           relations[m[1]] = true
296         end
297       else
298         return false
299       end
300     end
301     return true
302   rescue
303     return false
304   end
305
306   # Temporary method to match interface to nodes
307   def tags_as_hash
308     return self.tags
309   end
310 end