]> git.openstreetmap.org Git - rails.git/blob - app/controllers/amf_controller.rb
359b45326b99137b89bfaaba944959b15a45d503
[rails.git] / app / controllers / amf_controller.rb
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).
5 #
6 # See Also Potlatch::Potlatch and Potlatch::AMF
7 #
8 # Public domain.
9 # editions Systeme D / Richard Fairhurst 2004-2008
10 #
11 # All in/out parameters are floats unless explicitly stated.
12
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
16 # to log:
17 #   RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
18 class AmfController < ApplicationController
19   require 'stringio'
20
21   include Potlatch
22
23   session :off
24   before_filter :check_write_availability
25
26   # Main AMF handler. Tha talk method takes in AMF, figures out what to do and dispatched to the appropriate private method
27   def talk
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
33     renumberedways={}                                                   # Shared across repeated putways
34
35     # -------------
36     # Parse request
37
38     headers=AMF.getint(req)                                     # Read number of headers
39
40     headers.times do                                # Read each header
41       name=AMF.getstring(req)                           #  |
42       req.getc                                  #  | skip boolean
43       value=AMF.getvalue(req)                           #  |
44       header["name"]=value                              #  |
45     end
46
47     bodies=AMF.getint(req)                                      # Read number of bodies
48     bodies.times do                                     # Read each body
49       message=AMF.getstring(req)                        #  | get message name
50       index=AMF.getstring(req)                          #  | get index in response sequence
51       bytes=AMF.getlong(req)                            #  | get total size in bytes
52       args=AMF.getvalue(req)                            #  | get response (probably an array)
53
54       case message
55       when 'getpresets';                results[index]=AMF.putdata(index,getpresets)
56       when 'whichways';                 results[index]=AMF.putdata(index,whichways(args))
57       when 'whichways_deleted'; results[index]=AMF.putdata(index,whichways_deleted(args))
58       when 'getway';                    results[index]=AMF.putdata(index,getway(args))
59       when 'getrelation';               results[index]=AMF.putdata(index,getrelation(args))
60       when 'getway_old';                results[index]=AMF.putdata(index,getway_old(args))
61       when 'getway_history';    results[index]=AMF.putdata(index,getway_history(args))
62       when 'putway';                    r=putway(args,renumberednodes)
63                                                                 renumberednodes=r[3]
64                                                                 if r[1] != r[2]
65                                                                         renumberedways[r[1]] = r[2]
66                                                                 end
67                                                                 results[index]=AMF.putdata(index,r)
68       when 'putrelation';               results[index]=AMF.putdata(index,putrelation(args, renumberednodes, renumberedways))
69       when 'deleteway';                 results[index]=AMF.putdata(index,deleteway(args))
70       when 'putpoi';                    results[index]=AMF.putdata(index,putpoi(args))
71       when 'getpoi';                    results[index]=AMF.putdata(index,getpoi(args))
72       end
73     end
74
75     # ------------------
76     # Write out response
77
78     RAILS_DEFAULT_LOGGER.info("  Response: start")
79     a,b=results.length.divmod(256)
80     render :content_type => "application/x-amf", :text => proc { |response, output| 
81       output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
82       results.each do |k,v|
83         output.write(v)
84       end
85     }
86     RAILS_DEFAULT_LOGGER.info("  Response: end")
87   end
88
89   private
90
91   # Return presets (default tags and crap) to potlatch.
92   # Uses POTLATCH_PRESETS global, set up in OSM::Potlatch
93   def getpresets #:doc:
94     return POTLATCH_PRESETS
95   end
96
97   # ----- whichways
98   # Find all the way ids and nodes (including tags and projected lat/lng) which aren't part of those ways in an are
99   # 
100   # The argument is an array containing the following, in order:
101   # 0. minimum longitude
102   # 1. minimum latitude
103   # 2. maximum longitude
104   # 3. maximum latitude
105   # 4. baselong, 5. basey, 6. masterscale as above
106   def whichways(args) #:doc:
107     xmin = args[0].to_f-0.01
108     ymin = args[1].to_f-0.01
109     xmax = args[2].to_f+0.01
110     ymax = args[3].to_f+0.01
111     baselong    = args[4]
112     basey       = args[5]
113     masterscale = args[6]
114
115     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
116
117     # find the way ids in an area
118     nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => "current_nodes.visible = 1", :include => :ways)
119     way_ids = nodes_in_area.collect { |node| node.way_ids }.flatten.uniq
120
121     # find the node ids in an area that aren't part of ways
122     nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
123     points = nodes_not_used_in_area.collect { |n| [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash] }
124
125     # find the relations used by those nodes and ways
126     relation_ids = (Relation.find_for_nodes_and_ways(nodes_in_area.collect {|n| n.id}, way_ids)).collect {|n| n.id}.uniq
127
128     [way_ids,points,relation_ids]
129   end
130
131   # ----- whichways_deleted
132   #               return array of deleted ways in current bounding box
133   #               in:   as whichways
134   #               does: finds all deleted ways with a deleted node in bounding box
135   #               out:  [0] array of way ids
136   def whichways_deleted(args) #:doc:
137     xmin = args[0].to_f-0.01
138     ymin = args[1].to_f-0.01
139     xmax = args[2].to_f+0.01
140     ymax = args[3].to_f+0.01
141     baselong    = args[4]
142     basey       = args[5]
143     masterscale = args[6]
144
145     sql=<<-EOF
146      SELECT DISTINCT current_ways.id 
147        FROM current_nodes,way_nodes,current_ways 
148       WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")} 
149       AND way_nodes.node_id=current_nodes.id 
150       AND way_nodes.id=current_ways.id 
151       AND current_nodes.visible=0 
152       AND current_ways.visible=0 
153   EOF
154     waylist = ActiveRecord::Base.connection.select_all(sql)
155     ways = waylist.collect {|a| a['id'].to_i }
156     [ways]
157   end
158
159   # ----- getway
160   # Get a way with all of it's nodes and tags
161   # The input is an array with the following components, in order:
162   # 0. wayid - the ID of the way to get
163   # 1. baselong - origin of SWF map (longitude)
164   # 2. basey - origin of SWF map (latitude)
165   # 3. masterscale - SWF map scale
166   #
167   # The output is an array which contains all the nodes (with projected 
168   # latitude and longitude) and tags for a way (and all the nodes tags). 
169   # It also has the way's unprojected (WGS84) bbox.
170   #
171   # FIXME: The server really shouldn't be figuring out a ways bounding box and doing projection for potlatch
172   # FIXME: the argument splitting should be done in the 'talk' method, not here
173   def getway(args) #:doc:
174     wayid,baselong,basey,masterscale = args
175     wayid = wayid.to_i
176
177     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
178
179     # Ideally we would do ":include => :nodes" here but if we do that
180     # then rails only seems to return the first copy of a node when a
181     # way includes a node more than once
182     way = Way.find(wayid)
183
184     long_array = []
185     lat_array = []
186     points = []
187
188     way.nodes.each do |node|
189       projected_longitude = node.lon_potlatch(baselong,masterscale) # do projection for potlatch
190       projected_latitude = node.lat_potlatch(basey,masterscale)
191       id = node.id
192       tags_hash = node.tags_as_hash
193
194       points << [projected_longitude, projected_latitude, id, nil, tags_hash]
195       long_array << projected_longitude
196       lat_array << projected_latitude
197     end
198
199     [wayid,points,way.tags,long_array.min,long_array.max,lat_array.min,lat_array.max]
200   end
201
202   # ----- getway_old
203   #               returns old version of way
204   #               in:   [0] way id,
205   #                             [1] way version to get (or -1 for "last deleted version")
206   #                             [2] baselong, [3] basey, [4] masterscale
207   #               does: gets old version of way and all constituent nodes
208   #                             for undelete, always uses the most recent version of each node
209   #                               (even if it's moved)
210   #                             for revert, uses the historic version of each node, but if that node is
211   #                               still visible and has been changed since, generates a new node id
212   #               out:  [0] 0 (code for success), [1] SWF object name,
213   #                             [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
214   #                             [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
215   #                             [8] way version
216   def getway_old(args) #:doc:
217     RAILS_DEFAULT_LOGGER.info("  Message: getway_old (server is #{SERVER_URL})")
218     #   if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
219
220     wayid,version,baselong,basey,masterscale=args
221     wayid = wayid.to_i
222     version = version.to_i
223     xmin = ymin =  999999
224     xmax = ymax = -999999
225     points=[]
226     if version<0
227       historic=false
228       version=getlastversion(wayid,version)
229     else
230       historic=true
231     end
232     readwayquery_old(wayid,version,historic).each { |row|
233       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)]
234       xmin=[xmin,row['longitude'].to_f].min
235       xmax=[xmax,row['longitude'].to_f].max
236       ymin=[ymin,row['latitude' ].to_f].min
237       ymax=[ymax,row['latitude' ].to_f].max
238     }
239
240     # get tags from this version
241     attributes={}
242     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
243     attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
244     attributes['history']="Retrieved from v"+version.to_s
245
246     [0,wayid,points,attributes,xmin,xmax,ymin,ymax,version]
247   end
248
249   # ----- getway_history
250   #               find history of a way
251   #               in:   [0] way id
252   #               does: finds history of a way
253   #               out:  [0] array of previous versions (where each is
254   #                                     [0] version, [1] db timestamp (string),
255   #                                     [2] visible 0 or 1,
256   #                                     [3] username or 'anonymous' (string))
257   def getway_history(args) #:doc:
258     wayid=args[0]
259     history=[]
260     sql=<<-EOF
261   SELECT version,timestamp,visible,display_name,data_public
262     FROM ways,users
263    WHERE ways.id=#{wayid}
264      AND ways.user_id=users.id
265      AND ways.visible=1
266    ORDER BY version DESC
267   EOF
268     histlist=ActiveRecord::Base.connection.select_all(sql)
269     histlist.each { |row|
270       if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
271       history<<[row['version'],row['timestamp'],row['visible'],user]
272     }
273     [history]
274   end
275
276   # ----- getrelation
277   # Get a relation with all of it's tags, and member IDs
278   # The input is an array with the following components, in order:
279   # 0. relid - the ID of the relation to get
280   #
281   # The output is an array which contains:
282   # [0] relation id, [1] hash of tags, [2] list of members
283   def getrelation(args) #:doc:
284     relid = args[0]
285     relid = relid.to_i
286
287     RAILS_DEFAULT_LOGGER.info("  Message: getrel, id=#{relid}")
288
289     rel = Relation.find(relid)
290
291     [relid,rel.tags,rel.members]#nodes,ways]
292   end
293
294   # ----- getrelation
295   #               save relation to the database
296   #               in:   [0] user token (string),
297   #                             [1] original relation id (may be negative),
298   #                             [2] hash of tags, [3] list of members,
299   #                             [4] visible
300   #               out:  [0] 0 (success), [1] original relation id (unchanged),
301   #                             [2] new relation id
302   def putrelation(args, renumberednodes, renumberedways) #:doc:
303     usertoken,relid,tags,members,visible=args
304     uid=getuserid(usertoken)
305     if !uid then return -1,"You are not logged in, so the point could not be saved." end
306
307     relid = relid.to_i
308         visible = visible.to_i
309
310         # create a new relation, or find the existing one
311     if relid <= 0
312       rel = Relation.new
313     else
314       rel = Relation.find(relid)
315     end
316
317     # check the members are all positive, and correctly type
318     typedmembers = []
319     members.each do |m|
320       mid = m[1].to_i
321       if mid < 0
322         mid = renumberednodes[mid] if m[0] == 'node'
323         mid = renumberedways[mid] if m[0] == 'way'
324         if mid < 0
325           return -2, "Negative ID unresolved"
326         end
327       end
328       typedmembers << [m[0], mid, m[2]]
329     end
330
331         # assign new contents
332         rel.members = typedmembers
333         rel.tags = tags
334         rel.visible = visible
335         rel.user_id = uid
336
337     # check it then save it
338     # BUG: the following is commented out because it always fails on my
339     #  install. I think it's a Rails bug.
340
341     #if !rel.preconditions_ok?
342     #  return -2, "Relation preconditions failed"
343     #else
344       rel.save_with_history!
345     #end
346
347     [0,relid,rel.id]
348   end
349
350   # ----- putway
351   #               saves a way to the database
352   #               in:   [0] user token (string),
353   #                             [1] original way id (may be negative), 
354   #                             [2] array of points (as getway/getway_old),
355   #                             [3] hash of way tags,
356   #                             [4] original way version (0 if not a reverted/undeleted way),
357   #                             [5] baselong, [6] basey, [7] masterscale
358   #               does: saves way to the database
359   #                             all constituent nodes are created/updated as necessary
360   #                             (or deleted if they were in the old version and are otherwise unused)
361   #               out:  [0] 0 (code for success), [1] original way id (unchanged),
362   #                             [2] new way id, [3] hash of renumbered nodes (old id=>new id),
363   #                             [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
364   def putway(args,renumberednodes) #:doc:
365     RAILS_DEFAULT_LOGGER.info("  putway started")
366     usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
367     uid=getuserid(usertoken)
368     if !uid then return -1,"You are not logged in, so the way could not be saved." end
369
370     RAILS_DEFAULT_LOGGER.info("  putway authenticated happily")
371     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
372     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
373     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
374     originalway=originalway.to_i
375     oldversion=oldversion.to_i
376
377     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
378
379     # -- Check for null IDs, short ways or lats=90
380
381     points.each do |a|
382       if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
383       if coord2lat(a[1],masterscale,basey)==90 then return -2,"Server error - node with lat -90 found in way #{originalway}." end
384     end
385     
386     if points.length<2 then return -2,"Server error - way is only #{points.length} points long." end
387
388     # -- 3.     read original way into memory
389
390     xc={}; yc={}; tagc={}; vc={}
391     if originalway>0
392       way=originalway
393       if oldversion==0 then r=readwayquery(way,false)
394       else r=readwayquery_old(way,oldversion,true) end
395       r.each { |row|
396         id=row['id'].to_i
397         if (id>0) then
398           xc[id]=row['longitude'].to_f
399           yc[id]=row['latitude' ].to_f
400           tagc[id]=row['tags']
401           vc[id]=row['visible'].to_i
402         end
403       }
404       ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
405     else
406       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
407     end
408
409     # -- 4.     get version by inserting new row into ways
410
411     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
412
413     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
414
415     xmin=ymin= 999999
416     xmax=ymax=-999999
417     insertsql=''
418     nodelist=[]
419
420     points.each_index do |i|
421       xs=coord2long(points[i][0],masterscale,baselong)
422       ys=coord2lat(points[i][1],masterscale,basey)
423       xmin=[xs,xmin].min; xmax=[xs,xmax].max
424       ymin=[ys,ymin].min; ymax=[ys,ymax].max
425       node=points[i][2].to_i
426       tagstr=array2tag(points[i][4])
427       tagsql="'"+sqlescape(tagstr)+"'"
428       lat=(ys * 10000000).round
429       long=(xs * 10000000).round
430       tile=QuadTile.tile_for_point(ys, xs)
431
432       # compare node
433       if node<0
434         # new node - create
435         if renumberednodes[node.to_s].nil?
436           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})")
437           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})")
438           points[i][2]=newnode
439           nodelist.push(newnode)
440           renumberednodes[node.to_s]=newnode.to_s
441         else
442           points[i][2]=renumberednodes[node.to_s].to_i
443         end
444
445       elsif xc.has_key?(node)
446         nodelist.push(node)
447         # old node from original way - update
448         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)
449           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})")
450           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}")
451         end
452       else
453         # old node, created in another way and now added to this way
454       end
455     end
456
457     # -- 6a. delete any nodes not in modified way
458
459     createuniquenodes(way,db_uqn,nodelist)      # nodes which appear in this way but no other
460
461     sql=<<-EOF
462   INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)  
463   SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
464     FROM current_nodes AS cn,#{db_uqn}
465    WHERE cn.id=node_id
466     EOF
467     ActiveRecord::Base.connection.insert(sql)
468
469     sql=<<-EOF
470       UPDATE current_nodes AS cn, #{db_uqn}
471          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
472        WHERE cn.id=node_id
473     EOF
474     ActiveRecord::Base.connection.update(sql)
475
476     deleteuniquenoderelations(db_uqn,uid,db_now)
477     ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
478
479     #   6b. insert new version of route into way_nodes
480
481     insertsql =''
482     currentsql=''
483     sequence  =1
484     points.each do |p|
485       if insertsql !='' then insertsql +=',' end
486       if currentsql!='' then currentsql+=',' end
487       insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
488       currentsql+="(#{way},#{p[2]},#{sequence})"
489       sequence  +=1
490     end
491
492     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
493     ActiveRecord::Base.connection.insert( "INSERT INTO         way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
494     ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id        ) VALUES #{currentsql}");
495
496     # -- 7. insert new way tags
497
498     insertsql =''
499     currentsql=''
500     attributes.each do |k,v|
501       if v=='' or v.nil? then next end
502       if v[0,6]=='(type ' then next end
503       if insertsql !='' then insertsql +=',' end
504       if currentsql!='' then currentsql+=',' end
505       insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
506       currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
507     end
508
509     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
510     if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
511     if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
512
513     [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
514   end
515
516   # ----- putpoi
517   #               save POI to the database
518   #               in:   [0] user token (string),
519   #                             [1] original node id (may be negative),
520   #                             [2] projected longitude, [3] projected latitude,
521   #                             [4] hash of tags, [5] visible (0 to delete, 1 otherwise), 
522   #                             [6] baselong, [7] basey, [8] masterscale
523   #               does: saves POI node to the database
524   #                             refuses save if the node has since become part of a way
525   #               out:  [0] 0 (success), [1] original node id (unchanged),
526   #                             [2] new node id
527   def putpoi(args) #:doc:
528     usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
529     uid=getuserid(usertoken)
530     if !uid then return -1,"You are not logged in, so the point could not be saved." end
531
532     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
533     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
534
535     id=id.to_i
536     visible=visible.to_i
537     if visible==0 then
538       # if deleting, check node hasn't become part of a way 
539       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")
540       unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
541       deleteitemrelations(id,'node',uid,db_now)
542     end
543
544     x=coord2long(x.to_f,masterscale,baselong)
545     y=coord2lat(y.to_f,masterscale,basey)
546     tagsql="'"+sqlescape(array2tag(tags))+"'"
547     lat=(y * 10000000).round
548     long=(x * 10000000).round
549     tile=QuadTile.tile_for_point(y, x)
550
551     if (id>0) then
552       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})");
553       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}");
554       newid=id
555     else
556       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})");
557       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})");
558     end
559     [0,id,newid]
560   end
561
562   # ----- getpoi
563   # read POI from database
564   #               (only called on revert: POIs are usually read by whichways)
565   #               in:   [0] node id, [1] baselong, [2] basey, [3] masterscale
566   #               does: reads POI
567   #               out:  [0] id (unchanged), [1] projected long, [2] projected lat,
568   #                             [3] hash of tags
569   def getpoi(args) #:doc:
570     id,baselong,basey,masterscale = args
571     
572     n = Node.find(id.to_i)
573     if n
574       return [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash]
575     else
576       return [nil,nil,nil,'']
577     end
578   end
579
580   # ----- deleteway
581   #               delete way and constituent nodes from database
582   #               in:   [0] user token (string), [1] way id
583   #               does: deletes way from db and any constituent nodes not used elsewhere
584   #                             also removes ways/nodes from any relations they're in
585   #               out:  [0] 0 (success), [1] way id (unchanged)
586
587   def deleteway(args) #:doc:
588     usertoken,way_id=args
589     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way_id}")
590     uid=getuserid(usertoken)
591     if !uid then return -1,"You are not logged in, so the way could not be deleted." end
592
593         # FIXME
594         # the next bit removes the way from any relations
595         # the delete_with_relations_and_nodes_and_history method should do this,
596         #   but at present it just throws a 'precondition failed'
597     way=way.to_i 
598     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+way.abs.to_s+Time.new.to_i.to_s
599         db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+way.abs.to_s+Time.new.to_i.to_s
600     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
601         createuniquenodes(way,db_uqn,[])
602         deleteuniquenoderelations(db_uqn,uid,db_now)
603     deleteitemrelations(way_id,'way',uid,db_now)
604     ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
605         # end of FIXME
606
607         # now delete the way
608     user = User.find(uid)
609     way = Way.find(way_id)
610     way.delete_with_relations_and_nodes_and_history(user)  
611     return [0,way_id]
612   end
613
614
615   def readwayquery(id,insistonvisible) #:doc:
616     sql=<<-EOF
617     SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible 
618       FROM current_way_nodes,current_nodes 
619      WHERE current_way_nodes.id=#{id} 
620        AND current_way_nodes.node_id=current_nodes.id 
621   EOF
622     if insistonvisible then sql+=" AND current_nodes.visible=1 " end
623     sql+=" ORDER BY sequence_id"
624     ActiveRecord::Base.connection.select_all(sql)
625   end
626
627   # Get the latest version id of a way
628   def getlastversion(id,version) #:doc:
629     old_way = OldWay.find(:first, :conditions => ['visible=1 AND id=?' , id], :order => 'version DESC')
630     old_way.version
631   end
632
633   def readwayquery_old(id,version,historic) #:doc:
634     # Node handling on undelete (historic=false):
635     # - always use the node specified, even if it's moved
636
637     # Node handling on revert (historic=true):
638     # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
639     #   which means the SWF needs to allocate new ids
640     # - if it's an invisible node, we can reuse the old node id
641
642     # -----     get node list from specified version of way,
643     #           and the _current_ lat/long/tags of each node
644
645     row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
646     waytime=row['timestamp']
647
648     sql=<<-EOF
649   SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags 
650     FROM way_nodes wn,current_nodes cn 
651    WHERE wn.version=#{version} 
652      AND wn.id=#{id} 
653      AND wn.node_id=cn.id 
654    ORDER BY sequence_id
655   EOF
656     rows=ActiveRecord::Base.connection.select_all(sql)
657
658     # -----     if historic (full revert), get the old version of each node
659     #           - if it's in another way now, generate a new id
660     #           - if it's not in another way, use the old ID
661
662     if historic then
663       rows.each_index do |i|
664         sql=<<-EOF
665     SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway 
666       FROM nodes n
667  LEFT JOIN current_way_nodes cwn
668         ON cwn.node_id=n.id AND cwn.id!=#{id} 
669      WHERE n.id=#{rows[i]['id']} 
670        AND n.timestamp<="#{waytime}" 
671   ORDER BY n.timestamp DESC 
672      LIMIT 1
673     EOF
674         row=ActiveRecord::Base.connection.select_one(sql)
675         nx=row['longitude'].to_f
676         ny=row['latitude'].to_f
677         if (!row.nil?)
678           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
679                 end
680         rows[i]['longitude']=nx
681         rows[i]['latitude' ]=ny
682         rows[i]['tags'     ]=row['tags']
683       end
684     end
685     rows
686   end
687
688   def createuniquenodes(way,uqn_name,nodelist) #:doc:
689     # Find nodes which appear in this way but no others
690     sql=<<-EOF
691   CREATE TEMPORARY TABLE #{uqn_name}
692           SELECT a.node_id
693             FROM (SELECT DISTINCT node_id FROM current_way_nodes
694               WHERE id=#{way}) a
695          LEFT JOIN current_way_nodes b
696             ON b.node_id=a.node_id
697              AND b.id!=#{way}
698            WHERE b.node_id IS NULL
699   EOF
700     unless nodelist.empty? then
701       sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
702     end
703     ActiveRecord::Base.connection.execute(sql)
704   end
705
706
707
708   # ====================================================================
709   # Relations handling
710   # deleteuniquenoderelations(uqn_name,uid,db_now)
711   # deleteitemrelations(way|node,'way'|'node',uid,db_now)
712
713   def deleteuniquenoderelations(uqn_name,uid,db_now) #:doc:
714     sql=<<-EOF
715   SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr 
716    WHERE crm.member_id=node_id 
717      AND crm.member_type='node' 
718      AND crm.id=cr.id 
719      AND cr.visible=1
720   EOF
721
722     relnodes=ActiveRecord::Base.connection.select_all(sql)
723     relnodes.each do |a|
724       removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
725     end
726   end
727
728   def deleteitemrelations(objid,type,uid,db_now) #:doc:
729     sql=<<-EOF
730   SELECT cr.id FROM current_relation_members crm,current_relations cr 
731    WHERE crm.member_id=#{objid} 
732      AND crm.member_type='#{type}' 
733      AND crm.id=cr.id 
734      AND cr.visible=1
735   EOF
736
737     relways=ActiveRecord::Base.connection.select_all(sql)
738     relways.each do |a|
739       removefromrelation(objid,type,a['id'],uid,db_now)
740     end
741   end
742
743   def removefromrelation(objid,type,relation,uid,db_now) #:doc:
744     rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
745
746     tagsql=<<-EOF
747   INSERT INTO relation_tags (id,k,v,version) 
748   SELECT id,k,v,#{rver} FROM current_relation_tags 
749    WHERE id=#{relation} 
750   EOF
751     ActiveRecord::Base.connection.insert(tagsql)
752
753     membersql=<<-EOF
754   INSERT INTO relation_members (id,member_type,member_id,member_role,version) 
755   SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members 
756    WHERE id=#{relation} 
757      AND (member_id!=#{objid} OR member_type!='#{type}')
758   EOF
759     ActiveRecord::Base.connection.insert(membersql)
760
761     ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
762     ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
763   end
764
765   def sqlescape(a) #:doc:
766     a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
767   end
768
769   def tag2array(a) #:doc:
770     tags={}
771     Tags.split(a) do |k, v|
772       tags[k.gsub(':','|')]=v
773     end
774     tags
775   end
776
777   def array2tag(a) #:doc:
778     tags = []
779     a.each do |k,v|
780       if v=='' then next end
781       if v[0,6]=='(type ' then next end
782       tags << [k.gsub('|',':'), v]
783     end
784     return Tags.join(tags)
785   end
786
787   def getuserid(token) #:doc:
788     if (token =~ /^(.+)\+(.+)$/) then
789       user = User.authenticate(:username => $1, :password => $2)
790     else
791       user = User.authenticate(:token => token)
792     end
793
794     return user ? user.id : nil;
795   end
796
797   # ====================================================================
798   # Co-ordinate conversion
799
800   def lat2coord(a,basey,masterscale) #:doc:
801     -(lat2y(a)-basey)*masterscale
802   end
803
804   def long2coord(a,baselong,masterscale) #:doc:
805     (a-baselong)*masterscale
806   end
807
808   def lat2y(a) #:doc:
809     180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
810   end
811
812   def coord2lat(a,masterscale,basey) #:doc:
813     y2lat(a/-masterscale+basey)
814   end
815
816   def coord2long(a,masterscale,baselong) #:doc:
817     a/masterscale+baselong
818   end
819
820   def y2lat(a)
821     180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
822   end
823
824 end