1 # AMF Controller is a semi-standalone API for Flash clients, particularly Potlatch.
2 # All interaction between Potlatch (as a .SWF application) and the
3 # OSM database takes place using this controller. Messages are
4 # encoded in the Actionscript Message Format (AMF).
6 # See Also Potlatch::Potlatch and Potlatch::AMF
9 # editions Systeme D / Richard Fairhurst 2004-2008
11 # All in/out parameters are floats unless explicitly stated.
13 # to trap errors (getway_old,putway,putpoi,deleteway only):
14 # return(-1,"message") <-- just puts up a dialogue
15 # return(-2,"message") <-- also asks the user to e-mail me
17 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
18 class AmfController < ApplicationController
24 before_filter :check_write_availability
26 # Main AMF handler. Tha talk method takes in AMF, figures out what to do and dispatched to the appropriate private method
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=AMF.getint(req) # Read number of headers
39 headers.times do # Read each header
40 name=AMF.getstring(req) # |
41 req.getc # | skip boolean
42 value=AMF.getvalue(req) # |
43 header["name"]=value # |
46 bodies=AMF.getint(req) # Read number of bodies
47 bodies.times do # Read each body
48 message=AMF.getstring(req) # | get message name
49 index=AMF.getstring(req) # | get index in response sequence
50 bytes=AMF.getlong(req) # | get total size in bytes
51 args=AMF.getvalue(req) # | get response (probably an array)
54 when 'getpresets'; results[index]=AMF.putdata(index,getpresets)
55 when 'whichways'; results[index]=AMF.putdata(index,whichways(args))
56 when 'whichways_deleted'; results[index]=AMF.putdata(index,whichways_deleted(args))
57 when 'getway'; results[index]=AMF.putdata(index,getway(args))
58 when 'getway_old'; results[index]=AMF.putdata(index,getway_old(args))
59 when 'getway_history'; results[index]=AMF.putdata(index,getway_history(args))
60 when 'putway'; r=putway(args,renumberednodes)
62 results[index]=AMF.putdata(index,r)
63 when 'deleteway'; results[index]=AMF.putdata(index,deleteway(args))
64 when 'putpoi'; results[index]=AMF.putdata(index,putpoi(args))
65 when 'getpoi'; results[index]=AMF.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")
85 # Return presets (default tags and crap) to potlatch.
86 # Uses POTLATCH_PRESETS global, set up in OSM::Potlatch
88 return POTLATCH_PRESETS
92 # Find all the way ids and nodes (including tags and projected lat/lng) which aren't part of those ways in an are
94 # The argument is an array containing the following, in order:
95 # 0. minimum longitude
97 # 2. maximum longitude
99 # 4. baselong, 5. basey, 6. masterscale as above
100 def whichways(args) #:doc:
101 xmin = args[0].to_f-0.01
102 ymin = args[1].to_f-0.01
103 xmax = args[2].to_f+0.01
104 ymax = args[3].to_f+0.01
107 masterscale = args[6]
109 RAILS_DEFAULT_LOGGER.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
111 # find the way ids in an area
112 nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => "current_nodes.visible = 1", :include => :ways)
113 way_ids = nodes_in_area.collect { |node| node.way_ids }.flatten.uniq
115 # find the node ids in an area that aren't part of ways
116 nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
117 points = nodes_not_used_in_area.collect { |n| [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash] }
122 # ----- whichways_deleted
123 # return array of deleted ways in current bounding box
125 # does: finds all deleted ways with a deleted node in bounding box
126 # out: [0] array of way ids
127 def whichways_deleted(args) #:doc:
128 xmin = args[0].to_f-0.01
129 ymin = args[1].to_f-0.01
130 xmax = args[2].to_f+0.01
131 ymax = args[3].to_f+0.01
134 masterscale = args[6]
137 SELECT DISTINCT current_ways.id
138 FROM current_nodes,way_nodes,current_ways
139 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
140 AND way_nodes.node_id=current_nodes.id
141 AND way_nodes.id=current_ways.id
142 AND current_nodes.visible=0
143 AND current_ways.visible=0
145 waylist = ActiveRecord::Base.connection.select_all(sql)
146 ways = waylist.collect {|a| a['id'].to_i }
151 # Get a way with all of it's nodes and tags
152 # The input is an array with the following components, in order:
153 # 0. wayid - the ID of the way to get
154 # 1. baselong - origin of SWF map (longitude)
155 # 2. basey - origin of SWF map (latitude)
156 # 3. masterscale - SWF map scale
158 # The output is an array which contains all the nodes (with projected
159 # latitude and longitude) and tags for a way (and all the nodes tags).
160 # It also has the way's unprojected (WGS84) bbox.
162 # FIXME: The server really shouldn't be figuring out a ways bounding box and doing projection for potlatch
163 # FIXME: the argument splitting should be done in the 'talk' method, not here
164 def getway(args) #:doc:
165 wayid,baselong,basey,masterscale = args
168 RAILS_DEFAULT_LOGGER.info(" Message: getway, id=#{wayid}")
170 # Ideally we would do ":include => :nodes" here but if we do that
171 # then rails only seems to return the first copy of a node when a
172 # way includes a node more than once
173 way = Way.find(wayid)
179 way.nodes.each do |node|
180 projected_longitude = node.lon_potlatch(baselong,masterscale) # do projection for potlatch
181 projected_latitude = node.lat_potlatch(basey,masterscale)
183 tags_hash = node.tags_as_hash
185 points << [projected_longitude, projected_latitude, id, nil, tags_hash]
186 long_array << projected_longitude
187 lat_array << projected_latitude
190 [wayid,points,way.tags,long_array.min,long_array.max,lat_array.min,lat_array.max]
194 # returns old version of way
196 # [1] way version to get (or -1 for "last deleted version")
197 # [2] baselong, [3] basey, [4] masterscale
198 # does: gets old version of way and all constituent nodes
199 # for undelete, always uses the most recent version of each node
200 # (even if it's moved)
201 # for revert, uses the historic version of each node, but if that node is
202 # still visible and has been changed since, generates a new node id
203 # out: [0] 0 (code for success), [1] SWF object name,
204 # [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
205 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
207 def getway_old(args) #:doc:
208 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
209 # if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
211 wayid,version,baselong,basey,masterscale=args
213 version = version.to_i
215 xmax = ymax = -999999
219 version=getlastversion(wayid,version)
223 readwayquery_old(wayid,version,historic).each { |row|
224 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)]
225 xmin=[xmin,row['longitude'].to_f].min
226 xmax=[xmax,row['longitude'].to_f].max
227 ymin=[ymin,row['latitude' ].to_f].min
228 ymax=[ymax,row['latitude' ].to_f].max
231 # get tags from this version
233 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
234 attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
235 attributes['history']="Retrieved from v"+version.to_s
237 [0,wayid,points,attributes,xmin,xmax,ymin,ymax,version]
240 # ----- getway_history
241 # find history of a way
243 # does: finds history of a way
244 # out: [0] array of previous versions (where each is
245 # [0] version, [1] db timestamp (string),
246 # [2] visible 0 or 1,
247 # [3] username or 'anonymous' (string))
248 def getway_history(args) #:doc:
252 SELECT version,timestamp,visible,display_name,data_public
254 WHERE ways.id=#{wayid}
255 AND ways.user_id=users.id
257 ORDER BY version DESC
259 histlist=ActiveRecord::Base.connection.select_all(sql)
260 histlist.each { |row|
261 if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
262 history<<[row['version'],row['timestamp'],row['visible'],user]
268 # saves a way to the database
269 # in: [0] user token (string),
270 # [1] original way id (may be negative),
271 # [2] array of points (as getway/getway_old),
272 # [3] hash of way tags,
273 # [4] original way version (0 if not a reverted/undeleted way),
274 # [5] baselong, [6] basey, [7] masterscale
275 # does: saves way to the database
276 # all constituent nodes are created/updated as necessary
277 # (or deleted if they were in the old version and are otherwise unused)
278 # out: [0] 0 (code for success), [1] original way id (unchanged),
279 # [2] new way id, [3] hash of renumbered nodes (old id=>new id),
280 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
281 def putway(args,renumberednodes) #:doc:
282 RAILS_DEFAULT_LOGGER.info(" putway started")
283 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
284 uid=getuserid(usertoken)
285 if !uid then return -1,"You are not logged in, so the way could not be saved." end
287 RAILS_DEFAULT_LOGGER.info(" putway authenticated happily")
288 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
289 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
290 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
291 originalway=originalway.to_i
292 oldversion=oldversion.to_i
294 RAILS_DEFAULT_LOGGER.info(" Message: putway, id=#{originalway}")
296 # -- Check for null IDs or short ways
299 if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
302 if points.length<2 then return -2,"Server error - way is only #{points.length} points long." end
304 # -- 3. read original way into memory
306 xc={}; yc={}; tagc={}; vc={}
309 if oldversion==0 then r=readwayquery(way,false)
310 else r=readwayquery_old(way,oldversion,true) end
314 xc[id]=row['longitude'].to_f
315 yc[id]=row['latitude' ].to_f
317 vc[id]=row['visible'].to_i
320 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
322 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
325 # -- 4. get version by inserting new row into ways
327 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
329 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
336 points.each_index do |i|
337 xs=coord2long(points[i][0],masterscale,baselong)
338 ys=coord2lat(points[i][1],masterscale,basey)
339 xmin=[xs,xmin].min; xmax=[xs,xmax].max
340 ymin=[ys,ymin].min; ymax=[ys,ymax].max
341 node=points[i][2].to_i
342 tagstr=array2tag(points[i][4])
343 tagsql="'"+sqlescape(tagstr)+"'"
344 lat=(ys * 10000000).round
345 long=(xs * 10000000).round
346 tile=QuadTile.tile_for_point(ys, xs)
351 if renumberednodes[node.to_s].nil?
352 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})")
353 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})")
355 nodelist.push(newnode)
356 renumberednodes[node.to_s]=newnode.to_s
358 points[i][2]=renumberednodes[node.to_s].to_i
361 elsif xc.has_key?(node)
363 # old node from original way - update
364 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)
365 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})")
366 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}")
369 # old node, created in another way and now added to this way
373 # -- 6a. delete any nodes not in modified way
375 createuniquenodes(way,db_uqn,nodelist) # nodes which appear in this way but no other
378 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
379 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
380 FROM current_nodes AS cn,#{db_uqn}
383 ActiveRecord::Base.connection.insert(sql)
386 UPDATE current_nodes AS cn, #{db_uqn}
387 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
390 ActiveRecord::Base.connection.update(sql)
392 deleteuniquenoderelations(db_uqn,uid,db_now)
393 ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
395 # 6b. insert new version of route into way_nodes
401 if insertsql !='' then insertsql +=',' end
402 if currentsql!='' then currentsql+=',' end
403 insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
404 currentsql+="(#{way},#{p[2]},#{sequence})"
408 ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
409 ActiveRecord::Base.connection.insert( "INSERT INTO way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
410 ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id ) VALUES #{currentsql}");
412 # -- 7. insert new way tags
416 attributes.each do |k,v|
417 if v=='' or v.nil? then next end
418 if v[0,6]=='(type ' then next end
419 if insertsql !='' then insertsql +=',' end
420 if currentsql!='' then currentsql+=',' end
421 insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
422 currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
425 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
426 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
427 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
429 [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
433 # save POI to the database
434 # in: [0] user token (string),
435 # [1] original node id (may be negative),
436 # [2] projected longitude, [3] projected latitude,
437 # [4] hash of tags, [5] visible (0 to delete, 1 otherwise),
438 # [6] baselong, [7] basey, [8] masterscale
439 # does: saves POI node to the database
440 # refuses save if the node has since become part of a way
441 # out: [0] 0 (success), [1] original node id (unchanged),
443 def putpoi(args) #:doc:
444 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
445 uid=getuserid(usertoken)
446 if !uid then return -1,"You are not logged in, so the point could not be saved." end
448 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
449 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
454 # if deleting, check node hasn't become part of a way
455 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")
456 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
457 deleteitemrelations(id,'node',uid,db_now)
460 x=coord2long(x.to_f,masterscale,baselong)
461 y=coord2lat(y.to_f,masterscale,basey)
462 tagsql="'"+sqlescape(array2tag(tags))+"'"
463 lat=(y * 10000000).round
464 long=(x * 10000000).round
465 tile=QuadTile.tile_for_point(y, x)
468 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})");
469 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}");
472 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})");
473 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})");
479 # read POI from database
480 # (only called on revert: POIs are usually read by whichways)
481 # in: [0] node id, [1] baselong, [2] basey, [3] masterscale
483 # out: [0] id (unchanged), [1] projected long, [2] projected lat,
485 def getpoi(args) #:doc:
486 id,baselong,basey,masterscale = args
488 n = Node.find(id.to_i)
490 return [n.id, n.long_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash]
492 return [nil,nil,nil,'']
497 # delete way and constituent nodes from database
498 # in: [0] user token (string), [1] way id
499 # does: deletes way from db and any constituent nodes not used elsewhere
500 # also removes ways/nodes from any relations they're in
501 # out: [0] 0 (success), [1] way id (unchanged)
502 def deleteway(args) #:doc:
503 usertoken,way_id=args
504 RAILS_DEFAULT_LOGGER.info(" Message: deleteway, id=#{way_id}")
505 uid=getuserid(usertoken)
506 if !uid then return -1,"You are not logged in, so the way could not be deleted." end
508 user = User.find(uid)
510 way = Way.find(way_id)
512 way.delete_with_relations_and_nodes_and_history(user)
517 def readwayquery(id,insistonvisible) #:doc:
519 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible
520 FROM current_way_nodes,current_nodes
521 WHERE current_way_nodes.id=#{id}
522 AND current_way_nodes.node_id=current_nodes.id
524 if insistonvisible then sql+=" AND current_nodes.visible=1 " end
525 sql+=" ORDER BY sequence_id"
526 ActiveRecord::Base.connection.select_all(sql)
529 # Get the latest version id of a way
530 def getlastversion(id,version) #:doc:
531 old_way = OldWay.find(:first, :conditions => ['visible=1 AND id=?' , id], :order => 'version DESC')
535 def readwayquery_old(id,version,historic) #:doc:
536 # Node handling on undelete (historic=false):
537 # - always use the node specified, even if it's moved
539 # Node handling on revert (historic=true):
540 # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
541 # which means the SWF needs to allocate new ids
542 # - if it's an invisible node, we can reuse the old node id
544 # get node list from specified version of way,
545 # and the _current_ lat/long/tags of each node
547 row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
548 waytime=row['timestamp']
551 SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags
552 FROM way_nodes wn,current_nodes cn
553 WHERE wn.version=#{version}
558 rows=ActiveRecord::Base.connection.select_all(sql)
560 # if historic (full revert), get the old version of each node
561 # - if it's in another way now, generate a new id
562 # - if it's not in another way, use the old ID
564 rows.each_index do |i|
566 SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway
568 LEFT JOIN current_way_nodes cwn
570 WHERE n.id=#{rows[i]['id']}
571 AND n.timestamp<="#{waytime}"
573 ORDER BY n.timestamp DESC
576 row=ActiveRecord::Base.connection.select_one(sql)
578 nx=row['longitude'].to_f
579 ny=row['latitude'].to_f
580 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
581 rows[i]['longitude']=nx
582 rows[i]['latitude' ]=ny
583 rows[i]['tags' ]=row['tags']
590 def createuniquenodes(way,uqn_name,nodelist) #:doc:
591 # Find nodes which appear in this way but no others
593 CREATE TEMPORARY TABLE #{uqn_name}
595 FROM (SELECT DISTINCT node_id FROM current_way_nodes
597 LEFT JOIN current_way_nodes b
598 ON b.node_id=a.node_id
600 WHERE b.node_id IS NULL
602 unless nodelist.empty? then
603 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
605 ActiveRecord::Base.connection.execute(sql)
610 # ====================================================================
612 # deleteuniquenoderelations(uqn_name,uid,db_now)
613 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
615 def deleteuniquenoderelations(uqn_name,uid,db_now) #:doc:
617 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
618 WHERE crm.member_id=node_id
619 AND crm.member_type='node'
624 relnodes=ActiveRecord::Base.connection.select_all(sql)
626 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
630 def deleteitemrelations(objid,type,uid,db_now) #:doc:
632 SELECT cr.id FROM current_relation_members crm,current_relations cr
633 WHERE crm.member_id=#{objid}
634 AND crm.member_type='#{type}'
639 relways=ActiveRecord::Base.connection.select_all(sql)
641 removefromrelation(objid,type,a['id'],uid,db_now)
645 def removefromrelation(objid,type,relation,uid,db_now) #:doc:
646 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
649 INSERT INTO relation_tags (id,k,v,version)
650 SELECT id,k,v,#{rver} FROM current_relation_tags
653 ActiveRecord::Base.connection.insert(tagsql)
656 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
657 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
659 AND (member_id!=#{objid} OR member_type!='#{type}')
661 ActiveRecord::Base.connection.insert(membersql)
663 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
664 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
667 def sqlescape(a) #:doc:
668 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
671 def tag2array(a) #:doc:
673 Tags.split(a) do |k, v|
674 tags[k.gsub(':','|')]=v
679 def array2tag(a) #:doc:
682 if v=='' then next end
683 if v[0,6]=='(type ' then next end
684 tags << [k.gsub('|',':'), v]
686 return Tags.join(tags)
689 def getuserid(token) #:doc:
690 if (token =~ /^(.+)\+(.+)$/) then
691 user = User.authenticate(:username => $1, :password => $2)
693 user = User.authenticate(:token => token)
696 return user ? user.id : nil;
699 # ====================================================================
700 # Co-ordinate conversion
702 def lat2coord(a,basey,masterscale) #:doc:
703 -(lat2y(a)-basey)*masterscale
706 def long2coord(a,baselong,masterscale) #:doc:
707 (a-baselong)*masterscale
711 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
714 def coord2lat(a,masterscale,basey) #:doc:
715 y2lat(a/-masterscale+basey)
718 def coord2long(a,masterscale,baselong) #:doc:
719 a/masterscale+baselong
723 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)