adding the controller code to be able to get a specific version of a node, way or...
[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(user)
221     if self.visible
222       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 ])
223         raise OSM::APIPreconditionFailedError.new
224       else
225         #self.user_id = user.id
226         # FIXME we need to deal with changeset here, which is probably already dealt with
227         self.tags = []
228         self.members = []
229         self.visible = false
230         save_with_history!
231       end
232     else
233       raise OSM::APIAlreadyDeletedError.new
234     end
235   end
236
237   def update_from(new_relation, user)
238     if !new_relation.preconditions_ok?
239       raise OSM::APIPreconditionFailedError.new
240     elsif new_relation.version != version
241       raise OSM::APIVersionMismatchError.new(new_relation.version, version)
242     elsif new_relation.changeset.user_id != user.id
243       raise OSM::APIUserChangesetMismatchError.new
244     elsif not new_relation.changeset.open?
245       raise OSM::APIChangesetAlreadyClosedError.new
246     else
247       # FIXME need to deal with changeset etc
248       #self.user_id = user.id
249       self.changeset_id = new_relation.changeset_id
250       self.tags = new_relation.tags
251       self.members = new_relation.members
252       self.visible = true
253       save_with_history!
254     end
255   end
256
257   def preconditions_ok?
258     # These are hastables that store an id in the index of all 
259     # the nodes/way/relations that have already been added.
260     # Once we know the id of the node/way/relation exists
261     # we check to see if it is already existing in the hashtable
262     # if it does, then we return false. Otherwise
263     # we add it to the relevant hash table, with the value true..
264     # Thus if you have nodes with the ids of 50 and 1 already in the
265     # relation, then the hash table nodes would contain:
266     # => {50=>true, 1=>true}
267     nodes = Hash.new
268     ways = Hash.new
269     relations = Hash.new
270     self.members.each do |m|
271       if (m[0] == "node")
272         n = Node.find(:first, :conditions => ["id = ?", m[1]])
273         unless n and n.visible 
274           return false
275         end
276         if nodes[m[1]]
277           return false
278         else
279           nodes[m[1]] = true
280         end
281       elsif (m[0] == "way")
282         w = Way.find(:first, :conditions => ["id = ?", m[1]])
283         unless w and w.visible and w.preconditions_ok?
284           return false
285         end
286         if ways[m[1]]
287           return false
288         else
289           ways[m[1]] = true
290         end
291       elsif (m[0] == "relation")
292         e = Relation.find(:first, :conditions => ["id = ?", m[1]])
293         unless e and e.visible and e.preconditions_ok?
294           return false
295         end
296         if relations[m[1]]
297           return false
298         else
299           relations[m[1]] = true
300         end
301       else
302         return false
303       end
304     end
305     return true
306   rescue
307     return false
308   end
309
310   # Temporary method to match interface to nodes
311   def tags_as_hash
312     return self.tags
313   end
314 end