diff options
Diffstat (limited to 'app/controllers')
-rw-r--r-- | app/controllers/admin_public_body_controller.rb | 59 | ||||
-rw-r--r-- | app/controllers/admin_user_controller.rb | 12 | ||||
-rw-r--r-- | app/controllers/application_controller.rb | 48 | ||||
-rw-r--r-- | app/controllers/general_controller.rb | 33 | ||||
-rw-r--r-- | app/controllers/public_body_controller.rb | 28 | ||||
-rw-r--r-- | app/controllers/request_controller.rb | 109 | ||||
-rw-r--r-- | app/controllers/services_controller.rb | 32 | ||||
-rw-r--r-- | app/controllers/user_controller.rb | 31 |
8 files changed, 287 insertions, 65 deletions
diff --git a/app/controllers/admin_public_body_controller.rb b/app/controllers/admin_public_body_controller.rb index bd85f6eed..e249cef11 100644 --- a/app/controllers/admin_public_body_controller.rb +++ b/app/controllers/admin_public_body_controller.rb @@ -6,6 +6,8 @@ # # $Id: admin_public_body_controller.rb,v 1.23 2009-08-26 00:58:29 francis Exp $ +require "public_body_categories" + class AdminPublicBodyController < AdminController def index list @@ -138,41 +140,36 @@ class AdminPublicBodyController < AdminController def import_csv if params[:csv_file] - if !params[:tag].empty? - if params['commit'] == 'Dry run' - dry_run_only = true - elsif params['commit'] == 'Upload' - dry_run_only = false + if params['commit'] == 'Dry run' + dry_run_only = true + elsif params['commit'] == 'Upload' + dry_run_only = false + else + raise "internal error, unknown button label" + end + + # Try with dry run first + csv_contents = params[:csv_file].read + en = PublicBody.import_csv(csv_contents, params[:tag], params[:tag_behaviour], true, admin_http_auth_user(), I18n.available_locales) + errors = en[0] + notes = en[1] + + if errors.size == 0 + if dry_run_only + notes.push("Dry run was successful, real run would do as above.") else - raise "internal error, unknown button label" - end - - # Try with dry run first - csv_contents = params[:csv_file].read - en = PublicBody.import_csv(csv_contents, params[:tag], true, admin_http_auth_user(), available_locales) - errors = en[0] - notes = en[1] - - if errors.size == 0 - if dry_run_only - notes.push("Dry run was successful, real run would do as above.") - else - # And if OK, with real run - en = PublicBody.import_csv(csv_contents, params[:tag], false, admin_http_auth_user(), I18n.available_locales) - errors = en[0] - notes = en[1] - if errors.size != 0 - raise "dry run mismatched real run" - end - notes.push("Import was successful.") + # And if OK, with real run + en = PublicBody.import_csv(csv_contents, params[:tag], params[:tag_behaviour], false, admin_http_auth_user(), I18n.available_locales) + errors = en[0] + notes = en[1] + if errors.size != 0 + raise "dry run mismatched real run" end + notes.push("Import was successful.") end - @errors = errors.join("\n") - @notes = notes.join("\n") - else - @errors = "Please enter a tag, use a singular e.g. sea_fishery_committee" - @notes = "" end + @errors = errors.join("\n") + @notes = notes.join("\n") else @errors = "" @notes = "" diff --git a/app/controllers/admin_user_controller.rb b/app/controllers/admin_user_controller.rb index 404c4c3fe..5d90e74fe 100644 --- a/app/controllers/admin_user_controller.rb +++ b/app/controllers/admin_user_controller.rb @@ -28,6 +28,10 @@ class AdminUserController < AdminController # Don't use @user as that is any logged in user @admin_user = User.find(params[:id]) end + + def show_bounce_message + @admin_user = User.find(params[:id]) + end def edit @admin_user = User.find(params[:id]) @@ -57,6 +61,14 @@ class AdminUserController < AdminController flash[:notice] = 'Track destroyed' redirect_to user_admin_url(track_thing.tracking_user) end + + def clear_bounce + user = User.find(params[:id]) + user.email_bounced_at = nil + user.email_bounce_message = "" + user.save! + redirect_to user_admin_url(user) + end def login_as @admin_user = User.find(params[:id]) # check user does exist diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 6d14d0d7a..239145944 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -14,8 +14,14 @@ class ApplicationController < ActionController::Base # Standard headers, footers and navigation for whole site layout "default" include FastGettext::Translation # make functions like _, n_, N_ etc available) + + # Note: a filter stops the chain if it redirects or renders something + before_filter :authentication_check before_filter :set_gettext_locale + before_filter :check_in_post_redirect + before_filter :session_remember_me before_filter :set_vary_header + # scrub sensitive parameters from the logs filter_parameter_logging :password @@ -48,7 +54,14 @@ class ApplicationController < ActionController::Base else requested_locale = params[:locale] || session[:locale] || cookies[:locale] || I18n.default_locale end + requested_locale = FastGettext.best_locale_in(requested_locale) session[:locale] = FastGettext.set_locale(requested_locale) + if !@user.nil? + if @user.locale != requested_locale + @user.locale = session[:locale] + @user.save! + end + end end # scrub sensitive parameters from the logs @@ -85,7 +98,6 @@ class ApplicationController < ActionController::Base # Set cookie expiry according to "remember me" checkbox, as per "An easier # and more flexible hack" on this page: # http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions - before_filter :session_remember_me def session_remember_me # Reset the "sliding window" session expiry time. if request.env['rack.session.options'] @@ -199,7 +211,9 @@ class ApplicationController < ActionController::Base post_redirect = PostRedirect.new(:uri => request.request_uri, :post_params => params, :reason_params => reason_params) post_redirect.save! - redirect_to signin_url(:token => post_redirect.token) + # 'modal' controls whether the sign-in form will be displayed in the typical full-blown + # page or on its own, useful for pop-ups + redirect_to signin_url(:token => post_redirect.token, :modal => params[:modal]) return false end return true @@ -263,7 +277,6 @@ class ApplicationController < ActionController::Base end # If we are in a faked redirect to POST request, then set post params. - before_filter :check_in_post_redirect def check_in_post_redirect if params[:post_redirect] and session[:post_redirect_token] post_redirect = PostRedirect.find_by_token(session[:post_redirect_token]) @@ -272,7 +285,6 @@ class ApplicationController < ActionController::Base end # Default layout shows user in corner, so needs access to it - before_filter :authentication_check def authentication_check if session[:user_id] @user = authenticated_user @@ -346,14 +358,18 @@ class ApplicationController < ActionController::Base return (params[:page] || "1").to_i end - # Store last visited pages, for contact form + # Store last visited pages, for contact form; but only for logged in users, as otherwise this breaks caching def set_last_request(info_request) - session[:last_request_id] = info_request.id - session[:last_body_id] = nil + if !session[:user_id].nil? + session[:last_request_id] = info_request.id + session[:last_body_id] = nil + end end def set_last_body(public_body) - session[:last_request_id] = nil - session[:last_body_id] = public_body.id + if !session[:user_id].nil? + session[:last_request_id] = nil + session[:last_body_id] = public_body.id + end end def param_exists(item) @@ -472,6 +488,20 @@ class ApplicationController < ActionController::Base # Site-wide access to configuration settings include ConfigHelper + + # XXX: patch to improve usability of gettext's _(), which by default accepts only + # one parameter. This is normally done in a monkey patch file named 'i18n_fixes.rb'. + # For some reason - and only when running in production -, after adding a new controller + # in a theme, the monkey patch in 'i18n_fixes.rb' doesn't seem to take effect. + # But it works just fine in the views. + # It's probably related to the loading order of classes, but including the + # monkey patch before or after the theme makes no difference. Even more bizarrely, + # require'ing or load'ing the patch file here doesn't work (!?), I need to redefine + # the method explicitely. I'm going crazy... + def _(key, options = {}) + translation = FastGettext._(key) || key + gettext_interpolate(translation, options) + end end diff --git a/app/controllers/general_controller.rb b/app/controllers/general_controller.rb index 1ddf3acff..55abea3b7 100644 --- a/app/controllers/general_controller.rb +++ b/app/controllers/general_controller.rb @@ -50,11 +50,18 @@ class GeneralController < ApplicationController query = 'variety:response (status:successful OR status:partially_successful)' # query = 'variety:response' # XXX debug sortby = "described" - xapian_object = perform_search([InfoRequestEvent], query, sortby, 'request_title_collapse', 8) - @successful_request_events = xapian_object.results.map { |r| r[:model] } - @successful_request_events = @successful_request_events.sort_by { |e| e.described_at }.reverse + max_count = 5 + xapian_object = perform_search([InfoRequestEvent], query, sortby, 'request_title_collapse', max_count) + @request_events = xapian_object.results.map { |r| r[:model] } + @request_events = @request_events.sort_by { |e| e.described_at }.reverse + if @request_events.count < max_count + query = 'variety:sent' + xapian_object = perform_search([InfoRequestEvent], query, sortby, 'request_title_collapse', max_count-@request_events.count) + more_events = xapian_object.results.map { |r| r[:model] } + @request_events += more_events.sort_by { |e| e.described_at }.reverse + end rescue - @successful_request_events = [] + @request_events = [] end end end @@ -91,8 +98,8 @@ class GeneralController < ApplicationController if path.size > 0 && (['bodies', 'requests', 'users', 'all'].include?(path[-1])) @variety_postfix = path.pop end - @variety_postfix = params[:bodies] if @variety_postfix.nil? && !params[:bodies].nil? - @variety_postfix = "all" if @variety_postfix.nil? + @variety_postfix = "bodies" if @variety_postfix.nil? && !params[:bodies].nil? + @variety_postfix = "requests" if @variety_postfix.nil? if @variety_postfix != "users" @common_query = get_tags_from_params end @@ -118,7 +125,7 @@ class GeneralController < ApplicationController return end [:latest_status, :request_variety, :request_date_after, :request_date_before, :query, :tags].each do |x| - params[x] = session[x] + params[x] = session[x] if params[x].nil? end combined = params[:combined] @sortby = nil @@ -135,7 +142,9 @@ class GeneralController < ApplicationController @sort_postfix = combined.pop @sortby = @sort_postfix end - + if !params[:view].nil? + combined += [params[:view]] + end if combined.size > 0 && (['bodies', 'requests', 'users', 'all'].include?(combined[-1])) @variety_postfix = combined.pop case @variety_postfix @@ -151,9 +160,17 @@ class GeneralController < ApplicationController @bodies = false @requests = false @users = true + else + @variety_postfix = "all" end end @query = combined.join("/") + if params[:query].nil? + params[:query] = @query + end + if @variety_postfix != "all" && @requests + @query, _ = make_query_from_params + end @inputted_sortby = @sortby @common_query = get_tags_from_params if @sortby.nil? diff --git a/app/controllers/public_body_controller.rb b/app/controllers/public_body_controller.rb index ce70e1ab0..e4f8753af 100644 --- a/app/controllers/public_body_controller.rb +++ b/app/controllers/public_body_controller.rb @@ -90,12 +90,16 @@ class PublicBodyController < ApplicationController @query = "%#{params[:public_body_query].nil? ? "" : params[:public_body_query]}%" @tag = params[:tag] @locale = self.locale_from_params() - locale_condition = "(upper(public_body_translations.name) LIKE upper(?) OR upper(public_body_translations.notes) LIKE upper (?)) AND public_body_translations.locale = ?" + + 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}" if @tag.nil? or @tag == "all" @tag = "all" conditions = [locale_condition, @query, @query, @locale] elsif @tag == 'other' - category_list = PublicBodyCategories::CATEGORIES.map{|c| "'"+c+"'"}.join(",") + 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, @locale] @@ -112,15 +116,17 @@ class PublicBodyController < ApplicationController and has_tag_string_tags.model = \'PublicBody\' and has_tag_string_tags.name = ?) > 0', @query, @query, @locale, @tag] end - if @tag.size == 1 + if @tag == "all" + @description = "" + elsif @tag.size == 1 @description = _("beginning with") + " '" + @tag + "'" else - @description = PublicBodyCategories::CATEGORIES_BY_TAG[@tag] + @description = PublicBodyCategories::get().by_tag()[@tag] if @description.nil? @description = @tag end end - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do @public_bodies = PublicBody.paginate( :order => "public_body_translations.name", :page => params[:page], :per_page => 1000, # fit all councils on one page :conditions => conditions, @@ -173,5 +179,17 @@ class PublicBodyController < ApplicationController :filename => 'all-authorities.csv', :disposition =>'attachment', :encoding => 'utf8') end + + # Type ahead search + def search_typeahead + # Since acts_as_xapian doesn't support the Partial match flag, we work around it + # by making the last work a wildcard, which is quite the same + query = params[:q] + '*' + + query = query.split(' ').join(' OR ') # XXX: HACK for OR instead of default AND! + @xapian_requests = perform_search([PublicBody], query, 'relevant', 'request_collapse', 5) + + render :partial => "public_body/search_ahead" + end end diff --git a/app/controllers/request_controller.rb b/app/controllers/request_controller.rb index a76418e4e..06d8f15f4 100644 --- a/app/controllers/request_controller.rb +++ b/app/controllers/request_controller.rb @@ -7,6 +7,8 @@ # $Id: request_controller.rb,v 1.192 2009-10-19 19:26:40 francis Exp $ require 'alaveteli_file_types' +require 'zip/zip' +require 'open-uri' class RequestController < ApplicationController before_filter :check_read_only, :only => [ :new, :show_response, :describe_state, :upload_response ] @@ -22,6 +24,26 @@ class RequestController < ApplicationController rescue MissingSourceFile, NameError end + def select_authority + # Check whether we force the user to sign in right at the start, or we allow her + # to start filling the request anonymously + if force_registration_on_new_request && !authenticated?( + :web => _("To send your FOI request"), + :email => _("Then you'll be allowed to send FOI requests."), + :email_subject => _("Confirm your email address") + ) + # do nothing - as "authenticated?" has done the redirect to signin page for us + return + end + + if !params[:query].nil? + query = params[:query] + '*' + query = query.split(' ').join(' OR ') # XXX: HACK for OR instead of default AND! + @xapian_requests = perform_search([PublicBody], query, 'relevant', 'request_collapse', 5) + end + medium_cache + end + def show medium_cache @locale = self.locale_from_params() @@ -52,7 +74,6 @@ class RequestController < ApplicationController @status = @info_request.calculate_status @collapse_quotes = params[:unfold] ? false : true @update_status = params[:update_status] ? true : false - @is_owning_user = @info_request.is_owning_user?(authenticated_user) @old_unclassified = @info_request.is_old_unclassified? && !authenticated_user.nil? if @update_status @@ -66,7 +87,7 @@ class RequestController < ApplicationController @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 -1 + # Sidebar stuff # ... requests that have similar imporant terms behavior_cache :tag => ['similar', @info_request.id] do @@ -86,7 +107,7 @@ class RequestController < ApplicationController # For send followup link at bottom @last_response = @info_request.get_last_response - + @is_owning_user = @info_request.is_owning_user?(authenticated_user) respond_to do |format| format.html { @has_json = true; render :template => 'request/show'} format.json { render :json => @info_request.json_for_api(true) } @@ -131,10 +152,9 @@ class RequestController < ApplicationController @view = params[:view] params[:latest_status] = @view query = make_query_from_params - @title = "View and search requests" + @title = _("View and search requests") sortby = "newest" @page = get_search_page_from_params if !@page # used in cache case, as perform_search sets @page as side effect - behavior_cache :tag => [@view, @page] do xapian_object = perform_search([InfoRequestEvent], query, sortby, 'request_collapse') @list_results = xapian_object.results.map { |r| r[:model] } @@ -142,9 +162,8 @@ class RequestController < ApplicationController end @title = @title + " (page " + @page.to_s + ")" if (@page > 1) - - # XXX need to reinstate the following; @track_thing had previously been set to "TrackThing.create_track_for_all_new_requests" and "TrackThing.create_track_for_all_successful_requests" - # @feed_autodetect = [ { :url => do_track_url(@track_thing, 'feed'), :title => @track_thing.params[:title_in_rss], :has_json => true } ] + @track_thing = TrackThing.create_track_for_search_query(query) + @feed_autodetect = [ { :url => do_track_url(@track_thing, 'feed'), :title => @track_thing.params[:title_in_rss], :has_json => true } ] # Don't let robots go more than 20 pages in if @page > 20 @@ -729,5 +748,79 @@ class RequestController < ApplicationController return end end + + # Type ahead search + def search_typeahead + # Since acts_as_xapian doesn't support the Partial match flag, we work around it + # by making the last work a wildcard, which is quite the same + query = params[:q] + '*' + + query = query.split(' ').join(' OR ') # XXX: HACK for OR instead of default AND! + @xapian_requests = perform_search([InfoRequestEvent], query, 'relevant', 'request_collapse', 5) + + render :partial => "request/search_ahead.rhtml" + end + + def download_entire_request + @locale = self.locale_from_params() + PublicBody.with_locale(@locale) do + info_request = InfoRequest.find_by_url_title(params[:url_title]) + if info_request.nil? + raise ActiveRecord::RecordNotFound.new("Request not found") + end + if authenticated?( + :web => _("To download the zip file"), + :email => _("Then you can download a zip file of {{info_request_title}}.",:info_request_title=>info_request.title), + :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.get_last_event.created_at.to_s + info_request.updated_at.to_s) + @url_path = "/download/#{updated[0..1]}/#{updated}/#{params[:url_title]}.zip" + file_path = File.join(File.dirname(__FILE__), '../../cache/zips', @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 = MySociety::Config.get("HTML_TO_PDF_COMMAND") + done = false + if File.exists?(convert_command) + domain = MySociety::Config.get("DOMAIN") + url = "http://#{domain}#{request_url(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 = info_request + @info_request_events = info_request.info_request_events + template = File.read(File.join(File.dirname(__FILE__), "..", "views", "request", "simple_correspondence.rhtml")) + 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 + zipfile.get_output_stream(attachment.display_filename) { |f| + f.puts(attachment.body) + } + end + end + } + File.chmod(0644, file_path) + end + redirect_to @url_path + end + end + end end diff --git a/app/controllers/services_controller.rb b/app/controllers/services_controller.rb new file mode 100644 index 000000000..6fb20336e --- /dev/null +++ b/app/controllers/services_controller.rb @@ -0,0 +1,32 @@ +# controllers/application.rb: +# Parent class of all controllers in FOI site. Filters added to this controller +# apply to all controllers in the application. Likewise, all the methods added +# will be available for all controllers. +# +# Copyright (c) 2007 UK Citizens Online Democracy. All rights reserved. +# Email: francis@mysociety.org; WWW: http://www.mysociety.org/ +# +# $Id: application.rb,v 1.59 2009-09-17 13:01:56 francis Exp $ + +require 'open-uri' + +class ServicesController < ApplicationController + def other_country_message + text = "" + iso_country_code = MySociety::Config.get('ISO_COUNTRY_CODE').downcase + if country_from_ip.downcase != iso_country_code + found_country = WorldFOIWebsites.by_code(country_from_ip) + found_country_name = !found_country.nil? && found_country[:country_name] + if found_country_name + text = _("Hello! You can make Freedom of Information requests within {{country_name}} at {{link_to_website}}", :country_name => found_country_name, :link_to_website => "<a href=\"#{found_country[:url]}\">#{found_country[:name]}</a>") + else + current_country = WorldFOIWebsites.by_code(iso_country_code)[:country_name] + text = _("Hello! We have an <a href=\"/help/alaveteli?country_name=#{CGI.escape(current_country)}\">important message</a> for visitors outside {{country_name}}", :country_name => current_country) + end + end + if !text.empty? + text += ' <span class="close-button">X</span>' + end + render :text => text, :content_type => "text/plain" # XXX workaround the HTML validation in test suite + end +end diff --git a/app/controllers/user_controller.rb b/app/controllers/user_controller.rb index 6916b4456..96dbfba74 100644 --- a/app/controllers/user_controller.rb +++ b/app/controllers/user_controller.rb @@ -8,6 +8,8 @@ class UserController < ApplicationController + layout :select_layout + protect_from_forgery :only => [ :contact, :set_profile_photo, :signchangeemail, @@ -33,9 +35,16 @@ class UserController < ApplicationController # Use search query for this so can collapse and paginate easily # XXX really should just use SQL query here rather than Xapian. begin - @xapian_requests = perform_search([InfoRequestEvent], 'requested_by:' + @display_user.url_name, 'newest', 'request_collapse') - @xapian_comments = perform_search([InfoRequestEvent], 'commented_by:' + @display_user.url_name, 'newest', nil) - + requests_query = 'requested_by:' + @display_user.url_name + comments_query = 'commented_by:' + @display_user.url_name + if !params[:user_query].nil? + requests_query += " " + params[:user_query] + comments_query += " " + params[:user_query] + @match_phrase = _("{{search_results}} matching '{{query}}'", :search_results => "", :query => params[:user_query]) + end + @xapian_requests = perform_search([InfoRequestEvent], requests_query, 'newest', 'request_collapse') + @xapian_comments = perform_search([InfoRequestEvent], comments_query, 'newest', nil) + if (@page > 1) @page_desc = " (page " + @page.to_s + ")" else @@ -106,7 +115,12 @@ class UserController < ApplicationController session[:user_id] = @user_signin.id session[:user_circumstance] = nil session[:remember_me] = params[:remember_me] ? true : false - do_post_redirect @post_redirect + + if is_modal_dialog + render :action => 'signin_successful' + else + do_post_redirect @post_redirect + end else send_confirmation_mail @user_signin end @@ -504,6 +518,15 @@ class UserController < ApplicationController private + def is_modal_dialog + (params[:modal].to_i != 0) + end + + # when logging in through a modal iframe, don't display chrome around the content + def select_layout + is_modal_dialog ? 'no_chrome' : 'default' + end + # Decide where we are going to redirect back to after signin/signup, and record that def work_out_post_redirect # Redirect to front page later if nothing else specified |