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