1 class AmfController < ApplicationController
5 before_filter :check_write_availability
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).
13 # Public domain. Set your tab width to 4 to read this document. :)
14 # editions Systeme D / Richard Fairhurst 2004-2007
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
20 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
22 # ====================================================================
25 # ---- talk process AMF request
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
36 headers=getint(req) # Read number of headers
38 headers.times do # Read each header
39 name=getstring(req) # |
40 req.getc # | skip boolean
41 value=getvalue(req) # |
42 header["name"]=value # |
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)
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))
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
77 RAILS_DEFAULT_LOGGER.info(" Response: end")
83 # ====================================================================
87 # return presets,presetmenus and presetnames arrays
91 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
92 presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
96 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
98 # File.open("config/potlatch/presets.txt") do |file|
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....)
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)
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
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)
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)
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
146 lake: natural=water,landuse=
147 forest: landuse=forest,natural=
150 mini roundabout: highway=mini_roundabout
151 traffic lights: highway=traffic_signals
154 bridge: highway=bridge
157 cattle grid: highway=cattle_grid
163 lock gate: waterway=lock_gate
165 aqueduct: waterway=aqueduct
166 winding hole: waterway=turning_point
167 mooring: waterway=mooring
170 station: railway=station
171 viaduct: railway=viaduct
172 level crossing: railway=crossing
178 car park: amenity=parking
179 petrol station: amenity=fuel
182 bike park: amenity=bicycle_parking
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)
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=
204 StringIO.open(txt) do |file|
205 file.each_line {|line|
207 if (t=~/(\w+)\/(\w+)/) then
210 presetmenus[presettype].push(presetcategory)
211 presetnames[presettype][presetcategory]=["(no preset)"]
212 elsif (t=~/^(.+):\s?(.+)$/) then
214 presetnames[presettype][presetcategory].push(pre)
216 kv.split(',').each {|a|
217 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
222 [presets,presetmenus,presetnames]
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
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
237 masterscale = args[6]
239 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
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."))
249 ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
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")
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
263 # ----- whichways_deleted(left,bottom,right,top)
264 # return array of deleted ways in current bounding box
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
273 masterscale = args[6]
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
284 waylist = ActiveRecord::Base.connection.select_all(sql)
285 ways = waylist.collect {|a| a['id'].to_i }
289 # ----- getway (objectname, way, baselong, basey, masterscale)
290 # returns objectname, array of co-ordinates, attributes,
291 # xmin,xmax,ymin,ymax
294 objname,wayid,baselong,basey,masterscale=args
298 xmax = ymax = -999999
300 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
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
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'] }
314 [objname,points,attributes,xmin,xmax,ymin,ymax]
317 # ----- getway_old (objectname, way, version, baselong, basey, masterscale)
318 # returns old version of way
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
324 objname,wayid,version,baselong,basey,masterscale=args
326 version = version.to_i
328 xmax = ymax = -999999
332 version=getlastversion(wayid,version)
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
344 # get tags from this version
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
350 [0,objname,points,attributes,xmin,xmax,ymin,ymax,version]
353 # ----- getway_history (way)
354 # returns array of previous versions (version,timestamp,visible,user)
355 # should also show 'created_by'
357 def getway_history(wayid)
360 SELECT version,timestamp,visible,display_name,data_public
362 WHERE ways.id=#{wayid}
363 AND ways.user_id=users.id
364 ORDER BY version DESC
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]
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
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
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
392 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
394 # -- Temporary check for null IDs
397 if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
400 # -- 3. read original way into memory
402 xc={}; yc={}; tagc={}; vc={}
406 readwayquery(way).each { |row|
408 xc[id]=row['longitude'].to_f
409 yc[id]=row['latitude' ].to_f
414 readwayquery_old(way,oldversion,true).each { |row|
417 xc[id]=row['longitude'].to_f
418 yc[id]=row['latitude' ].to_f
420 vc[id]=row['visible'].to_i
424 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
426 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
429 # -- 4. get version by inserting new row into ways
431 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
433 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
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)
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})")
460 nodelist.push(newnode)
461 renumberednodes[node.to_s]=newnode.to_s
463 points[i][2]=renumberednodes[node.to_s].to_i
466 elsif xc.has_key?(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}")
474 # old node, created in another way and now added to this way
479 # -- 6a. delete any nodes not in modified way
481 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
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}
489 ActiveRecord::Base.connection.insert(sql)
492 UPDATE current_nodes AS cn, #{db_uqn}
493 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
496 ActiveRecord::Base.connection.update(sql)
498 deleteuniquenoderelations(db_uqn,uid,db_now)
499 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
501 # 6b. insert new version of route into way_nodes
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})"
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}");
518 # -- 7. insert new way tags
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)+"')"
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
535 [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
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
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
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()")
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)
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)
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}");
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})");
578 # ----- getpoi (id,baselong,basey,masterscale)
579 # returns id,x,y,tag array
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
587 long2coord(poi['lng'].to_f,baselong,masterscale),
588 lat2coord(poi['lat'].to_f,basey,masterscale),
589 tag2array(poi['tags'])]
592 # ----- deleteway (user token, way, nodes to keep)
593 # returns way ID only
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
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()")
607 # - delete any otherwise unused nodes
609 createuniquenodes(way,db_uqn,[])
611 # unless (preserve.empty?) then
612 # ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
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}
621 ActiveRecord::Base.connection.insert(sql)
624 UPDATE current_nodes AS cn, #{db_uqn}
625 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
628 ActiveRecord::Base.connection.update(sql)
630 deleteuniquenoderelations(db_uqn,uid,db_now)
631 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
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)
645 # ====================================================================
646 # Support functions for remote calls
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"
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")
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
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
671 # get node list from specified version of way,
672 # and the _current_ lat/long/tags of each node
674 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
675 waytime=row['timestamp']
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}
685 rows=ActiveRecord::Base.connection.select_all(sql)
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
690 rows.each_index do |i|
692 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
694 WHERE id=#{rows[i]['id']}
695 AND timestamp<="#{waytime}"
696 ORDER BY timestamp DESC
699 row=ActiveRecord::Base.connection.select_one(sql)
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
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!).
709 rows[i]['longitude']=nx
710 rows[i]['latitude' ]=ny
711 rows[i]['tags' ]=row['tags']
718 def createuniquenodes(way,uqn_name,nodelist)
719 # Find nodes which appear in this way but no others
721 CREATE TEMPORARY TABLE #{uqn_name}
723 FROM (SELECT DISTINCT node_id FROM current_way_nodes
725 LEFT JOIN current_way_nodes b
726 ON b.node_id=a.node_id
728 WHERE b.node_id IS NULL
730 unless nodelist.empty? then
731 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
733 ActiveRecord::Base.connection.execute(sql)
738 # ====================================================================
740 # deleteuniquenoderelations(uqn_name,uid,db_now)
741 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
743 def deleteuniquenoderelations(uqn_name,uid,db_now)
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'
752 relnodes=ActiveRecord::Base.connection.select_all(sql)
754 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
758 def deleteitemrelations(objid,type,uid,db_now)
760 SELECT cr.id FROM current_relation_members crm,current_relations cr
761 WHERE crm.member_id=#{objid}
762 AND crm.member_type='#{type}'
767 relways=ActiveRecord::Base.connection.select_all(sql)
769 removefromrelation(objid,type,a['id'],uid,db_now)
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)")
777 INSERT INTO relation_tags (id,k,v,version)
778 SELECT id,k,v,#{rver} FROM current_relation_tags
781 ActiveRecord::Base.connection.insert(tagsql)
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
787 AND (member_id!=#{objid} OR member_type!='#{type}')
789 ActiveRecord::Base.connection.insert(membersql)
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}")
797 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
802 Tags.split(a) do |k, v|
803 tags[k.gsub(':','|')]=v
811 if v=='' then next end
812 if v[0,6]=='(type ' then next end
813 tags << [k.gsub('|',':'), v]
815 return Tags.join(tags)
819 if (token =~ /^(.+)\+(.+)$/) then
820 user = User.authenticate(:username => $1, :password => $2)
822 user = User.authenticate(:token => token)
825 return user ? user.id : nil;
830 # ====================================================================
831 # AMF read subroutines
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
845 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
849 len=s.getc*256+s.getc
854 a=s.read(8).unpack('G') # G big-endian, E little-endian
869 while (key=getstring(s))
870 if (key=='') then break end
873 s.getc # skip the 9 'end of object' value
877 # ----- getvalue parse and get value
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
894 # ====================================================================
895 # AMF write subroutines
897 # ----- putdata envelope data into AMF writeable form
898 # ----- encodevalue pack variables as AMF
901 d =encodestring(index+"/onResult")
902 d+=encodestring("null")
910 a=10.chr+encodelong(n.length)
918 a+=encodestring(k)+encodevalue(v)
922 2.chr+encodestring(n)
923 when 'Bignum','Fixnum','Float'
924 0.chr+encodedouble(n)
928 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
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
937 a,b=n.size.divmod(256)
949 # ====================================================================
950 # Co-ordinate conversion
952 def lat2coord(a,basey,masterscale)
953 -(lat2y(a)-basey)*masterscale+250
956 def long2coord(a,baselong,masterscale)
957 (a-baselong)*masterscale+350
961 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
964 def coord2lat(a,masterscale,basey)
965 y2lat((a-250)/-masterscale+basey)
968 def coord2long(a,masterscale,baselong)
969 (a-350)/masterscale+baselong
973 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)