further refinement to revert
[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     presets={}
94     presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
95     presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
96     presettype=''
97     presetcategory=''
98
99     RAILS_DEFAULT_LOGGER.info("  Message: getpresets")
100
101     #           File.open("config/potlatch/presets.txt") do |file|
102
103     # Temporary patch to get around filepath problem
104     # To remove this patch and make the code nice again:
105     # 1. uncomment above line
106     # 2. fix the path in the above line
107     # 3. delete this here document, and the following line (StringIO....)
108
109     txt=<<-EOF
110 way/road
111 motorway: highway=motorway,ref=(type road number)
112 trunk road: highway=trunk,ref=(type road number),name=(type road name)
113 primary road: highway=primary,ref=(type road number),name=(type road name)
114 secondary road: highway=secondary,ref=(type road number),name=(type road name)
115 tertiary road: highway=tertiary,ref=,name=(type road name)
116 residential road: highway=residential,ref=,name=(type road name)
117 unclassified road: highway=unclassified,ref=,name=(type road name)
118
119 way/footway
120 footpath: highway=footway,foot=yes
121 bridleway: highway=bridleway,foot=yes
122 byway: highway=unsurfaced,foot=yes
123 permissive path: highway=footway,foot=permissive
124
125 way/cycleway
126 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
127 cycle track: highway=cycleway,cycleway=track,ncn_ref=
128 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
129 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
130
131 way/waterway
132 canal: waterway=canal,name=(type name here)
133 navigable river: waterway=river,boat=yes,name=(type name here)
134 navigable drain: waterway=drain,boat=yes,name=(type name here)
135 derelict canal: waterway=derelict_canal,name=(type name here)
136 unnavigable river: waterway=river,boat=no,name=(type name here)
137 unnavigable drain: waterway=drain,boat=no,name=(type name here)
138 stream: waterway=stream,boat=no,name=(type name here)
139
140 way/railway
141 railway: railway=rail
142 tramway: railway=tram
143 light railway: railway=light_rail
144 preserved railway: railway=preserved
145 disused railway tracks: railway=disused
146 course of old railway: railway=abandoned
147
148 way/natural
149 lake: natural=water,landuse=
150 forest: landuse=forest,natural=
151
152 point/road
153 mini roundabout: highway=mini_roundabout
154 traffic lights: highway=traffic_signals
155
156 point/footway
157 bridge: highway=bridge
158 gate: highway=gate
159 stile: highway=stile
160 cattle grid: highway=cattle_grid
161
162 point/cycleway
163 gate: highway=gate
164
165 point/waterway
166 lock gate: waterway=lock_gate
167 weir: waterway=weir
168 aqueduct: waterway=aqueduct
169 winding hole: waterway=turning_point
170 mooring: waterway=mooring
171
172 point/railway
173 station: railway=station
174 viaduct: railway=viaduct
175 level crossing: railway=crossing
176
177 point/natural
178 peak: natural=peak
179
180 POI/road
181 car park: amenity=parking
182 petrol station: amenity=fuel
183
184 POI/cycleway
185 bike park: amenity=bicycle_parking
186
187 POI/place
188 city: place=city,name=(type name here),is_in=(type region or county)
189 town: place=town,name=(type name here),is_in=(type region or county)
190 suburb: place=suburb,name=(type name here),is_in=(type region or county)
191 village: place=village,name=(type name here),is_in=(type region or county)
192 hamlet: place=hamlet,name=(type name here),is_in=(type region or county)
193
194 POI/tourism
195 attraction: tourism=attraction,amenity=,religion=,denomination=
196 church: tourism=,amenity=place_of_worship,name=(type name here),religion=christian,denomination=(type denomination here)
197 hotel: tourism=hotel,amenity=,religion=,denomination=
198 other religious: tourism=,amenity=place_of_worship,name=(type name here),religion=(type religion),denomination=
199 post box: amenity=post_box,tourism=,name=,religion=,denomination=
200 post office: amenity=post_office,tourism=,name=,religion=,denomination=
201 pub: tourism=,amenity=pub,name=(type name here),religion=,denomination=
202
203 POI/natural
204 peak: natural=peak
205 EOF
206
207     StringIO.open(txt) do |file|
208       file.each_line {|line|
209         t=line.chomp
210         if (t=~/(\w+)\/(\w+)/) then
211           presettype=$1
212           presetcategory=$2
213           presetmenus[presettype].push(presetcategory)
214           presetnames[presettype][presetcategory]=["(no preset)"]
215         elsif (t=~/^(.+):\s?(.+)$/) then
216           pre=$1; kv=$2
217           presetnames[presettype][presetcategory].push(pre)
218           presets[pre]={}
219           kv.split(',').each {|a|
220             if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
221           }
222         end
223       }
224     end
225     [presets,presetmenus,presetnames]
226   end
227
228   # ----- whichways(left,bottom,right,top)
229   #               return array of ways in current bounding box
230   #               at present, instead of using correct (=more complex) SQL to find
231   #               corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
232
233   def whichways(args)
234     xmin = args[0].to_f-0.01
235     ymin = args[1].to_f-0.01
236     xmax = args[2].to_f+0.01
237     ymax = args[3].to_f+0.01
238     baselong    = args[4]
239     basey       = args[5]
240     masterscale = args[6]
241
242     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
243
244     waylist = ActiveRecord::Base.connection.select_all("SELECT DISTINCT current_way_nodes.id AS wayid"+
245        "  FROM current_way_nodes,current_nodes,current_ways "+
246        " WHERE current_nodes.id=current_way_nodes.node_id "+
247        "   AND current_nodes.visible=1 "+
248        "   AND current_ways.id=current_way_nodes.id "+
249        "   AND current_ways.visible=1 "+
250        "   AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
251
252     ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
253
254     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 "+
255        "  FROM current_nodes "+
256        "  LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id "+
257        " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
258        "   AND cwn.id IS NULL "+
259        "   AND current_nodes.visible=1")
260
261     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
262
263     [ways,points]
264   end
265
266   # ----- whichways_deleted(left,bottom,right,top)
267   #               return array of deleted ways in current bounding box
268   
269   def whichways_deleted(args)
270     xmin = args[0].to_f-0.01
271     ymin = args[1].to_f-0.01
272     xmax = args[2].to_f+0.01
273     ymax = args[3].to_f+0.01
274     baselong    = args[4]
275     basey       = args[5]
276     masterscale = args[6]
277
278         sql=<<-EOF
279                  SELECT DISTINCT current_ways.id 
280                    FROM current_nodes,way_nodes,current_ways 
281                   WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")} 
282                         AND way_nodes.node_id=current_nodes.id 
283                         AND way_nodes.id=current_ways.id 
284                         AND current_nodes.visible=0 
285                         AND current_ways.visible=0 
286         EOF
287     waylist = ActiveRecord::Base.connection.select_all(sql)
288     ways = waylist.collect {|a| a['id'].to_i }
289         [ways]
290   end
291   
292   # ----- getway (objectname, way, baselong, basey, masterscale)
293   #               returns objectname, array of co-ordinates, attributes,
294   #                               xmin,xmax,ymin,ymax
295
296   def getway(args)
297     objname,wayid,baselong,basey,masterscale=args
298     wayid = wayid.to_i
299     points = []
300     xmin = ymin =  999999
301     xmax = ymax = -999999
302
303     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
304
305     readwayquery(wayid).each {|row|
306       points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,nil,tag2array(row['tags'])]
307       xmin = [xmin,row['longitude'].to_f].min
308       xmax = [xmax,row['longitude'].to_f].max
309       ymin = [ymin,row['latitude'].to_f].min
310       ymax = [ymax,row['latitude'].to_f].max
311     }
312
313     attributes={}
314     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
315     attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
316
317     [objname,points,attributes,xmin,xmax,ymin,ymax]
318   end
319   
320   # -----       getway_old (objectname, way, version, baselong, basey, masterscale)
321   #                     returns old version of way
322
323   def getway_old(args)
324     RAILS_DEFAULT_LOGGER.info("  Message: getway_old (server is #{SERVER_URL})")
325         if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
326         
327     objname,wayid,version,baselong,basey,masterscale=args
328     wayid = wayid.to_i
329     version = version.to_i
330     xmin = ymin =  999999
331     xmax = ymax = -999999
332         points=[]
333         if version<0
334           historic=false
335           version=getlastversion(wayid,version)
336         else
337           historic=true
338         end
339         readwayquery_old(wayid,version,historic).each { |row|
340       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)]
341       xmin=[xmin,row['longitude'].to_f].min
342       xmax=[xmax,row['longitude'].to_f].max
343       ymin=[ymin,row['latitude' ].to_f].min
344       ymax=[ymax,row['latitude' ].to_f].max
345         }
346
347         # get tags from this version
348     attributes={}
349     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
350     attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
351         attributes['history']="Retrieved from v"+version.to_s
352
353     [0,objname,points,attributes,xmin,xmax,ymin,ymax,version]
354   end
355
356   # -----       getway_history (way)
357   #                     returns array of previous versions (version,timestamp,visible,user)
358   #                     should also show 'created_by'
359
360   def getway_history(wayid)
361         history=[]
362         sql=<<-EOF
363         SELECT version,timestamp,visible,display_name,data_public
364           FROM ways,users
365          WHERE ways.id=#{wayid}
366            AND ways.user_id=users.id
367            AND ways.visible=1
368          ORDER BY version DESC
369         EOF
370         histlist=ActiveRecord::Base.connection.select_all(sql)
371         histlist.each { |row|
372                 if row['data_public'] then user=row['display_name'] else user='anonymous' end
373                 history<<[row['version'],row['timestamp'],row['visible'],user]
374         }
375         [history]
376   end
377
378   # -----       putway (user token, way, array of co-ordinates, array of attributes,
379   #                                     baselong, basey, masterscale)
380   #                     returns current way ID, new way ID, hash of renumbered nodes,
381   #                                     xmin,xmax,ymin,ymax
382
383   def putway(args,renumberednodes)
384     RAILS_DEFAULT_LOGGER.info("  putway started")
385     usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
386     uid=getuserid(usertoken)
387     if !uid then return -1,"You are not logged in, so the way could not be saved." end
388
389     RAILS_DEFAULT_LOGGER.info("  putway authenticated happily")
390     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
391     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
392     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
393     originalway=originalway.to_i
394         oldversion=oldversion.to_i
395         
396     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
397
398         # -- Temporary check for null IDs
399         
400         points.each do |a|
401           if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
402         end
403
404     # -- 3.     read original way into memory
405
406     xc={}; yc={}; tagc={}; vc={}
407     if originalway>0
408       way=originalway
409           if oldversion==0
410             readwayquery(way).each { |row|
411                   id=row['id'].to_i
412                   xc[id]=row['longitude'].to_f
413                   yc[id]=row['latitude' ].to_f
414                   tagc[id]=row['tags']
415                   vc[id]=1
416                 }
417           else
418             readwayquery_old(way,oldversion,true).each { |row|
419                   id=row['id'].to_i
420                   if (id>0) then
421                         xc[id]=row['longitude'].to_f
422                         yc[id]=row['latitude' ].to_f
423                         tagc[id]=row['tags']
424                         vc[id]=row['visible'].to_i
425                   end
426                 }
427           end
428       ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
429     else
430       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
431     end
432
433     # -- 4.     get version by inserting new row into ways
434
435     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
436
437     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
438
439     xmin=ymin= 999999
440     xmax=ymax=-999999
441     insertsql=''
442         nodelist=[]
443
444     points.each_index do |i|
445       xs=coord2long(points[i][0],masterscale,baselong)
446       ys=coord2lat(points[i][1],masterscale,basey)
447       xmin=[xs,xmin].min; xmax=[xs,xmax].max
448       ymin=[ys,ymin].min; ymax=[ys,ymax].max
449       node=points[i][2].to_i
450           tagstr=array2tag(points[i][4])
451       tagsql="'"+sqlescape(tagstr)+"'"
452       lat=(ys * 10000000).round
453       long=(xs * 10000000).round
454       tile=QuadTile.tile_for_point(ys, xs)
455
456       # compare node
457       if node<0
458         # new node - create
459                 if renumberednodes[node.to_s].nil?
460           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})")
461                   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})")
462           points[i][2]=newnode
463           nodelist.push(newnode)
464           renumberednodes[node.to_s]=newnode.to_s
465                 else
466           points[i][2]=renumberednodes[node.to_s].to_i
467                 end
468
469       elsif xc.has_key?(node)
470                 nodelist.push(node)
471         # old node from original way - update
472         if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
473           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})")
474           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}")
475         end
476       else
477         # old node, created in another way and now added to this way
478       end
479     end
480
481
482         # -- 6a. delete any nodes not in modified way
483
484     createuniquenodes(way,db_uqn,nodelist)      # nodes which appear in this way but no other
485
486     sql=<<-EOF
487         INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)  
488         SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
489           FROM current_nodes AS cn,#{db_uqn}
490          WHERE cn.id=node_id
491     EOF
492     ActiveRecord::Base.connection.insert(sql)
493
494     sql=<<-EOF
495       UPDATE current_nodes AS cn, #{db_uqn}
496          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
497        WHERE cn.id=node_id
498     EOF
499     ActiveRecord::Base.connection.update(sql)
500
501         deleteuniquenoderelations(db_uqn,uid,db_now)
502     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
503
504         #       6b. insert new version of route into way_nodes
505
506     insertsql =''
507     currentsql=''
508     sequence  =1
509     points.each do |p|
510       if insertsql !='' then insertsql +=',' end
511       if currentsql!='' then currentsql+=',' end
512       insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
513       currentsql+="(#{way},#{p[2]},#{sequence})"
514       sequence  +=1
515     end
516
517     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
518     ActiveRecord::Base.connection.insert( "INSERT INTO         way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
519     ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id        ) VALUES #{currentsql}");
520
521     # -- 7. insert new way tags
522
523     insertsql =''
524     currentsql=''
525     attributes.each do |k,v|
526       if v=='' or v.nil? then next end
527       if v[0,6]=='(type ' then next end
528       if insertsql !='' then insertsql +=',' end
529       if currentsql!='' then currentsql+=',' end
530       insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
531       currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
532     end
533
534     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
535     if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
536     if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
537
538     [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
539   end
540
541   # -----       putpoi (user token, id, x,y,tag array,visible,baselong,basey,masterscale)
542   #                     returns current id, new id
543   #                     if new: add new row to current_nodes and nodes
544   #                     if old: add new row to nodes, update current_nodes
545
546   def putpoi(args)
547     usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
548     uid=getuserid(usertoken)
549     if !uid then return -1,"You are not logged in, so the point could not be saved." end
550
551     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
552     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
553
554     id=id.to_i
555     visible=visible.to_i
556         if visible==0 then
557                 # if deleting, check node hasn't become part of a way 
558                 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")
559                 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
560                 deleteitemrelations(id,'node',uid,db_now)
561         end
562
563     x=coord2long(x.to_f,masterscale,baselong)
564     y=coord2lat(y.to_f,masterscale,basey)
565     tagsql="'"+sqlescape(array2tag(tags))+"'"
566     lat=(y * 10000000).round
567     long=(x * 10000000).round
568     tile=QuadTile.tile_for_point(y, x)
569         
570     if (id>0) then
571         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})");
572         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}");
573         newid=id
574     else
575         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})");
576               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})");
577     end
578     [0,id,newid]
579   end
580
581   # -----       getpoi (id,baselong,basey,masterscale)
582   #                     returns id,x,y,tag array
583   
584   def getpoi(args)
585         id,baselong,basey,masterscale=args; id=id.to_i
586         poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
587                 "FROM current_nodes WHERE visible=1 AND id=#{id}")
588         if poi.nil? then return [nil,nil,nil,''] end
589         [id,
590          long2coord(poi['lng'].to_f,baselong,masterscale),
591          lat2coord(poi['lat'].to_f,basey,masterscale),
592          tag2array(poi['tags'])]
593   end
594
595   # -----       deleteway (user token, way, nodes to keep)
596   #                     returns way ID only
597
598   def deleteway(args)
599     usertoken,way=args
600
601     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way}")
602     uid=getuserid(usertoken)
603     if !uid then return -1,"You are not logged in, so the way could not be deleted." end
604
605     way=way.to_i
606     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
607     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
608     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
609
610     # - delete any otherwise unused nodes
611   
612     createuniquenodes(way,db_uqn,[])
613
614 #       unless (preserve.empty?) then
615 #               ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
616 #       end
617
618     sql=<<-EOF
619         INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
620         SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
621           FROM current_nodes AS cn,#{db_uqn}
622          WHERE cn.id=node_id
623     EOF
624     ActiveRecord::Base.connection.insert(sql)
625
626     sql=<<-EOF
627       UPDATE current_nodes AS cn, #{db_uqn}
628          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
629        WHERE cn.id=node_id
630     EOF
631     ActiveRecord::Base.connection.update(sql)
632
633         deleteuniquenoderelations(db_uqn,uid,db_now)
634     ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
635
636     # - delete way
637         
638     ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
639     ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
640     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
641     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
642         deleteitemrelations(way,'way',uid,db_now)
643     [0,way]
644 end
645
646
647
648 # ====================================================================
649 # Support functions for remote calls
650
651 def readwayquery(id)
652   ActiveRecord::Base.connection.select_all "SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags "+
653       "    FROM current_way_nodes,current_nodes "+
654       "   WHERE current_way_nodes.id=#{id} "+
655       "     AND current_way_nodes.node_id=current_nodes.id "+
656       "     AND current_nodes.visible=1 "+
657       "   ORDER BY sequence_id"
658 end
659
660 def getlastversion(id,version)
661   row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
662   row['version']
663 end
664
665 def readwayquery_old(id,version,historic)
666   # Node handling on undelete (historic=false):
667   # - always use the node specified, even if it's moved
668   
669   # Node handling on revert (historic=true):
670   # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
671   #   which means the SWF needs to allocate new ids
672   # - if it's an invisible node, we can reuse the old node id
673
674   # get node list from specified version of way,
675   # and the _current_ lat/long/tags of each node
676
677   row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
678   waytime=row['timestamp']
679
680   sql=<<-EOF
681         SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags 
682           FROM way_nodes wn,current_nodes cn 
683          WHERE wn.version=#{version} 
684            AND wn.id=#{id} 
685            AND wn.node_id=cn.id 
686          ORDER BY sequence_id
687   EOF
688   rows=ActiveRecord::Base.connection.select_all(sql)
689
690   # if historic (full revert), get the old version of each node
691   # - if it's in another way now, generate a new id
692   # - if it's not in another way, use the old ID
693   if historic then
694         rows.each_index do |i|
695           sql=<<-EOF
696           SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway 
697             FROM nodes n
698    LEFT JOIN current_way_nodes cwn
699                   ON cwn.node_id=n.id
700            WHERE n.id=#{rows[i]['id']} 
701              AND n.timestamp<="#{waytime}" 
702                  AND cwn.id!=#{id} 
703            ORDER BY n.timestamp DESC 
704            LIMIT 1
705           EOF
706           row=ActiveRecord::Base.connection.select_one(sql)
707           unless row.nil? then
708             nx=row['longitude'].to_f
709             ny=row['latitude'].to_f
710             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
711                 rows[i]['longitude']=nx
712                 rows[i]['latitude' ]=ny
713                 rows[i]['tags'     ]=row['tags']
714           end
715     end
716   end
717   rows
718 end
719
720 def createuniquenodes(way,uqn_name,nodelist)
721         # Find nodes which appear in this way but no others
722         sql=<<-EOF
723         CREATE TEMPORARY TABLE #{uqn_name}
724                                         SELECT a.node_id
725                                           FROM (SELECT DISTINCT node_id FROM current_way_nodes
726                                                         WHERE id=#{way}) a
727                                  LEFT JOIN current_way_nodes b
728                                                 ON b.node_id=a.node_id
729                                            AND b.id!=#{way}
730                                          WHERE b.node_id IS NULL
731         EOF
732         unless nodelist.empty? then
733           sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
734         end
735         ActiveRecord::Base.connection.execute(sql)
736 end
737
738
739
740 # ====================================================================
741 # Relations handling
742 # deleteuniquenoderelations(uqn_name,uid,db_now)
743 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
744
745 def deleteuniquenoderelations(uqn_name,uid,db_now)
746         sql=<<-EOF
747         SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr 
748          WHERE crm.member_id=node_id 
749            AND crm.member_type='node' 
750            AND crm.id=cr.id 
751            AND cr.visible=1
752         EOF
753
754         relnodes=ActiveRecord::Base.connection.select_all(sql)
755         relnodes.each do |a|
756                 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
757         end
758 end
759
760 def deleteitemrelations(objid,type,uid,db_now)
761         sql=<<-EOF
762         SELECT cr.id FROM current_relation_members crm,current_relations cr 
763          WHERE crm.member_id=#{objid} 
764            AND crm.member_type='#{type}' 
765            AND crm.id=cr.id 
766            AND cr.visible=1
767         EOF
768         
769         relways=ActiveRecord::Base.connection.select_all(sql)
770         relways.each do |a|
771                 removefromrelation(objid,type,a['id'],uid,db_now)
772         end
773 end
774
775 def removefromrelation(objid,type,relation,uid,db_now)
776         rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
777
778         tagsql=<<-EOF
779         INSERT INTO relation_tags (id,k,v,version) 
780         SELECT id,k,v,#{rver} FROM current_relation_tags 
781          WHERE id=#{relation} 
782         EOF
783         ActiveRecord::Base.connection.insert(tagsql)
784
785         membersql=<<-EOF
786         INSERT INTO relation_members (id,member_type,member_id,member_role,version) 
787         SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members 
788          WHERE id=#{relation} 
789            AND (member_id!=#{objid} OR member_type!='#{type}')
790         EOF
791         ActiveRecord::Base.connection.insert(membersql)
792         
793         ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
794         ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
795 end
796
797
798 def sqlescape(a)
799   a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
800 end
801
802 def tag2array(a)
803   tags={}
804   Tags.split(a) do |k, v|
805     tags[k.gsub(':','|')]=v
806   end
807   tags
808 end
809
810 def array2tag(a)
811   tags = []
812   a.each do |k,v|
813     if v=='' then next end
814     if v[0,6]=='(type ' then next end
815     tags << [k.gsub('|',':'), v]
816   end
817   return Tags.join(tags)
818 end
819
820 def getuserid(token)
821   if (token =~ /^(.+)\+(.+)$/) then
822     user = User.authenticate(:username => $1, :password => $2)
823   else
824     user = User.authenticate(:token => token)
825   end
826
827   return user ? user.id : nil;
828 end
829
830
831
832 # ====================================================================
833 # AMF read subroutines
834
835 # ----- getint          return two-byte integer
836 # ----- getlong         return four-byte long
837 # ----- getstring       return string with two-byte length
838 # ----- getdouble       return eight-byte double-precision float
839 # ----- getobject       return object/hash
840 # ----- getarray        return numeric array
841
842 def getint(s)
843   s.getc*256+s.getc
844 end
845
846 def getlong(s)
847   ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
848 end
849
850 def getstring(s)
851   len=s.getc*256+s.getc
852   s.read(len)
853 end
854
855 def getdouble(s)
856   a=s.read(8).unpack('G')                       # G big-endian, E little-endian
857   a[0]
858 end
859
860 def getarray(s)
861   len=getlong(s)
862   arr=[]
863   for i in (0..len-1)
864     arr[i]=getvalue(s)
865   end
866   arr
867 end
868
869 def getobject(s)
870   arr={}
871   while (key=getstring(s))
872     if (key=='') then break end
873     arr[key]=getvalue(s)
874   end
875   s.getc                # skip the 9 'end of object' value
876   arr
877 end
878
879 # ----- getvalue        parse and get value
880
881 def getvalue(s)
882   case s.getc
883         when 0; return getdouble(s)                     # number
884         when 1; return s.getc                           # boolean
885         when 2; return getstring(s)                     # string
886         when 3; return getobject(s)                     # object/hash
887         when 5; return nil                                      # null
888         when 6; return nil                                      # undefined
889         when 8; s.read(4)                                       # mixedArray
890                         return getobject(s)                     #  |
891         when 10;return getarray(s)                      # array
892         else;   return nil                                      # error
893   end
894 end
895
896 # ====================================================================
897 # AMF write subroutines
898
899 # ----- putdata         envelope data into AMF writeable form
900 # ----- encodevalue     pack variables as AMF
901
902 def putdata(index,n)
903   d =encodestring(index+"/onResult")
904   d+=encodestring("null")
905   d+=[-1].pack("N")
906   d+=encodevalue(n)
907 end
908
909 def encodevalue(n)
910   case n.class.to_s
911   when 'Array'
912     a=10.chr+encodelong(n.length)
913     n.each do |b|
914       a+=encodevalue(b)
915     end
916     a
917   when 'Hash'
918     a=3.chr
919     n.each do |k,v|
920       a+=encodestring(k)+encodevalue(v)
921     end
922     a+0.chr+0.chr+9.chr
923   when 'String'
924     2.chr+encodestring(n)
925   when 'Bignum','Fixnum','Float'
926     0.chr+encodedouble(n)
927   when 'NilClass'
928     5.chr
929   else
930     RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
931   end
932 end
933
934 # ----- encodestring    encode string with two-byte length
935 # ----- encodedouble    encode number as eight-byte double precision float
936 # ----- encodelong              encode number as four-byte long
937
938 def encodestring(n)
939   a,b=n.size.divmod(256)
940   a.chr+b.chr+n
941 end
942
943 def encodedouble(n)
944   [n].pack('G')
945 end
946
947 def encodelong(n)
948   [n].pack('N')
949 end
950
951 # ====================================================================
952 # Co-ordinate conversion
953
954 def lat2coord(a,basey,masterscale)
955   -(lat2y(a)-basey)*masterscale+250
956 end
957
958 def long2coord(a,baselong,masterscale)
959   (a-baselong)*masterscale+350
960 end
961
962 def lat2y(a)
963   180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
964 end
965
966 def coord2lat(a,masterscale,basey)
967   y2lat((a-250)/-masterscale+basey)
968 end
969
970 def coord2long(a,masterscale,baselong)
971   (a-350)/masterscale+baselong
972 end
973
974 def y2lat(a)
975   180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
976 end
977
978 end