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