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