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