]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Add missing translation for new community submenu
[rails.git] / app / models / node.rb
1 class Node < ActiveRecord::Base
2   require 'xml/libxml'
3
4   include GeoRecord
5   include ConsistencyValidations
6
7   self.table_name = "current_nodes"
8
9   belongs_to :changeset
10
11   has_many :old_nodes, :order => :version
12
13   has_many :way_nodes
14   has_many :ways, :through => :way_nodes
15
16   has_many :node_tags
17   
18   has_many :old_way_nodes
19   has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way
20
21   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
22   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
23
24   validates_presence_of :id, :on => :update
25   validates_presence_of :timestamp,:version,  :changeset_id
26   validates_uniqueness_of :id
27   validates_inclusion_of :visible, :in => [ true, false ]
28   validates_numericality_of :latitude, :longitude, :changeset_id, :version, :integer_only => true
29   validates_numericality_of :id, :on => :update, :integer_only => true
30   validate :validate_position
31   validates_associated :changeset
32
33   scope :visible, where(:visible => true)
34   scope :invisible, where(:visible => false)
35
36   # Sanity check the latitude and longitude and add an error if it's broken
37   def validate_position
38     errors.add(:base, "Node is not in the world") unless in_world?
39   end
40
41   #
42   # Search for nodes matching tags within bounding_box
43   #
44   # Also adheres to limitations such as within max_number_of_nodes
45   #
46   def self.search(bounding_box, tags = {})
47     # @fixme a bit of a hack to search for only visible nodes
48     # couldn't think of another to add to tags condition
49     #conditions_hash = tags.merge({ 'visible' => 1 })
50   
51     # using named placeholders http://www.robbyonrails.com/articles/2005/10/21/using-named-placeholders-in-ruby
52     #keys = []
53     #values = {}
54
55     #conditions_hash.each do |key,value|
56     #  keys <<  "#{key} = :#{key}"
57     #  values[key.to_sym] = value
58     #end 
59     #conditions = keys.join(' AND ')
60  
61     find_by_area(bounding_box, :conditions => {:visible => true},
62                        :limit => MAX_NUMBER_OF_NODES+1)
63   end
64
65   # Read in xml as text and return it's Node object representation
66   def self.from_xml(xml, create=false)
67     begin
68       p = XML::Parser.string(xml)
69       doc = p.parse
70
71       doc.find('//osm/node').each do |pt|
72         return Node.from_xml_node(pt, create)
73       end
74       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
75     rescue LibXML::XML::Error, ArgumentError => ex
76       raise OSM::APIBadXMLError.new("node", xml, ex.message)
77     end
78   end
79
80   def self.from_xml_node(pt, create=false)
81     node = Node.new
82     
83     raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
84     raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
85     node.lat = pt['lat'].to_f
86     node.lon = pt['lon'].to_f
87     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
88     node.changeset_id = pt['changeset'].to_i
89
90     raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
91
92     # version must be present unless creating
93     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
94     node.version = create ? 0 : pt['version'].to_i
95
96     unless create
97       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
98       node.id = pt['id'].to_i
99       # .to_i will return 0 if there is no number that can be parsed. 
100       # We want to make sure that there is no id with zero anyway
101       raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
102     end
103
104     # We don't care about the time, as it is explicitly set on create/update/delete
105     # We don't care about the visibility as it is implicit based on the action
106     # and set manually before the actual delete
107     node.visible = true
108
109     # Start with no tags
110     node.tags = Hash.new
111
112     # Add in any tags from the XML
113     pt.find('tag').each do |tag|
114       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
115       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
116       node.add_tag_key_val(tag['k'],tag['v'])
117     end
118
119     return node
120   end
121
122   ##
123   # the bounding box around a node, which is used for determining the changeset's
124   # bounding box
125   def bbox
126     BoundingBox.new(longitude, latitude, longitude, latitude)
127   end
128
129   # Should probably be renamed delete_from to come in line with update
130   def delete_with_history!(new_node, user)
131     unless self.visible
132       raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
133     end
134
135     # need to start the transaction here, so that the database can 
136     # provide repeatable reads for the used-by checks. this means it
137     # shouldn't be possible to get race conditions.
138     Node.transaction do
139       self.lock!
140       check_consistency(self, new_node, user)
141       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
142       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
143       
144       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
145       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
146
147       self.changeset_id = new_node.changeset_id
148       self.tags = {}
149       self.visible = false
150       
151       # update the changeset with the deleted position
152       changeset.update_bbox!(bbox)
153       
154       save_with_history!
155     end
156   end
157
158   def update_from(new_node, user)
159     Node.transaction do
160       self.lock!
161       check_consistency(self, new_node, user)
162       
163       # update changeset first
164       self.changeset_id = new_node.changeset_id
165       self.changeset = new_node.changeset
166       
167       # update changeset bbox with *old* position first
168       changeset.update_bbox!(bbox);
169       
170       # FIXME logic needs to be double checked
171       self.latitude = new_node.latitude 
172       self.longitude = new_node.longitude
173       self.tags = new_node.tags
174       self.visible = true
175       
176       # update changeset bbox with *new* position
177       changeset.update_bbox!(bbox);
178       
179       save_with_history!
180     end
181   end
182   
183   def create_with_history(user)
184     check_create_consistency(self, user)
185     self.version = 0
186     self.visible = true
187
188     # update the changeset to include the new location
189     changeset.update_bbox!(bbox)
190
191     save_with_history!
192   end
193
194   def to_xml
195     doc = OSM::API.new.get_xml_doc
196     doc.root << to_xml_node()
197     return doc
198   end
199
200   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
201     el1 = XML::Node.new 'node'
202     el1['id'] = self.id.to_s
203     el1['lat'] = self.lat.to_s
204     el1['lon'] = self.lon.to_s
205     el1['version'] = self.version.to_s
206     el1['changeset'] = self.changeset_id.to_s
207
208     if changeset_cache.key?(self.changeset_id)
209       # use the cache if available
210     else
211       changeset_cache[self.changeset_id] = self.changeset.user_id
212     end
213
214     user_id = changeset_cache[self.changeset_id]
215
216     if user_display_name_cache.key?(user_id)
217       # use the cache if available
218     elsif self.changeset.user.data_public?
219       user_display_name_cache[user_id] = self.changeset.user.display_name
220     else
221       user_display_name_cache[user_id] = nil
222     end
223
224     if not user_display_name_cache[user_id].nil?
225       el1['user'] = user_display_name_cache[user_id]
226       el1['uid'] = user_id.to_s
227     end
228
229     self.tags.each do |k,v|
230       el2 = XML::Node.new('tag')
231       el2['k'] = k.to_s
232       el2['v'] = v.to_s
233       el1 << el2
234     end
235
236     el1['visible'] = self.visible.to_s
237     el1['timestamp'] = self.timestamp.xmlschema
238     return el1
239   end
240
241   def tags_as_hash
242     return tags
243   end
244
245   def tags
246     unless @tags
247       @tags = {}
248       self.node_tags.each do |tag|
249         @tags[tag.k] = tag.v
250       end
251     end
252     @tags
253   end
254
255   def tags=(t)
256     @tags = t 
257   end 
258
259   def add_tag_key_val(k,v)
260     @tags = Hash.new unless @tags
261
262     # duplicate tags are now forbidden, so we can't allow values
263     # in the hash to be overwritten.
264     raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
265
266     @tags[k] = v
267   end
268
269   ##
270   # are the preconditions OK? this is mainly here to keep the duck
271   # typing interface the same between nodes, ways and relations.
272   def preconditions_ok?
273     in_world?
274   end
275
276   ##
277   # dummy method to make the interfaces of node, way and relation
278   # more consistent.
279   def fix_placeholders!(id_map, placeholder_id = nil)
280     # nodes don't refer to anything, so there is nothing to do here
281   end
282   
283   private
284
285   def save_with_history!
286     t = Time.now.getutc
287     Node.transaction do
288       self.version += 1
289       self.timestamp = t
290       self.save!
291
292       # Create a NodeTag
293       tags = self.tags
294       NodeTag.delete_all(:node_id => self.id)
295       tags.each do |k,v|
296         tag = NodeTag.new
297         tag.node_id = self.id
298         tag.k = k 
299         tag.v = v 
300         tag.save!
301       end 
302
303       # Create an OldNode
304       old_node = OldNode.from_node(self)
305       old_node.timestamp = t
306       old_node.save_with_dependencies!
307
308       # tell the changeset we updated one element only
309       changeset.add_changes! 1
310
311       # save the changeset in case of bounding box updates
312       changeset.save!
313     end
314   end
315   
316 end