diff options
Diffstat (limited to 'app/controllers')
-rw-r--r-- | app/controllers/admin_controller.rb | 5 | ||||
-rw-r--r-- | app/controllers/admin_general_controller.rb | 5 | ||||
-rw-r--r-- | app/controllers/admin_incoming_message_controller.rb | 80 | ||||
-rw-r--r-- | app/controllers/admin_outgoing_message_controller.rb | 47 | ||||
-rw-r--r-- | app/controllers/admin_public_body_controller.rb | 5 | ||||
-rw-r--r-- | app/controllers/admin_request_controller.rb | 85 | ||||
-rw-r--r-- | app/controllers/application_controller.rb | 24 | ||||
-rw-r--r-- | app/controllers/public_body_controller.rb | 182 | ||||
-rw-r--r-- | app/controllers/request_controller.rb | 162 |
9 files changed, 390 insertions, 205 deletions
diff --git a/app/controllers/admin_controller.rb b/app/controllers/admin_controller.rb index 0bccd3358..8b606ea85 100644 --- a/app/controllers/admin_controller.rb +++ b/app/controllers/admin_controller.rb @@ -17,7 +17,7 @@ class AdminController < ApplicationController end # Always give full stack trace for admin interface - def local_request? + def show_rails_exceptions? true end @@ -29,8 +29,7 @@ class AdminController < ApplicationController FileUtils.rm_rf(cache_subpath) # Remove any download zips - download_dir = request_download_zip_dir(info_request) - FileUtils.rm_rf(download_dir) + FileUtils.rm_rf(info_request.download_zip_dir) # Remove the database caches of body / attachment text (the attachment text # one is after privacy rules are applied) diff --git a/app/controllers/admin_general_controller.rb b/app/controllers/admin_general_controller.rb index ec5f95eda..196616ed6 100644 --- a/app/controllers/admin_general_controller.rb +++ b/app/controllers/admin_general_controller.rb @@ -5,7 +5,6 @@ # Email: hello@mysociety.org; WWW: http://www.mysociety.org/ class AdminGeneralController < AdminController - skip_before_filter :authenticate, :only => :admin_js def index # ensure we have a trailing slash @@ -142,9 +141,5 @@ class AdminGeneralController < AdminController @request_env = request.env end - # TODO: Remove this when support for proxy admin interface is removed - def admin_js - render :layout => false, :content_type => "application/javascript" - end end diff --git a/app/controllers/admin_incoming_message_controller.rb b/app/controllers/admin_incoming_message_controller.rb new file mode 100644 index 000000000..6b50d0e36 --- /dev/null +++ b/app/controllers/admin_incoming_message_controller.rb @@ -0,0 +1,80 @@ +class AdminIncomingMessageController < AdminController + + def edit + @incoming_message = IncomingMessage.find(params[:id]) + end + + def update + @incoming_message = IncomingMessage.find(params[:id]) + old_prominence = @incoming_message.prominence + old_prominence_reason = @incoming_message.prominence_reason + @incoming_message.prominence = params[:incoming_message][:prominence] + @incoming_message.prominence_reason = params[:incoming_message][:prominence_reason] + if @incoming_message.save + @incoming_message.info_request.log_event('edit_incoming', + :incoming_message_id => @incoming_message.id, + :editor => admin_current_user(), + :old_prominence => old_prominence, + :prominence => @incoming_message.prominence, + :old_prominence_reason => old_prominence_reason, + :prominence_reason => @incoming_message.prominence_reason) + expire_for_request(@incoming_message.info_request) + flash[:notice] = 'Incoming message successfully updated.' + redirect_to admin_request_show_url(@incoming_message.info_request) + else + render :action => 'edit' + end + end + + def destroy + @incoming_message = IncomingMessage.find(params[:incoming_message_id]) + @info_request = @incoming_message.info_request + incoming_message_id = @incoming_message.id + + @incoming_message.fully_destroy + @incoming_message.info_request.log_event("destroy_incoming", + { :editor => admin_current_user(), :deleted_incoming_message_id => incoming_message_id }) + # expire cached files + expire_for_request(@info_request) + flash[:notice] = 'Incoming message successfully destroyed.' + redirect_to admin_request_show_url(@info_request) + end + + def redeliver + incoming_message = IncomingMessage.find(params[:redeliver_incoming_message_id]) + message_ids = params[:url_title].split(",").each {|x| x.strip} + previous_request = incoming_message.info_request + destination_request = nil + ActiveRecord::Base.transaction do + for m in message_ids + if m.match(/^[0-9]+$/) + destination_request = InfoRequest.find_by_id(m.to_i) + else + destination_request = InfoRequest.find_by_url_title!(m) + end + if destination_request.nil? + flash[:error] = "Failed to find destination request '" + m + "'" + return redirect_to admin_request_show_url(previous_request) + end + + raw_email_data = incoming_message.raw_email.data + mail = MailHandler.mail_from_raw_email(raw_email_data) + destination_request.receive(mail, raw_email_data, true) + + incoming_message_id = incoming_message.id + incoming_message.info_request.log_event("redeliver_incoming", { + :editor => admin_current_user(), + :destination_request => destination_request.id, + :deleted_incoming_message_id => incoming_message_id + }) + + flash[:notice] = "Message has been moved to request(s). Showing the last one:" + end + # expire cached files + expire_for_request(previous_request) + incoming_message.fully_destroy + end + redirect_to admin_request_show_url(destination_request) + end + +end diff --git a/app/controllers/admin_outgoing_message_controller.rb b/app/controllers/admin_outgoing_message_controller.rb new file mode 100644 index 000000000..ec0981677 --- /dev/null +++ b/app/controllers/admin_outgoing_message_controller.rb @@ -0,0 +1,47 @@ +class AdminOutgoingMessageController < AdminController + + def edit + @outgoing_message = OutgoingMessage.find(params[:id]) + end + + def destroy + @outgoing_message = OutgoingMessage.find(params[:outgoing_message_id]) + @info_request = @outgoing_message.info_request + outgoing_message_id = @outgoing_message.id + + @outgoing_message.fully_destroy + @outgoing_message.info_request.log_event("destroy_outgoing", + { :editor => admin_current_user(), :deleted_outgoing_message_id => outgoing_message_id }) + + flash[:notice] = 'Outgoing message successfully destroyed.' + redirect_to admin_request_show_url(@info_request) + end + + def update + @outgoing_message = OutgoingMessage.find(params[:id]) + + old_body = @outgoing_message.body + old_prominence = @outgoing_message.prominence + old_prominence_reason = @outgoing_message.prominence_reason + @outgoing_message.prominence = params[:outgoing_message][:prominence] + @outgoing_message.prominence_reason = params[:outgoing_message][:prominence_reason] + @outgoing_message.body = params[:outgoing_message][:body] + if @outgoing_message.save + @outgoing_message.info_request.log_event("edit_outgoing", + { :outgoing_message_id => @outgoing_message.id, + :editor => admin_current_user(), + :old_body => old_body, + :body => @outgoing_message.body, + :old_prominence => old_prominence, + :old_prominence_reason => old_prominence_reason, + :prominence => @outgoing_message.prominence, + :prominence_reason => @outgoing_message.prominence_reason }) + flash[:notice] = 'Outgoing message successfully updated.' + expire_for_request(@outgoing_message.info_request) + redirect_to admin_request_show_url(@outgoing_message.info_request) + else + render :action => 'edit' + end + end + +end diff --git a/app/controllers/admin_public_body_controller.rb b/app/controllers/admin_public_body_controller.rb index ec2a08dbc..e0da234b0 100644 --- a/app/controllers/admin_public_body_controller.rb +++ b/app/controllers/admin_public_body_controller.rb @@ -14,6 +14,7 @@ class AdminPublicBodyController < AdminController def _lookup_query_internal @locale = self.locale_from_params() + underscore_locale = @locale.gsub '-', '_' I18n.with_locale(@locale) do @query = params[:query] if @query == "" @@ -23,10 +24,10 @@ class AdminPublicBodyController < AdminController if @page == "" @page = nil end - @public_bodies = PublicBody.joins(:translations).where(@query.nil? ? "public_body_translations.locale = '#{@locale}'" : + @public_bodies = PublicBody.joins(:translations).where(@query.nil? ? "public_body_translations.locale = '#{underscore_locale}'" : ["(lower(public_body_translations.name) like lower('%'||?||'%') or lower(public_body_translations.short_name) like lower('%'||?||'%') or - lower(public_body_translations.request_email) like lower('%'||?||'%' )) AND (public_body_translations.locale = '#{@locale}')", @query, @query, @query]).paginate :order => "public_body_translations.name", :page => @page, :per_page => 100 + lower(public_body_translations.request_email) like lower('%'||?||'%' )) AND (public_body_translations.locale = '#{underscore_locale}')", @query, @query, @query]).paginate :order => "public_body_translations.name", :page => @page, :per_page => 100 end @public_bodies_by_tag = PublicBody.find_by_tag(@query) end diff --git a/app/controllers/admin_request_controller.rb b/app/controllers/admin_request_controller.rb index 40ccfb98c..4d45ced8b 100644 --- a/app/controllers/admin_request_controller.rb +++ b/app/controllers/admin_request_controller.rb @@ -106,39 +106,6 @@ class AdminRequestController < AdminController redirect_to admin_request_list_url end - def edit_outgoing - @outgoing_message = OutgoingMessage.find(params[:id]) - end - - def destroy_outgoing - @outgoing_message = OutgoingMessage.find(params[:outgoing_message_id]) - @info_request = @outgoing_message.info_request - outgoing_message_id = @outgoing_message.id - - @outgoing_message.fully_destroy - @outgoing_message.info_request.log_event("destroy_outgoing", - { :editor => admin_current_user(), :deleted_outgoing_message_id => outgoing_message_id }) - - flash[:notice] = 'Outgoing message successfully destroyed.' - redirect_to admin_request_show_url(@info_request) - end - - def update_outgoing - @outgoing_message = OutgoingMessage.find(params[:id]) - - old_body = @outgoing_message.body - - if @outgoing_message.update_attributes(params[:outgoing_message]) - @outgoing_message.info_request.log_event("edit_outgoing", - { :outgoing_message_id => @outgoing_message.id, :editor => admin_current_user(), - :old_body => old_body, :body => @outgoing_message.body }) - flash[:notice] = 'Outgoing message successfully updated.' - redirect_to admin_request_show_url(@outgoing_message.info_request) - else - render :action => 'edit_outgoing' - end - end - def edit_comment @comment = Comment.find(params[:id]) end @@ -163,58 +130,6 @@ class AdminRequestController < AdminController end end - - def destroy_incoming - @incoming_message = IncomingMessage.find(params[:incoming_message_id]) - @info_request = @incoming_message.info_request - incoming_message_id = @incoming_message.id - - @incoming_message.fully_destroy - @incoming_message.info_request.log_event("destroy_incoming", - { :editor => admin_current_user(), :deleted_incoming_message_id => incoming_message_id }) - # expire cached files - expire_for_request(@info_request) - flash[:notice] = 'Incoming message successfully destroyed.' - redirect_to admin_request_show_url(@info_request) - end - - def redeliver_incoming - incoming_message = IncomingMessage.find(params[:redeliver_incoming_message_id]) - message_ids = params[:url_title].split(",").each {|x| x.strip} - previous_request = incoming_message.info_request - destination_request = nil - ActiveRecord::Base.transaction do - for m in message_ids - if m.match(/^[0-9]+$/) - destination_request = InfoRequest.find_by_id(m.to_i) - else - destination_request = InfoRequest.find_by_url_title!(m) - end - if destination_request.nil? - flash[:error] = "Failed to find destination request '" + m + "'" - return redirect_to admin_request_show_url(previous_request) - end - - raw_email_data = incoming_message.raw_email.data - mail = MailHandler.mail_from_raw_email(raw_email_data) - destination_request.receive(mail, raw_email_data, true) - - incoming_message_id = incoming_message.id - incoming_message.info_request.log_event("redeliver_incoming", { - :editor => admin_current_user(), - :destination_request => destination_request.id, - :deleted_incoming_message_id => incoming_message_id - }) - - flash[:notice] = "Message has been moved to request(s). Showing the last one:" - end - # expire cached files - expire_for_request(previous_request) - incoming_message.fully_destroy - end - redirect_to admin_request_show_url(destination_request) - end - # change user or public body of a request magically def move_request info_request = InfoRequest.find(params[:info_request_id]) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 88b107861..cbdffc441 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -119,12 +119,9 @@ class ApplicationController < ActionController::Base end def render_exception(exception) - - # In development, or the admin interface, or for a local request, let Rails handle the exception - # with its stack trace templates. Local requests in testing are a special case so that we can - # test this method - there we use consider_all_requests_local to control behaviour. - if Rails.application.config.consider_all_requests_local || local_request? || - (request.local? && !Rails.env.test?) + # In development or the admin interface let Rails handle the exception + # with its stack trace templates + if Rails.application.config.consider_all_requests_local || show_rails_exceptions? raise exception end @@ -150,7 +147,7 @@ class ApplicationController < ActionController::Base end end - def local_request? + def show_rails_exceptions? false end @@ -214,19 +211,6 @@ class ApplicationController < ActionController::Base end end - def request_dirs(info_request) - first_three_digits = info_request.id.to_s()[0..2] - File.join(first_three_digits.to_s, info_request.id.to_s) - end - - def request_download_zip_dir(info_request) - File.join(download_zip_dir, "download", request_dirs(info_request)) - end - - def download_zip_dir() - File.join(Rails.root, '/cache/zips/') - end - # get the local locale def locale_from_params(*args) if params[:show_locale] diff --git a/app/controllers/public_body_controller.rb b/app/controllers/public_body_controller.rb index 374866eda..02f0ceb19 100644 --- a/app/controllers/public_body_controller.rb +++ b/app/controllers/public_body_controller.rb @@ -6,6 +6,7 @@ # Email: hello@mysociety.org; WWW: http://www.mysociety.org/ require 'fastercsv' +require 'confidence_intervals' class PublicBodyController < ApplicationController # XXX tidy this up with better error messages, and a more standard infrastructure for the redirect to canonical URL @@ -85,34 +86,45 @@ class PublicBodyController < ApplicationController def list long_cache # XXX move some of these tag SQL queries into has_tag_string.rb - @query = "%#{params[:public_body_query].nil? ? "" : params[:public_body_query]}%" + + like_query = params[:public_body_query] + like_query = "" if like_query.nil? + like_query = "%#{like_query}%" + @tag = params[:tag] - @locale = self.locale_from_params() - default_locale = I18n.default_locale.to_s - locale_condition = "(upper(public_body_translations.name) LIKE upper(?) - OR upper(public_body_translations.notes) LIKE upper (?)) - AND public_body_translations.locale = ? - AND public_bodies.id <> #{PublicBody.internal_admin_body.id}" + + @locale = self.locale_from_params + underscore_locale = @locale.gsub '-', '_' + underscore_default_locale = I18n.default_locale.to_s.gsub '-', '_' + + where_condition = "public_bodies.id <> #{PublicBody.internal_admin_body.id}" + where_parameters = [] + + first_letter = false + + base_tag_condition = " AND (SELECT count(*) FROM has_tag_string_tags" \ + " WHERE has_tag_string_tags.model_id = public_bodies.id" \ + " AND has_tag_string_tags.model = 'PublicBody'" + + # Restrict the public bodies shown according to the tag + # parameter supplied in the URL: if @tag.nil? or @tag == "all" @tag = "all" - conditions = [locale_condition, @query, @query, default_locale] elsif @tag == 'other' category_list = PublicBodyCategories::get().tags().map{|c| "'"+c+"'"}.join(",") - conditions = [locale_condition + ' AND (select count(*) from has_tag_string_tags where has_tag_string_tags.model_id = public_bodies.id - and has_tag_string_tags.model = \'PublicBody\' - and has_tag_string_tags.name in (' + category_list + ')) = 0', @query, @query, default_locale] + where_condition += base_tag_condition + " AND has_tag_string_tags.name in (#{category_list})) = 0" elsif @tag.size == 1 @tag.upcase! - conditions = [locale_condition + ' AND public_body_translations.first_letter = ?', @query, @query, default_locale, @tag] + # The first letter queries have to be done on + # translations, so just indicate to add that later: + first_letter = true elsif @tag.include?(":") name, value = HasTagString::HasTagStringTag.split_tag_into_name_value(@tag) - conditions = [locale_condition + ' AND (select count(*) from has_tag_string_tags where has_tag_string_tags.model_id = public_bodies.id - and has_tag_string_tags.model = \'PublicBody\' - and has_tag_string_tags.name = ? and has_tag_string_tags.value = ?) > 0', @query, @query, default_locale, name, value] + where_condition += base_tag_condition + " AND has_tag_string_tags.name = ? AND has_tag_string_tags.value = ?) > 0" + where_parameters.concat [name, value] else - conditions = [locale_condition + ' AND (select count(*) from has_tag_string_tags where has_tag_string_tags.model_id = public_bodies.id - and has_tag_string_tags.model = \'PublicBody\' - and has_tag_string_tags.name = ?) > 0', @query, @query, default_locale, @tag] + where_condition += base_tag_condition + " AND has_tag_string_tags.name = ?) > 0" + where_parameters.concat [@tag] end if @tag == "all" @@ -127,10 +139,45 @@ class PublicBodyController < ApplicationController @description = _("in the category ‘{{category_name}}’", :category_name=>category_name) end end + I18n.with_locale(@locale) do - @public_bodies = PublicBody.where(conditions).joins(:translations).order("public_body_translations.name").paginate( - :page => params[:page], :per_page => 100 - ) + + if AlaveteliConfiguration::public_body_list_fallback_to_default_locale + # Unfortunately, when we might fall back to the + # default locale, this is a rather complex query: + query = %Q{ + SELECT public_bodies.*, COALESCE(current_locale.name, default_locale.name) AS display_name + FROM public_bodies + LEFT OUTER JOIN public_body_translations as current_locale + ON (public_bodies.id = current_locale.public_body_id + AND current_locale.locale = ? AND #{get_public_body_list_translated_condition 'current_locale', first_letter}) + LEFT OUTER JOIN public_body_translations as default_locale + ON (public_bodies.id = default_locale.public_body_id + AND default_locale.locale = ? AND #{get_public_body_list_translated_condition 'default_locale', first_letter}) + WHERE #{where_condition} AND COALESCE(current_locale.name, default_locale.name) IS NOT NULL + ORDER BY display_name} + sql = [query, underscore_locale, like_query, like_query] + sql.push @tag if first_letter + sql += [underscore_default_locale, like_query, like_query] + sql.push @tag if first_letter + sql += where_parameters + @public_bodies = PublicBody.paginate_by_sql( + sql, + :page => params[:page], + :per_page => 100) + else + # The simpler case where we're just searching in the current locale: + where_condition = get_public_body_list_translated_condition('public_body_translations', first_letter, true) + + ' AND ' + where_condition + where_sql = [where_condition, like_query, like_query] + where_sql.push @tag if first_letter + where_sql += [underscore_locale] + where_parameters + @public_bodies = PublicBody.where(where_sql) \ + .joins(:translations) \ + .order("public_body_translations.name") \ + .paginate(:page => params[:page], :per_page => 100) + end + respond_to do |format| format.html { render :template => "public_body/list" } end @@ -149,6 +196,84 @@ class PublicBodyController < ApplicationController :disposition =>'attachment', :encoding => 'utf8') end + def statistics + unless AlaveteliConfiguration::public_body_statistics_page + raise ActiveRecord::RecordNotFound.new("Page not enabled") + end + + per_graph = 8 + minimum_requests = AlaveteliConfiguration::minimum_requests_for_statistics + # Make sure minimum_requests is > 0 to avoid division-by-zero + minimum_requests = [minimum_requests, 1].max + total_column = 'info_requests_count' + + @graph_list = [] + + [[total_column, + [{ + :title => _('Public bodies with the most requests'), + :y_axis => _('Number of requests'), + :highest => true}]], + ['info_requests_successful_count', + [{ + :title => _('Public bodies with the most successful requests'), + :y_axis => _('Percentage of total requests'), + :highest => true}, + { + :title => _('Public bodies with the fewest successful requests'), + :y_axis => _('Percentage of total requests'), + :highest => false}]], + ['info_requests_overdue_count', + [{ + :title => _('Public bodies with most overdue requests'), + :y_axis => _('Percentage of requests that are overdue'), + :highest => true}]], + ['info_requests_not_held_count', + [{ + :title => _('Public bodies that most frequently replied with "Not Held"'), + :y_axis => _('Percentage of total requests'), + :highest => true}]]].each do |column, graphs_properties| + + graphs_properties.each do |graph_properties| + + percentages = (column != total_column) + highest = graph_properties[:highest] + + data = nil + if percentages + data = PublicBody.get_request_percentages(column, + per_graph, + highest, + minimum_requests) + else + data = PublicBody.get_request_totals(per_graph, + highest, + minimum_requests) + end + + data_to_draw = { + 'id' => "#{column}-#{highest ? 'highest' : 'lowest'}", + 'x_axis' => _('Public Bodies'), + 'y_axis' => graph_properties[:y_axis], + 'errorbars' => percentages, + 'title' => graph_properties[:title]} + + if data + data_to_draw.update(data) + data_to_draw['x_values'] = data['public_bodies'].each_with_index.map { |pb, i| i } + data_to_draw['x_ticks'] = data['public_bodies'].each_with_index.map { |pb, i| [i, pb.name] } + end + + @graph_list.push data_to_draw + end + end + + respond_to do |format| + format.html { render :template => "public_body/statistics" } + format.json { render :json => @graph_list } + end + end + # Type ahead search def search_typeahead # Since acts_as_xapian doesn't support the Partial match flag, we work around it @@ -157,5 +282,18 @@ class PublicBodyController < ApplicationController @xapian_requests = perform_search_typeahead(query, PublicBody) render :partial => "public_body/search_ahead" end -end + private + def get_public_body_list_translated_condition(table, first_letter=false, locale=nil) + result = "(upper(#{table}.name) LIKE upper(?)" \ + " OR upper(#{table}.notes) LIKE upper (?))" + if first_letter + result += " AND #{table}.first_letter = ?" + end + if locale + result += " AND #{table}.locale = ?" + end + result + end + +end diff --git a/app/controllers/request_controller.rb b/app/controllers/request_controller.rb index 45d8b7de6..388473b51 100644 --- a/app/controllers/request_controller.rb +++ b/app/controllers/request_controller.rb @@ -63,26 +63,24 @@ class RequestController < ApplicationController # Look up by new style text names @info_request = InfoRequest.find_by_url_title!(params[:url_title]) - set_last_request(@info_request) # Test for whole request being hidden if !@info_request.user_can_view?(authenticated_user) return render_hidden end - # Other parameters - @info_request_events = @info_request.info_request_events - @status = @info_request.calculate_status - @collapse_quotes = params[:unfold] ? false : true + set_last_request(@info_request) + # assign variables from request parameters + @collapse_quotes = params[:unfold] ? false : true # Don't allow status update on external requests, otherwise accept param if @info_request.is_external? @update_status = false else @update_status = params[:update_status] ? true : false end - @old_unclassified = @info_request.is_old_unclassified? && !authenticated_user.nil? - @is_owning_user = @info_request.is_owning_user?(authenticated_user) + + assign_variables_for_show_template(@info_request) if @update_status return if !@is_owning_user && !authenticated_as_user?(@info_request.user, @@ -92,11 +90,8 @@ class RequestController < ApplicationController ) end - - @last_info_request_event_id = @info_request.last_event_id_needing_description - @new_responses_count = @info_request.events_needing_description.select {|i| i.event_type == 'response'}.size - # Sidebar stuff + @sidebar = true # ... requests that have similar imporant terms begin limit = 10 @@ -106,13 +101,11 @@ class RequestController < ApplicationController rescue @xapian_similar = nil end - # Track corresponding to this page @track_thing = TrackThing.create_track_for_request(@info_request) @feed_autodetect = [ { :url => do_track_url(@track_thing, 'feed'), :title => @track_thing.params[:title_in_rss], :has_json => true } ] - # For send followup link at bottom - @last_response = @info_request.get_last_response + respond_to do |format| format.html { @has_json = true; render :template => 'request/show'} format.json { render :json => @info_request.json_for_api(true) } @@ -304,7 +297,7 @@ class RequestController < ApplicationController # We don't want the error "Outgoing messages is invalid", as in this # case the list of errors will also contain a more specific error # describing the reason it is invalid. - @info_request.errors.delete("outgoing_messages") + @info_request.errors.delete(:outgoing_messages) render :action => 'new' return @@ -683,9 +676,13 @@ class RequestController < ApplicationController @info_request = incoming_message.info_request # used by view return render_hidden end + if !incoming_message.user_can_view?(authenticated_user) + @incoming_message = incoming_message # used by view + return render_hidden_message + end # Is this a completely public request that we can cache attachments for # to be served up without authentication? - if incoming_message.info_request.all_can_view? + if incoming_message.info_request.all_can_view? && incoming_message.all_can_view? @files_can_be_cached = true end end @@ -871,10 +868,6 @@ class RequestController < ApplicationController @locale = self.locale_from_params() I18n.with_locale(@locale) do @info_request = InfoRequest.find_by_url_title!(params[:url_title]) - # Test for whole request being hidden or requester-only - if !@info_request.all_can_view? - return render_hidden - end if authenticated?( :web => _("To download the zip file"), :email => _("Then you can download a zip file of {{info_request_title}}.", @@ -882,54 +875,17 @@ class RequestController < ApplicationController :email_subject => _("Log in to download a zip file of {{info_request_title}}", :info_request_title=>@info_request.title) ) - updated = Digest::SHA1.hexdigest(@info_request.info_request_events.last.created_at.to_i.to_s + @info_request.updated_at.to_i.to_s) - @url_path = File.join("/download", - request_dirs(@info_request), - updated, - "#{params[:url_title]}.zip") - file_path = File.expand_path(File.join(download_zip_dir(), @url_path)) - if !File.exists?(file_path) - FileUtils.mkdir_p(File.dirname(file_path)) - Zip::ZipFile.open(file_path, Zip::ZipFile::CREATE) { |zipfile| - convert_command = AlaveteliConfiguration::html_to_pdf_command - done = false - if !convert_command.blank? && File.exists?(convert_command) - url = "http://#{AlaveteliConfiguration::domain}#{request_path(@info_request)}?print_stylesheet=1" - tempfile = Tempfile.new('foihtml2pdf') - output = AlaveteliExternalCommand.run(convert_command, url, tempfile.path) - if !output.nil? - zipfile.get_output_stream("correspondence.pdf") { |f| - f.puts(File.open(tempfile.path).read) - } - done = true - else - logger.error("Could not convert info request #{@info_request.id} to PDF with command '#{convert_command} #{url} #{tempfile.path}'") - end - tempfile.close - else - logger.warn("No HTML -> PDF converter found at #{convert_command}") - end - if !done - @info_request_events = @info_request.info_request_events - template = File.read(File.join(File.dirname(__FILE__), "..", "views", "request", "simple_correspondence.html.erb")) - output = ERB.new(template).result(binding) - zipfile.get_output_stream("correspondence.txt") { |f| - f.puts(output) - } - end - for message in @info_request.incoming_messages - attachments = message.get_attachments_for_display - for attachment in attachments - filename = "#{attachment.url_part_number}_#{attachment.display_filename}" - zipfile.get_output_stream(filename) { |f| - f.puts(attachment.body) - } - end - end - } - File.chmod(0644, file_path) + # Test for whole request being hidden or requester-only + if !@info_request.user_can_view?(@user) + return render_hidden + end + cache_file_path = @info_request.make_zip_cache_path(@user) + if !File.exists?(cache_file_path) + FileUtils.mkdir_p(File.dirname(cache_file_path)) + make_request_zip(@info_request, cache_file_path) + File.chmod(0644, cache_file_path) end - redirect_to @url_path + send_file(cache_file_path, :filename => "#{@info_request.url_title}.zip") end end end @@ -938,12 +894,82 @@ class RequestController < ApplicationController def render_hidden respond_to do |format| - response_code = 410 # gone + response_code = 403 # forbidden format.html{ render :template => 'request/hidden', :status => response_code } format.any{ render :nothing => true, :status => response_code } end false end + def render_hidden_message + respond_to do |format| + response_code = 403 # forbidden + format.html{ render :template => 'request/hidden_correspondence', :status => response_code } + format.any{ render :nothing => true, :status => response_code } + end + false + end + + def assign_variables_for_show_template(info_request) + @info_request = info_request + @info_request_events = info_request.info_request_events + @status = info_request.calculate_status + @old_unclassified = info_request.is_old_unclassified? && !authenticated_user.nil? + @is_owning_user = info_request.is_owning_user?(authenticated_user) + @last_info_request_event_id = info_request.last_event_id_needing_description + @new_responses_count = info_request.events_needing_description.select {|i| i.event_type == 'response'}.size + # For send followup link at bottom + @last_response = info_request.get_last_public_response + end + + def make_request_zip(info_request, file_path) + Zip::ZipFile.open(file_path, Zip::ZipFile::CREATE) do |zipfile| + file_info = make_request_summary_file(info_request) + zipfile.get_output_stream(file_info[:filename]) { |f| f.puts(file_info[:data]) } + message_index = 0 + info_request.incoming_messages.each do |message| + next unless message.user_can_view?(authenticated_user) + message_index += 1 + message.get_attachments_for_display.each do |attachment| + filename = "#{message_index}_#{attachment.url_part_number}_#{attachment.display_filename}" + zipfile.get_output_stream(filename) { |f| f.puts(attachment.body) } + end + end + end + end + + def make_request_summary_file(info_request) + done = false + convert_command = AlaveteliConfiguration::html_to_pdf_command + assign_variables_for_show_template(info_request) + if !convert_command.blank? && File.exists?(convert_command) + @render_to_file = true + html_output = render_to_string(:template => 'request/show') + tmp_input = Tempfile.new(['foihtml2pdf-input', '.html']) + tmp_input.write(html_output) + tmp_input.close + tmp_output = Tempfile.new('foihtml2pdf-output') + output = AlaveteliExternalCommand.run(convert_command, tmp_input.path, tmp_output.path) + if !output.nil? + file_info = { :filename => 'correspondence.pdf', + :data => File.open(tmp_output.path).read } + done = true + else + logger.error("Could not convert info request #{info_request.id} to PDF with command '#{convert_command} #{tmp_input.path} #{tmp_output.path}'") + end + tmp_output.close + tmp_input.delete + tmp_output.delete + else + logger.warn("No HTML -> PDF converter found at #{convert_command}") + end + if !done + file_info = { :filename => 'correspondence.txt', + :data => render_to_string(:template => 'request/show.text', + :layout => false) } + end + file_info + end + end |