diff options
44 files changed, 430 insertions, 418 deletions
diff --git a/.gitignore b/.gitignore index 1155b055d..258ea5a17 100644 --- a/.gitignore +++ b/.gitignore @@ -19,4 +19,5 @@ TAGS /public/*theme /vendor/bundle .bundle -bin/
\ No newline at end of file +bin/ +config/aliases diff --git a/app/controllers/admin_censor_rule_controller.rb b/app/controllers/admin_censor_rule_controller.rb index 2c0c7ca4e..52df8dfc1 100644 --- a/app/controllers/admin_censor_rule_controller.rb +++ b/app/controllers/admin_censor_rule_controller.rb @@ -65,7 +65,7 @@ class AdminCensorRuleController < AdminController render :action => 'edit' end end - + def destroy censor_rule = CensorRule.find(params[:censor_rule_id]) info_request = censor_rule.info_request diff --git a/app/controllers/admin_general_controller.rb b/app/controllers/admin_general_controller.rb index 0b7e9bec0..e192d097c 100644 --- a/app/controllers/admin_general_controller.rb +++ b/app/controllers/admin_general_controller.rb @@ -31,7 +31,7 @@ class AdminGeneralController < AdminController @requires_admin_requests = InfoRequest.find(:all, :select => '*, ' + InfoRequest.last_event_time_clause + ' as last_event_time', :conditions => ["described_state = 'requires_admin'"], :order => "last_event_time") @error_message_requests = InfoRequest.find(:all, :select => '*, ' + InfoRequest.last_event_time_clause + ' as last_event_time', :conditions => ["described_state = 'error_message'"], :order => "last_event_time") @blank_contacts = PublicBody.find(:all, :conditions => ["request_email = ''"], :order => "updated_at") - @old_unclassified = InfoRequest.find_old_unclassified(:limit => 20, + @old_unclassified = InfoRequest.find_old_unclassified(:limit => 20, :conditions => ["prominence = 'normal'"]) @holding_pen_messages = InfoRequest.holding_pen_request.incoming_messages end @@ -82,7 +82,7 @@ class AdminGeneralController < AdminController @current_branch = `git branch | grep "\*" | awk '{print $2}'` repo = `git remote show origin -n | grep Fetch | awk '{print $3}' | sed -re 's/.*:(.*).git/\\1/'` @github_origin = "https://github.com/#{repo.strip}/tree/" - @request_env = request.env + @request_env = request.env end end diff --git a/app/controllers/admin_public_body_controller.rb b/app/controllers/admin_public_body_controller.rb index bf7c07905..be733ab7d 100644 --- a/app/controllers/admin_public_body_controller.rb +++ b/app/controllers/admin_public_body_controller.rb @@ -16,7 +16,7 @@ class AdminPublicBodyController < AdminController def _lookup_query_internal @locale = self.locale_from_params() - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do @query = params[:query] if @query == "" @query = nil @@ -26,13 +26,13 @@ class AdminPublicBodyController < AdminController @page = nil end @public_bodies = PublicBody.paginate :order => "public_body_translations.name", :page => @page, :per_page => 100, - :conditions => @query.nil? ? "public_body_translations.locale = '#{@locale}'" : - ["(lower(public_body_translations.name) like lower('%'||?||'%') or - lower(public_body_translations.short_name) like lower('%'||?||'%') or + :conditions => @query.nil? ? "public_body_translations.locale = '#{@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], :joins => :translations end - @public_bodies_by_tag = PublicBody.find_by_tag(@query) + @public_bodies_by_tag = PublicBody.find_by_tag(@query) end def list @@ -62,11 +62,11 @@ class AdminPublicBodyController < AdminController def missing_scheme # There might be a way to do this in ActiveRecord, but I can't find it @public_bodies = PublicBody.find_by_sql(" - SELECT a.id, a.name, a.url_name, COUNT(*) AS howmany - FROM public_bodies a JOIN info_requests r ON a.id = r.public_body_id - WHERE a.publication_scheme = '' - GROUP BY a.id, a.name, a.url_name - ORDER BY howmany DESC + SELECT a.id, a.name, a.url_name, COUNT(*) AS howmany + FROM public_bodies a JOIN info_requests r ON a.id = r.public_body_id + WHERE a.publication_scheme = '' + GROUP BY a.id, a.name, a.url_name + ORDER BY howmany DESC LIMIT 20 ") @stats = { @@ -77,7 +77,7 @@ class AdminPublicBodyController < AdminController def show @locale = self.locale_from_params() - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do @public_body = PublicBody.find(params[:id]) render end @@ -87,7 +87,7 @@ class AdminPublicBodyController < AdminController @public_body = PublicBody.new render end - + def create PublicBody.with_locale(I18n.default_locale) do params[:public_body][:last_edit_editor] = admin_http_auth_user() @@ -103,7 +103,7 @@ class AdminPublicBodyController < AdminController def edit @public_body = PublicBody.find(params[:id]) - @public_body.last_edit_comment = "" + @public_body.last_edit_comment = "" render end @@ -122,7 +122,7 @@ class AdminPublicBodyController < AdminController def destroy @locale = self.locale_from_params() - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do public_body = PublicBody.find(params[:id]) if public_body.info_requests.size > 0 @@ -147,7 +147,7 @@ class AdminPublicBodyController < AdminController 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) @@ -174,7 +174,7 @@ class AdminPublicBodyController < AdminController @errors = "" @notes = "" end - + end private diff --git a/app/controllers/admin_request_controller.rb b/app/controllers/admin_request_controller.rb index e5de4f8b7..3c700c567 100644 --- a/app/controllers/admin_request_controller.rb +++ b/app/controllers/admin_request_controller.rb @@ -60,10 +60,10 @@ class AdminRequestController < AdminController if @info_request.valid? @info_request.save! - @info_request.log_event("edit", - { :editor => admin_http_auth_user(), - :old_title => old_title, :title => @info_request.title, - :old_prominence => old_prominence, :prominence => @info_request.prominence, + @info_request.log_event("edit", + { :editor => admin_http_auth_user(), + :old_title => old_title, :title => @info_request.title, + :old_prominence => old_prominence, :prominence => @info_request.prominence, :old_described_state => old_described_state, :described_state => @info_request.described_state, :old_awaiting_description => old_awaiting_description, :awaiting_description => @info_request.awaiting_description, :old_allow_new_responses_from => old_allow_new_responses_from, :allow_new_responses_from => @info_request.allow_new_responses_from, @@ -75,7 +75,7 @@ class AdminRequestController < AdminController else render :action => 'edit' end - end + end def fully_destroy @info_request = InfoRequest.find(params[:id]) @@ -99,28 +99,28 @@ class AdminRequestController < AdminController outgoing_message_id = @outgoing_message.id @outgoing_message.fully_destroy - @outgoing_message.info_request.log_event("destroy_outgoing", + @outgoing_message.info_request.log_event("destroy_outgoing", { :editor => admin_http_auth_user(), :deleted_outgoing_message_id => outgoing_message_id }) flash[:notice] = 'Outgoing message successfully destroyed.' redirect_to request_admin_url(@info_request) - end + 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_http_auth_user(), + if @outgoing_message.update_attributes(params[:outgoing_message]) + @outgoing_message.info_request.log_event("edit_outgoing", + { :outgoing_message_id => @outgoing_message.id, :editor => admin_http_auth_user(), :old_body => old_body, :body => @outgoing_message.body }) flash[:notice] = 'Outgoing message successfully updated.' redirect_to request_admin_url(@outgoing_message.info_request) else render :action => 'edit_outgoing' end - end + end def edit_comment @comment = Comment.find(params[:id]) @@ -133,9 +133,9 @@ class AdminRequestController < AdminController old_visible = @comment.visible @comment.visible = params[:comment][:visible] == "true" ? true : false - if @comment.update_attributes(params[:comment]) - @comment.info_request.log_event("edit_comment", - { :comment_id => @comment.id, :editor => admin_http_auth_user(), + if @comment.update_attributes(params[:comment]) + @comment.info_request.log_event("edit_comment", + { :comment_id => @comment.id, :editor => admin_http_auth_user(), :old_body => old_body, :body => @comment.body, :old_visible => old_visible, :visible => @comment.visible, }) @@ -144,7 +144,7 @@ class AdminRequestController < AdminController else render :action => 'edit_comment' end - end + end def destroy_incoming @@ -153,12 +153,12 @@ class AdminRequestController < AdminController incoming_message_id = @incoming_message.id @incoming_message.fully_destroy - @incoming_message.info_request.log_event("destroy_incoming", + @incoming_message.info_request.log_event("destroy_incoming", { :editor => admin_http_auth_user(), :deleted_incoming_message_id => incoming_message_id }) flash[:notice] = 'Incoming message successfully destroyed.' redirect_to request_admin_url(@info_request) - end + end def redeliver_incoming incoming_message = IncomingMessage.find(params[:redeliver_incoming_message_id]) @@ -181,10 +181,10 @@ class AdminRequestController < AdminController incoming_message_id = incoming_message.id incoming_message.fully_destroy - incoming_message.info_request.log_event("redeliver_incoming", { - :editor => admin_http_auth_user(), - :destination_request => destination_request.id, - :deleted_incoming_message_id => incoming_message_id + incoming_message.info_request.log_event("redeliver_incoming", { + :editor => admin_http_auth_user(), + :destination_request => destination_request.id, + :deleted_incoming_message_id => incoming_message_id }) flash[:notice] = "Message has been moved to this request" @@ -202,10 +202,10 @@ class AdminRequestController < AdminController else info_request.user = destination_user info_request.save! - info_request.log_event("move_request", { - :editor => admin_http_auth_user(), - :old_user_url_name => old_user.url_name, - :user_url_name => destination_user.url_name + info_request.log_event("move_request", { + :editor => admin_http_auth_user(), + :old_user_url_name => old_user.url_name, + :user_url_name => destination_user.url_name }) info_request.reindex_request_events @@ -220,10 +220,10 @@ class AdminRequestController < AdminController else info_request.public_body = destination_public_body info_request.save! - info_request.log_event("move_request", { - :editor => admin_http_auth_user(), - :old_public_body_url_name => old_public_body.url_name, - :public_body_url_name => destination_public_body.url_name + info_request.log_event("move_request", { + :editor => admin_http_auth_user(), + :old_public_body_url_name => old_public_body.url_name, + :public_body_url_name => destination_public_body.url_name }) info_request.reindex_request_events @@ -288,10 +288,10 @@ class AdminRequestController < AdminController if domain.nil? @public_bodies = [] else - @public_bodies = PublicBody.find(:all, :order => "name", + @public_bodies = PublicBody.find(:all, :order => "name", :conditions => [ "lower(request_email) like lower('%'||?||'%')", domain ]) end - + # 2. Match the email address in the message without matching the hash @info_requests = InfoRequest.guess_by_incoming_email(@raw_email.incoming_message) diff --git a/app/controllers/admin_user_controller.rb b/app/controllers/admin_user_controller.rb index 249030537..4059ac0bb 100644 --- a/app/controllers/admin_user_controller.rb +++ b/app/controllers/admin_user_controller.rb @@ -15,7 +15,7 @@ class AdminUserController < AdminController def list @query = params[:query] @admin_users = User.paginate :order => "name", :page => params[:page], :per_page => 100, - :conditions => @query.nil? ? nil : ["lower(name) like lower('%'||?||'%') or + :conditions => @query.nil? ? nil : ["lower(name) like lower('%'||?||'%') or lower(email) like lower('%'||?||'%')", @query, @query] end @@ -28,7 +28,7 @@ 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 @@ -54,7 +54,7 @@ class AdminUserController < AdminController else render :action => 'edit' end - end + end def destroy_track track_thing = TrackThing.find(params[:track_id].to_i) @@ -62,7 +62,7 @@ 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 diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 47accae1c..e305e90f4 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -20,7 +20,7 @@ class ApplicationController < ActionController::Base # Send notification email on exceptions include ExceptionNotification::Notifiable - + # Note: a filter stops the chain if it redirects or renders something before_filter :authentication_check before_filter :set_gettext_locale @@ -34,7 +34,7 @@ class ApplicationController < ActionController::Base def set_vary_header response.headers['Vary'] = 'Cookie' end - + helper_method :anonymous_cache, :short_cache, :medium_cache, :long_cache def anonymous_cache(time) if session[:user_id].nil? @@ -131,7 +131,7 @@ class ApplicationController < ActionController::Base end end # Make sure expiry time for session is set (before_filters are - # otherwise missed by this override) + # otherwise missed by this override) session_remember_me case exception when ActiveRecord::RecordNotFound, ActionController::UnknownAction, ActionController::RoutingError @@ -153,13 +153,13 @@ class ApplicationController < ActionController::Base alias original_rescue_action_locally rescue_action_locally def rescue_action_locally(exception) # Make sure expiry time for session is set (before_filters are - # otherwise missed by this override) + # otherwise missed by this override) session_remember_me # Display default, detailed error for developers original_rescue_action_locally(exception) end - + def local_request? false end @@ -220,7 +220,7 @@ class ApplicationController < ActionController::Base end end - # get the local locale + # get the local locale def locale_from_params(*args) if params[:show_locale] params[:show_locale] @@ -320,7 +320,7 @@ class ApplicationController < ActionController::Base end end - # + # def check_read_only read_only = MySociety::Config.get('READ_ONLY', '') if !read_only.empty? @@ -349,7 +349,7 @@ class ApplicationController < ActionController::Base @http_auth_user = admin_http_auth_user end - # Convert URL name for sort by order, to Xapian query + # Convert URL name for sort by order, to Xapian query def order_to_sort_by(sortby) if sortby.nil? return [nil, nil] @@ -365,7 +365,7 @@ class ApplicationController < ActionController::Base end # Function for search - def perform_search(models, query, sortby, collapse, per_page = 25, this_page = nil) + def perform_search(models, query, sortby, collapse, per_page = 25, this_page = nil) @query = query @sortby = sortby @@ -401,7 +401,7 @@ class ApplicationController < ActionController::Base collapse = 'request_collapse' end options = { - :offset => (@page - 1) * @per_page, + :offset => (@page - 1) * @per_page, :limit => @per_page, :sort_by_prefix => nil, :sort_by_ascending => true, @@ -420,7 +420,7 @@ class ApplicationController < ActionController::Base if e.message =~ /^QueryParserError: Wildcard/ # Wildcard expands to too many terms logger.info "Wildcard query '#{query.strip + '*'}' caused: #{e.message}" - + user_query = ActsAsXapian.query_parser.parse_query( query, Xapian::QueryParser::FLAG_LOVEHATE | @@ -449,8 +449,8 @@ class ApplicationController < ActionController::Base def param_exists(item) return params[item] && !params[item].empty? - end - + end + def get_request_variety_from_params query = "" sortby = "newest" @@ -475,7 +475,7 @@ class ApplicationController < ActionController::Base def get_status_from_params query = "" - if params[:latest_status] + if params[:latest_status] statuses = [] if params[:latest_status].class == String params[:latest_status] = [params[:latest_status]] @@ -526,7 +526,7 @@ class ApplicationController < ActionController::Base query = "" tags = [] if param_exists(:tags) - params[:tags].split().each do |tag| + params[:tags].split().each do |tag| tags << "tag:#{tag}" end end @@ -535,7 +535,7 @@ class ApplicationController < ActionController::Base end return query end - + def make_query_from_params query = params[:query] || "" if query.nil? query += get_date_range_from_params diff --git a/app/controllers/comment_controller.rb b/app/controllers/comment_controller.rb index 86d5b0a06..d9cd002dd 100644 --- a/app/controllers/comment_controller.rb +++ b/app/controllers/comment_controller.rb @@ -9,14 +9,14 @@ class CommentController < ApplicationController before_filter :check_read_only, :only => [ :new ] protect_from_forgery :only => [ :new ] - + def new if params[:type] == 'request' @info_request = InfoRequest.find_by_url_title(params[:url_title]) @track_thing = TrackThing.create_track_for_request(@info_request) if params[:comment] @comment = Comment.new(params[:comment].merge({ - :comment_type => 'request', + :comment_type => 'request', :user => @user })) end @@ -38,7 +38,7 @@ class CommentController < ApplicationController # Default to subscribing to request when first viewing form params[:subscribe_to_request] = true end - + # See if values were valid or not if !params[:comment] || !@existing_comment.nil? || !@comment.valid? || params[:reedit] render :action => 'new' diff --git a/app/controllers/general_controller.rb b/app/controllers/general_controller.rb index 82b1b8629..6e89a2832 100644 --- a/app/controllers/general_controller.rb +++ b/app/controllers/general_controller.rb @@ -28,19 +28,19 @@ class GeneralController < ApplicationController @locale = self.locale_from_params() locale_condition = 'public_body_translations.locale = ?' conditions = [locale_condition, @locale] - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do if body_short_names.empty? # This is too slow - @popular_bodies = PublicBody.find(:all, - :select => "public_bodies.*, (select count(*) from info_requests where info_requests.public_body_id = public_bodies.id) as c", - :order => "c desc", + @popular_bodies = PublicBody.find(:all, + :select => "public_bodies.*, (select count(*) from info_requests where info_requests.public_body_id = public_bodies.id) as c", + :order => "c desc", :limit => 32, :conditions => conditions, :joins => :translations ) else conditions[0] += " and public_bodies.url_name in (" + body_short_names + ")" - @popular_bodies = PublicBody.find(:all, + @popular_bodies = PublicBody.find(:all, :conditions => conditions, :joins => :translations) end @@ -52,7 +52,7 @@ class GeneralController < ApplicationController max_count = 5 xapian_object = perform_search([InfoRequestEvent], query, sortby, 'request_title_collapse', max_count) @request_events = xapian_object.results.map { |r| r[:model] } - + # If there are not yet enough successful requests, fill out the list with # other requests if @request_events.count < max_count @@ -97,7 +97,7 @@ class GeneralController < ApplicationController query_parts = @query.split("/") if !['bodies', 'requests', 'users', 'all'].include?(query_parts[-1]) redirect_to search_url([@query, "all"], params) - else + else redirect_to search_url(@query, params) end end @@ -236,4 +236,4 @@ class GeneralController < ApplicationController end - + diff --git a/app/controllers/help_controller.rb b/app/controllers/help_controller.rb index b08438b52..e3b77271e 100644 --- a/app/controllers/help_controller.rb +++ b/app/controllers/help_controller.rb @@ -9,7 +9,7 @@ class HelpController < ApplicationController # we don't even have a control subroutine for most help pages, just see their templates - + before_filter :long_cache def unhappy @@ -61,7 +61,7 @@ class HelpController < ApplicationController @last_request, @last_body ) flash[:notice] = _("Your message has been sent. Thank you for getting in touch! We'll get back to you soon.") - redirect_to frontpage_url + redirect_to frontpage_url return end @@ -69,7 +69,7 @@ class HelpController < ApplicationController @contact.errors.clear end end - + end end diff --git a/app/controllers/holiday_controller.rb b/app/controllers/holiday_controller.rb index 916ff54c8..7f62aa26d 100644 --- a/app/controllers/holiday_controller.rb +++ b/app/controllers/holiday_controller.rb @@ -1,5 +1,5 @@ # app/controllers/holiday_controller.rb: -# Calculate dates +# Calculate dates # # Copyright (c) 2008 UK Citizens Online Democracy. All rights reserved. # Email: francis@mysociety.org; WWW: http://www.mysociety.org/ @@ -16,7 +16,7 @@ class HolidayController < ApplicationController @request_date = Date.strptime(params[:holiday]) or raise "Invalid date" @due_date = Holiday.due_date_from(@request_date, 20) @skipped = Holiday.all( - :conditions => [ 'day >= ? AND day <= ?', + :conditions => [ 'day >= ? AND day <= ?', @request_date.strftime("%F"), @due_date.strftime("%F") ] ).collect { |h| h.day }.sort diff --git a/app/controllers/public_body_controller.rb b/app/controllers/public_body_controller.rb index 00d1cc1e0..95d936e54 100644 --- a/app/controllers/public_body_controller.rb +++ b/app/controllers/public_body_controller.rb @@ -14,23 +14,23 @@ class PublicBodyController < ApplicationController def show long_cache if MySociety::Format.simplify_url_part(params[:url_name], 'body') != params[:url_name] - redirect_to :url_name => MySociety::Format.simplify_url_part(params[:url_name], 'body'), :status => :moved_permanently + redirect_to :url_name => MySociety::Format.simplify_url_part(params[:url_name], 'body'), :status => :moved_permanently return end @locale = self.locale_from_params() - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do @public_body = PublicBody.find_by_url_name_with_historic(params[:url_name]) raise ActiveRecord::RecordNotFound.new("None found") if @public_body.nil? if @public_body.url_name.nil? redirect_to :back return - end + end # If found by historic name, or alternate locale name, redirect to new name if @public_body.url_name != params[:url_name] - redirect_to show_public_body_url(:url_name => @public_body.url_name) + redirect_to show_public_body_url(:url_name => @public_body.url_name) return end - + set_last_body(@public_body) top_url = main_url("/") @@ -50,8 +50,8 @@ class PublicBodyController < ApplicationController begin @xapian_requests = perform_search([InfoRequestEvent], query, sortby, 'request_collapse') if (@page > 1) - @page_desc = " (page " + @page.to_s + ")" - else + @page_desc = " (page " + @page.to_s + ")" + else @page_desc = "" end rescue @@ -65,7 +65,7 @@ class PublicBodyController < ApplicationController format.html { @has_json = true; render :template => "public_body/show"} format.json { render :json => @public_body.json_for_api } end - + end end @@ -93,8 +93,8 @@ class PublicBodyController < ApplicationController @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 (?)) + 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" @@ -152,10 +152,10 @@ class PublicBodyController < ApplicationController report = StringIO.new CSV::Writer.generate(report, ',') do |title| title << [ - 'Name', + 'Name', 'Short name', # deliberately not including 'Request email' - 'URL name', + 'URL name', 'Tags', 'Home page', 'Publication scheme', @@ -164,12 +164,12 @@ class PublicBodyController < ApplicationController 'Version', ] public_bodies.each do |public_body| - title << [ - public_body.name, - public_body.short_name, + title << [ + public_body.name, + public_body.short_name, # DO NOT include request_email (we don't want to make it # easy to spam all authorities with requests) - public_body.url_name, + public_body.url_name, public_body.tag_string, public_body.calculated_home_page, public_body.publication_scheme, @@ -181,7 +181,7 @@ class PublicBodyController < ApplicationController end report.rewind send_data(report.read, :type=> 'text/csv; charset=utf-8; header=present', - :filename => 'all-authorities.csv', + :filename => 'all-authorities.csv', :disposition =>'attachment', :encoding => 'utf8') end diff --git a/app/controllers/request_controller.rb b/app/controllers/request_controller.rb index 36edab9fa..af142c530 100644 --- a/app/controllers/request_controller.rb +++ b/app/controllers/request_controller.rb @@ -17,7 +17,7 @@ class RequestController < ApplicationController MAX_RESULTS = 500 PER_PAGE = 25 - + @@custom_states_loaded = false begin if ENV["RAILS_ENV"] != "test" @@ -45,11 +45,11 @@ class RequestController < ApplicationController end medium_cache end - + def show medium_cache @locale = self.locale_from_params() - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do # Look up by old style numeric identifiers if params[:url_title].match(/^[0-9]+$/) @@ -58,7 +58,7 @@ class RequestController < ApplicationController return end - # Look up by new style text names + # Look up by new style text names @info_request = InfoRequest.find_by_url_title(params[:url_title]) if @info_request.nil? raise ActiveRecord::RecordNotFound.new("Request not found") @@ -70,7 +70,7 @@ class RequestController < ApplicationController render :template => 'request/hidden', :status => 410 # gone return end - + # Other parameters @info_request_events = @info_request.info_request_events @status = @info_request.calculate_status @@ -78,7 +78,7 @@ class RequestController < ApplicationController @update_status = params[:update_status] ? true : false @old_unclassified = @info_request.is_old_unclassified? && !authenticated_user.nil? @is_owning_user = @info_request.is_owning_user?(authenticated_user) - + if @update_status return if !@is_owning_user && !authenticated_as_user?(@info_request.user, :web => _("To update the status of this FOI request"), @@ -86,7 +86,7 @@ class RequestController < ApplicationController :email_subject => _("Update the status of your request to ") + @info_request.public_body.name ) 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 @@ -96,14 +96,14 @@ class RequestController < ApplicationController behavior_cache :tag => ['similar', @info_request.id] do begin limit = 10 - @xapian_similar = ::ActsAsXapian::Similar.new([InfoRequestEvent], @info_request.info_request_events, + @xapian_similar = ::ActsAsXapian::Similar.new([InfoRequestEvent], @info_request.info_request_events, :limit => limit, :collapse_by_prefix => 'request_collapse') @xapian_similar_more = (@xapian_similar.matches_estimated > limit) rescue @xapian_similar = nil end 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 } ] @@ -123,7 +123,7 @@ class RequestController < ApplicationController @info_request = InfoRequest.find_by_url_title(params[:url_title]) if @info_request.nil? raise ActiveRecord::RecordNotFound.new("Request not found") - else + else if !@info_request.user_can_view?(authenticated_user) render :template => 'request/hidden', :status => 410 # gone return @@ -139,16 +139,16 @@ class RequestController < ApplicationController @page = (params[:page] || "1").to_i @info_request = InfoRequest.find_by_url_title(params[:url_title]) raise ActiveRecord::RecordNotFound.new("Request not found") if @info_request.nil? - + if !@info_request.user_can_view?(authenticated_user) render :template => 'request/hidden', :status => 410 # gone return end - @xapian_object = ::ActsAsXapian::Similar.new([InfoRequestEvent], @info_request.info_request_events, + @xapian_object = ::ActsAsXapian::Similar.new([InfoRequestEvent], @info_request.info_request_events, :offset => (@page - 1) * @per_page, :limit => @per_page, :collapse_by_prefix => 'request_collapse') - + if (@page > 1) - @page_desc = " (page " + @page.to_s + ")" + @page_desc = " (page " + @page.to_s + ")" else @page_desc = "" end @@ -161,7 +161,7 @@ class RequestController < ApplicationController if @view == "recent" return redirect_to request_list_all_path(:action => "list", :view => "all", :page => @page), :status => :moved_permanently end - + # Later pages are very expensive to load if @page > MAX_RESULTS / PER_PAGE raise ActiveRecord::RecordNotFound.new("Sorry. No pages after #{MAX_RESULTS / PER_PAGE}.") @@ -171,14 +171,14 @@ class RequestController < ApplicationController query = make_query_from_params @title = _("View and search requests") sortby = "newest" - @cache_tag = Digest::MD5.hexdigest(query + @page.to_s + I18n.locale.to_s) + @cache_tag = Digest::MD5.hexdigest(query + @page.to_s + I18n.locale.to_s) behavior_cache :tag => [@cache_tag] do xapian_object = perform_search([InfoRequestEvent], query, sortby, 'request_collapse') @list_results = xapian_object.results.map { |r| r[:model] } @matches_estimated = xapian_object.matches_estimated @show_no_more_than = (@matches_estimated > MAX_RESULTS) ? MAX_RESULTS : @matches_estimated end - + @title = @title + " (page " + @page.to_s + ")" if (@page > 1) @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 } ] @@ -202,7 +202,7 @@ class RequestController < ApplicationController # get_undescribed_requests also allows one day since the response # arrived. if !@user.nil? && params[:submitted_new_request].nil? && !@user.can_leave_requests_undescribed? - @undescribed_requests = @user.get_undescribed_requests + @undescribed_requests = @user.get_undescribed_requests if @undescribed_requests.size > 1 render :action => 'new_please_describe' return @@ -248,7 +248,7 @@ class RequestController < ApplicationController elsif params[:public_body_id] params[:info_request][:public_body_id] = params[:public_body_id] end - if !params[:info_request][:public_body_id] + if !params[:info_request][:public_body_id] # compulsory to have a body by here, or go to front page which is start of process redirect_to frontpage_url return @@ -266,7 +266,7 @@ class RequestController < ApplicationController params[:outgoing_message][:info_request] = @info_request @outgoing_message = OutgoingMessage.new(params[:outgoing_message]) @outgoing_message.set_signature_name(@user.name) if !@user.nil? - + if @info_request.public_body.is_requestable? render :action => 'new' else @@ -289,8 +289,8 @@ class RequestController < ApplicationController # Create both FOI request and the first request message @info_request = InfoRequest.new(params[:info_request]) - @outgoing_message = OutgoingMessage.new(params[:outgoing_message].merge({ - :status => 'ready', + @outgoing_message = OutgoingMessage.new(params[:outgoing_message].merge({ + :status => 'ready', :message_type => 'initial_request' })) @info_request.outgoing_messages << @outgoing_message @@ -315,7 +315,7 @@ class RequestController < ApplicationController if params[:preview].to_i == 1 message = "" if @outgoing_message.contains_email? - if @user.nil? + if @user.nil? message += _("<p>You do not need to include your email in the request in order to get a reply, as we will ask for it on the next screen (<a href=\"%s\">details</a>).</p>") % [help_privacy_path+"#email_address"]; else message += _("<p>You do not need to include your email in the request in order to get a reply (<a href=\"%s\">details</a>).</p>") % [help_privacy_path+"#email_address"]; @@ -361,7 +361,7 @@ class RequestController < ApplicationController flash[:notice] = _("<p>Your {{law_used_full}} request has been <strong>sent on its way</strong>!</p> <p><strong>We will email you</strong> when there is a response, or after {{late_number_of_days}} working days if the authority still hasn't replied by then.</p> - <p>If you write about this request (for example in a forum or a blog) please link to this page, and add an + <p>If you write about this request (for example in a forum or a blog) please link to this page, and add an annotation below telling people about your writing.</p>",:law_used_full=>@info_request.law_used_full, :late_number_of_days => MySociety::Config.get('REPLY_LATE_AFTER_DAYS', 20)) redirect_to show_new_request_path(:url_title => @info_request.url_title) @@ -378,10 +378,10 @@ class RequestController < ApplicationController return end - @is_owning_user = @info_request.is_owning_user?(authenticated_user) + @is_owning_user = @info_request.is_owning_user?(authenticated_user) @last_info_request_event_id = @info_request.last_event_id_needing_description @old_unclassified = @info_request.is_old_unclassified? && !authenticated_user.nil? - + # Check authenticated, and parameters set. We check is_owning_user # to get admin overrides (see is_owning_user? above) if !@old_unclassified && !@is_owning_user && !authenticated_as_user?(@info_request.user, @@ -408,7 +408,7 @@ class RequestController < ApplicationController # Make the state change old_described_state = @info_request.described_state @info_request.set_described_state(params[:incoming_message][:described_state]) - + # If you're not the *actual* requester owner. e.g. you are playing the # classification game, or you're doing this just because you are an # admin user (not because you also own the request). @@ -417,24 +417,24 @@ class RequestController < ApplicationController # don't log if you were the requester XXX This is presumably so you # don't score for classifying your own requests. Could instead # always log and filter at display time. - @info_request.log_event("status_update", - { :user_id => authenticated_user.id, - :old_described_state => old_described_state, + @info_request.log_event("status_update", + { :user_id => authenticated_user.id, + :old_described_state => old_described_state, :described_state => @info_request.described_state, }) - + # Don't give advice on what to do next, as it isn't their request RequestMailer.deliver_old_unclassified_updated(@info_request) - if session[:request_game] + if session[:request_game] flash[:notice] = _('Thank you for updating the status of the request \'<a href="{{url}}">{{info_request_title}}</a>\'. There are some more requests below for you to classify.',:info_request_title=>CGI.escapeHTML(@info_request.title), :url=>CGI.escapeHTML(request_url(@info_request))) - redirect_to play_url + redirect_to play_url else flash[:notice] = _('Thank you for updating this request!') redirect_to request_url(@info_request) end return end - + # Display advice for requester on what to do next, as appropriate if @info_request.calculate_status == 'waiting_response' flash[:notice] = _("<p>Thank you! Hopefully your wait isn't too long.</p> <p>By law, you should get a response promptly, and normally before the end of <strong> @@ -450,14 +450,14 @@ class RequestController < ApplicationController flash[:notice] = _("<p>Thank you! Here are some ideas on what to do next:</p> <ul> <li>To send your request to another authority, first copy the text of your request below, then <a href=\"{{find_authority_url}}\">find the other authority</a>.</li> - <li>If you would like to contest the authority's claim that they do not hold the information, here is + <li>If you would like to contest the authority's claim that they do not hold the information, here is <a href=\"{{complain_url}}\">how to complain</a>. </li> <li>We have <a href=\"{{other_means_url}}\">suggestions</a> on other means to answer your question. </li> - </ul>", - :find_authority_url => "/new", + </ul>", + :find_authority_url => "/new", :complain_url => CGI.escapeHTML(unhappy_url(@info_request)), :other_means_url => CGI.escapeHTML(unhappy_url(@info_request)) + "#other_means") redirect_to request_url(@info_request) @@ -496,7 +496,7 @@ class RequestController < ApplicationController end end - # Used for links from polymorphic URLs e.g. in Atom feeds - just redirect to + # Used for links from polymorphic URLs e.g. in Atom feeds - just redirect to # proper URL for the message the event refers to def show_request_event @info_request_event = InfoRequestEvent.find(params[:info_request_event_id]) @@ -506,8 +506,8 @@ class RequestController < ApplicationController redirect_to outgoing_message_url(@info_request_event.outgoing_message), :status => :moved_permanently else # XXX maybe there are better URLs for some events than this - redirect_to request_url(@info_request_event.info_request), :status => :moved_permanently - end + redirect_to request_url(@info_request_event.info_request), :status => :moved_permanently + end end # Show an individual incoming message, and allow followup @@ -551,8 +551,8 @@ class RequestController < ApplicationController if params_outgoing_message.nil? params_outgoing_message = {} end - params_outgoing_message.merge!({ - :status => 'ready', + params_outgoing_message.merge!({ + :status => 'ready', :message_type => 'followup', :incoming_message_followup => @incoming_message, :info_request_id => @info_request.id @@ -576,7 +576,7 @@ class RequestController < ApplicationController render :template => 'request/hidden', :status => 410 # gone return end - + # Check address is good if !OutgoingMailer.is_followupable?(@info_request, @incoming_message) raise "unexpected followupable inconsistency" if @info_request.public_body.is_requestable? @@ -589,7 +589,7 @@ class RequestController < ApplicationController # to make sure they're the right user first, before they start writing a # message and wasting their time if they are not the requester. if !authenticated_as_user?(@info_request.user, - :web => @incoming_message.nil? ? + :web => @incoming_message.nil? ? _("To send a follow up message to ") + @info_request.public_body.name : _("To reply to ") + @info_request.public_body.name, :email => @incoming_message.nil? ? @@ -687,7 +687,7 @@ class RequestController < ApplicationController # Prevent spam to magic request address. Note that the binary # subsitution method used depends on the content type - @incoming_message.binary_mask_stuff!(@attachment.body, @attachment.content_type) + @incoming_message.binary_mask_stuff!(@attachment.body, @attachment.content_type) # we don't use @attachment.content_type here, as we want same mime type when cached in cache_attachments above response.content_type = AlaveteliFileTypes.filename_to_mimetype(params[:file_name].join("/")) || 'application/octet-stream' @@ -715,7 +715,7 @@ class RequestController < ApplicationController html.sub!("<prefix-here>", view_html_prefix) html.sub!("<attachment-url-here>", CGI.escape(@attachment_url)) - @incoming_message.html_mask_stuff!(html) + @incoming_message.html_mask_stuff!(html) response.content_type = 'text/html' render :text => html end @@ -740,7 +740,7 @@ class RequestController < ApplicationController else @original_filename = @filename end - + # check permissions raise "internal error, pre-auth filter should have caught this" if !@info_request.user_can_view?(authenticated_user) @attachment = IncomingMessage.get_attachment_by_url_part_number(@incoming_message.get_attachments_for_display, @part_number) @@ -757,7 +757,7 @@ class RequestController < ApplicationController # FOI officers can upload a response def upload_response @locale = self.locale_from_params() - PublicBody.with_locale(@locale) do + PublicBody.with_locale(@locale) do @info_request = InfoRequest.find_by_url_title(params[:url_title]) @reason_params = { @@ -827,7 +827,7 @@ class RequestController < ApplicationController updated = Digest::SHA1.hexdigest(info_request.get_last_event.created_at.to_i.to_s + info_request.updated_at.to_i.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) + 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") @@ -858,7 +858,7 @@ class RequestController < ApplicationController f.puts(output) } end - for message in info_request.incoming_messages + 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}" diff --git a/app/controllers/request_game_controller.rb b/app/controllers/request_game_controller.rb index 8a84575bb..904c44759 100644 --- a/app/controllers/request_game_controller.rb +++ b/app/controllers/request_game_controller.rb @@ -7,7 +7,7 @@ # $Id: request_game_controller.rb,v 1.9 2009-10-19 22:06:54 francis Exp $ class RequestGameController < ApplicationController - + def play session[:request_game] = Time.now @@ -20,7 +20,7 @@ class RequestGameController < ApplicationController @requests = old.sort_by{ rand }.slice(0..2) if @missing == 0 - flash[:notice] = _('<p>All done! Thank you very much for your help.</p><p>There are <a href="{{helpus_url}}">more things you can do</a> to help {{site_name}}.</p>', + flash[:notice] = _('<p>All done! Thank you very much for your help.</p><p>There are <a href="{{helpus_url}}">more things you can do</a> to help {{site_name}}.</p>', :helpus_url => help_credits_path+"#helpus", :site_name => site_name) end @@ -38,7 +38,7 @@ class RequestGameController < ApplicationController url_title = params[:url_title] if !authenticated?( :web => _("To play the request categorisation game"), - :email => _("Then you can play the request categorisation game."), + :email => _("Then you can play the request categorisation game."), :email_subject => _("Play the request categorisation game") ) # do nothing - as "authenticated?" has done the redirect to signin page for us diff --git a/app/controllers/user_controller.rb b/app/controllers/user_controller.rb index 08726183e..76c56c442 100644 --- a/app/controllers/user_controller.rb +++ b/app/controllers/user_controller.rb @@ -9,7 +9,7 @@ class UserController < ApplicationController layout :select_layout - + protect_from_forgery :only => [ :contact, :set_profile_photo, :signchangeemail, @@ -33,7 +33,7 @@ class UserController < ApplicationController @show_profile = false @show_requests = true end - + @display_user = User.find(:first, :conditions => [ "url_name = ? and email_confirmed = ?", params[:url_name], true ]) if not @display_user raise ActiveRecord::RecordNotFound.new("user not found, url_name=" + params[:url_name]) @@ -55,7 +55,7 @@ class UserController < ApplicationController 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 @@ -129,7 +129,7 @@ class UserController < ApplicationController session[:user_id] = @user_signin.id session[:user_circumstance] = nil session[:remember_me] = params[:remember_me] ? true : false - + if is_modal_dialog render :action => 'signin_successful' else @@ -319,7 +319,7 @@ class UserController < ApplicationController if (not session[:user_circumstance]) or (session[:user_circumstance] != "change_email") # don't store the password in the db params[:signchangeemail].delete(:password) - post_redirect = PostRedirect.new(:uri => signchangeemail_url(), + post_redirect = PostRedirect.new(:uri => signchangeemail_url(), :post_params => params, :circumstance => "change_email" # special login that lets you change your email ) @@ -538,12 +538,12 @@ class UserController < ApplicationController 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 diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index a0f16dfaf..df89a372c 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -32,14 +32,14 @@ module ApplicationHelper html[key] = 'errorExplanation' end end - + error_messages = [] for object in objects object.errors.each do |attr, message| error_messages << content_tag(:li, message) end end - + content_tag(:div, content_tag(:ul, error_messages), html @@ -48,7 +48,7 @@ module ApplicationHelper '' end end - + # Highlight words, also escapes HTML (other than spans that we add) def highlight_words(t, words, html = true) if html @@ -70,10 +70,10 @@ module ApplicationHelper t = highlight_words(t, words, html) return t end - + def locale_name(locale) return LanguageNames::get_language_name(locale) - end + end # Use our own algorithm for finding path of cache def foi_cache(name = {}, options = nil, &block) @@ -100,11 +100,11 @@ module ApplicationHelper def sanitized_object_name(object_name) object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/,"_").sub(/_$/,"") end - + def sanitized_method_name(method_name) method_name.sub(/\?$/, "") end - + def form_tag_id(object_name, method_name, locale=nil) if locale.nil? return "#{sanitized_object_name(object_name.to_s)}_#{sanitized_method_name(method_name.to_s)}" diff --git a/app/helpers/config_helper.rb b/app/helpers/config_helper.rb index b0381a2f5..543b60256 100644 --- a/app/helpers/config_helper.rb +++ b/app/helpers/config_helper.rb @@ -2,7 +2,7 @@ module ConfigHelper def site_name MySociety::Config.get('SITE_NAME', 'Alaveteli') end - + def force_registration_on_new_request MySociety::Config.get('FORCE_REGISTRATION_ON_NEW_REQUEST', false) end diff --git a/app/helpers/link_to_helper.rb b/app/helpers/link_to_helper.rb index 74c56dc8c..914b4dc12 100755 --- a/app/helpers/link_to_helper.rb +++ b/app/helpers/link_to_helper.rb @@ -1,6 +1,6 @@ # app/helpers/link_to_helper.rb: # This module is included into all controllers via controllers/application.rb -# - +# - # # Copyright (c) 2007 UK Citizens Online Democracy. All rights reserved. # Email: francis@mysociety.org; WWW: http://www.mysociety.org/ @@ -10,25 +10,25 @@ module LinkToHelper # Links to various models - + # Requests def request_url(info_request, extra_params={}) params = {:url_title => info_request.url_title, :only_path => true} return show_request_url(params.merge(extra_params)) end - + def request_link(info_request) link_to h(info_request.title), request_url(info_request) end - + def request_admin_url(info_request) return admin_url('request/show/' + info_request.id.to_s) end - + def request_both_links(info_request) link_to(h(info_request.title), main_url(request_url(info_request))) + " (" + link_to("admin", request_admin_url(info_request)) + ")" end - + def request_similar_url(info_request) return similar_request_url(:url_title => info_request.url_title, :only_path => true) end @@ -58,7 +58,7 @@ module LinkToHelper end return respond_url end - + # Public bodies def public_body_url(public_body) public_body.url_name.nil? ? '' : show_public_body_url(:url_name => public_body.url_name, :only_path => true) @@ -79,7 +79,7 @@ module LinkToHelper link_to(h(public_body.name), main_url(public_body_url(public_body))) + " (" + link_to("admin", public_body_admin_url(public_body)) + ")" end def list_public_bodies_default - list_public_bodies_url(:tag => 'all') + list_public_bodies_url(:tag => 'all') end # Users @@ -120,15 +120,15 @@ module LinkToHelper def do_track_url(track_thing, feed = 'track') if track_thing.track_type == 'request_updates' track_request_url(:url_title => track_thing.info_request.url_title, :feed => feed) - elsif track_thing.track_type == 'all_new_requests' + elsif track_thing.track_type == 'all_new_requests' track_list_url(:view => 'recent', :feed => feed) - elsif track_thing.track_type == 'all_successful_requests' + elsif track_thing.track_type == 'all_successful_requests' track_list_url(:view => 'successful', :feed => feed) - elsif track_thing.track_type == 'public_body_updates' + elsif track_thing.track_type == 'public_body_updates' track_public_body_url(:url_name => track_thing.public_body.url_name, :feed => feed) - elsif track_thing.track_type == 'user_updates' + elsif track_thing.track_type == 'user_updates' track_user_url(:url_name => track_thing.tracked_user.url_name, :feed => feed) - elsif track_thing.track_type == 'search_query' + elsif track_thing.track_type == 'search_query' track_search_url(:query_array => track_thing.track_query, :feed => feed) else raise "unknown tracking type " + track_thing.track_type @@ -141,7 +141,7 @@ module LinkToHelper query = query - ["", nil] query = query.join("/") end - routing_info = {:controller => 'general', + routing_info = {:controller => 'general', :action => 'search', :combined => query, :view => nil} diff --git a/app/models/application_mailer.rb b/app/models/application_mailer.rb index e9f82a2c3..80f0d7289 100644 --- a/app/models/application_mailer.rb +++ b/app/models/application_mailer.rb @@ -28,7 +28,7 @@ class ApplicationMailer < ActionMailer::Base # views (for links) and mailers (for use in emails), so include them into # all of all. include LinkToHelper - + # Site-wide access to configuration settings include ConfigHelper end diff --git a/app/models/change_email_validator.rb b/app/models/change_email_validator.rb index e3f8fa892..80db96c64 100644 --- a/app/models/change_email_validator.rb +++ b/app/models/change_email_validator.rb @@ -30,7 +30,7 @@ class ChangeEmailValidator < ActiveRecord::BaseWithoutTable validates_presence_of :old_email, :message => N_("Please enter your old email address") validates_presence_of :new_email, :message => N_("Please enter your new email address") validates_presence_of :password, :message => N_("Please enter your password"), :unless => :changing_email - + def changing_email() self.user_circumstance == 'change_email' end diff --git a/app/models/contact_mailer.rb b/app/models/contact_mailer.rb index 0390fc347..74c213c7a 100644 --- a/app/models/contact_mailer.rb +++ b/app/models/contact_mailer.rb @@ -25,7 +25,7 @@ class ContactMailer < ApplicationMailer # they shouldn't, and this might help. (Have had mysterious cases of a # reply coming in duplicate from a public body to both From and envelope # from) - + # Send message to another user def user_message(from_user, recipient_user, from_user_url, subject, message) @from = from_user.name_and_email @@ -34,7 +34,7 @@ class ContactMailer < ApplicationMailer headers 'Return-Path' => blackhole_email, 'Reply-To' => @from @recipients = recipient_user.name_and_email @subject = subject - @body = { + @body = { :message => message, :from_user => from_user, :recipient_user => recipient_user, diff --git a/app/models/exim_log.rb b/app/models/exim_log.rb index 77e5e2d21..2c6bea4f8 100644 --- a/app/models/exim_log.rb +++ b/app/models/exim_log.rb @@ -40,7 +40,7 @@ class EximLog < ActiveRecord::Base ActiveRecord::Base.transaction do # see if we already have it - done = EximLogDone.find_by_filename(file_name_db) + done = EximLogDone.find_by_filename(file_name_db) if !done.nil? if modified.utc == done.last_stat.utc # already have that, nothing to do @@ -124,7 +124,7 @@ class EximLog < ActiveRecord::Base return ok end - + end diff --git a/app/models/foi_attachment.rb b/app/models/foi_attachment.rb index da92d1c2d..1906b56db 100644 --- a/app/models/foi_attachment.rb +++ b/app/models/foi_attachment.rb @@ -177,7 +177,7 @@ class FoiAttachment < ActiveRecord::Base filename = filename.gsub(/\//, "-") return filename - end + end # XXX changing this will break existing URLs, so have a care - maybe # make another old_display_filename see above @@ -248,16 +248,16 @@ class FoiAttachment < ActiveRecord::Base return !! { "application/pdf" => true, # .pdf "image/tiff" => true, # .tiff - + "application/vnd.ms-word" => true, # .doc "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => true, # .docx - + "application/vnd.ms-powerpoint" => true, # .ppt "application/vnd.openxmlformats-officedocument.presentationml.presentation" => true, # .pptx - + "application/vnd.ms-excel" => true, # .xls "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => true, # .xlsx - + } [self.content_type] end @@ -277,16 +277,16 @@ class FoiAttachment < ActiveRecord::Base return { "text/plain" => "Text file", 'application/rtf' => "RTF file", - + 'application/pdf' => "PDF file", 'image/tiff' => "TIFF image", - + 'application/vnd.ms-word' => "Word document", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => "Word document", - + 'application/vnd.ms-powerpoint' => "PowerPoint presentation", 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => "PowerPoint presentation", - + 'application/vnd.ms-excel' => "Excel spreadsheet", 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => "Excel spreadsheet", }[self.content_type] @@ -345,7 +345,7 @@ class FoiAttachment < ActiveRecord::Base if self.has_google_docs_viewer? wrapper_id = "wrapper_google_embed" ret = ret + "<iframe src='http://docs.google.com/viewer?url=<attachment-url-here>&embedded=true' width='100%' height='100%' style='border: none;'></iframe>"; - else + else ret = ret + "<p>Sorry, we were unable to convert this file to HTML. Please use the download link at the top right.</p>" end ret = ret + "</body></html>" diff --git a/app/models/holiday.rb b/app/models/holiday.rb index 60b5ff443..1fa599c13 100644 --- a/app/models/holiday.rb +++ b/app/models/holiday.rb @@ -10,7 +10,7 @@ # models/holiday.rb: # -# Store details on, and perform calculations with, public holidays on which +# Store details on, and perform calculations with, public holidays on which # the clock for answering FOI requests does not run: # # ... "working day" means any day other than a Saturday, a Sunday, Christmas @@ -37,7 +37,7 @@ class Holiday < ActiveRecord::Base # Count forward (20) working days. We start with today as "day zero". The # first of the twenty full working days is the next day. We return the # date of the last of the twenty. - + # This response for example of a public authority complains that we had # it wrong. We didn't (even thought I changed the code for a while, # it's changed back now). A day is a day, our lawyer tells us. diff --git a/app/models/incoming_message.rb b/app/models/incoming_message.rb index 2896de68a..8de6e5ba8 100644 --- a/app/models/incoming_message.rb +++ b/app/models/incoming_message.rb @@ -81,7 +81,7 @@ class IncomingMessage < ActiveRecord::Base # http://www.whatdotheyknow.com/request/reviews_of_unduly_lenient_senten#incoming-4830 # Report of TMail bug: # http://rubyforge.org/tracker/index.php?func=detail&aid=21810&group_id=4512&atid=17370 - copy_of_raw_data = self.raw_email.data.gsub(/; boundary=\s+"/ims,'; boundary="') + copy_of_raw_data = self.raw_email.data.gsub(/; boundary=\s+"/ims,'; boundary="') @mail = TMail::Mail.parse(copy_of_raw_data) @mail.base64_decode @@ -92,7 +92,7 @@ class IncomingMessage < ActiveRecord::Base # Returns the name of the person the incoming message is from, or nil if # there isn't one or if there is only an email address. XXX can probably # remove from_name_if_present (which is a monkey patch) by just calling - # .from_addrs[0].name here instead? + # .from_addrs[0].name here instead? # Return false if for some reason this is a message that we shouldn't let them reply to def _calculate_valid_to_reply_to @@ -178,7 +178,7 @@ class IncomingMessage < ActiveRecord::Base def safe_mail_from if !self.mail_from.nil? mail_from = self.mail_from.dup - self.info_request.apply_censor_rules_to_text!(mail_from) + self.info_request.apply_censor_rules_to_text!(mail_from) return mail_from end end @@ -191,7 +191,7 @@ class IncomingMessage < ActiveRecord::Base # XXX This fills in part.rfc822_attachment and part.url_part_number within # all the parts of the email (see TMail monkeypatch above for how these # attributes are added). ensure_parts_counted must be called before using - # the attributes. + # the attributes. def ensure_parts_counted @count_parts_count = 0 _count_parts_recursive(self.mail) @@ -215,7 +215,7 @@ class IncomingMessage < ActiveRecord::Base # e.g. http://www.whatdotheyknow.com/request/chinese_names_for_british_politi msg = Mapi::Msg.open(StringIO.new(part.body)) part.rfc822_attachment = TMail::Mail.parse(msg.to_mime.to_s) - elsif part.content_type == 'application/ms-tnef' + elsif part.content_type == 'application/ms-tnef' # A set of attachments in a TNEF file part.rfc822_attachment = TNEF.as_tmail(part.body) end @@ -289,7 +289,7 @@ class IncomingMessage < ActiveRecord::Base # buggy versions of pdftk sometimes fail on # compression, I don't see it's a disaster in # these cases to save an uncompressed version? - recompressed_text = censored_uncompressed_text + recompressed_text = censored_uncompressed_text logger.warn "Unable to compress PDF; problem with your pdftk version?" end if !recompressed_text.nil? && !recompressed_text.empty? @@ -297,10 +297,10 @@ class IncomingMessage < ActiveRecord::Base end end end - return + return end - self._binary_mask_stuff_internal!(text) + self._binary_mask_stuff_internal!(text) end # Used by binary_mask_stuff - replace text in place @@ -309,7 +309,7 @@ class IncomingMessage < ActiveRecord::Base orig_size = text.size # Replace ASCII email addresses... - text.gsub!(MySociety::Validate.email_find_regexp) do |email| + text.gsub!(MySociety::Validate.email_find_regexp) do |email| email.gsub(/[^@.]/, 'x') end @@ -320,7 +320,7 @@ class IncomingMessage < ActiveRecord::Base emails = ascii_chars.scan(MySociety::Validate.email_find_regexp) # Convert back to UCS-2, making a mask at the same time emails.map! {|email| [ - Iconv.conv('ucs-2le', 'ascii', email[0]), + Iconv.conv('ucs-2le', 'ascii', email[0]), Iconv.conv('ucs-2le', 'ascii', email[0].gsub(/[^@.]/, 'x')) ] } # Now search and replace the UCS-2 email with the UCS-2 mask @@ -416,7 +416,7 @@ class IncomingMessage < ActiveRecord::Base # http://www.whatdotheyknow.com/request/secured_convictions_aided_by_cct multiline_original_message = '(' + '''>>>.* \d\d/\d\d/\d\d\d\d\s+\d\d:\d\d(?::\d\d)?\s*>>>''' + ')' text.gsub!(/^(#{multiline_original_message}\n.*)$/ms, replacement) - + # Single line sections text.gsub!(/^(>.*\n)/, replacement) text.gsub!(/^(On .+ (wrote|said):\n)/, replacement) @@ -453,8 +453,8 @@ class IncomingMessage < ActiveRecord::Base # http://www.whatdotheyknow.com/request/123/response/192 # http://www.whatdotheyknow.com/request/235/response/513 # http://www.whatdotheyknow.com/request/445/response/743 - original_message = - '(' + '''----* This is a copy of the message, including all the headers. ----*''' + + original_message = + '(' + '''----* This is a copy of the message, including all the headers. ----*''' + '|' + '''----*\s*Original Message\s*----*''' + '|' + '''----*\s*Forwarded message.+----*''' + '|' + '''----*\s*Forwarded by.+----*''' + @@ -482,7 +482,7 @@ class IncomingMessage < ActiveRecord::Base return part_file_name end - # (This risks losing info if the unchosen alternative is the only one to contain + # (This risks losing info if the unchosen alternative is the only one to contain # useful info, but let's worry about that another time) def get_attachment_leaves force = true @@ -538,7 +538,7 @@ class IncomingMessage < ActiveRecord::Base if calc_mime curr_mail.content_type = calc_mime end - end + end # Use standard content types for Word documents etc. curr_mail.content_type = normalise_content_type(curr_mail.content_type) @@ -660,11 +660,11 @@ class IncomingMessage < ActiveRecord::Base # Test if it's good UTF-8 text = Iconv.conv('utf-8', 'utf-8', text) rescue Iconv::IllegalSequence - # Text looks like unlabelled nonsense, + # Text looks like unlabelled nonsense, # strip out anything that isn't UTF-8 begin - text = Iconv.conv('utf-8//IGNORE', source_charset, text) + - _("\n\n[ {{site_name}} note: The above text was badly encoded, and has had strange characters removed. ]", + text = Iconv.conv('utf-8//IGNORE', source_charset, text) + + _("\n\n[ {{site_name}} note: The above text was badly encoded, and has had strange characters removed. ]", :site_name => MySociety::Config.get('SITE_NAME', 'Alaveteli')) rescue Iconv::InvalidEncoding, Iconv::IllegalSequence if source_charset != "utf-8" @@ -673,7 +673,7 @@ class IncomingMessage < ActiveRecord::Base end end end - + # Fix DOS style linefeeds to Unix style ones (or other later regexps won't work) # Needed for e.g. http://www.whatdotheyknow.com/request/60/response/98 @@ -693,7 +693,7 @@ class IncomingMessage < ActiveRecord::Base # Find first part which is text/plain or text/html # (We have to include HTML, as increasingly there are mail clients that # include no text alternative for the main part, and we don't want to - # instead use the first text attachment + # instead use the first text attachment # e.g. http://www.whatdotheyknow.com/request/list_of_public_authorties) leaves.each do |p| if p.content_type == 'text/plain' or p.content_type == 'text/html' @@ -707,8 +707,8 @@ class IncomingMessage < ActiveRecord::Base return p end end - - # ... or if none, consider first part + + # ... or if none, consider first part p = leaves[0] # if it is a known type then don't use it, return no body (nil) if !p.nil? && AlaveteliFileTypes.mimetype_to_extension(p.content_type) @@ -752,7 +752,7 @@ class IncomingMessage < ActiveRecord::Base :display_size => "0K") attachment.save! attachments << attachment - end + end return attachments end @@ -802,7 +802,7 @@ class IncomingMessage < ActiveRecord::Base # XXX call _convert_part_body_to_text here, but need to get charset somehow # e.g. http://www.whatdotheyknow.com/request/1593/response/3088/attach/4/Freedom%20of%20Information%20request%20-%20car%20oval%20sticker:%20Article%2020,%20Convention%20on%20Road%20Traffic%201949.txt body = headers + "\n" + body - + # This is quick way of getting all headers, but instead we only add some a) to # make it more usable, b) as at least one authority accidentally leaked security # information into a header. @@ -836,7 +836,7 @@ class IncomingMessage < ActiveRecord::Base end # now get rid of any attachments we no longer have - FoiAttachment.destroy_all("id NOT IN (#{attachments.join(',')}) AND incoming_message_id = #{self.id}") + FoiAttachment.destroy_all("id NOT IN (#{attachments.join(',')}) AND incoming_message_id = #{self.id}") end # Returns body text as HTML with quotes flattened, and emails removed. @@ -898,13 +898,13 @@ class IncomingMessage < ActiveRecord::Base self.remove_privacy_sensitive_things!(text) # This can be useful for memory debugging #STDOUT.puts 'xxx '+ MySociety::DebugHelpers::allocated_string_size_around_gc - + # Save clipped version for snippets if self.cached_attachment_text_clipped.nil? self.cached_attachment_text_clipped = text[0..MAX_ATTACHMENT_TEXT_CLIPPED] self.save! end - + return text end # Returns a version reduced to a sensible maximum size - this @@ -987,7 +987,7 @@ class IncomingMessage < ActiveRecord::Base for entry in zip_file if entry.file? filename = entry.to_s - begin + begin body = entry.get_input_stream.read rescue # move to next attachment silently if there were problems @@ -1001,7 +1001,7 @@ class IncomingMessage < ActiveRecord::Base else content_type = 'application/octet-stream' end - + text += _get_attachment_text_internal_one_file(content_type, body) end end @@ -1051,7 +1051,7 @@ class IncomingMessage < ActiveRecord::Base end end - # Search all info requests for + # Search all info requests for def IncomingMessage.find_all_unknown_mime_types for incoming_message in IncomingMessage.find(:all) for attachment in incoming_message.get_attachments_for_display @@ -1117,7 +1117,7 @@ class IncomingMessage < ActiveRecord::Base content_type = 'application/vnd.ms-excel' end if content_type == 'application/mspowerpoint' or content_type == 'application/x-ms-powerpoint' - content_type = 'application/vnd.ms-powerpoint' + content_type = 'application/vnd.ms-powerpoint' end if content_type == 'application/msword' or content_type == 'application/x-ms-word' content_type = 'application/vnd.ms-word' diff --git a/app/models/info_request.rb b/app/models/info_request.rb index e570150bb..3b86f4cb3 100644 --- a/app/models/info_request.rb +++ b/app/models/info_request.rb @@ -51,14 +51,14 @@ class InfoRequest < ActiveRecord::Base # user described state (also update in info_request_event, admin_request/edit.rhtml) validate :must_be_valid_state - validates_inclusion_of :prominence, :in => [ - 'normal', + validates_inclusion_of :prominence, :in => [ + 'normal', 'backpage', 'hidden', 'requester_only' ] - validates_inclusion_of :law_used, :in => [ + validates_inclusion_of :law_used, :in => [ 'foi', # Freedom of Information Act 'eir', # Environmental Information Regulations ] @@ -77,13 +77,13 @@ class InfoRequest < ActiveRecord::Base ] def self.enumerate_states - states = [ + states = [ 'waiting_response', - 'waiting_clarification', + 'waiting_clarification', 'gone_postal', 'not_held', 'rejected', # this is called 'refused' in UK FOI law and the user interface, but 'rejected' internally for historic reasons - 'successful', + 'successful', 'partially_successful', 'internal_review', 'error_message', @@ -97,7 +97,7 @@ class InfoRequest < ActiveRecord::Base end def must_be_valid_state - errors.add(:described_state, "is not a valid state") if + errors.add(:described_state, "is not a valid state") if !InfoRequest.enumerate_states.include? described_state end @@ -123,7 +123,7 @@ class InfoRequest < ActiveRecord::Base errors.add(:title, _('Please describe more what the request is about in the subject. There is no need to say it is an FOI request, we add that on anyway.')) end end - + OLD_AGE_IN_DAYS = 21.days def after_initialize @@ -169,7 +169,7 @@ class InfoRequest < ActiveRecord::Base end end # Force reindex when tag string changes - alias_method :orig_tag_string=, :tag_string= + alias_method :orig_tag_string=, :tag_string= def tag_string=(tag_string) ret = self.orig_tag_string=(tag_string) reindex_request_events @@ -222,7 +222,7 @@ public end # Email which public body should use to respond to request. This is in - # the format PREFIXrequest-ID-HASH@DOMAIN. Here ID is the id of the + # the format PREFIXrequest-ID-HASH@DOMAIN. Here ID is the id of the # FOI request, and HASH is a signature for that id. def incoming_email return self.magic_email("request-") @@ -254,7 +254,7 @@ public end end - # Two sorts of laws for requests, FOI or EIR + # Two sorts of laws for requests, FOI or EIR def law_used_full if self.law_used == 'foi' return _("Freedom of Information") @@ -309,7 +309,7 @@ public guesses = [] # 1. Try to guess based on the email address(es) addresses = - (incoming_message.mail.to || []) + + (incoming_message.mail.to || []) + (incoming_message.mail.cc || []) + (incoming_message.mail.envelope_to || []) addresses.uniq! @@ -541,7 +541,7 @@ public self.base_calculate_status end end - + def base_calculate_status return 'waiting_classification' if self.awaiting_description return described_state unless self.described_state == "waiting_response" @@ -561,13 +561,13 @@ public curr_state = nil for event in self.info_request_events.reverse event.xapian_mark_needs_index # we need to reindex all events in order to update their latest_* terms - if curr_state.nil? + if curr_state.nil? if !event.described_state.nil? curr_state = event.described_state end end - if !curr_state.nil? && event.event_type == 'response' + if !curr_state.nil? && event.event_type == 'response' if event.calculated_state != curr_state event.calculated_state = curr_state event.last_described_at = Time.now() @@ -581,7 +581,7 @@ public elsif !curr_state.nil? && (event.event_type == 'followup_sent' || event.event_type == 'sent') && !event.described_state.nil? && (event.described_state == 'waiting_response' || event.described_state == 'internal_review') # Followups can set the status to waiting response / internal # review. Initial requests ('sent') set the status to waiting response. - + # We want to store that in calculated_state state so it gets # indexed. if event.calculated_state != event.described_state @@ -725,8 +725,8 @@ public def index_of_last_described_event events = self.info_request_events events.each_index do |i| - revi = events.size - 1 - i - m = events[revi] + revi = events.size - 1 - i + m = events[revi] if not m.described_state.nil? return revi end @@ -737,7 +737,7 @@ public def last_event_id_needing_description last_event = events_needing_description[-1] last_event.nil? ? 0 : last_event.id - end + end # Returns all the events which the user hasn't described yet - an empty array if all described. def events_needing_description @@ -825,11 +825,11 @@ public track_thing.destroy end self.user_info_request_sent_alerts.each { |a| a.destroy } - self.info_request_events.each do |info_request_event| + self.info_request_events.each do |info_request_event| info_request_event.track_things_sent_emails.each { |a| a.destroy } info_request_event.destroy end - self.exim_logs.each do |exim_log| + self.exim_logs.each do |exim_log| exim_log.destroy end self.outgoing_messages.each { |a| a.destroy } @@ -844,8 +844,8 @@ public return InfoRequest.magic_email_for_id(prefix_part, self.id) end - def InfoRequest.magic_email_for_id(prefix_part, id) - magic_email = MySociety::Config.get("INCOMING_EMAIL_PREFIX", "") + def InfoRequest.magic_email_for_id(prefix_part, id) + magic_email = MySociety::Config.get("INCOMING_EMAIL_PREFIX", "") magic_email += prefix_part + id.to_s magic_email += "-" + InfoRequest.hash_from_id(id) magic_email += "@" + MySociety::Config.get("INCOMING_EMAIL_DOMAIN", "localhost") @@ -890,14 +890,14 @@ public def InfoRequest.find_old_unclassified(extra_params={}) last_response_created_at = last_event_time_clause('response') age = extra_params[:age_in_days] ? extra_params[:age_in_days].days : OLD_AGE_IN_DAYS - params = {:select => "*, #{last_response_created_at} as last_response_time", - :conditions => ["awaiting_description = ? and #{last_response_created_at} < ? and url_title != 'holding_pen'", - true, Time.now() - age], + params = {:select => "*, #{last_response_created_at} as last_response_time", + :conditions => ["awaiting_description = ? and #{last_response_created_at} < ? and url_title != 'holding_pen'", + true, Time.now() - age], :order => "last_response_time"} params[:limit] = extra_params[:limit] if extra_params[:limit] params[:include] = extra_params[:include] if extra_params[:include] if extra_params[:order] - params[:order] = extra_params[:order] + params[:order] = extra_params[:order] params.delete(:select) end if extra_params[:conditions] @@ -907,7 +907,7 @@ public end find(:all, params) end - + def is_old_unclassified? return false if !awaiting_description return false if url_title == 'holding_pen' @@ -926,7 +926,7 @@ public next end incoming_message.safe_mail_from - + email = OutgoingMailer.email_for_followup(self, incoming_message) name = OutgoingMailer.name_for_followup(self, incoming_message) @@ -955,7 +955,7 @@ public end end end - + def apply_censor_rules_to_binary!(binary) for censor_rule in self.censor_rules censor_rule.apply_to_binary!(binary) @@ -966,7 +966,7 @@ public end end end - + def is_owning_user?(user) !user.nil? && (user.id == user_id || user.owns_every_request?) end @@ -975,10 +975,10 @@ public end def user_can_view?(user) - if self.prominence == 'hidden' + if self.prominence == 'hidden' return User.view_hidden_requests?(user) end - if self.prominence == 'requester_only' + if self.prominence == 'requester_only' return self.is_owning_user?(user) end return true @@ -1019,7 +1019,7 @@ public end def json_for_api(deep) - ret = { + ret = { :id => self.id, :url_title => self.url_title, :title => self.title, diff --git a/app/models/info_request_event.rb b/app/models/info_request_event.rb index cb49596cb..9ce191f6b 100644 --- a/app/models/info_request_event.rb +++ b/app/models/info_request_event.rb @@ -36,7 +36,7 @@ class InfoRequestEvent < ActiveRecord::Base has_many :track_things_sent_emails validates_presence_of :event_type - + def self.enumerate_event_types [ 'sent', @@ -64,27 +64,27 @@ class InfoRequestEvent < ActiveRecord::Base validate :must_be_valid_state # whether event is publicly visible - validates_inclusion_of :prominence, :in => [ - 'normal', + validates_inclusion_of :prominence, :in => [ + 'normal', 'hidden', 'requester_only' ] def must_be_valid_state if !described_state.nil? and !InfoRequest.enumerate_states.include?(described_state) - errors.add(described_state, "is not a valid state") + errors.add(described_state, "is not a valid state") end end - + def user_can_view?(user) if !self.info_request.user_can_view?(user) raise "internal error, called user_can_view? on event when there is not permission to view entire request" end - if self.prominence == 'hidden' + if self.prominence == 'hidden' return User.view_hidden_requests?(user) end - if self.prominence == 'requester_only' + if self.prominence == 'requester_only' return self.info_request.is_owning_user?(user) end return true @@ -93,7 +93,7 @@ class InfoRequestEvent < ActiveRecord::Base # Full text search indexing acts_as_xapian :texts => [ :search_text_main, :title ], - :values => [ + :values => [ [ :created_at, 0, "range_search", :date ], # for QueryParser range searches e.g. 01/01/2008..14/01/2008 [ :created_at_numeric, 1, "created_at", :number ], # for sorting [ :described_at_numeric, 2, "described_at", :number ], # XXX using :number for lack of :datetime support in Xapian values @@ -110,7 +110,7 @@ class InfoRequestEvent < ActiveRecord::Base [ :latest_status, 'L', "latest_status" ], [ :waiting_classification, 'W', "waiting_classification" ], [ :filetype, 'T', "filetype" ], - [ :tags, 'U', "tag" ] + [ :tags, 'U', "tag" ] ], :if => :indexed_by_search?, :eager_load => [ :outgoing_message, :comment, { :info_request => [ :user, :public_body, :censor_rules ] } ] @@ -119,7 +119,7 @@ class InfoRequestEvent < ActiveRecord::Base self.info_request.user.url_name end def requested_from - # acts_as_xapian will detect translated fields via Globalize and add all the + # acts_as_xapian will detect translated fields via Globalize and add all the # available locales to the index. But 'requested_from' is not translated directly, # although it relies on a translated field in PublicBody. Hence, we need to # manually add all the localized values to the index (Xapian can handle a list @@ -174,15 +174,15 @@ class InfoRequestEvent < ActiveRecord::Base end def described_at_numeric # format it here as no datetime support in Xapian's value ranges - return self.described_at.strftime("%Y%m%d%H%M%S") + return self.described_at.strftime("%Y%m%d%H%M%S") end def created_at_numeric # format it here as no datetime support in Xapian's value ranges - return self.created_at.strftime("%Y%m%d%H%M%S") + return self.created_at.strftime("%Y%m%d%H%M%S") end - + def incoming_message_selective_columns(fields) - message = IncomingMessage.find(:all, + message = IncomingMessage.find(:all, :select => fields + ", incoming_messages.info_request_id", :joins => "INNER JOIN info_request_events ON incoming_messages.id = incoming_message_id ", :conditions => "info_request_events.id = #{self.id}" @@ -218,7 +218,7 @@ class InfoRequestEvent < ActiveRecord::Base # performance reasons. Xapian will take the full text. def search_text_main(clipped = false) text = '' - if self.event_type == 'sent' + if self.event_type == 'sent' text = text + self.outgoing_message.get_text_for_indexing + "\n\n" elsif self.event_type == 'followup_sent' text = text + self.outgoing_message.get_text_for_indexing + "\n\n" @@ -236,7 +236,7 @@ class InfoRequestEvent < ActiveRecord::Base return text end def title - if self.event_type == 'sent' + if self.event_type == 'sent' return self.info_request.title end return '' @@ -317,26 +317,26 @@ class InfoRequestEvent < ActiveRecord::Base old_value = old_params[key].to_s new_value = new_params[key].to_s if old_value != new_value - ret = ret + "<em>" + CGI.escapeHTML(key) + ":</em> " - ret = ret + - CGI.escapeHTML(MySociety::Format.wrap_email_body_by_lines(old_value).strip).gsub(/\n/, '<br>') + - " => " + + ret = ret + "<em>" + CGI.escapeHTML(key) + ":</em> " + ret = ret + + CGI.escapeHTML(MySociety::Format.wrap_email_body_by_lines(old_value).strip).gsub(/\n/, '<br>') + + " => " + CGI.escapeHTML(MySociety::Format.wrap_email_body_by_lines(new_value).strip).gsub(/\n/, '<br>') ret = ret + "<br>" end end for key, value in other_params - ret = ret + "<em>" + CGI.escapeHTML(key.to_s) + ":</em> " - ret = ret + CGI.escapeHTML(value.to_s.strip) + ret = ret + "<em>" + CGI.escapeHTML(key.to_s) + ":</em> " + ret = ret + CGI.escapeHTML(value.to_s.strip) ret = ret + "<br>" end return ret end - - def is_incoming_message?() not self.incoming_message_selective_columns("incoming_messages.id").nil? end - def is_outgoing_message?() not self.outgoing_message.nil? end - def is_comment?() not self.comment.nil? end + + def is_incoming_message?() not self.incoming_message_selective_columns("incoming_messages.id").nil? end + def is_outgoing_message?() not self.outgoing_message.nil? end + def is_comment?() not self.comment.nil? end # Display version of status def display_status @@ -406,7 +406,7 @@ class InfoRequestEvent < ActiveRecord::Base end def json_for_api(deep, snippet_highlight_proc = nil) - ret = { + ret = { :id => self.id, :event_type => self.event_type, # params_yaml has possibly sensitive data in it, don't include it @@ -431,7 +431,7 @@ class InfoRequestEvent < ActiveRecord::Base ret[:snippet] = snippet_highlight_proc.call(self.search_text_main(true)) end - if deep + if deep ret[:info_request] = self.info_request.json_for_api(false) ret[:public_body] = self.info_request.public_body.json_for_api ret[:user] = self.info_request.user.json_for_api diff --git a/app/models/outgoing_mailer.rb b/app/models/outgoing_mailer.rb index bf81bb89f..8562c5b68 100644 --- a/app/models/outgoing_mailer.rb +++ b/app/models/outgoing_mailer.rb @@ -10,12 +10,12 @@ # separated) paragraphs, as is the convention for all the other mailers. This # turned out to fit better with user exepectations when formatting messages. # -# XXX The other mail templates are written to use blank line separated +# XXX The other mail templates are written to use blank line separated # paragraphs. They could be rewritten, and the wrapping method made uniform # throughout the application. class OutgoingMailer < ApplicationMailer - + # Email to public body requesting info def initial_request(info_request, outgoing_message) @wrap_lines_as_paragraphs = true @@ -96,4 +96,4 @@ class OutgoingMailer < ApplicationMailer end end - + diff --git a/app/models/outgoing_message.rb b/app/models/outgoing_message.rb index de3c916aa..29445d587 100644 --- a/app/models/outgoing_message.rb +++ b/app/models/outgoing_message.rb @@ -37,7 +37,7 @@ class OutgoingMessage < ActiveRecord::Base # can have many events, for items which were resent by site admin e.g. if # contact address changed - has_many :info_request_events + has_many :info_request_events # To override the default letter attr_accessor :default_letter @@ -45,7 +45,7 @@ class OutgoingMessage < ActiveRecord::Base # reindex if body text is edited (e.g. by admin interface) after_update :xapian_reindex_after_update def xapian_reindex_after_update - if self.changes.include?('body') + if self.changes.include?('body') for info_request_event in self.info_request_events info_request_event.xapian_mark_needs_index end @@ -83,11 +83,11 @@ class OutgoingMessage < ActiveRecord::Base "\n\n" + "I am writing to request an internal review of " + self.info_request.public_body.name + - "'s handling of my FOI request " + - "'" + self.info_request.title + "'." + + "'s handling of my FOI request " + + "'" + self.info_request.title + "'." + "\n\n\n\n [ " + self.get_internal_review_insert_here_note + " ] \n\n\n\n" + "A full history of my FOI request and all correspondence is available on the Internet at this address:\n" + - "http://" + MySociety::Config.get("DOMAIN", '127.0.0.1:3000') + "/request/" + self.info_request.url_title + "http://" + MySociety::Config.get("DOMAIN", '127.0.0.1:3000') + "/request/" + self.info_request.url_title else "" end @@ -98,7 +98,7 @@ class OutgoingMessage < ActiveRecord::Base def set_signature_name(name) # XXX We use raw_body here to get unstripped one if self.raw_body == self.get_default_message - self.body = self.raw_body + name + self.body = self.raw_body + name end end @@ -130,7 +130,7 @@ class OutgoingMessage < ActiveRecord::Base def contains_postcode? MySociety::Validate.contains_postcode?(self.body) end - + # Set default letter def after_initialize if self.body.nil? diff --git a/app/models/post_redirect.rb b/app/models/post_redirect.rb index c9a6229a4..2b636453f 100644 --- a/app/models/post_redirect.rb +++ b/app/models/post_redirect.rb @@ -64,7 +64,7 @@ class PostRedirect < ActiveRecord::Base MySociety::Util.generate_token end - # Make the token + # Make the token def after_initialize # The token is used to return you to what you are doing after the login form. if not self.token diff --git a/app/models/profile_photo.rb b/app/models/profile_photo.rb index 798094d90..6c66d868a 100644 --- a/app/models/profile_photo.rb +++ b/app/models/profile_photo.rb @@ -27,9 +27,9 @@ class ProfilePhoto < ActiveRecord::Base belongs_to :user # deliberately don't strip_attributes, so keeps raw photo properly - + attr_accessor :x, :y, :w, :h - + # convert binary data blob into ImageMagick image when assigned attr_accessor :image def after_initialize @@ -45,7 +45,7 @@ class ProfilePhoto < ActiveRecord::Base self.image = nil return end - + self.image = image_list[0] # XXX perhaps take largest image or somesuch if there were multiple in the file? self.convert_image end @@ -68,7 +68,7 @@ class ProfilePhoto < ActiveRecord::Base # draft images are before the user has cropped them if !self.draft && (image.columns != WIDTH || image.rows != HEIGHT) # do any exact cropping (taken from Jcrop interface) - if self.w && self.h + if self.w && self.h image.crop!(self.x.to_i, self.y.to_i, self.w.to_i, self.h.to_i) end # do any further cropping @@ -98,7 +98,7 @@ class ProfilePhoto < ActiveRecord::Base if self.image.format != 'PNG' errors.add(:data, N_("Failed to convert image to a PNG")) end - + if !self.draft && (self.image.columns != WIDTH || self.image.rows != HEIGHT) errors.add(:data, N_("Failed to convert image to the correct size: at %{cols}x%{rows}, need %{width}x%{height}" % { :cols => self.image.columns, :rows => self.image.rows, :width => WIDTH, :height => HEIGHT })) end diff --git a/app/models/public_body.rb b/app/models/public_body.rb index 54af547bd..0e21037ef 100644 --- a/app/models/public_body.rb +++ b/app/models/public_body.rb @@ -58,11 +58,11 @@ class PublicBody < ActiveRecord::Base short_long_name = t.short_name if t.short_name and !t.short_name.empty? t.url_name = MySociety::Format.simplify_url_part(short_long_name, 'body') end - + def translated_versions translations end - + def translated_versions=(translation_attrs) def skip?(attrs) valueless = attrs.inject({}) { |h, (k, v)| h[k] = v if v != '' and k != 'locale'; h } # because we want to fall back to alternative translations where there are empty values @@ -86,7 +86,7 @@ class PublicBody < ActiveRecord::Base end end end - + # Make sure publication_scheme gets the correct default value. # (This would work automatically, were publication_scheme not a translated attribute) def after_initialize @@ -96,7 +96,7 @@ class PublicBody < ActiveRecord::Base # like find_by_url_name but also search historic url_name if none found def self.find_by_url_name_with_historic(name) locale = self.locale || I18n.locale - PublicBody.with_locale(locale) do + PublicBody.with_locale(locale) do found = PublicBody.find(:all, :conditions => ["public_body_translations.url_name='#{name}'"], :joins => :translations, @@ -192,15 +192,15 @@ class PublicBody < ActiveRecord::Base end acts_as_xapian :texts => [ :name, :short_name, :notes ], - :values => [ + :values => [ [ :created_at_numeric, 1, "created_at", :number ] # for sorting ], :terms => [ [ :variety, 'V', "variety" ], - [ :tag_array_for_search, 'U', "tag" ] + [ :tag_array_for_search, 'U', "tag" ] ] def created_at_numeric # format it here as no datetime support in Xapian's value ranges - return self.created_at.strftime("%Y%m%d%H%M%S") + return self.created_at.strftime("%Y%m%d%H%M%S") end def variety return "authority" @@ -236,7 +236,7 @@ class PublicBody < ActiveRecord::Base def update_url_name self.url_name = MySociety::Format.simplify_url_part(self.short_or_long_name, 'body') end - + # Return the short name if present, or else long name def short_or_long_name if self.short_name.nil? || self.short_name.empty? # 'nil' can happen during construction @@ -253,7 +253,7 @@ class PublicBody < ActiveRecord::Base first = true for tag in self.tags if PublicBodyCategories::get().by_tag().include?(tag.name) - desc = PublicBodyCategories::get().singular_by_tag()[tag.name] + desc = PublicBodyCategories::get().singular_by_tag()[tag.name] if first # terrible that Ruby/Rails doesn't have an equivalent of ucfirst # (capitalize shockingly converts later characters to lowercase) @@ -270,7 +270,7 @@ class PublicBody < ActiveRecord::Base if types.size > 0 ret = types[0, types.size - 1].join(", ") if types.size > 1 - ret = ret + " and " + ret = ret + " and " end ret = ret + types[-1] return ret @@ -351,12 +351,12 @@ class PublicBody < ActiveRecord::Base for existing_body in bodies # Hide InternalAdminBody from import notes next if existing_body.id == PublicBody.internal_admin_body.id - + bodies_by_name[existing_body.name] = existing_body set_of_existing.add(existing_body.name) end end - + set_of_importing = Set.new() field_names = { 'name'=>1, 'request_email'=>2 } # Default values in case no field list is given line = 0 @@ -372,7 +372,7 @@ class PublicBody < ActiveRecord::Base fields = {} field_names.each{|name, i| fields[name] = row[i]} - + name = row[field_names['name']] email = row[field_names['request_email']] next if name.nil? @@ -384,7 +384,7 @@ class PublicBody < ActiveRecord::Base errors.push "error: line #{line.to_s}: invalid email '#{email}' for authority '#{name}'" next end - + field_list = ['name', 'short_name', 'request_email', 'notes', 'publication_scheme', 'home_page', 'tag_string'] if public_body = bodies_by_name[name] # Existing public body @@ -394,7 +394,7 @@ class PublicBody < ActiveRecord::Base field_list.each do |field_name| localized_field_name = (locale.to_s == I18n.default_locale.to_s) ? field_name : "#{field_name}.#{locale}" localized_value = field_names[localized_field_name] && row[field_names[localized_field_name]] - + # Tags are a special case, as we support adding to the field, not just setting a new value if localized_field_name == 'tag_string' if localized_value.nil? @@ -402,11 +402,11 @@ class PublicBody < ActiveRecord::Base else if tag_behaviour == 'add' localized_value = "#{localized_value} #{tag}" unless tag.empty? - localized_value = "#{localized_value} #{public_body.tag_string}" + localized_value = "#{localized_value} #{public_body.tag_string}" end end end - + if !localized_value.nil? and public_body.send(field_name) != localized_value changed[field_name] = "#{public_body.send(field_name)}: #{localized_value}" public_body.send("#{field_name}=", localized_value) @@ -416,14 +416,14 @@ class PublicBody < ActiveRecord::Base unless changed.empty? notes.push "line #{line.to_s}: updating authority '#{name}' (locale: #{locale}):\n\t#{changed.to_json}" public_body.last_edit_editor = editor - public_body.last_edit_comment = 'Updated from spreadsheet' + public_body.last_edit_comment = 'Updated from spreadsheet' public_body.save! end end end else # New public body public_body = PublicBody.new(:name=>"", :short_name=>"", :request_email=>"") - available_locales.each do |locale| + available_locales.each do |locale| PublicBody.with_locale(locale) do changed = ActiveSupport::OrderedHash.new field_list.each do |field_name| @@ -433,7 +433,7 @@ class PublicBody < ActiveRecord::Base if localized_field_name == 'tag_string' and tag_behaviour == 'add' localized_value = "#{localized_value} #{tag}" unless tag.empty? end - + if !localized_value.nil? and public_body.send(field_name) != localized_value changed[field_name] = localized_value public_body.send("#{field_name}=", localized_value) @@ -444,7 +444,7 @@ class PublicBody < ActiveRecord::Base notes.push "line #{line.to_s}: creating new authority '#{name}' (locale: #{locale}):\n\t#{changed.to_json}" public_body.publication_scheme = public_body.publication_scheme || "" public_body.last_edit_editor = editor - public_body.last_edit_comment = 'Created from spreadsheet' + public_body.last_edit_comment = 'Created from spreadsheet' public_body.save! end end @@ -454,7 +454,7 @@ class PublicBody < ActiveRecord::Base set_of_importing.add(name) end - # Give an error listing ones that are to be deleted + # Give an error listing ones that are to be deleted deleted_ones = set_of_existing - set_of_importing if deleted_ones.size > 0 notes.push "Notes: Some " + tag + " bodies are in database, but not in CSV file:\n " + Array(deleted_ones).sort.join("\n ") + "\nYou may want to delete them manually.\n" @@ -530,7 +530,7 @@ class PublicBody < ActiveRecord::Base end def json_for_api - return { + return { :id => self.id, :url_name => self.url_name, :name => self.name, @@ -538,7 +538,7 @@ class PublicBody < ActiveRecord::Base # :request_email # we hide this behind a captcha, to stop people doing bulk requests easily :created_at => self.created_at, :updated_at => self.updated_at, - # don't add the history as some edit comments contain sensitive information + # don't add the history as some edit comments contain sensitive information # :version, :last_edit_editor, :last_edit_comment :home_page => self.calculated_home_page, :notes => self.notes, diff --git a/app/models/raw_email.rb b/app/models/raw_email.rb index 1feb9c70b..29122e692 100644 --- a/app/models/raw_email.rb +++ b/app/models/raw_email.rb @@ -16,7 +16,7 @@ class RawEmail < ActiveRecord::Base # deliberately don't strip_attributes, so keeps raw email properly - + has_one :incoming_message # We keep the old data_text field (which is of type text) for backwards @@ -30,7 +30,7 @@ class RawEmail < ActiveRecord::Base return File.join(Rails.root, 'files/raw_email_test') else return File.join(MySociety::Config.get('RAW_EMAILS_LOCATION', - 'files/raw_emails'), + 'files/raw_emails'), request_id[0..2], request_id) end end diff --git a/app/models/request_mailer.rb b/app/models/request_mailer.rb index 177a39241..e336111ee 100644 --- a/app/models/request_mailer.rb +++ b/app/models/request_mailer.rb @@ -9,7 +9,7 @@ require 'alaveteli_file_types' class RequestMailer < ApplicationMailer - + # Used when an FOI officer uploads a response from their web browser - this is # the "fake" email used to store in the same format in the database as if they @@ -38,7 +38,7 @@ class RequestMailer < ApplicationMailer @subject = "Your response to an FOI request was not delivered" attachment :content_type => 'message/rfc822', :body => raw_email_data, :filename => "original.eml", :transfer_encoding => '7bit', :content_disposition => 'inline' - @body = { + @body = { :info_request => info_request, :contact_email => MySociety::Config.get("CONTACT_EMAIL", 'contact@localhost') } @@ -142,7 +142,7 @@ class RequestMailer < ApplicationMailer # Tell the requester that they need to clarify their request def not_clarified_alert(info_request, incoming_message) respond_url = show_response_url(:id => info_request.id, :incoming_message_id => incoming_message.id) - respond_url = respond_url + "#followup" + respond_url = respond_url + "#followup" post_redirect = PostRedirect.new( :uri => respond_url, @@ -182,7 +182,7 @@ class RequestMailer < ApplicationMailer # Class function, called by script/mailin with all incoming responses. # [ This is a copy (Monkeypatch!) of function from action_mailer/base.rb, # but which additionally passes the raw_email to the member function, as we - # want to record it. + # want to record it. # # That is because we want to be sure we properly record the actual message # received in its raw form - so any information won't be lost in a round @@ -215,7 +215,7 @@ class RequestMailer < ApplicationMailer # Find which info requests the email is for reply_info_requests = self.requests_matching_email(email) # Nothing found, so save in holding pen - if reply_info_requests.size == 0 + if reply_info_requests.size == 0 reason = _("Could not identify the request from the email address") request = InfoRequest.holding_pen_request request.receive(email, raw_email, false, reason) @@ -225,7 +225,7 @@ class RequestMailer < ApplicationMailer # Send the message to each request, to be archived with it for reply_info_request in reply_info_requests # If environment variable STOP_DUPLICATES is set, don't send message with same id again - if ENV['STOP_DUPLICATES'] + if ENV['STOP_DUPLICATES'] if reply_info_request.already_received?(email, raw_email) raise "message " + email.message_id + " already received by request" end @@ -275,7 +275,7 @@ class RequestMailer < ApplicationMailer end end - # Send email alerts for new responses which haven't been classified. By default, + # Send email alerts for new responses which haven't been classified. By default, # it goes out 3 days after last update of event, then after 10, then after 24. def self.alert_new_response_reminders MySociety::Config.get("NEW_RESPONSE_REMINDER_AFTER_DAYS", [3, 10, 24]).each_with_index do |days, i| @@ -283,10 +283,10 @@ class RequestMailer < ApplicationMailer end end def self.alert_new_response_reminders_internal(days_since, type_code) - info_requests = InfoRequest.find_old_unclassified(:order => 'info_requests.id', - :include => [:user], + info_requests = InfoRequest.find_old_unclassified(:order => 'info_requests.id', + :include => [:user], :age_in_days => days_since) - + for info_request in info_requests alert_event_id = info_request.get_last_response_event_id last_response_message = info_request.get_last_response @@ -302,7 +302,7 @@ class RequestMailer < ApplicationMailer store_sent.user = info_request.user store_sent.alert_type = type_code store_sent.info_request_event_id = alert_event_id - # XXX uses same template for reminder 1 and reminder 2 right now. + # XXX uses same template for reminder 1 and reminder 2 right now. RequestMailer.deliver_new_response_reminder_alert(info_request, last_response_message) store_sent.save! end @@ -340,11 +340,11 @@ class RequestMailer < ApplicationMailer # Send email alert to request submitter for new comments on the request. def self.alert_comment_on_request() - + # We only check comments made in the last month - this means if the # cron jobs broke for more than a month events would be lost, but no # matter. I suspect the performance gain will be needed (with an index on updated_at) - + # XXX the :order part info_request_events.created_at is a work around # for a very old Rails bug which means eager loading does not respect # association orders. @@ -352,7 +352,7 @@ class RequestMailer < ApplicationMailer # http://lists.rubyonrails.org/pipermail/rails-core/2006-July/001798.html # That that patch has not been applied, despite bribes of beer, is # typical of the lack of quality of Rails. - + info_requests = InfoRequest.find(:all, :conditions => [ "info_requests.id in ( diff --git a/app/models/track_mailer.rb b/app/models/track_mailer.rb index 0c053c4ad..f618fba49 100644 --- a/app/models/track_mailer.rb +++ b/app/models/track_mailer.rb @@ -48,7 +48,7 @@ class TrackMailer < ApplicationMailer end for user in users next if !user.should_be_emailed? - + email_about_things = [] track_things = TrackThing.find(:all, :conditions => [ "tracking_user_id = ? and track_medium = ?", user.id, 'email_daily' ]) for track_thing in track_things @@ -56,7 +56,7 @@ class TrackMailer < ApplicationMailer # # We only use track_things_sent_emails records which are less than 14 days old. # In the search query loop below, we also only use items described in last 7 days. - # An item described that recently definitely can't appear in track_things_sent_emails + # An item described that recently definitely can't appear in track_things_sent_emails # earlier, so this is safe (with a week long margin of error). If the alerts break # for a whole week, then they will miss some items. Tough. done_info_request_events = {} @@ -70,7 +70,7 @@ class TrackMailer < ApplicationMailer # Query for things in this track. We use described_at for the # ordering, so we catch anything new (before described), or # anything whose new status has been described. - xapian_object = InfoRequest.full_search([InfoRequestEvent], track_thing.track_query, 'described_at', true, nil, 100, 1) + xapian_object = InfoRequest.full_search([InfoRequestEvent], track_thing.track_query, 'described_at', true, nil, 100, 1) # Go through looking for unalerted things alert_results = [] for result in xapian_object.results @@ -86,7 +86,7 @@ class TrackMailer < ApplicationMailer alert_results.push(result) end # If there were more alerts for this track, then store them - if alert_results.size > 0 + if alert_results.size > 0 email_about_things.push([track_thing, alert_results, xapian_object]) end end diff --git a/app/models/track_thing.rb b/app/models/track_thing.rb index bdcd87e4f..446060279 100644 --- a/app/models/track_thing.rb +++ b/app/models/track_thing.rb @@ -35,17 +35,17 @@ class TrackThing < ActiveRecord::Base has_many :track_things_sent_emails - validates_inclusion_of :track_type, :in => [ - 'request_updates', + validates_inclusion_of :track_type, :in => [ + 'request_updates', 'all_new_requests', 'all_successful_requests', - 'public_body_updates', + 'public_body_updates', 'user_updates', 'search_query' ] - validates_inclusion_of :track_medium, :in => [ - 'email_daily', + validates_inclusion_of :track_medium, :in => [ + 'email_daily', 'feed' ] @@ -69,7 +69,7 @@ class TrackThing < ActiveRecord::Base end def track_query_description - # XXX this is very brittle... we should probably ask users + # XXX this is very brittle... we should probably ask users # simply to name their tracks when they make them? original_text = parsed_text = self.track_query.gsub(/([()]|OR)/, "") filters = parsed_text.scan /\b\S+:\S+\b/ @@ -101,7 +101,7 @@ class TrackThing < ActiveRecord::Base end if filter =~ /waiting/ statuses << _("awaiting a response") - end + end end if filters.empty? parsed_text = original_text @@ -195,7 +195,7 @@ class TrackThing < ActiveRecord::Base if self.track_type == 'request_updates' @params = { # Website - :list_description => _("'{{link_to_request}}', a request", :link_to_request => "<a href=\"/request/" + CGI.escapeHTML(self.info_request.url_title) + "\">" + CGI.escapeHTML(self.info_request.title) + "</a>"), # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how + :list_description => _("'{{link_to_request}}', a request", :link_to_request => "<a href=\"/request/" + CGI.escapeHTML(self.info_request.url_title) + "\">" + CGI.escapeHTML(self.info_request.title) + "</a>"), # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how :verb_on_page => _("Track this request by email"), :verb_on_page_already => _("You are already tracking this request by email"), # Email @@ -246,7 +246,7 @@ class TrackThing < ActiveRecord::Base elsif self.track_type == 'public_body_updates' @params = { # Website - :list_description => _("'{{link_to_authority}}', a public authority", :link_to_authority => "<a href=\"/body/" + CGI.escapeHTML(self.public_body.url_name) + "\">" + CGI.escapeHTML(self.public_body.name) + "</a>"), # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how + :list_description => _("'{{link_to_authority}}', a public authority", :link_to_authority => "<a href=\"/body/" + CGI.escapeHTML(self.public_body.url_name) + "\">" + CGI.escapeHTML(self.public_body.name) + "</a>"), # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how :verb_on_page => _("Track requests to {{public_body_name}} by email",:public_body_name=>CGI.escapeHTML(self.public_body.name)), :verb_on_page_already => _("You are already tracking requests to {{public_body_name}} by email", :public_body_name=>CGI.escapeHTML(self.public_body.name)), # Email @@ -262,7 +262,7 @@ class TrackThing < ActiveRecord::Base elsif self.track_type == 'user_updates' @params = { # Website - :list_description => _("'{{link_to_user}}', a person", :link_to_user => "<a href=\"/user/" + CGI.escapeHTML(self.tracked_user.url_name) + "\">" + CGI.escapeHTML(self.tracked_user.name) + "</a>"), # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how + :list_description => _("'{{link_to_user}}', a person", :link_to_user => "<a href=\"/user/" + CGI.escapeHTML(self.tracked_user.url_name) + "\">" + CGI.escapeHTML(self.tracked_user.name) + "</a>"), # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how :verb_on_page => _("Track this person by email"), :verb_on_page_already => _("You are already tracking this person by email"), # Email @@ -278,7 +278,7 @@ class TrackThing < ActiveRecord::Base elsif self.track_type == 'search_query' @params = { # Website - :list_description => "<a href=\"/search/" + CGI.escapeHTML(self.track_query) + "/newest/advanced\">" + self.track_query_description + "</a>", # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how + :list_description => "<a href=\"/search/" + CGI.escapeHTML(self.track_query) + "/newest/advanced\">" + self.track_query_description + "</a>", # XXX yeuch, sometimes I just want to call view helpers from the model, sorry! can't work out how :verb_on_page => _("Track things matching this search by email"), :verb_on_page_already => _("You are already tracking things matching this search by email"), # Email diff --git a/app/models/user.rb b/app/models/user.rb index 73d65a8ca..cd8d3e721 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -52,22 +52,22 @@ class User < ActiveRecord::Base attr_accessor :password_confirmation, :no_xapian_reindex validates_confirmation_of :password, :message => _("Please enter the same password twice") - validates_inclusion_of :admin_level, :in => [ + validates_inclusion_of :admin_level, :in => [ 'none', - 'super', + 'super', ], :message => N_('Admin level is not included in list') acts_as_xapian :texts => [ :name, :about_me ], - :values => [ + :values => [ [ :created_at_numeric, 1, "created_at", :number ] # for sorting ], :terms => [ [ :variety, 'V', "variety" ] ], :if => :indexed_by_search? def created_at_numeric # format it here as no datetime support in Xapian's value ranges - return self.created_at.strftime("%Y%m%d%H%M%S") + return self.created_at.strftime("%Y%m%d%H%M%S") end - + def variety "user" end @@ -79,7 +79,7 @@ class User < ActiveRecord::Base if self.new_record? # make alert emails go out at a random time for each new user, so # overall they are spread out throughout the day. - self.last_daily_track_email = User.random_time_in_last_day + self.last_daily_track_email = User.random_time_in_last_day end end @@ -101,7 +101,7 @@ class User < ActiveRecord::Base end end end - + def get_locale if !self.locale.nil? locale = self.locale @@ -117,10 +117,10 @@ class User < ActiveRecord::Base def validate if self.email != "" && !MySociety::Validate.is_valid_email(self.email) - errors.add(:email, _("Please enter a valid email address")) + errors.add(:email, _("Please enter a valid email address")) end if MySociety::Validate.is_valid_email(self.name) - errors.add(:name, _("Please enter your name, not your email address, in the name field.")) + errors.add(:name, _("Please enter your name, not your email address, in the name field.")) end end @@ -139,7 +139,7 @@ class User < ActiveRecord::Base end # Return user given login email, password and other form parameters (e.g. name) - # + # # The specific_user_login parameter says that login as a particular user is # expected, so no parallel registration form is being displayed. def User.authenticate_from_form(params, specific_user_login = false) @@ -235,10 +235,10 @@ class User < ActiveRecord::Base # changed more than a day ago) def get_undescribed_requests self.info_requests.find( - :all, - :conditions => [ 'awaiting_description = ? and ' + InfoRequest.last_event_time_clause + ' < ?', - true, Time.now() - 1.day - ] + :all, + :conditions => [ 'awaiting_description = ? and ' + InfoRequest.last_event_time_clause + ' < ?', + true, Time.now() - 1.day + ] ) end @@ -256,7 +256,7 @@ class User < ActiveRecord::Base def owns_every_request? self.admin_level == 'super' end - + def User.owns_every_request?(user) !user.nil? && user.owns_every_request? end @@ -271,7 +271,7 @@ class User < ActiveRecord::Base def User.stay_logged_in_on_redirect?(user) !user.nil? && user.admin_level == 'super' end - + # Does the user get "(admin)" links on each page on the main site? def admin_page_links? self.admin_level == 'super' @@ -287,21 +287,21 @@ class User < ActiveRecord::Base def exceeded_limit? # Some users have no limit return false if self.no_limit - + # Has the user issued as many as MAX_REQUESTS_PER_USER_PER_DAY requests in the past 24 hours? daily_limit = MySociety::Config.get("MAX_REQUESTS_PER_USER_PER_DAY") return false if daily_limit.nil? recent_requests = InfoRequest.count(:conditions => ["user_id = ? and created_at > now() - '1 day'::interval", self.id]) - + return (recent_requests >= daily_limit) end def next_request_permitted_at return nil if self.no_limit - + daily_limit = MySociety::Config.get("MAX_REQUESTS_PER_USER_PER_DAY") n_most_recent_requests = InfoRequest.all(:conditions => ["user_id = ? and created_at > now() - '1 day'::interval", self.id], :order => "created_at DESC", :limit => daily_limit) return nil if n_most_recent_requests.size < daily_limit - + nth_most_recent_request = n_most_recent_requests[-1] return nth_most_recent_request.created_at + 1.day end @@ -375,7 +375,7 @@ class User < ActiveRecord::Base end def json_for_api - return { + return { :id => self.id, :url_name => self.url_name, :name => self.name, @@ -391,11 +391,11 @@ class User < ActiveRecord::Base self.email_bounce_message = message self.save! end - + def should_be_emailed? return (self.email_confirmed && self.email_bounced_at.nil?) end - + def indexed_by_search? return self.email_confirmed end @@ -406,17 +406,17 @@ class User < ActiveRecord::Base def create_new_salt self.salt = self.object_id.to_s + rand.to_s end - + ## Class methods def User.encrypted_password(password, salt) string_to_hash = password + salt # XXX need to add a secret here too? Digest::SHA1.hexdigest(string_to_hash) end - + def User.record_bounce_for_email(email, message) user = User.find_user_by_email(email) return false if user.nil? - + if user.email_bounced_at.nil? user.record_bounce(message) end diff --git a/app/models/user_info_request_sent_alert.rb b/app/models/user_info_request_sent_alert.rb index 5f23355bf..15cac515f 100644 --- a/app/models/user_info_request_sent_alert.rb +++ b/app/models/user_info_request_sent_alert.rb @@ -23,7 +23,7 @@ class UserInfoRequestSentAlert < ActiveRecord::Base belongs_to :user belongs_to :info_request - validates_inclusion_of :alert_type, :in => [ + validates_inclusion_of :alert_type, :in => [ 'overdue_1', # tell user that info request has become overdue 'very_overdue_1', # tell user that info request has become very overdue 'new_response_reminder_1', # reminder user to classify the recent response diff --git a/app/views/layouts/default.rhtml b/app/views/layouts/default.rhtml index f439b27d2..5f6d5c721 100644 --- a/app/views/layouts/default.rhtml +++ b/app/views/layouts/default.rhtml @@ -154,6 +154,20 @@ <br /> <input type="text"> </div> + <% + ga_code = MySociety::Config.get('GA_CODE', '') + unless ga_code.empty? + %> + <script> + var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); + document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); + </script> + <script> + var pageTracker = _gat._getTracker("<%=ga_code%>"); + pageTracker._trackPageview(); + </script> + <% end %> + </body> </html> diff --git a/config/general.yml-example b/config/general.yml-example index 7325202c1..3c50e8005 100644 --- a/config/general.yml-example +++ b/config/general.yml-example @@ -1,7 +1,7 @@ # general.yml-example: # Example values for the "general" config file. # -# Configuration parameters, in YAML syntax. +# Configuration parameters, in YAML syntax. # # Copy this file to one called "general.yml" in the same directory. Or # have multiple config files and use a symlink to change between them. @@ -37,7 +37,7 @@ FRONTPAGE_PUBLICBODY_EXAMPLES: 'tgq' # URL of theme to install (when running rails-post-deploy script) THEME_URL: 'git://github.com/sebbacon/alavetelitheme.git' -# Whether a user neis eds to sign in to start the New Request process +# Whether a user needs to sign in to start the New Request process FORCE_REGISTRATION_ON_NEW_REQUEST: false @@ -146,11 +146,10 @@ EXCEPTION_NOTIFICATIONS_TO: # This rate limiting can be turned off per-user via the admin interface MAX_REQUESTS_PER_USER_PER_DAY: 6 + # This is used to work out where to send purge requests. Should be # unset if you aren't running behind varnish VARNISH_HOST: localhost -# Set this to true if you want to use secure the admin interface with -# HTTP Basic auth - -# config_username = MySociety::Config.get('ADMIN_USERNAME', '') +# Adding a value here will enable Google Analytics on all non-admin pages. +GA_CODE: '' diff --git a/config/test.yml b/config/test.yml index c35001747..460d7c6c1 100644 --- a/config/test.yml +++ b/config/test.yml @@ -125,3 +125,4 @@ EXCEPTION_NOTIFICATIONS_TO: MAX_REQUESTS_PER_USER_PER_DAY: 2 VARNISH_HOST: varnish.localdomain +SKIP_ADMIN_AUTH: true
\ No newline at end of file diff --git a/doc/CHANGES.md b/doc/CHANGES.md index 4796b726f..1ffa78372 100644 --- a/doc/CHANGES.md +++ b/doc/CHANGES.md @@ -7,6 +7,9 @@ less likely, when using Varnish, that users will be presented with stale content. Fixes [issue #436](https://github.com/sebbacon/alaveteli/issues/436) +* Adding a `GA_CODE` to `general.yml` will cause the relevant Google + Analytics code to be added to your rendered pages + ## Upgrade notes * Existing installations will need to install the Bundler gem. See diff --git a/spec/controllers/admin_public_body_controller_spec.rb b/spec/controllers/admin_public_body_controller_spec.rb index 2fa893a93..171cb21b5 100644 --- a/spec/controllers/admin_public_body_controller_spec.rb +++ b/spec/controllers/admin_public_body_controller_spec.rb @@ -4,10 +4,6 @@ describe AdminPublicBodyController, "when administering public bodies" do integrate_views before do - username = MySociety::Config.get('ADMIN_USERNAME', '') - password = MySociety::Config.get('ADMIN_PASSWORD', '') - basic_auth_login @request - @old_filters = ActionController::Routing::Routes.filters ActionController::Routing::Routes.filters = RoutingFilter::Chain.new end @@ -80,6 +76,17 @@ describe AdminPublicBodyController, "when administering public bodies and paying integrate_views + before do + config = MySociety::Config.load_default() + config['SKIP_ADMIN_AUTH'] = false + basic_auth_login @request + end + after do + config = MySociety::Config.load_default() + config['SKIP_ADMIN_AUTH'] = true + end + + it "disallows non-authenticated users to do anything" do @request.env["HTTP_AUTHORIZATION"] = "" n = PublicBody.count @@ -145,12 +152,6 @@ end describe AdminPublicBodyController, "when administering public bodies with i18n" do integrate_views - before do - username = MySociety::Config.get('ADMIN_USERNAME', '') - password = MySociety::Config.get('ADMIN_PASSWORD', '') - basic_auth_login @request - end - it "shows the index page" do get :index end @@ -214,10 +215,6 @@ describe AdminPublicBodyController, "when creating public bodies with i18n" do integrate_views before do - username = MySociety::Config.get('ADMIN_USERNAME', '') - password = MySociety::Config.get('ADMIN_PASSWORD', '') - basic_auth_login @request - @old_filters = ActionController::Routing::Routes.filters ActionController::Routing::Routes.filters = RoutingFilter::Chain.new end diff --git a/spec/controllers/admin_user_controller_spec.rb b/spec/controllers/admin_user_controller_spec.rb index c2d645fd2..cf3665c9f 100644 --- a/spec/controllers/admin_user_controller_spec.rb +++ b/spec/controllers/admin_user_controller_spec.rb @@ -2,9 +2,6 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AdminUserController, "when administering users" do integrate_views - before do - basic_auth_login @request - end it "shows the index/list page" do get :index |