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 # All in/out parameters are floats unless explicitly stated.
17 # Note that in getway/getway_old, SWF object name and way id are
18 #ĂŠidentical and one could probably be eliminated.
20 # to trap errors (getway_old,putway,putpoi,deleteway only):
21 # return(-1,"message") <-- just puts up a dialogue
22 # return(-2,"message") <-- also asks the user to e-mail me
24 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
26 # ====================================================================
29 # ---- talk process AMF request
32 req=StringIO.new(request.raw_post+0.chr) # Get POST data as request
33 # (cf http://www.ruby-forum.com/topic/122163)
34 req.read(2) # Skip version indicator and client ID
35 results={} # Results of each body
36 renumberednodes={} # Shared across repeated putways
41 headers=getint(req) # Read number of headers
43 headers.times do # Read each header
44 name=getstring(req) # |
45 req.getc # | skip boolean
46 value=getvalue(req) # |
47 header["name"]=value # |
50 bodies=getint(req) # Read number of bodies
51 bodies.times do # Read each body
52 message=getstring(req) # | get message name
53 index=getstring(req) # | get index in response sequence
54 bytes=getlong(req) # | get total size in bytes
55 args=getvalue(req) # | get response (probably an array)
58 when 'getpresets'; results[index]=putdata(index,getpresets)
59 when 'whichways'; results[index]=putdata(index,whichways(args))
60 when 'whichways_deleted'; results[index]=putdata(index,whichways_deleted(args))
61 when 'getway'; results[index]=putdata(index,getway(args))
62 when 'getway_old'; results[index]=putdata(index,getway_old(args))
63 when 'getway_history'; results[index]=putdata(index,getway_history(args))
64 when 'putway'; r=putway(args,renumberednodes)
66 results[index]=putdata(index,r)
67 when 'deleteway'; results[index]=putdata(index,deleteway(args))
68 when 'putpoi'; results[index]=putdata(index,putpoi(args))
69 when 'getpoi'; results[index]=putdata(index,getpoi(args))
76 RAILS_DEFAULT_LOGGER.info(" Response: start")
77 a,b=results.length.divmod(256)
78 render :content_type => "application/x-amf", :text => proc { |response, output|
79 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
84 RAILS_DEFAULT_LOGGER.info(" Response: end")
91 # ====================================================================
96 # does: reads tag preset menus, colours, and autocomplete config files
97 # out: [0] presets, [1] presetmenus, [2] presetnames,
98 # [3] colours, [4] casing, [5] areas, [6] autotags
102 RAILS_DEFAULT_LOGGER.info(" Message: getpresets")
106 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
107 presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
110 # StringIO.open(txt) do |file|
111 File.open("#{RAILS_ROOT}/config/potlatch/presets.txt") do |file|
112 file.each_line {|line|
114 if (t=~/(\w+)\/(\w+)/) then
117 presetmenus[presettype].push(presetcategory)
118 presetnames[presettype][presetcategory]=["(no preset)"]
119 elsif (t=~/^(.+):\s?(.+)$/) then
121 presetnames[presettype][presetcategory].push(pre)
123 kv.split(',').each {|a|
124 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
130 # Read colours/styling
131 colours={}; casing={}; areas={}
132 File.open("#{RAILS_ROOT}/config/potlatch/colours.txt") do |file|
133 file.each_line {|line|
135 if (t=~/(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/) then
137 if ($2!='-') then colours[tag]=$2.hex end
138 if ($3!='-') then casing[tag]=$3.hex end
139 if ($4!='-') then areas[tag]=$4.hex end
145 autotags={}; autotags['point']={}; autotags['way']={}; autotags['POI']={};
146 File.open("#{RAILS_ROOT}/config/potlatch/autocomplete.txt") do |file|
147 file.each_line {|line|
149 if (t=~/^(\w+)\/(\w+)\s+(.+)$/) then
150 tag=$1; type=$2; values=$3
151 if values=='-' then autotags[type][tag]=[]
152 else autotags[type][tag]=values.split(',').sort.reverse end
157 [presets,presetmenus,presetnames,colours,casing,areas,autotags]
161 # return array of ways in current bounding box
163 # in: [0] xmin, [1] ymin, [2] xmax, [3] ymax (bbox in degrees)
164 # [4] baselong (longitude of SWF map origin),
165 # [5] basey (projected latitude of SWF map origin),
166 # [6] masterscale (SWF map scale)
167 # does: finds all ways and POI nodes in bounding box
168 # at present, instead of using correct (=more complex) SQL to find
169 # corner-crossing ways, it simply enlarges the bounding box
170 # out: [0] array of way ids,
172 # (where each POI is an array containing:
173 # [0] id, [1] projected long, [2] projected lat, [3] hash of tags)
176 xmin = args[0].to_f-0.01
177 ymin = args[1].to_f-0.01
178 xmax = args[2].to_f+0.01
179 ymax = args[3].to_f+0.01
182 masterscale = args[6]
184 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
186 waylist = ActiveRecord::Base.connection.select_all("SELECT DISTINCT current_way_nodes.id AS wayid"+
187 " FROM current_way_nodes,current_nodes,current_ways "+
188 " WHERE current_nodes.id=current_way_nodes.node_id "+
189 " AND current_nodes.visible=1 "+
190 " AND current_ways.id=current_way_nodes.id "+
191 " AND current_ways.visible=1 "+
192 " AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
194 ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
196 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 "+
197 " FROM current_nodes "+
198 " LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id "+
199 " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
200 " AND cwn.id IS NULL "+
201 " AND current_nodes.visible=1")
203 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
208 # ----- whichways_deleted
209 # return array of deleted ways in current bounding box
212 # does: finds all deleted ways with a deleted node in bounding box
213 # out: [0] array of way ids
215 def whichways_deleted(args)
216 xmin = args[0].to_f-0.01
217 ymin = args[1].to_f-0.01
218 xmax = args[2].to_f+0.01
219 ymax = args[3].to_f+0.01
222 masterscale = args[6]
225 SELECT DISTINCT current_ways.id
226 FROM current_nodes,way_nodes,current_ways
227 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
228 AND way_nodes.node_id=current_nodes.id
229 AND way_nodes.id=current_ways.id
230 AND current_nodes.visible=0
231 AND current_ways.visible=0
233 waylist = ActiveRecord::Base.connection.select_all(sql)
234 ways = waylist.collect {|a| a['id'].to_i }
238 # Get a way with all of it's nodes and tags
239 # The input is an array with the following components, in order:
240 # 0. SWF object name (String?) - fuck knows
241 # 1. wayid (String?) - the ID of the way to get
242 # 2. baselong - fuck knows
243 # 3. basey - fuck knows
244 # 4. masterscale - fuck knows
246 # The output is an array which contains all the nodes (with projected latitude and longitude) and tags for a way (and all the nodes tags). It also has the way's unprojected (WGS84) bbox.
248 # FIXME: The server really shouldn't be figuring out a ways bounding box and doing projection for potlatch
249 # FIXME: the argument splitting should be done in the 'talk' method, not here
252 objname,wayid,baselong,basey,masterscale = args
255 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
257 way = Way.find_eager(wayid)
262 way.way_nodes.each do |way_node|
263 node = way_node.node # get the node record
264 projected_longitude = node.lon_potlatch(baselong,masterscale) # do projection for potlatch
265 projected_latitude = node.lat_potlatch(basey,masterscale)
266 id = node.id # node ide
267 tags_hash = node.tags_as_hash # hash of tags
269 points << [projected_longitude, projected_latitude, id, nil, tags_hash] # FIXME remove the nil in potlatch. performance matters y'know!
270 long_array << projected_longitude
271 lat_array << projected_latitude
274 [objname,points,way.tags,long_array.min,long_array.max,lat_array.min,lat_array.max]
278 # returns old version of way
280 # in: [0] SWF object name, [1] way id,
281 # [2] way version to get (or -1 for "last deleted version")
282 # [3] baselong, [4] basey, [5] masterscale
283 # does: gets old version of way and all constituent nodes
284 # for undelete, always uses the most recent version of each node
285 # (even if it's moved)
286 # for revert, uses the historic version of each node, but if that node is
287 # still visible and has been changed since, generates a new node id
288 # out: [0] 0 (code for success), [1] SWF object name,
289 # [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
290 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
294 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
295 # if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
297 objname,wayid,version,baselong,basey,masterscale=args
299 version = version.to_i
301 xmax = ymax = -999999
305 version=getlastversion(wayid,version)
309 readwayquery_old(wayid,version,historic).each { |row|
310 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)]
311 xmin=[xmin,row['longitude'].to_f].min
312 xmax=[xmax,row['longitude'].to_f].max
313 ymin=[ymin,row['latitude' ].to_f].min
314 ymax=[ymax,row['latitude' ].to_f].max
317 # get tags from this version
319 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
320 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
321 attributes['history']="Retrieved from v"+version.to_s
323 [0,objname,points,attributes,xmin,xmax,ymin,ymax,version]
326 # ----- getway_history
327 # find history of a way
330 # does: finds history of a way
331 # out: [0] array of previous versions (where each is
332 # [0] version, [1] db timestamp (string),
333 # [2] visible 0 or 1,
334 # [3] username or 'anonymous' (string))
336 def getway_history(args)
340 SELECT version,timestamp,visible,display_name,data_public
342 WHERE ways.id=#{wayid}
343 AND ways.user_id=users.id
345 ORDER BY version DESC
347 histlist=ActiveRecord::Base.connection.select_all(sql)
348 histlist.each { |row|
349 if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
350 history<<[row['version'],row['timestamp'],row['visible'],user]
356 # saves a way to the database
358 # in: [0] user token (string),
359 # [1] original way id (may be negative),
360 # [2] array of points (as getway/getway_old),
361 # [3] hash of way tags,
362 # [4] original way version (0 if not a reverted/undeleted way),
363 # [5] baselong, [6] basey, [7] masterscale
364 # does: saves way to the database
365 # all constituent nodes are created/updated as necessary
366 # (or deleted if they were in the old version and are otherwise unused)
367 # out: [0] 0 (code for success), [1] original way id (unchanged),
368 # [2] new way id, [3] hash of renumbered nodes (old id=>new id),
369 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
371 def putway(args,renumberednodes)
372 RAILS_DEFAULT_LOGGER.info(" putway started")
373 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
374 uid=getuserid(usertoken)
375 if !uid then return -1,"You are not logged in, so the way could not be saved." end
377 RAILS_DEFAULT_LOGGER.info(" putway authenticated happily")
378 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
379 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
380 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
381 originalway=originalway.to_i
382 oldversion=oldversion.to_i
384 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
386 # -- Temporary check for null IDs
389 if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
392 # -- 3. read original way into memory
394 xc={}; yc={}; tagc={}; vc={}
397 if oldversion==0 then r=readwayquery(way,false)
398 else r=readwayquery_old(way,oldversion,true) end
402 xc[id]=row['longitude'].to_f
403 yc[id]=row['latitude' ].to_f
405 vc[id]=row['visible'].to_i
408 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
410 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
413 # -- 4. get version by inserting new row into ways
415 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
417 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
424 points.each_index do |i|
425 xs=coord2long(points[i][0],masterscale,baselong)
426 ys=coord2lat(points[i][1],masterscale,basey)
427 xmin=[xs,xmin].min; xmax=[xs,xmax].max
428 ymin=[ys,ymin].min; ymax=[ys,ymax].max
429 node=points[i][2].to_i
430 tagstr=array2tag(points[i][4])
431 tagsql="'"+sqlescape(tagstr)+"'"
432 lat=(ys * 10000000).round
433 long=(xs * 10000000).round
434 tile=QuadTile.tile_for_point(ys, xs)
439 if renumberednodes[node.to_s].nil?
440 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})")
441 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})")
443 nodelist.push(newnode)
444 renumberednodes[node.to_s]=newnode.to_s
446 points[i][2]=renumberednodes[node.to_s].to_i
449 elsif xc.has_key?(node)
451 # old node from original way - update
452 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)
453 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})")
454 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}")
457 # old node, created in another way and now added to this way
462 # -- 6a. delete any nodes not in modified way
464 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
467 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
468 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
469 FROM current_nodes AS cn,#{db_uqn}
472 ActiveRecord::Base.connection.insert(sql)
475 UPDATE current_nodes AS cn, #{db_uqn}
476 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
479 ActiveRecord::Base.connection.update(sql)
481 deleteuniquenoderelations(db_uqn,uid,db_now)
482 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
484 # 6b. insert new version of route into way_nodes
490 if insertsql !='' then insertsql +=',' end
491 if currentsql!='' then currentsql+=',' end
492 insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
493 currentsql+="(#{way},#{p[2]},#{sequence})"
497 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
498 ActiveRecord::Base.connection.insert( "INSERT INTO way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
499 ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id ) VALUES #{currentsql}");
501 # -- 7. insert new way tags
505 attributes.each do |k,v|
506 if v=='' or v.nil? then next end
507 if v[0,6]=='(type ' then next end
508 if insertsql !='' then insertsql +=',' end
509 if currentsql!='' then currentsql+=',' end
510 insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
511 currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
514 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
515 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
516 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
518 [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
522 # save POI to the database
524 # in: [0] user token (string),
525 # [1] original node id (may be negative),
526 # [2] projected longitude, [3] projected latitude,
527 # [4] hash of tags, [5] visible (0 to delete, 1 otherwise),
528 # [6] baselong, [7] basey, [8] masterscale
529 # does: saves POI node to the database
530 # refuses save if the node has since become part of a way
531 # out: [0] 0 (success), [1] original node id (unchanged),
535 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
536 uid=getuserid(usertoken)
537 if !uid then return -1,"You are not logged in, so the point could not be saved." end
539 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
540 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
545 # if deleting, check node hasn't become part of a way
546 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")
547 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
548 deleteitemrelations(id,'node',uid,db_now)
551 x=coord2long(x.to_f,masterscale,baselong)
552 y=coord2lat(y.to_f,masterscale,basey)
553 tagsql="'"+sqlescape(array2tag(tags))+"'"
554 lat=(y * 10000000).round
555 long=(x * 10000000).round
556 tile=QuadTile.tile_for_point(y, x)
559 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})");
560 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}");
563 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})");
564 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})");
570 # read POI from database
571 # (only called on revert: POIs are usually read by whichways)
573 # in: [0] node id, [1] baselong, [2] basey, [3] masterscale
575 # out: [0] id (unchanged), [1] projected long, [2] projected lat,
579 id,baselong,basey,masterscale=args; id=id.to_i
580 poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
581 "FROM current_nodes WHERE visible=1 AND id=#{id}")
582 if poi.nil? then return [nil,nil,nil,''] end
584 long2coord(poi['lng'].to_f,baselong,masterscale),
585 lat2coord(poi['lat'].to_f,basey,masterscale),
586 tag2array(poi['tags'])]
590 # delete way and constituent nodes from database
592 # in: [0] user token (string), [1] way id
593 # does: deletes way from db and any constituent nodes not used elsewhere
594 # also removes ways/nodes from any relations they're in
595 # out: [0] 0 (success), [1] way id (unchanged)
600 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way}")
601 uid=getuserid(usertoken)
602 if !uid then return -1,"You are not logged in, so the way could not be deleted." end
605 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
606 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
607 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
609 # - delete any otherwise unused nodes
611 createuniquenodes(way,db_uqn,[])
613 # unless (preserve.empty?) then
614 # ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
618 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
619 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
620 FROM current_nodes AS cn,#{db_uqn}
623 ActiveRecord::Base.connection.insert(sql)
626 UPDATE current_nodes AS cn, #{db_uqn}
627 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
630 ActiveRecord::Base.connection.update(sql)
632 deleteuniquenoderelations(db_uqn,uid,db_now)
633 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
637 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
638 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
639 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
640 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
641 deleteitemrelations(way,'way',uid,db_now)
647 # ====================================================================
648 # Support functions for remote calls
650 def readwayquery(id,insistonvisible)
652 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible
653 FROM current_way_nodes,current_nodes
654 WHERE current_way_nodes.id=#{id}
655 AND current_way_nodes.node_id=current_nodes.id
657 if insistonvisible then sql+=" AND current_nodes.visible=1 " end
658 sql+=" ORDER BY sequence_id"
659 ActiveRecord::Base.connection.select_all(sql)
662 def getlastversion(id,version)
663 row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
667 def readwayquery_old(id,version,historic)
668 # Node handling on undelete (historic=false):
669 # - always use the node specified, even if it's moved
671 # Node handling on revert (historic=true):
672 # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
673 # which means the SWF needs to allocate new ids
674 # - if it's an invisible node, we can reuse the old node id
676 # get node list from specified version of way,
677 # and the _current_ lat/long/tags of each node
679 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
680 waytime=row['timestamp']
683 SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
684 FROM way_nodes wn,current_nodes cn
685 WHERE wn.version=#{version}
690 rows=ActiveRecord::Base.connection.select_all(sql)
692 # if historic (full revert), get the old version of each node
693 # - if it's in another way now, generate a new id
694 # - if it's not in another way, use the old ID
696 rows.each_index do |i|
698 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway
700 LEFT JOIN current_way_nodes cwn
702 WHERE n.id=#{rows[i]['id']}
703 AND n.timestamp<="#{waytime}"
705 ORDER BY n.timestamp DESC
708 row=ActiveRecord::Base.connection.select_one(sql)
710 nx=row['longitude'].to_f
711 ny=row['latitude'].to_f
712 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
713 rows[i]['longitude']=nx
714 rows[i]['latitude' ]=ny
715 rows[i]['tags' ]=row['tags']
722 def createuniquenodes(way,uqn_name,nodelist)
723 # Find nodes which appear in this way but no others
725 CREATE TEMPORARY TABLE #{uqn_name}
727 FROM (SELECT DISTINCT node_id FROM current_way_nodes
729 LEFT JOIN current_way_nodes b
730 ON b.node_id=a.node_id
732 WHERE b.node_id IS NULL
734 unless nodelist.empty? then
735 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
737 ActiveRecord::Base.connection.execute(sql)
742 # ====================================================================
744 # deleteuniquenoderelations(uqn_name,uid,db_now)
745 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
747 def deleteuniquenoderelations(uqn_name,uid,db_now)
749 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
750 WHERE crm.member_id=node_id
751 AND crm.member_type='node'
756 relnodes=ActiveRecord::Base.connection.select_all(sql)
758 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
762 def deleteitemrelations(objid,type,uid,db_now)
764 SELECT cr.id FROM current_relation_members crm,current_relations cr
765 WHERE crm.member_id=#{objid}
766 AND crm.member_type='#{type}'
771 relways=ActiveRecord::Base.connection.select_all(sql)
773 removefromrelation(objid,type,a['id'],uid,db_now)
777 def removefromrelation(objid,type,relation,uid,db_now)
778 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
781 INSERT INTO relation_tags (id,k,v,version)
782 SELECT id,k,v,#{rver} FROM current_relation_tags
785 ActiveRecord::Base.connection.insert(tagsql)
788 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
789 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
791 AND (member_id!=#{objid} OR member_type!='#{type}')
793 ActiveRecord::Base.connection.insert(membersql)
795 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
796 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
800 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
805 Tags.split(a) do |k, v|
806 tags[k.gsub(':','|')]=v
814 if v=='' then next end
815 if v[0,6]=='(type ' then next end
816 tags << [k.gsub('|',':'), v]
818 return Tags.join(tags)
822 if (token =~ /^(.+)\+(.+)$/) then
823 user = User.authenticate(:username => $1, :password => $2)
825 user = User.authenticate(:token => token)
828 return user ? user.id : nil;
833 # ====================================================================
834 # AMF read subroutines
836 # ----- getint return two-byte integer
837 # ----- getlong return four-byte long
838 # ----- getstring return string with two-byte length
839 # ----- getdouble return eight-byte double-precision float
840 # ----- getobject return object/hash
841 # ----- getarray return numeric array
848 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
852 len=s.getc*256+s.getc
857 a=s.read(8).unpack('G') # G big-endian, E little-endian
872 while (key=getstring(s))
873 if (key=='') then break end
876 s.getc # skip the 9 'end of object' value
880 # ----- getvalue parse and get value
884 when 0; return getdouble(s) # number
885 when 1; return s.getc # boolean
886 when 2; return getstring(s) # string
887 when 3; return getobject(s) # object/hash
888 when 5; return nil # null
889 when 6; return nil # undefined
890 when 8; s.read(4) # mixedArray
891 return getobject(s) # |
892 when 10;return getarray(s) # array
893 else; return nil # error
897 # ====================================================================
898 # AMF write subroutines
900 # ----- putdata envelope data into AMF writeable form
901 # ----- encodevalue pack variables as AMF
904 d =encodestring(index+"/onResult")
905 d+=encodestring("null")
913 a=10.chr+encodelong(n.length)
921 a+=encodestring(k)+encodevalue(v)
925 2.chr+encodestring(n)
926 when 'Bignum','Fixnum','Float'
927 0.chr+encodedouble(n)
931 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
935 # ----- encodestring encode string with two-byte length
936 # ----- encodedouble encode number as eight-byte double precision float
937 # ----- encodelong encode number as four-byte long
940 a,b=n.size.divmod(256)
952 # ====================================================================
953 # Co-ordinate conversion
955 def lat2coord(a,basey,masterscale)
956 -(lat2y(a)-basey)*masterscale+250
959 def long2coord(a,baselong,masterscale)
960 (a-baselong)*masterscale+350
964 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
967 def coord2lat(a,masterscale,basey)
968 y2lat((a-250)/-masterscale+basey)
971 def coord2long(a,masterscale,baselong)
972 (a-350)/masterscale+baselong
976 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)