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