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-2008
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
32 renumberednodes={} # Shared across repeated putways
37 headers=getint(req) # Read number of headers
39 headers.times do # Read each header
40 name=getstring(req) # |
41 req.getc # | skip boolean
42 value=getvalue(req) # |
43 header["name"]=value # |
46 bodies=getint(req) # Read number of bodies
47 bodies.times do # Read each body
48 message=getstring(req) # | get message name
49 index=getstring(req) # | get index in response sequence
50 bytes=getlong(req) # | get total size in bytes
51 args=getvalue(req) # | get response (probably an array)
54 when 'getpresets'; results[index]=putdata(index,getpresets)
55 when 'whichways'; results[index]=putdata(index,whichways(args))
56 when 'whichways_deleted'; results[index]=putdata(index,whichways_deleted(args))
57 when 'getway'; results[index]=putdata(index,getway(args))
58 when 'getway_old'; results[index]=putdata(index,getway_old(args))
59 when 'getway_history'; results[index]=putdata(index,getway_history(args))
60 when 'putway'; r=putway(args,renumberednodes)
62 results[index]=putdata(index,r)
63 when 'deleteway'; results[index]=putdata(index,deleteway(args))
64 when 'putpoi'; results[index]=putdata(index,putpoi(args))
65 when 'getpoi'; results[index]=putdata(index,getpoi(args))
72 RAILS_DEFAULT_LOGGER.info(" Response: start")
73 a,b=results.length.divmod(256)
74 render :content_type => "application/x-amf", :text => proc { |response, output|
75 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
80 RAILS_DEFAULT_LOGGER.info(" Response: end")
87 # ====================================================================
92 # does: reads tag preset menus, colours, and autocomplete config files
93 # out: [0] presets, [1] presetmenus, [2] presetnames,
94 # [3] colours, [4] casing, [5] areas, [6] autotags (all hashes)
97 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
101 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
102 presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
105 # StringIO.open(txt) do |file|
106 File.open("#{RAILS_ROOT}/config/potlatch/presets.txt") do |file|
107 file.each_line {|line|
109 if (t=~/(\w+)\/(\w+)/) then
112 presetmenus[presettype].push(presetcategory)
113 presetnames[presettype][presetcategory]=["(no preset)"]
114 elsif (t=~/^(.+):\s?(.+)$/) then
116 presetnames[presettype][presetcategory].push(pre)
118 kv.split(',').each {|a|
119 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
125 # Read colours/styling
126 colours={}; casing={}; areas={}
127 File.open("#{RAILS_ROOT}/config/potlatch/colours.txt") do |file|
128 file.each_line {|line|
130 if (t=~/(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/) then
132 if ($2!='-') then colours[tag]=$2.hex end
133 if ($3!='-') then casing[tag]=$3.hex end
134 if ($4!='-') then areas[tag]=$4.hex end
140 autotags={}; autotags['point']={}; autotags['way']={}; autotags['POI']={};
141 File.open("#{RAILS_ROOT}/config/potlatch/autocomplete.txt") do |file|
142 file.each_line {|line|
144 if (t=~/^(\w+)\/(\w+)\s+(.+)$/) then
145 tag=$1; type=$2; values=$3
146 if values=='-' then autotags[type][tag]=[]
147 else autotags[type][tag]=values.split(',').sort.reverse end
152 [presets,presetmenus,presetnames,colours,casing,areas,autotags]
156 # return array of ways in current bounding box
158 # in: [0] xmin, [1] ymin, [2] xmax, [3] ymax (bbox in degrees)
159 # [4] baselong (longitude of SWF map origin),
160 # [5] basey (projected latitude of SWF map origin),
161 # [6] masterscale (SWF map scale)
162 # does: finds all ways and POI nodes in bounding box
163 # at present, instead of using correct (=more complex) SQL to find
164 # corner-crossing ways, it simply enlarges the bounding box
165 # out: [0] array of way ids,
167 # (where each POI is an array containing:
168 # [0] id, [1] projected long, [2] projected lat, [3] hash of tags)
171 xmin = args[0].to_f-0.01
172 ymin = args[1].to_f-0.01
173 xmax = args[2].to_f+0.01
174 ymax = args[3].to_f+0.01
177 masterscale = args[6]
179 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
181 waylist = ActiveRecord::Base.connection.select_all("SELECT DISTINCT current_way_nodes.id AS wayid"+
182 " FROM current_way_nodes,current_nodes,current_ways "+
183 " WHERE current_nodes.id=current_way_nodes.node_id "+
184 " AND current_nodes.visible=1 "+
185 " AND current_ways.id=current_way_nodes.id "+
186 " AND current_ways.visible=1 "+
187 " AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
189 ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
191 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 "+
192 " FROM current_nodes "+
193 " LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id "+
194 " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
195 " AND cwn.id IS NULL "+
196 " AND current_nodes.visible=1")
198 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
203 # ----- whichways_deleted
204 # return array of deleted ways in current bounding box
207 # does: finds all deleted ways with a deleted node in bounding box
208 # out: [0] array of way ids
210 def whichways_deleted(args)
211 xmin = args[0].to_f-0.01
212 ymin = args[1].to_f-0.01
213 xmax = args[2].to_f+0.01
214 ymax = args[3].to_f+0.01
217 masterscale = args[6]
220 SELECT DISTINCT current_ways.id
221 FROM current_nodes,way_nodes,current_ways
222 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
223 AND way_nodes.node_id=current_nodes.id
224 AND way_nodes.id=current_ways.id
225 AND current_nodes.visible=0
226 AND current_ways.visible=0
228 waylist = ActiveRecord::Base.connection.select_all(sql)
229 ways = waylist.collect {|a| a['id'].to_i }
234 # in: [0] SWF object name, [1] way id, [2] baselong, [3] basey,
236 # does: gets way and all nodes
237 # out: [0] SWF object name (unchanged),
238 # [1] array of points
239 # (where each point is an array containing
240 # [0] projected long, [1] projected lat, [2] node id,
241 # [3] null, [4] hash of node tags),
242 # [2] xmin, [3] xmax, [4] ymin, [5] ymax (unprojected bbox)
245 objname,wayid,baselong,basey,masterscale=args
249 xmax = ymax = -999999
251 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
253 readwayquery(wayid,true).each {|row|
254 points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,nil,tag2array(row['tags'])]
255 xmin = [xmin,row['longitude'].to_f].min
256 xmax = [xmax,row['longitude'].to_f].max
257 ymin = [ymin,row['latitude'].to_f].min
258 ymax = [ymax,row['latitude'].to_f].max
262 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
263 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
265 [objname,points,attributes,xmin,xmax,ymin,ymax]
269 # returns old version of way
271 # in: [0] SWF object name, [1] way id,
272 # [2] way version to get (or -1 for "last deleted version")
273 # [3] baselong, [4] basey, [5] masterscale
274 # does: gets old version of way and all constituent nodes
275 # for undelete, always uses the most recent version of each node
276 # (even if it's moved)
277 # for revert, uses the historic version of each node, but if that node is
278 # still visible and has been changed since, generates a new node id
279 # out: [0] 0 (code for success), [1] SWF object name,
280 # [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
281 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
285 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
286 # if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
288 objname,wayid,version,baselong,basey,masterscale=args
290 version = version.to_i
292 xmax = ymax = -999999
296 version=getlastversion(wayid,version)
300 readwayquery_old(wayid,version,historic).each { |row|
301 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)]
302 xmin=[xmin,row['longitude'].to_f].min
303 xmax=[xmax,row['longitude'].to_f].max
304 ymin=[ymin,row['latitude' ].to_f].min
305 ymax=[ymax,row['latitude' ].to_f].max
308 # get tags from this version
310 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
311 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
312 attributes['history']="Retrieved from v"+version.to_s
314 [0,objname,points,attributes,xmin,xmax,ymin,ymax,version]
317 # ----- getway_history
318 # find history of a way
321 # does: finds history of a way
322 # out: [0] array of previous versions (where each is
323 # [0] version, [1] db timestamp, [2] visible 0 or 1,
324 # [3] username or 'anonymous')
326 def getway_history(wayid)
329 SELECT version,timestamp,visible,display_name,data_public
331 WHERE ways.id=#{wayid}
332 AND ways.user_id=users.id
334 ORDER BY version DESC
336 histlist=ActiveRecord::Base.connection.select_all(sql)
337 histlist.each { |row|
338 if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
339 history<<[row['version'],row['timestamp'],row['visible'],user]
345 # saves a way to the database
347 # in: [0] user token, [1] original way id (may be negative),
348 # [2] array of points (as getway/getway_old), [3] hash of way tags,
349 # [4] original way version (0 if not a reverted/undeleted way),
350 # [5] baselong, [6] basey, [7] masterscale
351 # does: saves way to the database
352 # all constituent nodes are created/updated as necessary
353 # (or deleted if they were in the old version and are otherwise unused)
354 # out: [0] 0 (code for success), [1] original way id (unchanged),
355 # [2] new way id, [3] hash of renumbered nodes (old id=>new id),
356 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
358 def putway(args,renumberednodes)
359 RAILS_DEFAULT_LOGGER.info(" putway started")
360 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
361 uid=getuserid(usertoken)
362 if !uid then return -1,"You are not logged in, so the way could not be saved." end
364 RAILS_DEFAULT_LOGGER.info(" putway authenticated happily")
365 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
366 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
367 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
368 originalway=originalway.to_i
369 oldversion=oldversion.to_i
371 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
373 # -- Temporary check for null IDs
376 if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
379 # -- 3. read original way into memory
381 xc={}; yc={}; tagc={}; vc={}
384 if oldversion==0 then r=readwayquery(way,false)
385 else r=readwayquery_old(way,oldversion,true) end
389 xc[id]=row['longitude'].to_f
390 yc[id]=row['latitude' ].to_f
392 vc[id]=row['visible'].to_i
395 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
397 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
400 # -- 4. get version by inserting new row into ways
402 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
404 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
411 points.each_index do |i|
412 xs=coord2long(points[i][0],masterscale,baselong)
413 ys=coord2lat(points[i][1],masterscale,basey)
414 xmin=[xs,xmin].min; xmax=[xs,xmax].max
415 ymin=[ys,ymin].min; ymax=[ys,ymax].max
416 node=points[i][2].to_i
417 tagstr=array2tag(points[i][4])
418 tagsql="'"+sqlescape(tagstr)+"'"
419 lat=(ys * 10000000).round
420 long=(xs * 10000000).round
421 tile=QuadTile.tile_for_point(ys, xs)
426 if renumberednodes[node.to_s].nil?
427 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})")
428 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})")
430 nodelist.push(newnode)
431 renumberednodes[node.to_s]=newnode.to_s
433 points[i][2]=renumberednodes[node.to_s].to_i
436 elsif xc.has_key?(node)
438 # old node from original way - update
439 if ((xs/0.0000001).round!=(xc[node]/0.0000001).round or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
440 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})")
441 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}")
444 # old node, created in another way and now added to this way
449 # -- 6a. delete any nodes not in modified way
451 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
454 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
455 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
456 FROM current_nodes AS cn,#{db_uqn}
459 ActiveRecord::Base.connection.insert(sql)
462 UPDATE current_nodes AS cn, #{db_uqn}
463 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
466 ActiveRecord::Base.connection.update(sql)
468 deleteuniquenoderelations(db_uqn,uid,db_now)
469 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
471 # 6b. insert new version of route into way_nodes
477 if insertsql !='' then insertsql +=',' end
478 if currentsql!='' then currentsql+=',' end
479 insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
480 currentsql+="(#{way},#{p[2]},#{sequence})"
484 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
485 ActiveRecord::Base.connection.insert( "INSERT INTO way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
486 ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id ) VALUES #{currentsql}");
488 # -- 7. insert new way tags
492 attributes.each do |k,v|
493 if v=='' or v.nil? then next end
494 if v[0,6]=='(type ' then next end
495 if insertsql !='' then insertsql +=',' end
496 if currentsql!='' then currentsql+=',' end
497 insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
498 currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
501 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
502 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
503 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
505 [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
509 # save POI to the database
511 # in: [0] user token, [1] original node id (may be negative),
512 # [2] projected longitude, [3] projected latitude, [4] hash of tags,
513 # [5] visible (0 to delete, 1 otherwise),
514 # [6] baselong, [7] basey, [8] masterscale
515 # does: saves POI node to the database
516 # refuses save if the node has since become part of a way
517 # out: [0] 0 (success), [1] original node id (unchanged), [2] new node id
520 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
521 uid=getuserid(usertoken)
522 if !uid then return -1,"You are not logged in, so the point could not be saved." end
524 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
525 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
530 # if deleting, check node hasn't become part of a way
531 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")
532 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
533 deleteitemrelations(id,'node',uid,db_now)
536 x=coord2long(x.to_f,masterscale,baselong)
537 y=coord2lat(y.to_f,masterscale,basey)
538 tagsql="'"+sqlescape(array2tag(tags))+"'"
539 lat=(y * 10000000).round
540 long=(x * 10000000).round
541 tile=QuadTile.tile_for_point(y, x)
544 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})");
545 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}");
548 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})");
549 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})");
555 # read POI from database
556 # (only called on revert: POIs are usually read by whichways)
558 # in: [0] node id, [1] baselong, [2] basey, [3] masterscale
560 # out: [0] id (unchanged), [1] projected long, [2] projected lat, [3] hash of tags
563 id,baselong,basey,masterscale=args; id=id.to_i
564 poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
565 "FROM current_nodes WHERE visible=1 AND id=#{id}")
566 if poi.nil? then return [nil,nil,nil,''] end
568 long2coord(poi['lng'].to_f,baselong,masterscale),
569 lat2coord(poi['lat'].to_f,basey,masterscale),
570 tag2array(poi['tags'])]
574 # delete way and constituent nodes from database
576 # in: [0] user token, [1] way id
577 # does: deletes way from db and any constituent nodes not used elsewhere
578 # also removes ways/nodes from any relations they're in
579 # out: [0] 0 (success), [1] way id (unchanged)
584 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
585 uid=getuserid(usertoken)
586 if !uid then return -1,"You are not logged in, so the way could not be deleted." end
589 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
590 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
591 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
593 # - delete any otherwise unused nodes
595 createuniquenodes(way,db_uqn,[])
597 # unless (preserve.empty?) then
598 # ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
602 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
603 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
604 FROM current_nodes AS cn,#{db_uqn}
607 ActiveRecord::Base.connection.insert(sql)
610 UPDATE current_nodes AS cn, #{db_uqn}
611 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
614 ActiveRecord::Base.connection.update(sql)
616 deleteuniquenoderelations(db_uqn,uid,db_now)
617 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
621 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
622 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
623 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
624 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
625 deleteitemrelations(way,'way',uid,db_now)
631 # ====================================================================
632 # Support functions for remote calls
634 def readwayquery(id,insistonvisible)
636 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible
637 FROM current_way_nodes,current_nodes
638 WHERE current_way_nodes.id=#{id}
639 AND current_way_nodes.node_id=current_nodes.id
641 if insistonvisible then sql+=" AND current_nodes.visible=1 " end
642 sql+=" ORDER BY sequence_id"
643 ActiveRecord::Base.connection.select_all(sql)
646 def getlastversion(id,version)
647 row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
651 def readwayquery_old(id,version,historic)
652 # Node handling on undelete (historic=false):
653 # - always use the node specified, even if it's moved
655 # Node handling on revert (historic=true):
656 # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
657 # which means the SWF needs to allocate new ids
658 # - if it's an invisible node, we can reuse the old node id
660 # get node list from specified version of way,
661 # and the _current_ lat/long/tags of each node
663 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
664 waytime=row['timestamp']
667 SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
668 FROM way_nodes wn,current_nodes cn
669 WHERE wn.version=#{version}
674 rows=ActiveRecord::Base.connection.select_all(sql)
676 # if historic (full revert), get the old version of each node
677 # - if it's in another way now, generate a new id
678 # - if it's not in another way, use the old ID
680 rows.each_index do |i|
682 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway
684 LEFT JOIN current_way_nodes cwn
686 WHERE n.id=#{rows[i]['id']}
687 AND n.timestamp<="#{waytime}"
689 ORDER BY n.timestamp DESC
692 row=ActiveRecord::Base.connection.select_one(sql)
694 nx=row['longitude'].to_f
695 ny=row['latitude'].to_f
696 if (row['currentway'] && (nx!=rows[i]['longitude'].to_f or ny!=rows[i]['latitude'].to_f or row['tags']!=rows[i]['tags'])) then rows[i]['id']=-1 end
697 rows[i]['longitude']=nx
698 rows[i]['latitude' ]=ny
699 rows[i]['tags' ]=row['tags']
706 def createuniquenodes(way,uqn_name,nodelist)
707 # Find nodes which appear in this way but no others
709 CREATE TEMPORARY TABLE #{uqn_name}
711 FROM (SELECT DISTINCT node_id FROM current_way_nodes
713 LEFT JOIN current_way_nodes b
714 ON b.node_id=a.node_id
716 WHERE b.node_id IS NULL
718 unless nodelist.empty? then
719 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
721 ActiveRecord::Base.connection.execute(sql)
726 # ====================================================================
728 # deleteuniquenoderelations(uqn_name,uid,db_now)
729 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
731 def deleteuniquenoderelations(uqn_name,uid,db_now)
733 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
734 WHERE crm.member_id=node_id
735 AND crm.member_type='node'
740 relnodes=ActiveRecord::Base.connection.select_all(sql)
742 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
746 def deleteitemrelations(objid,type,uid,db_now)
748 SELECT cr.id FROM current_relation_members crm,current_relations cr
749 WHERE crm.member_id=#{objid}
750 AND crm.member_type='#{type}'
755 relways=ActiveRecord::Base.connection.select_all(sql)
757 removefromrelation(objid,type,a['id'],uid,db_now)
761 def removefromrelation(objid,type,relation,uid,db_now)
762 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
765 INSERT INTO relation_tags (id,k,v,version)
766 SELECT id,k,v,#{rver} FROM current_relation_tags
769 ActiveRecord::Base.connection.insert(tagsql)
772 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
773 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
775 AND (member_id!=#{objid} OR member_type!='#{type}')
777 ActiveRecord::Base.connection.insert(membersql)
779 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
780 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
785 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
790 Tags.split(a) do |k, v|
791 tags[k.gsub(':','|')]=v
799 if v=='' then next end
800 if v[0,6]=='(type ' then next end
801 tags << [k.gsub('|',':'), v]
803 return Tags.join(tags)
807 if (token =~ /^(.+)\+(.+)$/) then
808 user = User.authenticate(:username => $1, :password => $2)
810 user = User.authenticate(:token => token)
813 return user ? user.id : nil;
818 # ====================================================================
819 # AMF read subroutines
821 # ----- getint return two-byte integer
822 # ----- getlong return four-byte long
823 # ----- getstring return string with two-byte length
824 # ----- getdouble return eight-byte double-precision float
825 # ----- getobject return object/hash
826 # ----- getarray return numeric array
833 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
837 len=s.getc*256+s.getc
842 a=s.read(8).unpack('G') # G big-endian, E little-endian
857 while (key=getstring(s))
858 if (key=='') then break end
861 s.getc # skip the 9 'end of object' value
865 # ----- getvalue parse and get value
869 when 0; return getdouble(s) # number
870 when 1; return s.getc # boolean
871 when 2; return getstring(s) # string
872 when 3; return getobject(s) # object/hash
873 when 5; return nil # null
874 when 6; return nil # undefined
875 when 8; s.read(4) # mixedArray
876 return getobject(s) # |
877 when 10;return getarray(s) # array
878 else; return nil # error
882 # ====================================================================
883 # AMF write subroutines
885 # ----- putdata envelope data into AMF writeable form
886 # ----- encodevalue pack variables as AMF
889 d =encodestring(index+"/onResult")
890 d+=encodestring("null")
898 a=10.chr+encodelong(n.length)
906 a+=encodestring(k)+encodevalue(v)
910 2.chr+encodestring(n)
911 when 'Bignum','Fixnum','Float'
912 0.chr+encodedouble(n)
916 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
920 # ----- encodestring encode string with two-byte length
921 # ----- encodedouble encode number as eight-byte double precision float
922 # ----- encodelong encode number as four-byte long
925 a,b=n.size.divmod(256)
937 # ====================================================================
938 # Co-ordinate conversion
940 def lat2coord(a,basey,masterscale)
941 -(lat2y(a)-basey)*masterscale+250
944 def long2coord(a,baselong,masterscale)
945 (a-baselong)*masterscale+350
949 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
952 def coord2lat(a,masterscale,basey)
953 y2lat((a-250)/-masterscale+basey)
956 def coord2long(a,masterscale,baselong)
957 (a-350)/masterscale+baselong
961 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)