]> git.openstreetmap.org Git - rails.git/blob - app/controllers/amf_controller.rb
fixed null value bug in rake task
[rails.git] / app / controllers / amf_controller.rb
1 # AMF Controller is a semi-standalone API for Flash clients, particularly Potlatch.
2 # All interaction between Potlatch (as a .SWF application) and the 
3 # OSM database takes place using this controller. Messages are 
4 # encoded in the Actionscript Message Format (AMF).
5 #
6 # See Also Potlatch::Potlatch and Potlatch::AMF
7 #
8 # Public domain.
9 # editions Systeme D / Richard Fairhurst 2004-2008
10 #
11 # All in/out parameters are floats unless explicitly stated.
12
13 # to trap errors (getway_old,putway,putpoi,deleteway only):
14 #   return(-1,"message")                <-- just puts up a dialogue
15 #   return(-2,"message")                <-- also asks the user to e-mail me
16 # to log:
17 #   RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
18 class AmfController < ApplicationController
19   require 'stringio'
20
21   include Potlatch
22
23   session :off
24   before_filter :check_write_availability
25
26   # Main AMF handler. Tha talk method takes in AMF, figures out what to do and dispatched to the appropriate private method
27   def talk
28     req=StringIO.new(request.raw_post+0.chr)    # Get POST data as request
29     # (cf http://www.ruby-forum.com/topic/122163)
30     req.read(2)                                                                 # Skip version indicator and client ID
31     results={}                                                                  # Results of each body
32     renumberednodes={}                                                  # Shared across repeated putways
33
34     # -------------
35     # Parse request
36
37     headers=AMF.getint(req)                                     # Read number of headers
38
39     headers.times do                                # Read each header
40       name=AMF.getstring(req)                           #  |
41       req.getc                                  #  | skip boolean
42       value=AMF.getvalue(req)                           #  |
43       header["name"]=value                              #  |
44     end
45
46     bodies=AMF.getint(req)                                      # Read number of bodies
47     bodies.times do                                     # Read each body
48       message=AMF.getstring(req)                        #  | get message name
49       index=AMF.getstring(req)                          #  | get index in response sequence
50       bytes=AMF.getlong(req)                            #  | get total size in bytes
51       args=AMF.getvalue(req)                            #  | get response (probably an array)
52
53       case message
54       when 'getpresets';                results[index]=AMF.putdata(index,getpresets)
55       when 'whichways';                 results[index]=AMF.putdata(index,whichways(args))
56       when 'whichways_deleted'; results[index]=AMF.putdata(index,whichways_deleted(args))
57       when 'getway';                    results[index]=AMF.putdata(index,getway(args))
58       when 'getway_old';                results[index]=AMF.putdata(index,getway_old(args))
59       when 'getway_history';    results[index]=AMF.putdata(index,getway_history(args))
60       when 'putway';                    r=putway(args,renumberednodes)
61         renumberednodes=r[3]
62         results[index]=AMF.putdata(index,r)
63       when 'deleteway';                 results[index]=AMF.putdata(index,deleteway(args))
64       when 'putpoi';                    results[index]=AMF.putdata(index,putpoi(args))
65       when 'getpoi';                    results[index]=AMF.putdata(index,getpoi(args))
66       end
67     end
68
69     # ------------------
70     # Write out response
71
72     RAILS_DEFAULT_LOGGER.info("  Response: start")
73     a,b=results.length.divmod(256)
74     render :content_type => "application/x-amf", :text => proc { |response, output| 
75       output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
76       results.each do |k,v|
77         output.write(v)
78       end
79     }
80     RAILS_DEFAULT_LOGGER.info("  Response: end")
81   end
82
83   private
84
85   # Return presets (default tags and crap) to potlatch.
86   # Uses POTLATCH_PRESETS global, set up in OSM::Potlatch
87   def getpresets #:doc:
88     return POTLATCH_PRESETS
89   end
90
91   # ----- whichways
92   # Find all the way ids and nodes (including tags and projected lat/lng) which aren't part of those ways in an are
93   # 
94   # The argument is an array containing the following, in order:
95   # 0. minimum longitude
96   # 1. minimum latitude
97   # 2. maximum longitude
98   # 3. maximum latitude
99   # 4. baselong, 5. basey, 6. masterscale as above
100   def whichways(args) #:doc:
101     xmin = args[0].to_f-0.01
102     ymin = args[1].to_f-0.01
103     xmax = args[2].to_f+0.01
104     ymax = args[3].to_f+0.01
105     baselong    = args[4]
106     basey       = args[5]
107     masterscale = args[6]
108
109     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
110
111     # find the way ids in an area
112     nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax,:conditions => "visible = 1", :include => :way_nodes)
113     waynodes_in_area = nodes_in_area.collect {|node| node.way_nodes }.flatten
114     ways = waynodes_in_area.collect {|way_node| way_node.id[0]}.uniq
115
116     # find the node ids in an area that aren't part of ways
117     node_ids_in_area = nodes_in_area.collect {|node| node.id}.uniq
118     node_ids_used_in_ways = waynodes_in_area.collect {|way_node| way_node.node_id}.uniq
119     node_ids_not_used_in_area = node_ids_in_area - node_ids_used_in_ways
120     nodes_not_used_in_area = Node.find(node_ids_not_used_in_area)
121     points = nodes_not_used_in_area.collect {|n| [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash] }
122
123     [ways,points]
124   end
125
126   # ----- whichways_deleted
127   #               return array of deleted ways in current bounding box
128   #               in:   as whichways
129   #               does: finds all deleted ways with a deleted node in bounding box
130   #               out:  [0] array of way ids
131   def whichways_deleted(args) #:doc:
132     xmin = args[0].to_f-0.01
133     ymin = args[1].to_f-0.01
134     xmax = args[2].to_f+0.01
135     ymax = args[3].to_f+0.01
136     baselong    = args[4]
137     basey       = args[5]
138     masterscale = args[6]
139
140     sql=<<-EOF
141      SELECT DISTINCT current_ways.id 
142        FROM current_nodes,way_nodes,current_ways 
143       WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")} 
144       AND way_nodes.node_id=current_nodes.id 
145       AND way_nodes.id=current_ways.id 
146       AND current_nodes.visible=0 
147       AND current_ways.visible=0 
148   EOF
149     waylist = ActiveRecord::Base.connection.select_all(sql)
150     ways = waylist.collect {|a| a['id'].to_i }
151     [ways]
152   end
153
154   # ----- getway
155   # Get a way with all of it's nodes and tags
156   # The input is an array with the following components, in order:
157   # 0. wayid - the ID of the way to get
158   # 1. baselong - origin of SWF map (longitude)
159   # 2. basey - origin of SWF map (latitude)
160   # 3. masterscale - SWF map scale
161   #
162   # The output is an array which contains all the nodes (with projected 
163   # latitude and longitude) and tags for a way (and all the nodes tags). 
164   # It also has the way's unprojected (WGS84) bbox.
165   #
166   # FIXME: The server really shouldn't be figuring out a ways bounding box and doing projection for potlatch
167   # FIXME: the argument splitting should be done in the 'talk' method, not here
168   def getway(args) #:doc:
169     wayid,baselong,basey,masterscale = args
170     wayid = wayid.to_i
171
172     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
173
174     way = Way.find_eager(wayid)
175     long_array = []
176     lat_array = []
177     points = []
178
179     way.way_nodes.each do |way_node|
180       node = way_node.node # get the node record
181       projected_longitude = node.lon_potlatch(baselong,masterscale) # do projection for potlatch
182       projected_latitude = node.lat_potlatch(basey,masterscale)
183       id = node.id
184       tags_hash = node.tags_as_hash
185
186       points << [projected_longitude, projected_latitude, id, nil, tags_hash]
187       long_array << projected_longitude
188       lat_array << projected_latitude
189     end
190
191     [wayid,points,way.tags,long_array.min,long_array.max,lat_array.min,lat_array.max]
192   end
193
194   # ----- getway_old
195   #               returns old version of way
196   #               in:   [0] way id,
197   #                             [1] way version to get (or -1 for "last deleted version")
198   #                             [2] baselong, [3] basey, [4] masterscale
199   #               does: gets old version of way and all constituent nodes
200   #                             for undelete, always uses the most recent version of each node
201   #                               (even if it's moved)
202   #                             for revert, uses the historic version of each node, but if that node is
203   #                               still visible and has been changed since, generates a new node id
204   #               out:  [0] 0 (code for success), [1] SWF object name,
205   #                             [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
206   #                             [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
207   #                             [8] way version
208   def getway_old(args) #:doc:
209     RAILS_DEFAULT_LOGGER.info("  Message: getway_old (server is #{SERVER_URL})")
210     #   if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
211
212     wayid,version,baselong,basey,masterscale=args
213     wayid = wayid.to_i
214     version = version.to_i
215     xmin = ymin =  999999
216     xmax = ymax = -999999
217     points=[]
218     if version<0
219       historic=false
220       version=getlastversion(wayid,version)
221     else
222       historic=true
223     end
224     readwayquery_old(wayid,version,historic).each { |row|
225       points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,row['visible'].to_i,tag2array(row['tags'].to_s)]
226       xmin=[xmin,row['longitude'].to_f].min
227       xmax=[xmax,row['longitude'].to_f].max
228       ymin=[ymin,row['latitude' ].to_f].min
229       ymax=[ymax,row['latitude' ].to_f].max
230     }
231
232     # get tags from this version
233     attributes={}
234     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
235     attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
236     attributes['history']="Retrieved from v"+version.to_s
237
238     [0,wayid,points,attributes,xmin,xmax,ymin,ymax,version]
239   end
240
241   # ----- getway_history
242   #               find history of a way
243   #               in:   [0] way id
244   #               does: finds history of a way
245   #               out:  [0] array of previous versions (where each is
246   #                                     [0] version, [1] db timestamp (string),
247   #                                     [2] visible 0 or 1,
248   #                                     [3] username or 'anonymous' (string))
249   def getway_history(args) #:doc:
250     wayid=args[0]
251     history=[]
252     sql=<<-EOF
253   SELECT version,timestamp,visible,display_name,data_public
254     FROM ways,users
255    WHERE ways.id=#{wayid}
256      AND ways.user_id=users.id
257      AND ways.visible=1
258    ORDER BY version DESC
259   EOF
260     histlist=ActiveRecord::Base.connection.select_all(sql)
261     histlist.each { |row|
262       if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
263       history<<[row['version'],row['timestamp'],row['visible'],user]
264     }
265     [history]
266   end
267
268   # ----- putway
269   #               saves a way to the database
270   #               in:   [0] user token (string),
271   #                             [1] original way id (may be negative), 
272   #                             [2] array of points (as getway/getway_old),
273   #                             [3] hash of way tags,
274   #                             [4] original way version (0 if not a reverted/undeleted way),
275   #                             [5] baselong, [6] basey, [7] masterscale
276   #               does: saves way to the database
277   #                             all constituent nodes are created/updated as necessary
278   #                             (or deleted if they were in the old version and are otherwise unused)
279   #               out:  [0] 0 (code for success), [1] original way id (unchanged),
280   #                             [2] new way id, [3] hash of renumbered nodes (old id=>new id),
281   #                             [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
282   def putway(args,renumberednodes) #:doc:
283     RAILS_DEFAULT_LOGGER.info("  putway started")
284     usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
285     uid=getuserid(usertoken)
286     if !uid then return -1,"You are not logged in, so the way could not be saved." end
287
288     RAILS_DEFAULT_LOGGER.info("  putway authenticated happily")
289     db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s    # temp uniquenodes table name, typically 51 chars
290     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s    # 'now' variable name, typically 51 chars
291     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
292     originalway=originalway.to_i
293     oldversion=oldversion.to_i
294
295     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
296
297     # -- Temporary check for null IDs
298
299     points.each do |a|
300       if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
301     end
302
303     # -- 3.     read original way into memory
304
305     xc={}; yc={}; tagc={}; vc={}
306     if originalway>0
307       way=originalway
308       if oldversion==0 then r=readwayquery(way,false)
309       else r=readwayquery_old(way,oldversion,true) end
310       r.each { |row|
311         id=row['id'].to_i
312         if (id>0) then
313           xc[id]=row['longitude'].to_f
314           yc[id]=row['latitude' ].to_f
315           tagc[id]=row['tags']
316           vc[id]=row['visible'].to_i
317         end
318       }
319       ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
320     else
321       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
322     end
323
324     # -- 4.     get version by inserting new row into ways
325
326     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
327
328     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
329
330     xmin=ymin= 999999
331     xmax=ymax=-999999
332     insertsql=''
333     nodelist=[]
334
335     points.each_index do |i|
336       xs=coord2long(points[i][0],masterscale,baselong)
337       ys=coord2lat(points[i][1],masterscale,basey)
338       xmin=[xs,xmin].min; xmax=[xs,xmax].max
339       ymin=[ys,ymin].min; ymax=[ys,ymax].max
340       node=points[i][2].to_i
341       tagstr=array2tag(points[i][4])
342       tagsql="'"+sqlescape(tagstr)+"'"
343       lat=(ys * 10000000).round
344       long=(xs * 10000000).round
345       tile=QuadTile.tile_for_point(ys, xs)
346
347       # compare node
348       if node<0
349         # new node - create
350         if renumberednodes[node.to_s].nil?
351           newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (   latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (           #{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
352           ActiveRecord::Base.connection.insert("INSERT INTO nodes         (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{newnode},#{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
353           points[i][2]=newnode
354           nodelist.push(newnode)
355           renumberednodes[node.to_s]=newnode.to_s
356         else
357           points[i][2]=renumberednodes[node.to_s].to_i
358         end
359
360       elsif xc.has_key?(node)
361         nodelist.push(node)
362         # old node from original way - update
363         if ((xs/0.0000001).round!=(xc[node]/0.0000001).round or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
364           ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{node},#{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
365           ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{lat},longitude=#{long},timestamp=#{db_now},user_id=#{uid},tags=#{tagsql},visible=1,tile=#{tile} WHERE id=#{node}")
366         end
367       else
368         # old node, created in another way and now added to this way
369       end
370     end
371
372     # -- 6a. delete any nodes not in modified way
373
374     createuniquenodes(way,db_uqn,nodelist)      # nodes which appear in this way but no other
375
376     sql=<<-EOF
377   INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)  
378   SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
379     FROM current_nodes AS cn,#{db_uqn}
380    WHERE cn.id=node_id
381     EOF
382     ActiveRecord::Base.connection.insert(sql)
383
384     sql=<<-EOF
385       UPDATE current_nodes AS cn, #{db_uqn}
386          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
387        WHERE cn.id=node_id
388     EOF
389     ActiveRecord::Base.connection.update(sql)
390
391     deleteuniquenoderelations(db_uqn,uid,db_now)
392     ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
393
394     #   6b. insert new version of route into way_nodes
395
396     insertsql =''
397     currentsql=''
398     sequence  =1
399     points.each do |p|
400       if insertsql !='' then insertsql +=',' end
401       if currentsql!='' then currentsql+=',' end
402       insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
403       currentsql+="(#{way},#{p[2]},#{sequence})"
404       sequence  +=1
405     end
406
407     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
408     ActiveRecord::Base.connection.insert( "INSERT INTO         way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
409     ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id        ) VALUES #{currentsql}");
410
411     # -- 7. insert new way tags
412
413     insertsql =''
414     currentsql=''
415     attributes.each do |k,v|
416       if v=='' or v.nil? then next end
417       if v[0,6]=='(type ' then next end
418       if insertsql !='' then insertsql +=',' end
419       if currentsql!='' then currentsql+=',' end
420       insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
421       currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
422     end
423
424     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
425     if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
426     if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
427
428     [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
429   end
430
431   # ----- putpoi
432   #               save POI to the database
433   #               in:   [0] user token (string),
434   #                             [1] original node id (may be negative),
435   #                             [2] projected longitude, [3] projected latitude,
436   #                             [4] hash of tags, [5] visible (0 to delete, 1 otherwise), 
437   #                             [6] baselong, [7] basey, [8] masterscale
438   #               does: saves POI node to the database
439   #                             refuses save if the node has since become part of a way
440   #               out:  [0] 0 (success), [1] original node id (unchanged),
441   #                             [2] new node id
442   def putpoi(args) #:doc:
443     usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
444     uid=getuserid(usertoken)
445     if !uid then return -1,"You are not logged in, so the point could not be saved." end
446
447     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+id.to_i.abs.to_s+Time.new.to_i.to_s     # 'now' variable name, typically 51 chars
448     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
449
450     id=id.to_i
451     visible=visible.to_i
452     if visible==0 then
453       # if deleting, check node hasn't become part of a way 
454       inway=ActiveRecord::Base.connection.select_one("SELECT cw.id FROM current_ways cw,current_way_nodes cwn WHERE cw.id=cwn.id AND cw.visible=1 AND cwn.node_id=#{id} LIMIT 1")
455       unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
456       deleteitemrelations(id,'node',uid,db_now)
457     end
458
459     x=coord2long(x.to_f,masterscale,baselong)
460     y=coord2lat(y.to_f,masterscale,basey)
461     tagsql="'"+sqlescape(array2tag(tags))+"'"
462     lat=(y * 10000000).round
463     long=(x * 10000000).round
464     tile=QuadTile.tile_for_point(y, x)
465
466     if (id>0) then
467       ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{id},#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
468       ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{lat},longitude=#{long},timestamp=#{db_now},user_id=#{uid},visible=#{visible},tags=#{tagsql},tile=#{tile} WHERE id=#{id}");
469       newid=id
470     else
471       newid=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
472       ActiveRecord::Base.connection.update("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{newid},#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
473     end
474     [0,id,newid]
475   end
476
477   # ----- getpoi
478   #               read POI from database
479   #               (only called on revert: POIs are usually read by whichways)
480   #               in:   [0] node id, [1] baselong, [2] basey, [3] masterscale
481   #               does: reads POI
482   #               out:  [0] id (unchanged), [1] projected long, [2] projected lat,
483   #                             [3] hash of tags
484   def getpoi(args) #:doc:
485     id,baselong,basey,masterscale=args; id=id.to_i
486     poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
487     "FROM current_nodes WHERE visible=1 AND id=#{id}")
488     if poi.nil? then return [nil,nil,nil,''] end
489     [id,
490       long2coord(poi['lng'].to_f,baselong,masterscale),
491       lat2coord(poi['lat'].to_f,basey,masterscale),
492       tag2array(poi['tags'])]
493   end
494
495   # ----- deleteway
496   #               delete way and constituent nodes from database
497   #               in:   [0] user token (string), [1] way id
498   #               does: deletes way from db and any constituent nodes not used elsewhere
499   #                             also removes ways/nodes from any relations they're in
500   #               out:  [0] 0 (success), [1] way id (unchanged)
501   def deleteway(args) #:doc:
502
503     usertoken,way=args
504
505     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way}")
506     uid=getuserid(usertoken)
507     if !uid then return -1,"You are not logged in, so the way could not be deleted." end
508
509     way=way.to_i
510     db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s    # temp uniquenodes table name, typically 51 chars
511     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s    # 'now' variable name, typically 51 chars
512     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
513
514     # - delete any otherwise unused nodes
515
516     createuniquenodes(way,db_uqn,[])
517
518     #   unless (preserve.empty?) then
519     #           ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
520     #   end
521
522     sql=<<-EOF
523   INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
524   SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
525     FROM current_nodes AS cn,#{db_uqn}
526    WHERE cn.id=node_id
527     EOF
528     ActiveRecord::Base.connection.insert(sql)
529
530     sql=<<-EOF
531       UPDATE current_nodes AS cn, #{db_uqn}
532          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
533        WHERE cn.id=node_id
534     EOF
535     ActiveRecord::Base.connection.update(sql)
536
537     deleteuniquenoderelations(db_uqn,uid,db_now)
538     ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
539
540     # - delete way
541
542     ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
543     ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
544     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
545     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
546     deleteitemrelations(way,'way',uid,db_now)
547     [0,way]
548   end
549
550   def readwayquery(id,insistonvisible) #:doc:
551     sql=<<-EOF
552     SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible 
553       FROM current_way_nodes,current_nodes 
554      WHERE current_way_nodes.id=#{id} 
555        AND current_way_nodes.node_id=current_nodes.id 
556   EOF
557     if insistonvisible then sql+=" AND current_nodes.visible=1 " end
558     sql+=" ORDER BY sequence_id"
559     ActiveRecord::Base.connection.select_all(sql)
560   end
561
562   def getlastversion(id,version) #:doc:
563     row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
564     row['version']
565   end
566
567   def readwayquery_old(id,version,historic) #:doc:
568     # Node handling on undelete (historic=false):
569     # - always use the node specified, even if it's moved
570
571     # Node handling on revert (historic=true):
572     # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
573     #   which means the SWF needs to allocate new ids
574     # - if it's an invisible node, we can reuse the old node id
575
576     # get node list from specified version of way,
577     # and the _current_ lat/long/tags of each node
578
579     row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
580     waytime=row['timestamp']
581
582     sql=<<-EOF
583   SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags 
584     FROM way_nodes wn,current_nodes cn 
585    WHERE wn.version=#{version} 
586      AND wn.id=#{id} 
587      AND wn.node_id=cn.id 
588    ORDER BY sequence_id
589   EOF
590     rows=ActiveRecord::Base.connection.select_all(sql)
591
592     # if historic (full revert), get the old version of each node
593     # - if it's in another way now, generate a new id
594     # - if it's not in another way, use the old ID
595     if historic then
596       rows.each_index do |i|
597         sql=<<-EOF
598     SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway 
599       FROM nodes n
600    LEFT JOIN current_way_nodes cwn
601       ON cwn.node_id=n.id
602      WHERE n.id=#{rows[i]['id']} 
603        AND n.timestamp<="#{waytime}" 
604      AND cwn.id!=#{id} 
605      ORDER BY n.timestamp DESC 
606      LIMIT 1
607     EOF
608         row=ActiveRecord::Base.connection.select_one(sql)
609         unless row.nil? then
610           nx=row['longitude'].to_f
611           ny=row['latitude'].to_f
612           if (row['currentway'] && (nx!=rows[i]['longitude'].to_f or ny!=rows[i]['latitude'].to_f or row['tags']!=rows[i]['tags'])) then rows[i]['id']=-1 end
613           rows[i]['longitude']=nx
614           rows[i]['latitude' ]=ny
615           rows[i]['tags'     ]=row['tags']
616         end
617       end
618     end
619     rows
620   end
621
622   def createuniquenodes(way,uqn_name,nodelist) #:doc:
623     # Find nodes which appear in this way but no others
624     sql=<<-EOF
625   CREATE TEMPORARY TABLE #{uqn_name}
626           SELECT a.node_id
627             FROM (SELECT DISTINCT node_id FROM current_way_nodes
628               WHERE id=#{way}) a
629          LEFT JOIN current_way_nodes b
630             ON b.node_id=a.node_id
631              AND b.id!=#{way}
632            WHERE b.node_id IS NULL
633   EOF
634     unless nodelist.empty? then
635       sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
636     end
637     ActiveRecord::Base.connection.execute(sql)
638   end
639
640
641
642   # ====================================================================
643   # Relations handling
644   # deleteuniquenoderelations(uqn_name,uid,db_now)
645   # deleteitemrelations(way|node,'way'|'node',uid,db_now)
646
647   def deleteuniquenoderelations(uqn_name,uid,db_now) #:doc:
648     sql=<<-EOF
649   SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr 
650    WHERE crm.member_id=node_id 
651      AND crm.member_type='node' 
652      AND crm.id=cr.id 
653      AND cr.visible=1
654   EOF
655
656     relnodes=ActiveRecord::Base.connection.select_all(sql)
657     relnodes.each do |a|
658       removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
659     end
660   end
661
662   def deleteitemrelations(objid,type,uid,db_now) #:doc:
663     sql=<<-EOF
664   SELECT cr.id FROM current_relation_members crm,current_relations cr 
665    WHERE crm.member_id=#{objid} 
666      AND crm.member_type='#{type}' 
667      AND crm.id=cr.id 
668      AND cr.visible=1
669   EOF
670
671     relways=ActiveRecord::Base.connection.select_all(sql)
672     relways.each do |a|
673       removefromrelation(objid,type,a['id'],uid,db_now)
674     end
675   end
676
677   def removefromrelation(objid,type,relation,uid,db_now) #:doc:
678     rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
679
680     tagsql=<<-EOF
681   INSERT INTO relation_tags (id,k,v,version) 
682   SELECT id,k,v,#{rver} FROM current_relation_tags 
683    WHERE id=#{relation} 
684   EOF
685     ActiveRecord::Base.connection.insert(tagsql)
686
687     membersql=<<-EOF
688   INSERT INTO relation_members (id,member_type,member_id,member_role,version) 
689   SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members 
690    WHERE id=#{relation} 
691      AND (member_id!=#{objid} OR member_type!='#{type}')
692   EOF
693     ActiveRecord::Base.connection.insert(membersql)
694
695     ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
696     ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
697   end
698
699   def sqlescape(a) #:doc:
700     a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
701   end
702
703   def tag2array(a) #:doc:
704     tags={}
705     Tags.split(a) do |k, v|
706       tags[k.gsub(':','|')]=v
707     end
708     tags
709   end
710
711   def array2tag(a) #:doc:
712     tags = []
713     a.each do |k,v|
714       if v=='' then next end
715       if v[0,6]=='(type ' then next end
716       tags << [k.gsub('|',':'), v]
717     end
718     return Tags.join(tags)
719   end
720
721   def getuserid(token) #:doc:
722     if (token =~ /^(.+)\+(.+)$/) then
723       user = User.authenticate(:username => $1, :password => $2)
724     else
725       user = User.authenticate(:token => token)
726     end
727
728     return user ? user.id : nil;
729   end
730
731   # ====================================================================
732   # Co-ordinate conversion
733
734   def lat2coord(a,basey,masterscale) #:doc:
735     -(lat2y(a)-basey)*masterscale+250
736   end
737
738   def long2coord(a,baselong,masterscale) #:doc:
739     (a-baselong)*masterscale+350
740   end
741
742   def lat2y(a) #:doc:
743     180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
744   end
745
746   def coord2lat(a,masterscale,basey) #:doc:
747     y2lat((a-250)/-masterscale+basey)
748   end
749
750   def coord2long(a,masterscale,baselong) #:doc:
751     (a-350)/masterscale+baselong
752   end
753
754   def y2lat(a)
755     180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
756   end
757
758 end