]> git.openstreetmap.org Git - rails.git/blob - app/controllers/note_controller.rb
Tidy up the note model a bit
[rails.git] / app / controllers / note_controller.rb
1 class NoteController < ApplicationController
2
3   layout 'site', :only => [:mine]
4
5   before_filter :check_api_readable
6   before_filter :authorize_web, :only => [:create, :close, :update, :delete, :mine]
7   before_filter :check_api_writable, :only => [:create, :close, :update, :delete]
8   before_filter :require_moderator, :only => [:delete]
9   before_filter :set_locale, :only => [:mine]
10   after_filter :compress_output
11   around_filter :api_call_handle_error, :api_call_timeout
12
13   # Help methods for checking boundary sanity and area size
14   include MapBoundary
15
16   def list
17     # Figure out the bbox
18     bbox = params['bbox']
19
20     if bbox and bbox.count(',') == 3
21       bbox = bbox.split(',')
22       @min_lon, @min_lat, @max_lon, @max_lat = sanitise_boundaries(bbox)
23     else
24       #Fallback to old style, this is deprecated and should not be used
25       raise OSM::APIBadUserInput.new("No l was given") unless params['l']
26       raise OSM::APIBadUserInput.new("No r was given") unless params['r']
27       raise OSM::APIBadUserInput.new("No b was given") unless params['b']
28       raise OSM::APIBadUserInput.new("No t was given") unless params['t']
29
30       @min_lon = params['l'].to_f
31       @max_lon = params['r'].to_f
32       @min_lat = params['b'].to_f
33       @max_lat = params['t'].to_f
34     end
35
36     limit = getLimit
37     conditions = closedCondition
38         
39     check_boundaries(@min_lon, @min_lat, @max_lon, @max_lat, MAX_NOTE_REQUEST_AREA)
40
41     @notes = Note.find_by_area(@min_lat, @min_lon, @max_lat, @max_lon, :include => :comments, :order => "updated_at DESC", :limit => limit, :conditions => conditions)
42
43     respond_to do |format|
44       format.html {render :template => 'note/list.rjs', :content_type => "text/javascript"}
45       format.rss {render :template => 'note/list.rss'}
46       format.js
47       format.xml {render :template => 'note/list.xml'}
48       format.json { render :json => @notes.to_json(:methods => [:lat, :lon], :only => [:id, :status, :created_at], :include => { :comments => { :only => [:author_name, :created_at, :body]}}) }          
49       format.gpx {render :template => 'note/list.gpx'}
50     end
51   end
52
53   def create
54     raise OSM::APIBadUserInput.new("No lat was given") unless params['lat']
55     raise OSM::APIBadUserInput.new("No lon was given") unless params['lon']
56     raise OSM::APIBadUserInput.new("No text was given") unless params['text']
57
58     lon = params['lon'].to_f
59     lat = params['lat'].to_f
60     comment = params['text']
61
62     name = "NoName"
63     name = params['name'] if params['name']
64
65     #Include in a transaction to ensure that there is always a note_comment for every note
66     Note.transaction do
67       @note = Note.create(:lat => lat, :lon => lon)
68       raise OSM::APIBadUserInput.new("The note is outside this world") unless @note.in_world?
69
70       #TODO: move this into a helper function
71       begin
72         url = "http://nominatim.openstreetmap.org/reverse?lat=" + lat.to_s + "&lon=" + lon.to_s + "&zoom=16" 
73         response = REXML::Document.new(Net::HTTP.get(URI.parse(url))) 
74                 
75         if result = response.get_text("reversegeocode/result") 
76           @note.nearby_place = result.to_s 
77         else 
78           @note.nearby_place = "unknown"
79         end
80       rescue Exception => err
81         @note.nearby_place = "unknown"
82       end
83
84       @note.save
85
86       add_comment(@note, comment, name, "opened")
87     end
88  
89     render_ok
90   end
91
92   def update
93     raise OSM::APIBadUserInput.new("No id was given") unless params['id']
94     raise OSM::APIBadUserInput.new("No text was given") unless params['text']
95
96     name = "NoName"
97     name = params['name'] if params['name']
98         
99     id = params['id'].to_i
100
101     note = Note.find(id)
102     raise OSM::APINotFoundError unless note
103     raise OSM::APIAlreadyDeletedError unless note.visible?
104
105     Note.transaction do
106       add_comment(note, params['text'], name, "commented")
107     end
108
109     render_ok
110   end
111
112   def close
113     raise OSM::APIBadUserInput.new("No id was given") unless params['id']
114         
115     id = params['id'].to_i
116     name = "NoName"
117     name = params['name'] if params['name']
118
119     note = Note.find_by_id(id)
120     raise OSM::APINotFoundError unless note
121     raise OSM::APIAlreadyDeletedError unless note.visible?
122
123     Note.transaction do
124       note.close
125       add_comment(note, :nil, name, "closed")
126     end
127
128     render_ok
129   end 
130
131   def rss
132     limit = getLimit
133     conditions = closedCondition
134
135     # Figure out the bbox
136     bbox = params['bbox']
137
138     if bbox and bbox.count(',') == 3
139       bbox = bbox.split(',')
140       @min_lon, @min_lat, @max_lon, @max_lat = sanitise_boundaries(bbox)
141
142       check_boundaries(@min_lon, @min_lat, @max_lon, @max_lat, MAX_NOTE_REQUEST_AREA)
143
144       conditions = cond_merge conditions, [OSM.sql_for_area(@min_lat, @min_lon, @max_lat, @max_lon)]
145     end
146
147     @comments = NoteComment.find(:all, :limit => limit, :order => "created_at DESC", :joins => :note, :include => :note, :conditions => conditions)
148     render :template => 'note/rss.rss'
149   end
150
151   def read
152     @note = Note.find(params['id'])
153     raise OSM::APINotFoundError unless @note
154     raise OSM::APIAlreadyDeletedError unless @note.visible?
155     
156     respond_to do |format|
157       format.rss
158       format.xml
159       format.json { render :json => @note.to_json(:methods => [:lat, :lon], :only => [:id, :status, :created_at], :include => { :comments => { :only => [:author_name, :created_at, :body]}}) }   
160       format.gpx
161     end
162   end
163
164   def delete
165     note = note.find(params['id'])
166     raise OSM::APINotFoundError unless note
167     raise OSM::APIAlreadyDeletedError unless note.visible?
168
169     Note.transaction do
170       note.status = "hidden"
171       note.save
172       add_comment(note, :nil, name, "hidden")
173     end
174
175     render :text => "ok\n", :content_type => "text/html" 
176   end
177
178   def search
179     raise OSM::APIBadUserInput.new("No query string was given") unless params['q']
180     limit = getLimit
181     conditions = closedCondition
182     conditions = cond_merge conditions, ['note_comments.body ~ ?', params['q']]
183         
184     #TODO: There should be a better way to do this.   CloseConditions are ignored at the moment
185
186     @notes = Note.find(:all, :limit => limit, :order => "updated_at DESC", :joins => :comments, :include => :comments, :conditions => conditions).uniq
187     respond_to do |format|
188       format.html {render :template => 'note/list.rjs', :content_type => "text/javascript"}
189       format.rss {render :template => 'note/list.rss'}
190       format.js
191       format.xml {render :template => 'note/list.xml'}
192       format.json { render :json => @notes.to_json(:methods => [:lat, :lon], :only => [:id, :status, :created_at], :include => { :comments => { :only => [:author_name, :created_at, :body]}}) }
193       format.gpx {render :template => 'note/list.gpx'}
194     end
195   end
196
197   def mine
198     if params[:display_name] 
199       @user2 = User.find_by_display_name(params[:display_name], :conditions => { :status => ["active", "confirmed"] }) 
200  
201       if @user2  
202         if @user2.data_public? or @user2 == @user 
203           conditions = ['note_comments.author_id = ?', @user2.id] 
204         else 
205           conditions = ['false'] 
206         end 
207       else #if request.format == :html 
208         @title = t 'user.no_such_user.title' 
209         @not_found_user = params[:display_name] 
210         render :template => 'user/no_such_user', :status => :not_found 
211         return
212       end 
213     end
214
215     if @user2 
216       user_link = render_to_string :partial => "user", :object => @user2 
217     end 
218     
219     @title =  t 'note.mine.title', :user => @user2.display_name 
220     @heading =  t 'note.mine.heading', :user => @user2.display_name 
221     @description = t 'note.mine.description', :user => user_link
222     
223     @page = (params[:page] || 1).to_i 
224     @page_size = 10
225
226     @notes = Note.find(:all, 
227                        :include => [:comments, {:comments => :author}],
228                        :joins => :comments,
229                        :order => "updated_at DESC",
230                        :conditions => conditions,
231                        :offset => (@page - 1) * @page_size, 
232                        :limit => @page_size).uniq
233   end
234
235 private 
236   #------------------------------------------------------------ 
237   # utility functions below. 
238   #------------------------------------------------------------   
239  
240   ## 
241   # merge two conditions 
242   # TODO: this is a copy from changeset_controler.rb and should be factored out to share
243   def cond_merge(a, b) 
244     if a and b 
245       a_str = a.shift 
246       b_str = b.shift 
247       return [ a_str + " AND " + b_str ] + a + b 
248     elsif a  
249       return a 
250     else b 
251       return b 
252     end 
253   end 
254
255   def render_ok
256     output_js = :false
257     output_js = :true if params['format'] == "js"
258
259     if output_js == :true
260       render :text => "osbResponse();", :content_type => "text/javascript" 
261     else
262       render :text => "ok " + @note.id.to_s + "\n", :content_type => "text/html" if @note
263       render :text => "ok\n", :content_type => "text/html" unless @note
264     end
265   end
266
267   def getLimit
268     limit = 100
269     limit = params['limit'] if ((params['limit']) && (params['limit'].to_i < 10000) && (params['limit'].to_i > 0))
270     return limit
271   end
272
273   def closedCondition
274     closed_since = 7 unless params['closed']
275     closed_since = params['closed'].to_i if params['closed']
276         
277     if closed_since < 0
278       conditions = ["status != 'hidden'"]
279     elsif closed_since > 0
280       conditions = ["((status = 'open') OR ((status = 'closed' ) AND (closed_at > '" + (Time.now - closed_since.days).to_s + "')))"]
281     else
282       conditions = ["status = 'open'"]
283     end
284
285     return conditions
286   end
287
288   def add_comment(note, text, name, event) 
289     comment = note.comments.create(:visible => true, :event => event)
290     comment.body = text unless text == :nil
291     if @user  
292       comment.author_id = @user.id
293       comment.author_name = @user.display_name
294     else  
295       comment.author_ip = request.remote_ip
296       comment.author_name = name + " (a)"
297     end
298     comment.save 
299     note.save
300
301     sent_to = Set.new
302     note.comments.each do | cmt |
303       if cmt.author
304         unless sent_to.include?(cmt.author)
305           Notifier.deliver_note_comment_notification(note_comment, cmt.author) unless cmt.author == @user
306           sent_to.add(cmt.author)
307         end
308       end
309     end
310   end
311 end