forked from mccabe615/ruby-metaprogramming-sec-issues
-
Notifications
You must be signed in to change notification settings - Fork 0
/
application_controllerfromcanvas-lms.rb
1751 lines (1565 loc) · 66.8 KB
/
application_controllerfromcanvas-lms.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## FROM https://github.com/instructure/canvas-lms/blob/e92b943882154cd9b2675c4b5e5f9de159bc131e/app/controllers/application_controller.rb#L710
#
# Copyright (C) 2011 - 2013 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
def self.promote_view_path(path)
self.view_paths = self.view_paths.to_ary.reject{ |p| p.to_s == path }
prepend_view_path(path)
end
attr_accessor :active_tab
attr_reader :context
include Api
include LocaleSelection
include Api::V1::User
include Api::V1::WikiPage
include Lti::MessageHelper
around_filter :set_locale
helper :all
include AuthenticationMethods
protect_from_forgery
# load_user checks masquerading permissions, so this needs to be cleared first
before_filter :clear_cached_contexts
before_filter :load_account, :load_user
before_filter Filters::AllowAppProfiling
before_filter :check_pending_otp
before_filter :set_user_id_header
before_filter :set_time_zone
before_filter :set_page_view
before_filter :refresh_cas_ticket
before_filter :require_reacceptance_of_terms
after_filter :log_page_view
after_filter :discard_flash_if_xhr
after_filter :cache_buster
# Yes, we're calling this before and after so that we get the user id logged
# on events that log someone in and log someone out.
after_filter :set_user_id_header
before_filter :fix_xhr_requests
before_filter :init_body_classes
after_filter :set_response_headers
after_filter :update_enrollment_last_activity_at
include Tour
add_crumb(proc {
title = I18n.t('links.dashboard', 'My Dashboard')
crumb = <<-END
<i class="icon-home standalone-icon"
title="#{title}">
<span class="screenreader-only">#{title}</span>
</i>
END
crumb.html_safe
}, :root_path, class: 'home')
##
# Sends data from rails to JavaScript
#
# The data you send will eventually make its way into the view by simply
# calling `to_json` on the data.
#
# It won't allow you to overwrite a key that has already been set
#
# Please use *ALL_CAPS* for keys since these are considered constants
# Also, please don't name it stuff from JavaScript's Object.prototype
# like `hasOwnProperty`, `constructor`, `__defineProperty__` etc.
#
# This method is available in controllers and views
#
# example:
#
# # ruby
# js_env :FOO_BAR => [1,2,3], :COURSE => @course
#
# # coffeescript
# require ['ENV'], (ENV) ->
# ENV.FOO_BAR #> [1,2,3]
#
def js_env(hash = {})
# set some defaults
unless @js_env
@js_env = {
:current_user_id => @current_user.try(:id),
:current_user => user_display_json(@current_user, :profile),
:current_user_roles => @current_user.try(:roles),
:AUTHENTICITY_TOKEN => form_authenticity_token,
:files_domain => HostUrl.file_host(@domain_root_account || Account.default, request.host_with_port),
}
@js_env[:lolcalize] = true if ENV['LOLCALIZE']
end
hash.each do |k,v|
if @js_env[k]
raise "js_env key #{k} is already taken"
else
@js_env[k] = v
end
end
@js_env[:IS_LARGE_ROSTER] = true if !@js_env[:IS_LARGE_ROSTER] && @context.respond_to?(:large_roster?) && @context.large_roster?
@js_env[:context_asset_string] = @context.try(:asset_string) if !@js_env[:context_asset_string]
@js_env[:ping_url] = polymorphic_url([:api_v1, @context, :ping]) if @context.is_a?(Course)
@js_env[:TIMEZONE] = Time.zone.tzinfo.identifier if !@js_env[:TIMEZONE]
@js_env[:CONTEXT_TIMEZONE] = @context.time_zone.tzinfo.identifier if !@js_env[:CONTEXT_TIMEZONE] && @context.respond_to?(:time_zone) && @context.time_zone.present?
@js_env[:LOCALE] = I18n.qualified_locale if !@js_env[:LOCALE]
@js_env
end
helper_method :js_env
def k12?
@domain_root_account && @domain_root_account.feature_enabled?('k12')
end
helper_method 'k12?'
def use_new_styles?
@domain_root_account && @domain_root_account.feature_enabled?(:use_new_styles)
end
helper_method 'use_new_styles?'
# Reject the request by halting the execution of the current handler
# and returning a helpful error message (and HTTP status code).
#
# @param [String] cause
# The reason the request is rejected for.
# @param [Optional, Fixnum|Symbol, Default :bad_request] status
# HTTP status code or symbol.
def reject!(cause, status=:bad_request)
raise RequestError.new(cause, status)
end
# returns the user actually logged into canvas, even if they're currently masquerading
#
# This is used by the google docs integration, among other things --
# having @real_current_user first ensures that a masquerading user never sees the
# masqueradee's files, but in general you may want to block access to google
# docs for masqueraders earlier in the request
def logged_in_user
@real_current_user || @current_user
end
def rescue_action_dispatch_exception
rescue_action_in_public(request.env['action_dispatch.exception'])
end
protected
def assign_localizer
I18n.localizer = lambda {
infer_locale :context => @context,
:user => @current_user,
:root_account => @domain_root_account,
:session_locale => session[:locale],
:accept_language => request.headers['Accept-Language']
}
end
def set_locale
store_session_locale
assign_localizer
yield if block_given?
ensure
I18n.localizer = nil
end
def store_session_locale
return unless locale = params[:session_locale]
supported_locales = I18n.available_locales.map(&:to_s)
session[:locale] = locale if supported_locales.include? locale
end
def init_body_classes
@body_classes = []
end
def set_user_id_header
headers['X-Canvas-User-Id'] ||= @current_user.global_id.to_s if @current_user
headers['X-Canvas-Real-User-Id'] ||= @real_current_user.global_id.to_s if @real_current_user
end
# make things requested from jQuery go to the "format.js" part of the "respond_to do |format|" block
# see http://codetunes.com/2009/01/31/rails-222-ajax-and-respond_to/ for why
def fix_xhr_requests
request.format = :js if request.xhr? && request.format == :html && !params[:html_xhr]
end
# scopes all time objects to the user's specified time zone
def set_time_zone
if @current_user && !@current_user.time_zone.blank?
Time.zone = @current_user.time_zone
if Time.zone && Time.zone.name == "UTC" && @current_user.time_zone && @current_user.time_zone.name.match(/\s/)
Time.zone = @current_user.time_zone.name.split(/\s/)[1..-1].join(" ") rescue nil
end
else
Time.zone = @domain_root_account && @domain_root_account.default_time_zone
end
end
# retrieves the root account for the given domain
def load_account
@domain_root_account = request.env['canvas.domain_root_account'] || LoadAccount.default_domain_root_account
@files_domain = request.host_with_port != HostUrl.context_host(@domain_root_account) && HostUrl.is_file_host?(request.host_with_port)
@domain_root_account
end
def set_response_headers
# we can't block frames on the files domain, since files domain requests
# are typically embedded in an iframe in canvas, but the hostname is
# different
if !files_domain? && Setting.get('block_html_frames', 'true') == 'true' && !@embeddable
headers['X-Frame-Options'] = 'SAMEORIGIN'
end
true
end
def files_domain?
!!@files_domain
end
def check_pending_otp
if session[:pending_otp] && !(params[:action] == 'otp_login' && request.post?)
reset_session
redirect_to login_url
end
end
# used to generate context-specific urls without having to
# check which type of context it is everywhere
def named_context_url(context, name, *opts)
if context.is_a?(UserProfile)
name = name.to_s.sub(/context/, "profile")
else
klass = context.class.base_ar_class
name = name.to_s.sub(/context/, klass.name.underscore)
opts.unshift(context)
end
opts.push({}) unless opts[-1].is_a?(Hash)
include_host = opts[-1].delete(:include_host)
if !include_host
opts[-1][:host] = context.host_name rescue nil
opts[-1][:only_path] = true
end
self.send name, *opts
end
def user_url(*opts)
opts[0] == @current_user && !@current_user.grants_right?(@current_user, session, :view_statistics) ?
user_profile_url(@current_user) :
super
end
def tab_enabled?(id)
return true unless @context && @context.respond_to?(:tabs_available)
tabs = @context.tabs_available(@current_user,
:session => session,
:include_hidden_unused => true,
:root_account => @domain_root_account)
valid = tabs.any?{|t| t[:id] == id }
render_tab_disabled unless valid
return valid
end
def render_tab_disabled
msg = tab_disabled_message(@context)
respond_to do |format|
format.html {
flash[:notice] = msg
redirect_to named_context_url(@context, :context_url)
}
format.json {
render :json => { :message => msg }, :status => :not_found
}
end
end
def tab_disabled_message(context)
if context.is_a?(Account)
t "#application.notices.page_disabled_for_account", "That page has been disabled for this account"
elsif context.is_a?(Course)
t "#application.notices.page_disabled_for_course", "That page has been disabled for this course"
elsif context.is_a?(Group)
t "#application.notices.page_disabled_for_group", "That page has been disabled for this group"
else
t "#application.notices.page_disabled", "That page has been disabled"
end
end
def require_password_session
if session[:used_remember_me_token]
flash[:warning] = t "#application.warnings.please_log_in", "For security purposes, please enter your password to continue"
store_location
redirect_to login_url
return false
end
true
end
# checks the authorization policy for the given object using
# the vendor/plugins/adheres_to_policy plugin. If authorized,
# returns true, otherwise renders unauthorized messages and returns
# false. To be used as follows:
# if authorized_action(object, @current_user, session, :update)
# render
# end
def authorized_action(object, *opts)
can_do = is_authorized_action?(object, *opts)
render_unauthorized_action unless can_do
can_do
end
alias :authorized_action? :authorized_action
def is_authorized_action?(object, *opts)
return false unless object
user = opts.shift
action_session ||= session
action_session = opts.shift if !opts[0].is_a?(Symbol) && !opts[0].is_a?(Array)
actions = Array(opts.shift).flatten
begin
return object.grants_any_right?(user, action_session, *actions)
rescue => e
logger.warn "#{object.inspect} raised an error while granting rights. #{e.inspect}" if logger
end
false
end
def render_unauthorized_action
respond_to do |format|
@show_left_side = false
clear_crumbs
params = request.path_parameters
params[:format] = nil
@headers = !!@current_user if @headers != false
@files_domain = @account_domain && @account_domain.host_type == 'files'
format.html {
store_location
return if !@current_user && initiate_delegated_login(request.host_with_port)
if @context.is_a?(Course) && @context_enrollment
start_date = @context_enrollment.enrollment_dates.map(&:first).compact.min if @context_enrollment.state_based_on_date == :inactive
if @context.claimed?
@unauthorized_message = t('#application.errors.unauthorized.unpublished', "This course has not been published by the instructor yet.")
@unauthorized_reason = :unpublished
elsif start_date && start_date > Time.now.utc
@unauthorized_message = t('#application.errors.unauthorized.not_started_yet', "The course you are trying to access has not started yet. It will start %{date}.", :date => TextHelper.date_string(start_date))
@unauthorized_reason = :unpublished
end
end
@is_delegated = delegated_authentication_url?
render :template => "shared/unauthorized", :layout => "application", :status => :unauthorized
}
format.zip { redirect_to(url_for(params)) }
format.json { render_json_unauthorized }
end
response.headers["Pragma"] = "no-cache"
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
end
def delegated_authentication_url?
@domain_root_account.delegated_authentication? &&
!@domain_root_account.ldap_authentication? &&
!params[:canvas_login]
end
# To be used as a before_filter, requires controller or controller actions
# to have their urls scoped to a context in order to be valid.
# So /courses/5/assignments or groups/1/assignments would be valid, but
# not /assignments
def require_context
get_context
if !@context
if request.path.match(/\A\/profile/)
store_location
redirect_to login_url
elsif params[:context_id]
raise ActiveRecord::RecordNotFound.new("Cannot find #{params[:context_type] || 'Context'} for ID: #{params[:context_id]}")
else
raise ActiveRecord::RecordNotFound.new("Context is required, but none found")
end
end
return @context != nil
end
helper_method :clean_return_to
MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS = 3
# Can be used as a before_filter, or just called from controller code.
# Assigns the variable @context to whatever context the url is scoped
# to. So /courses/5/assignments would have a @context=Course.find(5).
# Also assigns @context_membership to the membership type of @current_user
# if @current_user is a member of the context.
def get_context
unless @context
if params[:course_id]
@context = api_find(Course.active, params[:course_id])
params[:context_id] = params[:course_id]
params[:context_type] = "Course"
if @context && session[:enrollment_uuid_course_id] == @context.id
session[:enrollment_uuid_count] ||= 0
if session[:enrollment_uuid_count] > 4
session[:enrollment_uuid_count] = 0
self.extend(TextHelper)
flash[:html_notice] = mt "#application.notices.need_to_accept_enrollment", "You'll need to [accept the enrollment invitation](%{url}) before you can fully participate in this course.", :url => course_url(@context)
end
session[:enrollment_uuid_count] += 1
end
@context_enrollment = @context.enrollments.find_all_by_user_id(@current_user.id).sort_by{|e| [e.state_sortable, e.rank_sortable, e.id] }.first if @context && @current_user
@context_membership = @context_enrollment
elsif params[:account_id] || (self.is_a?(AccountsController) && params[:account_id] = params[:id])
@context = api_find(Account, params[:account_id])
params[:context_id] = @context.id
params[:context_type] = "Account"
@context_enrollment = @context.account_users.find_by_user_id(@current_user.id) if @context && @current_user
@context_membership = @context_enrollment
@account = @context
elsif params[:group_id]
@context = api_find(Group, params[:group_id])
params[:context_id] = params[:group_id]
params[:context_type] = "Group"
@context_enrollment = @context.group_memberships.find_by_user_id(@current_user.id) if @context && @current_user
@context_membership = @context_enrollment
elsif params[:user_id] || (self.is_a?(UsersController) && params[:user_id] = params[:id])
@context = api_find(User, params[:user_id])
params[:context_id] = params[:user_id]
params[:context_type] = "User"
@context_membership = @context if @context == @current_user
elsif params[:course_section_id] || (self.is_a?(SectionsController) && params[:course_section_id] = params[:id])
params[:context_id] = params[:course_section_id]
params[:context_type] = "CourseSection"
@context = api_find(CourseSection, params[:course_section_id])
elsif request.path.match(/\A\/profile/) || request.path == '/' || request.path.match(/\A\/dashboard\/files/) || request.path.match(/\A\/calendar/) || request.path.match(/\A\/assignments/) || request.path.match(/\A\/files/)
@context = @current_user
@context_membership = @context
end
if @context.is_a?(Account) && [email protected]_account?
account_chain = @context.account_chain.to_a.select {|a| a.grants_right?(@current_user, session, :read) }
account_chain.slice!(0) # the first element is the current context
count = account_chain.length
account_chain.reverse.each_with_index do |a, idx|
if idx == 1 && count >= MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS
add_crumb(I18n.t('#lib.text_helper.ellipsis', '...'), nil)
elsif count >= MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS && idx > 0 && idx <= count - MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS
next
else
add_crumb(a.short_name, account_url(a.id), :id => "crumb_#{a.asset_string}")
end
end
end
set_badge_counts_for(@context, @current_user, @current_enrollment)
assign_localizer if @context.present?
if @context && @context.respond_to?(:short_name)
crumb_url = named_context_url(@context, :context_url) if @context.grants_right?(@current_user, :read)
add_crumb(@context.short_name, crumb_url)
end
end
end
# This is used by a number of actions to retrieve a list of all contexts
# associated with the given context. If the context is a user then it will
# include all the user's current contexts.
# Assigns it to the variable @contexts
def get_all_pertinent_contexts(opts = {})
return if @already_ran_get_all_pertinent_contexts
@already_ran_get_all_pertinent_contexts = true
raise(ArgumentError, "Need a starting context") if @context.nil?
@contexts = [@context]
only_contexts = ActiveRecord::Base.parse_asset_string_list(params[:only_contexts])
if @context && @context.is_a?(User)
# we already know the user can read these courses and groups, so skip
# the grants_right? check to avoid querying for the various memberships
# again.
courses = @context.current_enrollments.with_each_shard.select { |e| e.state_based_on_date == :active }.map(&:course).uniq
groups = opts[:include_groups] ? @context.current_groups.with_each_shard.reject{|g| g.context_type == "Course" &&
g.context.concluded?} : []
if only_contexts.present?
# find only those courses and groups passed in the only_contexts
# parameter, but still scoped by user so we know they have rights to
# view them.
course_ids = only_contexts.select { |c| c.first == "Course" }.map(&:last)
courses = course_ids.empty? ? [] : courses.select { |c| course_ids.include?(c.id) }
group_ids = only_contexts.select { |c| c.first == "Group" }.map(&:last)
groups = group_ids.empty? ? [] : groups.select { |g| group_ids.include?(g.id) } if opts[:include_groups]
end
if opts[:favorites_first]
favorite_course_ids = @context.favorite_context_ids("Course")
courses = courses.sort_by {|c| [favorite_course_ids.include?(c.id) ? 0 : 1, Canvas::ICU.collation_key(c.name)]}
end
@contexts.concat courses
@contexts.concat groups
end
if params[:include_contexts]
params[:include_contexts].split(",").each do |include_context|
# don't load it again if we've already got it
next if @contexts.any? { |c| c.asset_string == include_context }
context = Context.find_by_asset_string(include_context)
@contexts << context if context && context.grants_right?(@current_user, :read)
end
end
@contexts = @contexts.uniq
Course.require_assignment_groups(@contexts)
@context_enrollment = @context.membership_for_user(@current_user) if @context.respond_to?(:membership_for_user)
@context_membership = @context_enrollment
end
def set_badge_counts_for(context, user, enrollment=nil)
return if @js_env && @js_env[:badge_counts].present?
return unless context.present? && user.present?
return unless context.respond_to?(:content_participation_counts) # just Course and Group so far
js_env(:badge_counts => badge_counts_for(context, user, enrollment))
end
def badge_counts_for(context, user, enrollment=nil)
badge_counts = {}
['Submission'].each do |type|
participation_count = context.content_participation_counts.
where(:user_id => user.id, :content_type => type).first
participation_count ||= ContentParticipationCount.create_or_update({
:context => context,
:user => user,
:content_type => type,
})
badge_counts[type.underscore.pluralize] = participation_count.unread_count
end
badge_counts
end
# Retrieves all assignments for all contexts held in the @contexts variable.
# Also retrieves submissions and sorts the assignments based on
# their due dates and submission status for the given user.
def get_sorted_assignments
@courses = @contexts.select{ |c| c.is_a?(Course) }
@just_viewing_one_course = @context.is_a?(Course) && @courses.length == 1
@context_codes = @courses.map(&:asset_string)
@context = @courses.first
if @just_viewing_one_course
# fake assignment used for checking if the @current_user can read unpublished assignments
fake = @context.assignments.scoped.new
fake.workflow_state = 'unpublished'
assignment_scope = :active_assignments
if @context.feature_enabled?(:draft_state) && !fake.grants_right?(@current_user, session, :read)
# user should not see unpublished assignments
assignment_scope = :published_assignments
end
@groups = @context.assignment_groups.active
@assignments = AssignmentGroup.visible_assignments(@current_user, @context, @groups)
else
assignments_and_groups = Shard.partition_by_shard(@courses) do |courses|
[[Assignment.published.for_course(courses).all,
AssignmentGroup.active.for_course(courses).order(:position).all]]
end
@assignments = assignments_and_groups.map(&:first).flatten
@groups = assignments_and_groups.map(&:last).flatten
end
@assignment_groups = @groups
@courses.each { |course| log_course(course) }
if @current_user
@submissions = @current_user.submissions.with_each_shard
@submissions.each{ |s| s.mute if s.muted_assignment? }
else
@submissions = []
end
@assignments.map! {|a| a.overridden_for(@current_user)}
sorted = SortsAssignments.by_due_date({
:assignments => @assignments,
:user => @current_user,
:session => session,
:upcoming_limit => 1.week.from_now,
:submissions => @submissions
})
@past_assignments = sorted.past
@undated_assignments = sorted.undated
@ungraded_assignments = sorted.ungraded
@upcoming_assignments = sorted.upcoming
@future_assignments = sorted.future
@overdue_assignments = sorted.overdue
condense_assignments if requesting_main_assignments_page?
categorized_assignments.each(&:sort!)
end
def categorized_assignments
[
@assignments,
@upcoming_assignments,
@past_assignments,
@ungraded_assignments,
@undated_assignments,
@future_assignments
]
end
def condense_assignments
num_weeks = @future_assignments.length > 5 ? 2 : 4
@future_assignments = SortsAssignments.up_to(@future_assignments, num_weeks.weeks.from_now)
num_weeks = @past_assignments.length < 5 ? 2 : 4
@past_assignments = SortsAssignments.down_to(@past_assignments, num_weeks.weeks.ago)
@overdue_assignments = SortsAssignments.down_to(@overdue_assignments, 4.weeks.ago)
@ungraded_assignments = SortsAssignments.down_to(@ungraded_assignments, 4.weeks.ago)
end
def log_course(course)
log_asset_access("assignments:#{course.asset_string}", "assignments", "other")
end
def requesting_main_assignments_page?
request.path.match(/\A\/assignments/)
end
# Calculates the file storage quota for @context
def get_quota
quota_params = Attachment.get_quota(@context)
@quota = quota_params[:quota]
@quota_used = quota_params[:quota_used]
end
# Renders a quota exceeded message if the @context's quota is exceeded
def quota_exceeded(redirect=nil)
redirect ||= root_url
get_quota
if response.body.size + @quota_used > @quota
if @context.is_a?(Account)
error = t "#application.errors.quota_exceeded_account", "Account storage quota exceeded"
elsif @context.is_a?(Course)
error = t "#application.errors.quota_exceeded_course", "Course storage quota exceeded"
elsif @context.is_a?(Group)
error = t "#application.errors.quota_exceeded_group", "Group storage quota exceeded"
elsif @context.is_a?(User)
error = t "#application.errors.quota_exceeded_user", "User storage quota exceeded"
else
error = t "#application.errors.quota_exceeded", "Storage quota exceeded"
end
respond_to do |format|
flash[:error] = error unless request.format.to_s == "text/plain"
format.html {redirect_to redirect }
format.json {render :json => {:errors => {:base => error}} }
format.text {render :json => {:errors => {:base => error}} }
end
return true
end
false
end
# Used to retrieve the context from a :feed_code parameter. These
# :feed_code attributes are keyed off the object type and the object's
# uuid. Using the uuid attribute gives us an unguessable url so
# that we can offer the feeds without requiring password authentication.
def get_feed_context(opts={})
pieces = params[:feed_code].split("_", 2)
if params[:feed_code].match(/\Agroup_membership/)
pieces = ["group_membership", params[:feed_code].split("_", 3)[-1]]
end
@context = nil
@problem = nil
if pieces[0] == "enrollment"
@enrollment = Enrollment.find_by_uuid(pieces[1]) if pieces[1]
@context_type = "Course"
if !@enrollment
@problem = t "#application.errors.mismatched_verification_code", "The verification code does not match any currently enrolled user."
elsif @enrollment.course && [email protected]?
@problem = t "#application.errors.feed_unpublished_course", "Feeds for this course cannot be accessed until it is published."
end
@context = @enrollment.course unless @problem
@current_user = @enrollment.user unless @problem
elsif pieces[0] == 'group_membership'
@membership = GroupMembership.active.find_by_uuid(pieces[1]) if pieces[1]
@context_type = "Group"
if !@membership
@problem = t "#application.errors.mismatched_verification_code", "The verification code does not match any currently enrolled user."
elsif @membership.group && [email protected]?
@problem = t "#application.errors.feed_unpublished_group", "Feeds for this group cannot be accessed until it is published."
end
@context = @membership.group unless @problem
@current_user = @membership.user unless @problem
else
@context_type = pieces[0].classify
if Context::ContextTypes.const_defined?(@context_type)
@context_class = Context::ContextTypes.const_get(@context_type)
@context = @context_class.find_by_uuid(pieces[1]) if pieces[1]
end
if !@context
@problem = t "#application.errors.invalid_verification_code", "The verification code is invalid."
elsif ([email protected]_public rescue false) && ([email protected]_to?(:uuid) || pieces[1] != @context.uuid)
if @context_type == 'course'
@problem = t "#application.errors.feed_private_course", "The matching course has gone private, so public feeds like this one will no longer be visible."
elsif @context_type == 'group'
@problem = t "#application.errors.feed_private_group", "The matching group has gone private, so public feeds like this one will no longer be visible."
else
@problem = t "#application.errors.feed_private", "The matching context has gone private, so public feeds like this one will no longer be visible."
end
end
@context = nil if @problem
@current_user = @context if @context.is_a?(User)
end
if !@context || (opts[:only] && !opts[:only].include?(@context.class.to_s.underscore.to_sym))
@problem ||= t("#application.errors.invalid_feed_parameters", "Invalid feed parameters.") if (opts[:only] && !opts[:only].include?(@context.class.to_s.underscore.to_sym))
@problem ||= t "#application.errors.feed_not_found", "Could not find feed."
render template: "shared/unauthorized_feed", status: :bad_request, formats: [:html]
return false
end
@context
end
def discard_flash_if_xhr
flash.discard if request.xhr? || request.format.to_s == 'text/plain'
end
def cancel_cache_buster
@cancel_cache_buster = true
end
def cache_buster
# Annoying problem. If I set the cache-control to anything other than "no-cache, no-store"
# then the local cache is used when the user clicks the 'back' button. I don't know how
# to tell the browser to ALWAYS check back other than to disable caching...
return true if @cancel_cache_buster || request.xhr? || api_request?
response.headers["Pragma"] = "no-cache"
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
end
def clear_cached_contexts
RoleOverride.clear_cached_contexts
end
def set_page_view
return true if !page_views_enabled?
ENV['RAILS_HOST_WITH_PORT'] ||= request.host_with_port rescue nil
# We only record page_views for html page requests coming from within the
# app, or if coming from a developer api request and specified as a
# page_view.
if (@developer_key && params[:user_request]) || (!@developer_key && @current_user && !request.xhr? && request.get?)
generate_page_view
end
end
def refresh_cas_ticket
if session[:cas_session] && @current_pseudonym
@current_pseudonym.claim_cas_ticket(session[:cas_session])
end
end
def require_reacceptance_of_terms
if session[:require_terms] && !api_request? && request.get?
render :template => "shared/terms_required", :layout => "application", :status => :unauthorized
false
end
end
def generate_page_view
attributes = { :user => @current_user, :developer_key => @developer_key, :real_user => @real_current_user }
@page_view = PageView.generate(request, attributes)
@page_view.user_request = true if params[:user_request] || (@current_user && !request.xhr? && request.get?)
@page_before_render = Time.now.utc
end
def generate_new_page_view
return true if !page_views_enabled?
generate_page_view
@page_view.generated_by_hand = true
end
def disable_page_views
@log_page_views = false
true
end
def update_enrollment_last_activity_at
if @context.is_a?(Course) && @context_enrollment
@context_enrollment.record_recent_activity
end
end
# Asset accesses are used for generating usage statistics. This is how
# we say, "the user just downloaded this file" or "the user just
# viewed this wiki page". We can then after-the-fact build statistics
# and reports from these accesses. This is currently being used
# to generate access reports per student per course.
def log_asset_access(asset, asset_category, asset_group=nil, level=nil, membership_type=nil)
return unless @current_user && @context && asset
return if asset.respond_to?(:new_record?) && asset.new_record?
@accessed_asset = {
:code => asset.is_a?(String) ? asset : asset.asset_string,
:group_code => asset_group.is_a?(String) ? asset_group : (asset_group.asset_string rescue 'unknown'),
:category => asset_category,
:membership_type => membership_type || (@context_membership && @context_membership.class.to_s rescue nil),
:level => level
}
end
def log_page_view
return true if !page_views_enabled?
if @current_user && @log_page_views != false
updated_fields = params.slice(:interaction_seconds)
if request.xhr? && params[:page_view_id] && !updated_fields.empty? && !(@page_view && @page_view.generated_by_hand)
@page_view = PageView.find_for_update(params[:page_view_id])
if @page_view
response.headers["X-Canvas-Page-View-Id"] = @page_view.id.to_s if @page_view.id
@page_view.do_update(updated_fields)
@page_view_update = true
end
end
# If we're logging the asset access, and it's either a participatory action
# or it's not an update to an already-existing page_view. We check to make sure
# it's not an update because if the page_view already existed, we don't want to
# double-count it as multiple views when it's really just a single view.
if @current_user && @accessed_asset && (@accessed_asset[:level] == 'participate' || !@page_view_update)
@access = AssetUserAccess.find_or_initialize_by_user_id_and_asset_code(@current_user.id, @accessed_asset[:code])
@accessed_asset[:level] ||= 'view'
access_context = @context.is_a?(UserProfile) ? @context.user : @context
@access.log access_context, @accessed_asset
if @page_view.nil? && page_views_enabled? && %w{participate submit}.include?(@accessed_asset[:level])
generate_page_view
end
if @page_view
@page_view.participated = %w{participate submit}.include?(@accessed_asset[:level])
@page_view.asset_user_access = @access
end
@page_view_update = true
end
if @page_view && !request.xhr? && request.get? && (response.content_type || "").to_s.match(/html/)
@page_view.render_time ||= (Time.now.utc - @page_before_render) rescue nil
@page_view_update = true
end
if @page_view && @page_view_update
@page_view.context = @context if !@page_view.context_id
@page_view.account_id = @domain_root_account.id
@page_view.store
end
else
@page_view.destroy if @page_view && !@page_view.new_record?
end
rescue => e
logger.error "Pageview error!"
raise e if Rails.env.development?
true
end
rescue_from Exception, :with => :rescue_exception
# analogous to rescue_action_without_handler from ActionPack 2.3
def rescue_exception(exception)
ActiveSupport::Deprecation.silence do
message = "\n#{exception.class} (#{exception.message}):\n"
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
message << " " << exception.backtrace.join("\n ")
logger.fatal("#{message}\n\n")
end
if config.consider_all_requests_local || local_request?
rescue_action_locally(exception)
else
rescue_action_in_public(exception)
end
end
def interpret_status(code)
message = Rack::Utils::HTTP_STATUS_CODES[code]
code, message = [500, Rack::Utils::HTTP_STATUS_CODES[500]] unless message
"#{code} #{message}"
end
def response_code_for_rescue(exception)
ActionDispatch::ExceptionWrapper.status_code_for_exception(exception.class.name)
end
def render_optional_error_file(status)
path = "#{Rails.public_path}/#{status.to_s[0,3]}"
if File.exist?(path)
render :file => path, :status => status, :content_type => Mime::HTML, :layout => false, :formats => [:html]
else
head status
end
end
# Custom error catching and message rendering.
def rescue_action_in_public(exception)
response_code = exception.response_status if exception.respond_to?(:response_status)
response_code ||= response_code_for_rescue(exception) || 500
begin
status_code = interpret_status(response_code)
status = status_code
status = 'AUT' if exception.is_a?(ActionController::InvalidAuthenticityToken)
type = nil
type = '404' if status == '404 Not Found'
unless exception.respond_to?(:skip_error_report?) && exception.skip_error_report?
error = ErrorReport.log_exception(type, exception, {
:url => request.url,
:user => @current_user,
:user_agent => request.headers['User-Agent'],
:request_context_id => RequestContextGenerator.request_id,
:account => @domain_root_account,
:request_method => request.request_method_symbol,
:format => request.format,
}.merge(ErrorReport.useful_http_env_stuff_from_request(request)))
end
if api_request?
rescue_action_in_api(exception, error, response_code)
else
render_rescue_action(exception, error, status, status_code)
end
rescue => e
# error generating the error page? failsafe.
render_optional_error_file response_code_for_rescue(exception)
ErrorReport.log_exception(:default, e)
end
end
def render_rescue_action(exception, error, status, status_code)
clear_crumbs
@headers = nil
load_account unless @domain_root_account
session[:last_error_id] = error.id rescue nil
if request.xhr? || request.format == :text
render :status => status_code, :json => {
:errors => {
:base => "Unexpected error, ID: #{error.id rescue "unknown"}"
},
:status => status
}
else
request.format = :html
erbfile = "#{status.to_s[0,3]}_message.html.erb"
erbpath = File.join('app', 'views', 'shared', 'errors', erbfile)
erbfile = "500_message.html.erb" unless File.exists?(erbpath)
@status_code = status_code
message = exception.is_a?(RequestError) ? exception.message : nil
render :template => "shared/errors/#{erbfile}",
:layout => 'application',
:status => status,
:locals => {
:error => error,
:exception => exception,
:status => status,
:message => message,
}
end
end
def rescue_action_in_api(exception, error_report, response_code)
data = exception.error_json if exception.respond_to?(:error_json)
data ||= api_error_json(exception, response_code)
if error_report.try(:id)
data[:error_report_id] = error_report.id
end
render :json => data, :status => response_code
end
def api_error_json(exception, status_code)
case exception
when ActiveRecord::RecordInvalid
errors = exception.record.errors
errors.set_reporter(:hash, Api::Errors::Reporter)
data = errors.to_hash
when Api::Error