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