]> git.openstreetmap.org Git - rails.git/blob - app/controllers/amf_controller.rb
Show nearby users map in account view page
[rails.git] / app / controllers / amf_controller.rb
1 class AmfController < ApplicationController
2   require 'stringio'
3
4   session :off
5   before_filter :check_write_availability
6
7   # AMF controller for Potlatch
8   # ---------------------------
9   # All interaction between Potlatch (as a .SWF application) and the 
10   # OSM database takes place using this controller. Messages are 
11   # encoded in the Actionscript Message Format (AMF).
12   #
13   # Public domain. Set your tab width to 4 to read this document. :)
14   # editions Systeme D / Richard Fairhurst 2004-2008
15   
16   # to trap errors (getway_old,putway,putpoi,deleteway only):
17   #   return(-1,"message")              <-- just puts up a dialogue
18   #   return(-2,"message")              <-- also asks the user to e-mail me
19   # to log:
20   #   RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
21
22   # ====================================================================
23   # Main AMF handler
24
25   # ---- talk   process AMF request
26
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
34     # -------------
35     # Parse request
36
37     headers=getint(req)                                 # Read number of headers
38
39     headers.times do                                # Read each header
40       name=getstring(req)                               #  |
41       req.getc                                  #  | skip boolean
42       value=getvalue(req)                               #  |
43       header["name"]=value                              #  |
44     end
45
46     bodies=getint(req)                                  # Read number of bodies
47     bodies.times do                                     # Read each body
48       message=getstring(req)                    #  | get message name
49       index=getstring(req)                              #  | get index in response sequence
50       bytes=getlong(req)                                #  | get total size in bytes
51       args=getvalue(req)                                #  | get response (probably an array)
52
53       case message
54                   when 'getpresets';            results[index]=putdata(index,getpresets)
55                   when 'whichways';                     results[index]=putdata(index,whichways(args))
56                   when 'whichways_deleted';     results[index]=putdata(index,whichways_deleted(args))
57                   when 'getway';                        results[index]=putdata(index,getway(args))
58                   when 'getway_old';            results[index]=putdata(index,getway_old(args))
59                   when 'getway_history';        results[index]=putdata(index,getway_history(args))
60                   when 'putway';                        r=putway(args,renumberednodes)
61                                                                         renumberednodes=r[3]
62                                                                         results[index]=putdata(index,r)
63                   when 'deleteway';                     results[index]=putdata(index,deleteway(args))
64                   when 'putpoi';                        results[index]=putdata(index,putpoi(args))
65                   when 'getpoi';                        results[index]=putdata(index,getpoi(args))
66       end
67     end
68
69     # ------------------
70     # Write out response
71
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
76                 results.each do |k,v|
77                   output.write(v)
78                 end
79         }
80     RAILS_DEFAULT_LOGGER.info("  Response: end")
81
82   end
83
84   private
85
86
87   # ====================================================================
88   # Remote calls
89
90   # ----- getpresets
91   #               in:   none
92   #               does: reads tag preset menus, colours, and autocomplete config files
93   #           out:  [0] presets, [1] presetmenus, [2] presetnames,
94   #                             [3] colours, [4] casing, [5] areas, [6] autotags (all hashes)
95
96   def getpresets
97     RAILS_DEFAULT_LOGGER.info("  Message: getpresets")
98
99         # Read preset menus
100     presets={}
101     presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
102     presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
103     presettype=''
104     presetcategory=''
105 #       StringIO.open(txt) do |file|
106         File.open("#{RAILS_ROOT}/config/potlatch/presets.txt") do |file|
107       file.each_line {|line|
108         t=line.chomp
109         if (t=~/(\w+)\/(\w+)/) then
110           presettype=$1
111           presetcategory=$2
112           presetmenus[presettype].push(presetcategory)
113           presetnames[presettype][presetcategory]=["(no preset)"]
114         elsif (t=~/^(.+):\s?(.+)$/) then
115           pre=$1; kv=$2
116           presetnames[presettype][presetcategory].push(pre)
117           presets[pre]={}
118           kv.split(',').each {|a|
119             if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
120           }
121         end
122       }
123     end
124     
125     # Read colours/styling
126         colours={}; casing={}; areas={}
127         File.open("#{RAILS_ROOT}/config/potlatch/colours.txt") do |file|
128           file.each_line {|line|
129                 t=line.chomp
130                 if (t=~/(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/) then
131                   tag=$1
132                   if ($2!='-') then colours[tag]=$2.hex end
133                   if ($3!='-') then casing[tag]=$3.hex end
134                   if ($4!='-') then areas[tag]=$4.hex end
135                 end
136           }
137         end
138         
139         # Read auto-complete
140         autotags={}; autotags['point']={}; autotags['way']={}; autotags['POI']={};
141         File.open("#{RAILS_ROOT}/config/potlatch/autocomplete.txt") do |file|
142                 file.each_line {|line|
143                         t=line.chomp
144                         if (t=~/^(\w+)\/(\w+)\s+(.+)$/) then
145                                 tag=$1; type=$2; values=$3
146                                 if values=='-' then autotags[type][tag]=[]
147                                                            else autotags[type][tag]=values.split(',').sort.reverse end
148                         end
149                 }
150         end
151         
152     [presets,presetmenus,presetnames,colours,casing,areas,autotags]
153   end
154
155   # ----- whichways
156   #               return array of ways in current bounding box
157
158   #               in:   [0] xmin, [1] ymin, [2] xmax, [3] ymax (bbox in degrees)
159   #                             [4] baselong (longitude of SWF map origin),
160   #                             [5] basey (projected latitude of SWF map origin),
161   #                             [6] masterscale (SWF map scale)
162   #               does: finds all ways and POI nodes in bounding box
163   #                             at present, instead of using correct (=more complex) SQL to find
164   #                             corner-crossing ways, it simply enlarges the bounding box
165   #               out:  [0] array of way ids,
166   #                             [1] array of POIs
167   #                             (where each POI is an array containing:
168   #                              [0] id, [1] projected long, [2] projected lat, [3] hash of tags)
169
170   def whichways(args)
171     xmin = args[0].to_f-0.01
172     ymin = args[1].to_f-0.01
173     xmax = args[2].to_f+0.01
174     ymax = args[3].to_f+0.01
175     baselong    = args[4]
176     basey       = args[5]
177     masterscale = args[6]
178
179     RAILS_DEFAULT_LOGGER.info("  Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
180
181     waylist = ActiveRecord::Base.connection.select_all("SELECT DISTINCT current_way_nodes.id AS wayid"+
182        "  FROM current_way_nodes,current_nodes,current_ways "+
183        " WHERE current_nodes.id=current_way_nodes.node_id "+
184        "   AND current_nodes.visible=1 "+
185        "   AND current_ways.id=current_way_nodes.id "+
186        "   AND current_ways.visible=1 "+
187        "   AND "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes."))
188
189     ways = waylist.collect {|a| a['wayid'].to_i } # get an array of way IDs
190
191     pointlist = ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.latitude*0.0000001 AS lat,current_nodes.longitude*0.0000001 AS lng,current_nodes.tags "+
192        "  FROM current_nodes "+
193        "  LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id "+
194        " WHERE "+OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")+
195        "   AND cwn.id IS NULL "+
196        "   AND current_nodes.visible=1")
197
198     points = pointlist.collect {|a| [a['id'],long2coord(a['lng'].to_f,baselong,masterscale),lat2coord(a['lat'].to_f,basey,masterscale),tag2array(a['tags'])]    } # get a list of node ids and their tags
199
200     [ways,points]
201   end
202
203   # ----- whichways_deleted
204   #               return array of deleted ways in current bounding box
205
206   #               in:   as whichways
207   #               does: finds all deleted ways with a deleted node in bounding box
208   #               out:  [0] array of way ids
209   
210   def whichways_deleted(args)
211     xmin = args[0].to_f-0.01
212     ymin = args[1].to_f-0.01
213     xmax = args[2].to_f+0.01
214     ymax = args[3].to_f+0.01
215     baselong    = args[4]
216     basey       = args[5]
217     masterscale = args[6]
218
219         sql=<<-EOF
220                  SELECT DISTINCT current_ways.id 
221                    FROM current_nodes,way_nodes,current_ways 
222                   WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")} 
223                         AND way_nodes.node_id=current_nodes.id 
224                         AND way_nodes.id=current_ways.id 
225                         AND current_nodes.visible=0 
226                         AND current_ways.visible=0 
227         EOF
228     waylist = ActiveRecord::Base.connection.select_all(sql)
229     ways = waylist.collect {|a| a['id'].to_i }
230         [ways]
231   end
232   
233   # ----- getway
234   #               in:   [0] SWF object name, [1] way id, [2] baselong, [3] basey,
235   #                             [4] masterscale
236   #               does: gets way and all nodes
237   #               out:  [0] SWF object name (unchanged),
238   #                             [1] array of points
239   #                                     (where each point is an array containing
240   #                                      [0] projected long, [1] projected lat, [2] node id,
241   #                                      [3] null, [4] hash of node tags),
242   #                             [2] xmin, [3] xmax, [4] ymin, [5] ymax (unprojected bbox)
243
244   def getway(args)
245     objname,wayid,baselong,basey,masterscale=args
246     wayid = wayid.to_i
247     points = []
248     xmin = ymin =  999999
249     xmax = ymax = -999999
250
251     RAILS_DEFAULT_LOGGER.info("  Message: getway, id=#{wayid}")
252
253     readwayquery(wayid,true).each {|row|
254       points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,nil,tag2array(row['tags'])]
255       xmin = [xmin,row['longitude'].to_f].min
256       xmax = [xmax,row['longitude'].to_f].max
257       ymin = [ymin,row['latitude'].to_f].min
258       ymax = [ymax,row['latitude'].to_f].max
259     }
260
261     attributes={}
262     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
263     attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
264
265     [objname,points,attributes,xmin,xmax,ymin,ymax]
266   end
267   
268   # ----- getway_old
269   #               returns old version of way
270
271   #               in:   [0] SWF object name, [1] way id,
272   #                             [2] way version to get (or -1 for "last deleted version")
273   #                             [3] baselong, [4] basey, [5] masterscale
274   #               does: gets old version of way and all constituent nodes
275   #                             for undelete, always uses the most recent version of each node
276   #                               (even if it's moved)
277   #                             for revert, uses the historic version of each node, but if that node is
278   #                               still visible and has been changed since, generates a new node id
279   #               out:  [0] 0 (code for success), [1] SWF object name,
280   #                             [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
281   #                             [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
282   #                             [8] way version
283
284   def getway_old(args)
285     RAILS_DEFAULT_LOGGER.info("  Message: getway_old (server is #{SERVER_URL})")
286 #       if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
287         
288     objname,wayid,version,baselong,basey,masterscale=args
289     wayid = wayid.to_i
290     version = version.to_i
291     xmin = ymin =  999999
292     xmax = ymax = -999999
293         points=[]
294         if version<0
295           historic=false
296           version=getlastversion(wayid,version)
297         else
298           historic=true
299         end
300         readwayquery_old(wayid,version,historic).each { |row|
301       points<<[long2coord(row['longitude'].to_f,baselong,masterscale),lat2coord(row['latitude'].to_f,basey,masterscale),row['id'].to_i,row['visible'].to_i,tag2array(row['tags'].to_s)]
302       xmin=[xmin,row['longitude'].to_f].min
303       xmax=[xmax,row['longitude'].to_f].max
304       ymin=[ymin,row['latitude' ].to_f].min
305       ymax=[ymax,row['latitude' ].to_f].max
306         }
307
308         # get tags from this version
309     attributes={}
310     attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM way_tags WHERE id=#{wayid} AND version=#{version}"
311     attrlist.each {|a| attributes[a['k'].gsub(':','|')]=a['v'] }
312         attributes['history']="Retrieved from v"+version.to_s
313
314     [0,objname,points,attributes,xmin,xmax,ymin,ymax,version]
315   end
316
317   # ----- getway_history
318   #               find history of a way
319
320   #               in:   [0] way id
321   #               does: finds history of a way
322   #               out:  [0] array of previous versions (where each is
323   #                                     [0] version, [1] db timestamp, [2] visible 0 or 1,
324   #                                     [3] username or 'anonymous')
325
326   def getway_history(wayid)
327         history=[]
328         sql=<<-EOF
329         SELECT version,timestamp,visible,display_name,data_public
330           FROM ways,users
331          WHERE ways.id=#{wayid}
332            AND ways.user_id=users.id
333            AND ways.visible=1
334          ORDER BY version DESC
335         EOF
336         histlist=ActiveRecord::Base.connection.select_all(sql)
337         histlist.each { |row|
338                 if row['data_public'].to_i==1 then user=row['display_name'] else user='anonymous' end
339                 history<<[row['version'],row['timestamp'],row['visible'],user]
340         }
341         [history]
342   end
343
344   # ----- putway
345   #               saves a way to the database
346   
347   #               in:   [0] user token, [1] original way id (may be negative), 
348   #                             [2] array of points (as getway/getway_old), [3] hash of way tags,
349   #                             [4] original way version (0 if not a reverted/undeleted way),
350   #                             [5] baselong, [6] basey, [7] masterscale
351   #               does: saves way to the database
352   #                             all constituent nodes are created/updated as necessary
353   #                             (or deleted if they were in the old version and are otherwise unused)
354   #               out:  [0] 0 (code for success), [1] original way id (unchanged),
355   #                             [2] new way id, [3] hash of renumbered nodes (old id=>new id),
356   #                             [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
357
358   def putway(args,renumberednodes)
359     RAILS_DEFAULT_LOGGER.info("  putway started")
360     usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
361     uid=getuserid(usertoken)
362     if !uid then return -1,"You are not logged in, so the way could not be saved." end
363
364     RAILS_DEFAULT_LOGGER.info("  putway authenticated happily")
365     db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s    # temp uniquenodes table name, typically 51 chars
366     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s    # 'now' variable name, typically 51 chars
367     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
368     originalway=originalway.to_i
369         oldversion=oldversion.to_i
370         
371     RAILS_DEFAULT_LOGGER.info("  Message: putway, id=#{originalway}")
372
373         # -- Temporary check for null IDs
374         
375         points.each do |a|
376           if a[2]==0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
377         end
378
379     # -- 3.     read original way into memory
380
381     xc={}; yc={}; tagc={}; vc={}
382     if originalway>0
383       way=originalway
384           if oldversion==0 then r=readwayquery(way,false)
385                                            else r=readwayquery_old(way,oldversion,true) end
386           r.each { |row|
387                 id=row['id'].to_i
388                 if (id>0) then
389                   xc[id]=row['longitude'].to_f
390                   yc[id]=row['latitude' ].to_f
391                   tagc[id]=row['tags']
392                   vc[id]=row['visible'].to_i
393             end
394           }
395       ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
396     else
397       way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
398     end
399
400     # -- 4.     get version by inserting new row into ways
401
402     version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
403
404     # -- 5. compare nodes and update xmin,xmax,ymin,ymax
405
406     xmin=ymin= 999999
407     xmax=ymax=-999999
408     insertsql=''
409         nodelist=[]
410
411     points.each_index do |i|
412       xs=coord2long(points[i][0],masterscale,baselong)
413       ys=coord2lat(points[i][1],masterscale,basey)
414       xmin=[xs,xmin].min; xmax=[xs,xmax].max
415       ymin=[ys,ymin].min; ymax=[ys,ymax].max
416       node=points[i][2].to_i
417           tagstr=array2tag(points[i][4])
418       tagsql="'"+sqlescape(tagstr)+"'"
419       lat=(ys * 10000000).round
420       long=(xs * 10000000).round
421       tile=QuadTile.tile_for_point(ys, xs)
422
423       # compare node
424       if node<0
425         # new node - create
426                 if renumberednodes[node.to_s].nil?
427           newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (   latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (           #{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
428                   ActiveRecord::Base.connection.insert("INSERT INTO nodes         (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{newnode},#{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
429           points[i][2]=newnode
430           nodelist.push(newnode)
431           renumberednodes[node.to_s]=newnode.to_s
432                 else
433           points[i][2]=renumberednodes[node.to_s].to_i
434                 end
435
436       elsif xc.has_key?(node)
437                 nodelist.push(node)
438         # old node from original way - update
439         if ((xs/0.0000001).round!=(xc[node]/0.0000001).round or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node] or vc[node]==0)
440           ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{node},#{lat},#{long},#{db_now},#{uid},1,#{tagsql},#{tile})")
441           ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{lat},longitude=#{long},timestamp=#{db_now},user_id=#{uid},tags=#{tagsql},visible=1,tile=#{tile} WHERE id=#{node}")
442         end
443       else
444         # old node, created in another way and now added to this way
445       end
446     end
447
448
449         # -- 6a. delete any nodes not in modified way
450
451     createuniquenodes(way,db_uqn,nodelist)      # nodes which appear in this way but no other
452
453     sql=<<-EOF
454         INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)  
455         SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
456           FROM current_nodes AS cn,#{db_uqn}
457          WHERE cn.id=node_id
458     EOF
459     ActiveRecord::Base.connection.insert(sql)
460
461     sql=<<-EOF
462       UPDATE current_nodes AS cn, #{db_uqn}
463          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
464        WHERE cn.id=node_id
465     EOF
466     ActiveRecord::Base.connection.update(sql)
467
468         deleteuniquenoderelations(db_uqn,uid,db_now)
469     ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
470
471         #       6b. insert new version of route into way_nodes
472
473     insertsql =''
474     currentsql=''
475     sequence  =1
476     points.each do |p|
477       if insertsql !='' then insertsql +=',' end
478       if currentsql!='' then currentsql+=',' end
479       insertsql +="(#{way},#{p[2]},#{sequence},#{version})"
480       currentsql+="(#{way},#{p[2]},#{sequence})"
481       sequence  +=1
482     end
483
484     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}");
485     ActiveRecord::Base.connection.insert( "INSERT INTO         way_nodes (id,node_id,sequence_id,version) VALUES #{insertsql}");
486     ActiveRecord::Base.connection.insert( "INSERT INTO current_way_nodes (id,node_id,sequence_id        ) VALUES #{currentsql}");
487
488     # -- 7. insert new way tags
489
490     insertsql =''
491     currentsql=''
492     attributes.each do |k,v|
493       if v=='' or v.nil? then next end
494       if v[0,6]=='(type ' then next end
495       if insertsql !='' then insertsql +=',' end
496       if currentsql!='' then currentsql+=',' end
497       insertsql +="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"',#{version})"
498       currentsql+="(#{way},'"+sqlescape(k.gsub('|',':'))+"','"+sqlescape(v)+"')"
499     end
500
501     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
502     if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
503     if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
504
505     [0,originalway,way,renumberednodes,xmin,xmax,ymin,ymax]
506   end
507
508   # ----- putpoi
509   #               save POI to the database
510   
511   #               in:   [0] user token, [1] original node id (may be negative),
512   #                             [2] projected longitude, [3] projected latitude, [4] hash of tags,
513   #                             [5] visible (0 to delete, 1 otherwise), 
514   #                             [6] baselong, [7] basey, [8] masterscale
515   #               does: saves POI node to the database
516   #                             refuses save if the node has since become part of a way
517   #               out:  [0] 0 (success), [1] original node id (unchanged), [2] new node id
518
519   def putpoi(args)
520     usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
521     uid=getuserid(usertoken)
522     if !uid then return -1,"You are not logged in, so the point could not be saved." end
523
524     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+id.to_i.abs.to_s+Time.new.to_i.to_s     # 'now' variable name, typically 51 chars
525     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
526
527     id=id.to_i
528     visible=visible.to_i
529         if visible==0 then
530                 # if deleting, check node hasn't become part of a way 
531                 inway=ActiveRecord::Base.connection.select_one("SELECT cw.id FROM current_ways cw,current_way_nodes cwn WHERE cw.id=cwn.id AND cw.visible=1 AND cwn.node_id=#{id} LIMIT 1")
532                 unless inway.nil? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
533                 deleteitemrelations(id,'node',uid,db_now)
534         end
535
536     x=coord2long(x.to_f,masterscale,baselong)
537     y=coord2lat(y.to_f,masterscale,basey)
538     tagsql="'"+sqlescape(array2tag(tags))+"'"
539     lat=(y * 10000000).round
540     long=(x * 10000000).round
541     tile=QuadTile.tile_for_point(y, x)
542         
543     if (id>0) then
544         ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{id},#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
545         ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{lat},longitude=#{long},timestamp=#{db_now},user_id=#{uid},visible=#{visible},tags=#{tagsql},tile=#{tile} WHERE id=#{id}");
546         newid=id
547     else
548         newid=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes (latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
549               ActiveRecord::Base.connection.update("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags,tile) VALUES (#{newid},#{lat},#{long},#{db_now},#{uid},#{visible},#{tagsql},#{tile})");
550     end
551     [0,id,newid]
552   end
553
554   # ----- getpoi
555   #               read POI from database
556   #               (only called on revert: POIs are usually read by whichways)
557   
558   #               in:   [0] node id, [1] baselong, [2] basey, [3] masterscale
559   #               does: reads POI
560   #               out:  [0] id (unchanged), [1] projected long, [2] projected lat, [3] hash of tags
561   
562   def getpoi(args)
563         id,baselong,basey,masterscale=args; id=id.to_i
564         poi=ActiveRecord::Base.connection.select_one("SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lng,tags "+
565                 "FROM current_nodes WHERE visible=1 AND id=#{id}")
566         if poi.nil? then return [nil,nil,nil,''] end
567         [id,
568          long2coord(poi['lng'].to_f,baselong,masterscale),
569          lat2coord(poi['lat'].to_f,basey,masterscale),
570          tag2array(poi['tags'])]
571   end
572
573   # ----- deleteway
574   #               delete way and constituent nodes from database
575   
576   #               in:   [0] user token, [1] way id
577   #               does: deletes way from db and any constituent nodes not used elsewhere
578   #                             also removes ways/nodes from any relations they're in
579   #               out:  [0] 0 (success), [1] way id (unchanged)
580
581   def deleteway(args)
582     usertoken,way=args
583
584     RAILS_DEFAULT_LOGGER.info("  Message: deleteway, id=#{way}")
585     uid=getuserid(usertoken)
586     if !uid then return -1,"You are not logged in, so the way could not be deleted." end
587
588     way=way.to_i
589     db_uqn='unin'+(rand*100).to_i.to_s+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s    # temp uniquenodes table name, typically 51 chars
590     db_now='@now'+(rand*100).to_i.to_s+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s    # 'now' variable name, typically 51 chars
591     ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
592
593     # - delete any otherwise unused nodes
594   
595     createuniquenodes(way,db_uqn,[])
596
597 #       unless (preserve.empty?) then
598 #               ActiveRecord::Base.connection.execute("DELETE FROM #{db_uqn} WHERE node_id IN ("+preserve.join(',')+")")
599 #       end
600
601     sql=<<-EOF
602         INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tile)
603         SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0,cn.tile
604           FROM current_nodes AS cn,#{db_uqn}
605          WHERE cn.id=node_id
606     EOF
607     ActiveRecord::Base.connection.insert(sql)
608
609     sql=<<-EOF
610       UPDATE current_nodes AS cn, #{db_uqn}
611          SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid} 
612        WHERE cn.id=node_id
613     EOF
614     ActiveRecord::Base.connection.update(sql)
615
616         deleteuniquenoderelations(db_uqn,uid,db_now)
617     ActiveRecord::Base.connection.execute("DROP TEMPORARY TABLE #{db_uqn}")
618
619     # - delete way
620         
621     ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
622     ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
623     ActiveRecord::Base.connection.execute("DELETE FROM current_way_nodes WHERE id=#{way}")
624     ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
625         deleteitemrelations(way,'way',uid,db_now)
626     [0,way]
627 end
628
629
630
631 # ====================================================================
632 # Support functions for remote calls
633
634 def readwayquery(id,insistonvisible)
635   sql=<<-EOF
636     SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,current_nodes.id,tags,visible 
637       FROM current_way_nodes,current_nodes 
638      WHERE current_way_nodes.id=#{id} 
639        AND current_way_nodes.node_id=current_nodes.id 
640   EOF
641   if insistonvisible then sql+=" AND current_nodes.visible=1 " end
642   sql+=" ORDER BY sequence_id"
643   ActiveRecord::Base.connection.select_all(sql)
644 end
645
646 def getlastversion(id,version)
647   row=ActiveRecord::Base.connection.select_one("SELECT version FROM ways WHERE id=#{id} AND visible=1 ORDER BY version DESC LIMIT 1")
648   row['version']
649 end
650
651 def readwayquery_old(id,version,historic)
652   # Node handling on undelete (historic=false):
653   # - always use the node specified, even if it's moved
654   
655   # Node handling on revert (historic=true):
656   # - if it's a visible node, use a new node id (i.e. not mucking up the old one)
657   #   which means the SWF needs to allocate new ids
658   # - if it's an invisible node, we can reuse the old node id
659
660   # get node list from specified version of way,
661   # and the _current_ lat/long/tags of each node
662
663   row=ActiveRecord::Base.connection.select_one("SELECT timestamp FROM ways WHERE version=#{version} AND id=#{id}")
664   waytime=row['timestamp']
665
666   sql=<<-EOF
667         SELECT cn.id,visible,latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags 
668           FROM way_nodes wn,current_nodes cn 
669          WHERE wn.version=#{version} 
670            AND wn.id=#{id} 
671            AND wn.node_id=cn.id 
672          ORDER BY sequence_id
673   EOF
674   rows=ActiveRecord::Base.connection.select_all(sql)
675
676   # if historic (full revert), get the old version of each node
677   # - if it's in another way now, generate a new id
678   # - if it's not in another way, use the old ID
679   if historic then
680         rows.each_index do |i|
681           sql=<<-EOF
682           SELECT latitude*0.0000001 AS latitude,longitude*0.0000001 AS longitude,tags,cwn.id AS currentway 
683             FROM nodes n
684    LEFT JOIN current_way_nodes cwn
685                   ON cwn.node_id=n.id
686            WHERE n.id=#{rows[i]['id']} 
687              AND n.timestamp<="#{waytime}" 
688                  AND cwn.id!=#{id} 
689            ORDER BY n.timestamp DESC 
690            LIMIT 1
691           EOF
692           row=ActiveRecord::Base.connection.select_one(sql)
693           unless row.nil? then
694             nx=row['longitude'].to_f
695             ny=row['latitude'].to_f
696             if (row['currentway'] && (nx!=rows[i]['longitude'].to_f or ny!=rows[i]['latitude'].to_f or row['tags']!=rows[i]['tags'])) then rows[i]['id']=-1 end
697                 rows[i]['longitude']=nx
698                 rows[i]['latitude' ]=ny
699                 rows[i]['tags'     ]=row['tags']
700           end
701     end
702   end
703   rows
704 end
705
706 def createuniquenodes(way,uqn_name,nodelist)
707         # Find nodes which appear in this way but no others
708         sql=<<-EOF
709         CREATE TEMPORARY TABLE #{uqn_name}
710                                         SELECT a.node_id
711                                           FROM (SELECT DISTINCT node_id FROM current_way_nodes
712                                                         WHERE id=#{way}) a
713                                  LEFT JOIN current_way_nodes b
714                                                 ON b.node_id=a.node_id
715                                            AND b.id!=#{way}
716                                          WHERE b.node_id IS NULL
717         EOF
718         unless nodelist.empty? then
719           sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
720         end
721         ActiveRecord::Base.connection.execute(sql)
722 end
723
724
725
726 # ====================================================================
727 # Relations handling
728 # deleteuniquenoderelations(uqn_name,uid,db_now)
729 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
730
731 def deleteuniquenoderelations(uqn_name,uid,db_now)
732         sql=<<-EOF
733         SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr 
734          WHERE crm.member_id=node_id 
735            AND crm.member_type='node' 
736            AND crm.id=cr.id 
737            AND cr.visible=1
738         EOF
739
740         relnodes=ActiveRecord::Base.connection.select_all(sql)
741         relnodes.each do |a|
742                 removefromrelation(a['node_id'],'node',a['id'],uid,db_now)
743         end
744 end
745
746 def deleteitemrelations(objid,type,uid,db_now)
747         sql=<<-EOF
748         SELECT cr.id FROM current_relation_members crm,current_relations cr 
749          WHERE crm.member_id=#{objid} 
750            AND crm.member_type='#{type}' 
751            AND crm.id=cr.id 
752            AND cr.visible=1
753         EOF
754         
755         relways=ActiveRecord::Base.connection.select_all(sql)
756         relways.each do |a|
757                 removefromrelation(objid,type,a['id'],uid,db_now)
758         end
759 end
760
761 def removefromrelation(objid,type,relation,uid,db_now)
762         rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
763
764         tagsql=<<-EOF
765         INSERT INTO relation_tags (id,k,v,version) 
766         SELECT id,k,v,#{rver} FROM current_relation_tags 
767          WHERE id=#{relation} 
768         EOF
769         ActiveRecord::Base.connection.insert(tagsql)
770
771         membersql=<<-EOF
772         INSERT INTO relation_members (id,member_type,member_id,member_role,version) 
773         SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members 
774          WHERE id=#{relation} 
775            AND (member_id!=#{objid} OR member_type!='#{type}')
776         EOF
777         ActiveRecord::Base.connection.insert(membersql)
778         
779         ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
780         ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
781 end
782
783
784 def sqlescape(a)
785   a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
786 end
787
788 def tag2array(a)
789   tags={}
790   Tags.split(a) do |k, v|
791     tags[k.gsub(':','|')]=v
792   end
793   tags
794 end
795
796 def array2tag(a)
797   tags = []
798   a.each do |k,v|
799     if v=='' then next end
800     if v[0,6]=='(type ' then next end
801     tags << [k.gsub('|',':'), v]
802   end
803   return Tags.join(tags)
804 end
805
806 def getuserid(token)
807   if (token =~ /^(.+)\+(.+)$/) then
808     user = User.authenticate(:username => $1, :password => $2)
809   else
810     user = User.authenticate(:token => token)
811   end
812
813   return user ? user.id : nil;
814 end
815
816
817
818 # ====================================================================
819 # AMF read subroutines
820
821 # ----- getint          return two-byte integer
822 # ----- getlong         return four-byte long
823 # ----- getstring       return string with two-byte length
824 # ----- getdouble       return eight-byte double-precision float
825 # ----- getobject       return object/hash
826 # ----- getarray        return numeric array
827
828 def getint(s)
829   s.getc*256+s.getc
830 end
831
832 def getlong(s)
833   ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
834 end
835
836 def getstring(s)
837   len=s.getc*256+s.getc
838   s.read(len)
839 end
840
841 def getdouble(s)
842   a=s.read(8).unpack('G')                       # G big-endian, E little-endian
843   a[0]
844 end
845
846 def getarray(s)
847   len=getlong(s)
848   arr=[]
849   for i in (0..len-1)
850     arr[i]=getvalue(s)
851   end
852   arr
853 end
854
855 def getobject(s)
856   arr={}
857   while (key=getstring(s))
858     if (key=='') then break end
859     arr[key]=getvalue(s)
860   end
861   s.getc                # skip the 9 'end of object' value
862   arr
863 end
864
865 # ----- getvalue        parse and get value
866
867 def getvalue(s)
868   case s.getc
869         when 0; return getdouble(s)                     # number
870         when 1; return s.getc                           # boolean
871         when 2; return getstring(s)                     # string
872         when 3; return getobject(s)                     # object/hash
873         when 5; return nil                                      # null
874         when 6; return nil                                      # undefined
875         when 8; s.read(4)                                       # mixedArray
876                         return getobject(s)                     #  |
877         when 10;return getarray(s)                      # array
878         else;   return nil                                      # error
879   end
880 end
881
882 # ====================================================================
883 # AMF write subroutines
884
885 # ----- putdata         envelope data into AMF writeable form
886 # ----- encodevalue     pack variables as AMF
887
888 def putdata(index,n)
889   d =encodestring(index+"/onResult")
890   d+=encodestring("null")
891   d+=[-1].pack("N")
892   d+=encodevalue(n)
893 end
894
895 def encodevalue(n)
896   case n.class.to_s
897   when 'Array'
898     a=10.chr+encodelong(n.length)
899     n.each do |b|
900       a+=encodevalue(b)
901     end
902     a
903   when 'Hash'
904     a=3.chr
905     n.each do |k,v|
906       a+=encodestring(k)+encodevalue(v)
907     end
908     a+0.chr+0.chr+9.chr
909   when 'String'
910     2.chr+encodestring(n)
911   when 'Bignum','Fixnum','Float'
912     0.chr+encodedouble(n)
913   when 'NilClass'
914     5.chr
915   else
916     RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
917   end
918 end
919
920 # ----- encodestring    encode string with two-byte length
921 # ----- encodedouble    encode number as eight-byte double precision float
922 # ----- encodelong              encode number as four-byte long
923
924 def encodestring(n)
925   a,b=n.size.divmod(256)
926   a.chr+b.chr+n
927 end
928
929 def encodedouble(n)
930   [n].pack('G')
931 end
932
933 def encodelong(n)
934   [n].pack('N')
935 end
936
937 # ====================================================================
938 # Co-ordinate conversion
939
940 def lat2coord(a,basey,masterscale)
941   -(lat2y(a)-basey)*masterscale+250
942 end
943
944 def long2coord(a,baselong,masterscale)
945   (a-baselong)*masterscale+350
946 end
947
948 def lat2y(a)
949   180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
950 end
951
952 def coord2lat(a,masterscale,basey)
953   y2lat((a-250)/-masterscale+basey)
954 end
955
956 def coord2long(a,masterscale,baselong)
957   (a-350)/masterscale+baselong
958 end
959
960 def y2lat(a)
961   180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
962 end
963
964 end