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