forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccount.rb
2316 lines (1953 loc) · 85.8 KB
/
account.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
# frozen_string_literal: true
#
# Copyright (C) 2011 - present 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/>.
#
require "atom"
class Account < ActiveRecord::Base
include Context
include OutcomeImportContext
include Pronouns
INSTANCE_GUID_SUFFIX = "canvas-lms"
# a list of columns necessary for validation and save callbacks to work on a slim object
BASIC_COLUMNS_FOR_CALLBACKS = %i[id parent_account_id root_account_id name workflow_state settings].freeze
include Workflow
include BrandConfigHelpers
belongs_to :root_account, class_name: "Account"
belongs_to :parent_account, class_name: "Account"
has_many :courses
has_many :favorites, inverse_of: :root_account
has_many :all_courses, class_name: "Course", foreign_key: "root_account_id"
has_one :terms_of_service, dependent: :destroy
has_one :terms_of_service_content, dependent: :destroy
has_many :group_categories, -> { where(deleted_at: nil) }, as: :context, inverse_of: :context
has_many :all_group_categories, class_name: "GroupCategory", foreign_key: "root_account_id", inverse_of: :root_account
has_many :groups, as: :context, inverse_of: :context
has_many :all_groups, class_name: "Group", foreign_key: "root_account_id", inverse_of: :root_account
has_many :all_group_memberships, source: "group_memberships", through: :all_groups
has_many :enrollment_terms, foreign_key: "root_account_id"
has_many :active_enrollment_terms, -> { where("enrollment_terms.workflow_state<>'deleted'") }, class_name: "EnrollmentTerm", foreign_key: "root_account_id"
has_many :grading_period_groups, inverse_of: :root_account, dependent: :destroy
has_many :grading_periods, through: :grading_period_groups
has_many :enrollments, -> { where("enrollments.type<>'StudentViewEnrollment'") }, foreign_key: "root_account_id"
has_many :all_enrollments, class_name: "Enrollment", foreign_key: "root_account_id"
has_many :sub_accounts, -> { where("workflow_state<>'deleted'") }, class_name: "Account", foreign_key: "parent_account_id"
has_many :all_accounts, -> { order(:name) }, class_name: "Account", foreign_key: "root_account_id"
has_many :account_users, dependent: :destroy
has_many :active_account_users, -> { active }, class_name: "AccountUser"
has_many :course_sections, foreign_key: "root_account_id"
has_many :sis_batches
has_many :abstract_courses, class_name: "AbstractCourse"
has_many :root_abstract_courses, class_name: "AbstractCourse", foreign_key: "root_account_id"
has_many :all_users, -> { distinct }, through: :user_account_associations, source: :user
has_many :users, through: :active_account_users
has_many :user_past_lti_ids, as: :context, inverse_of: :context
has_many :pseudonyms, -> { preload(:user) }, inverse_of: :account
has_many :role_overrides, as: :context, inverse_of: :context
has_many :course_account_associations
has_many :child_courses, -> { where(course_account_associations: { depth: 0 }) }, through: :course_account_associations, source: :course
has_many :attachments, as: :context, inverse_of: :context, dependent: :destroy
has_many :active_assignments, -> { where("assignments.workflow_state<>'deleted'") }, as: :context, inverse_of: :context, class_name: "Assignment"
has_many :folders, -> { order("folders.name") }, as: :context, inverse_of: :context, dependent: :destroy
has_many :active_folders, -> { where("folder.workflow_state<>'deleted'").order("folders.name") }, class_name: "Folder", as: :context, inverse_of: :context
has_many :developer_keys
has_many :developer_key_account_bindings, inverse_of: :account, dependent: :destroy
has_many :authentication_providers,
-> { ordered },
inverse_of: :account,
extend: AuthenticationProvider::FindWithType
has_many :account_reports, inverse_of: :account
has_many :grading_standards, -> { where("workflow_state<>'deleted'") }, as: :context, inverse_of: :context
has_many :assessment_question_banks, -> { preload(:assessment_questions, :assessment_question_bank_users) }, as: :context, inverse_of: :context
has_many :assessment_questions, through: :assessment_question_banks
has_many :roles
has_many :all_roles, class_name: "Role", foreign_key: "root_account_id"
has_many :progresses, as: :context, inverse_of: :context
has_many :content_migrations, as: :context, inverse_of: :context
has_many :sis_batch_errors, foreign_key: :root_account_id, inverse_of: :root_account
has_many :canvadocs_annotation_contexts
has_one :outcome_proficiency, -> { preload(:outcome_proficiency_ratings) }, as: :context, inverse_of: :context, dependent: :destroy
has_one :outcome_calculation_method, as: :context, inverse_of: :context, dependent: :destroy
has_many :auditor_authentication_records,
class_name: "Auditors::ActiveRecord::AuthenticationRecord",
dependent: :destroy,
inverse_of: :account
has_many :auditor_course_records,
class_name: "Auditors::ActiveRecord::CourseRecord",
dependent: :destroy,
inverse_of: :account
has_many :auditor_grade_change_records,
class_name: "Auditors::ActiveRecord::GradeChangeRecord",
dependent: :destroy,
inverse_of: :account
has_many :auditor_root_grade_change_records,
foreign_key: "root_account_id",
class_name: "Auditors::ActiveRecord::GradeChangeRecord",
dependent: :destroy,
inverse_of: :root_account
has_many :auditor_feature_flag_records,
foreign_key: "root_account_id",
class_name: "Auditors::ActiveRecord::FeatureFlagRecord",
dependent: :destroy,
inverse_of: :root_account
has_many :auditor_pseudonym_records,
foreign_key: "root_account_id",
class_name: "Auditors::ActiveRecord::PseudonymRecord",
inverse_of: :root_account
has_many :lti_resource_links,
as: :context,
inverse_of: :context,
class_name: "Lti::ResourceLink",
dependent: :destroy
belongs_to :course_template, class_name: "Course", inverse_of: :templated_accounts
def inherited_assessment_question_banks(include_self = false, *additional_contexts)
sql, conds = [], []
contexts = additional_contexts + account_chain
contexts.delete(self) unless include_self
contexts.each do |c|
sql << "context_type = ? AND context_id = ?"
conds += [c.class.to_s, c.id]
end
conds.unshift(sql.join(" OR "))
AssessmentQuestionBank.where(conds)
end
include LearningOutcomeContext
include RubricContext
has_many :context_external_tools, -> { order(:name) }, as: :context, inverse_of: :context, dependent: :destroy
has_many :error_reports
has_many :announcements, class_name: "AccountNotification"
has_many :alerts, -> { preload(:criteria) }, as: :context, inverse_of: :context
has_many :user_account_associations
has_many :report_snapshots
has_many :external_integration_keys, as: :context, inverse_of: :context, dependent: :destroy
has_many :shared_brand_configs
belongs_to :brand_config, foreign_key: "brand_config_md5"
has_many :blackout_dates, as: :context, inverse_of: :context
before_validation :verify_unique_sis_source_id
before_save :ensure_defaults
before_create :enable_sis_imports, if: :root_account?
after_save :update_account_associations_if_changed
after_save :check_downstream_caches
before_save :setup_cache_invalidation
after_save :invalidate_caches_if_changed
after_update :clear_special_account_cache_if_special
after_update :clear_cached_short_name, if: :saved_change_to_name?
after_create :create_default_objects
serialize :settings, Hash
include TimeZoneHelper
time_zone_attribute :default_time_zone, default: "America/Denver"
def default_time_zone
if read_attribute(:default_time_zone) || root_account?
super
else
root_account.default_time_zone
end
end
alias_method :time_zone, :default_time_zone
validates_locale :default_locale, allow_nil: true
validates :name, length: { maximum: maximum_string_length, allow_blank: true }
validate :account_chain_loop, if: :parent_account_id_changed?
validate :validate_auth_discovery_url
validates :workflow_state, presence: true
validate :no_active_courses, if: ->(a) { a.workflow_state_changed? && !a.active? }
validate :no_active_sub_accounts, if: ->(a) { a.workflow_state_changed? && !a.active? }
validate :validate_help_links, if: ->(a) { a.settings_changed? }
validate :validate_course_template, if: ->(a) { a.has_attribute?(:course_template_id) && a.course_template_id_changed? }
include StickySisFields
are_sis_sticky :name, :parent_account_id
include FeatureFlags
def feature_flag_cache
MultiCache.cache
end
def self.recursive_default_locale_for_id(account_id)
local_id, shard = Shard.local_id_for(account_id)
(shard || Shard.current).activate do
obj = Account.new(id: local_id) # someday i should figure out a better way to avoid instantiating an object instead of tricking cache register
Rails.cache.fetch_with_batched_keys("default_locale_for_id", batch_object: obj, batched_keys: [:account_chain, :default_locale]) do
# couldn't find the cache so now we actually need to find the account
acc = Account.find(local_id)
acc.default_locale || (acc.parent_account_id && recursive_default_locale_for_id(acc.parent_account_id))
end
end
end
def default_locale
result = read_attribute(:default_locale)
result = nil unless I18n.locale_available?(result)
result
end
def resolved_outcome_proficiency
cache_key = ["outcome_proficiency", cache_key(:resolved_outcome_proficiency), cache_key(:account_chain)].cache_key
Rails.cache.fetch(cache_key) do
if outcome_proficiency&.active?
outcome_proficiency
elsif parent_account
parent_account.resolved_outcome_proficiency
elsif feature_enabled?(:account_level_mastery_scales)
OutcomeProficiency.find_or_create_default!(self)
end
end
end
def resolved_outcome_calculation_method
cache_key = ["outcome_calculation_method", cache_key(:resolved_outcome_calculation_method), cache_key(:account_chain)].cache_key
Rails.cache.fetch(cache_key) do
if outcome_calculation_method&.active?
outcome_calculation_method
elsif parent_account
parent_account.resolved_outcome_calculation_method
elsif feature_enabled?(:account_level_mastery_scales)
OutcomeCalculationMethod.find_or_create_default!(self)
end
end
end
def allow_student_anonymous_discussion_topics
false
end
include ::Account::Settings
include ::Csp::AccountHelper
# these settings either are or could be easily added to
# the account settings page
add_setting :sis_app_token, root_only: true
add_setting :sis_app_url, root_only: true
add_setting :sis_name, root_only: true
add_setting :sis_syncing, boolean: true, default: false, inheritable: true
add_setting :sis_default_grade_export, boolean: true, default: false, inheritable: true
add_setting :include_integration_ids_in_gradebook_exports, boolean: true, default: false, root_only: true
add_setting :sis_require_assignment_due_date, boolean: true, default: false, inheritable: true
add_setting :sis_assignment_name_length, boolean: true, default: false, inheritable: true
add_setting :sis_assignment_name_length_input, inheritable: true
add_setting :global_includes, root_only: true, boolean: true, default: false
add_setting :sub_account_includes, boolean: true, default: false
# Microsoft Sync Account Settings
add_setting :microsoft_sync_enabled, root_only: true, boolean: true, default: false
add_setting :microsoft_sync_tenant, root_only: true
add_setting :microsoft_sync_login_attribute, root_only: true
add_setting :microsoft_sync_login_attribute_suffix, root_only: true
add_setting :microsoft_sync_remote_attribute, root_only: true
# Help link settings
add_setting :custom_help_links, root_only: true
add_setting :new_custom_help_links, root_only: true
add_setting :help_link_icon, root_only: true
add_setting :help_link_name, root_only: true
add_setting :support_url, root_only: true
add_setting :prevent_course_renaming_by_teachers, boolean: true, root_only: true
add_setting :prevent_course_availability_editing_by_teachers, boolean: true, root_only: true
add_setting :login_handle_name, root_only: true
add_setting :change_password_url, root_only: true
add_setting :unknown_user_url, root_only: true
add_setting :fft_registration_url, root_only: true
add_setting :restrict_student_future_view, boolean: true, default: false, inheritable: true
add_setting :restrict_student_future_listing, boolean: true, default: false, inheritable: true
add_setting :restrict_student_past_view, boolean: true, default: false, inheritable: true
add_setting :teachers_can_create_courses, boolean: true, root_only: true, default: false
add_setting :students_can_create_courses, boolean: true, root_only: true, default: false
add_setting :no_enrollments_can_create_courses, boolean: true, root_only: true, default: false
add_setting :teachers_can_create_courses_anywhere, boolean: true, root_only: true, default: true
add_setting :students_can_create_courses_anywhere, boolean: true, root_only: true, default: true
add_setting :restrict_quiz_questions, boolean: true, root_only: true, default: false
add_setting :allow_sending_scores_in_emails, boolean: true, root_only: true
add_setting :can_add_pronouns, boolean: true, root_only: true, default: false
add_setting :can_change_pronouns, boolean: true, root_only: true, default: true
add_setting :enable_sis_export_pronouns, boolean: true, root_only: true, default: true
add_setting :pronouns, root_only: true
add_setting :self_enrollment
add_setting :equella_endpoint
add_setting :equella_teaser
add_setting :enable_alerts, boolean: true, root_only: true
add_setting :enable_eportfolios, boolean: true, root_only: true
add_setting :users_can_edit_name, boolean: true, root_only: true, default: true
add_setting :open_registration, boolean: true, root_only: true
add_setting :show_scheduler, boolean: true, root_only: true, default: false
add_setting :enable_profiles, boolean: true, root_only: true, default: false
add_setting :enable_turnitin, boolean: true, default: false
add_setting :mfa_settings, root_only: true
add_setting :mobile_qr_login_is_enabled, boolean: true, root_only: true, default: true
add_setting :admins_can_change_passwords, boolean: true, root_only: true, default: false
add_setting :admins_can_view_notifications, boolean: true, root_only: true, default: false
add_setting :canvadocs_prefer_office_online, boolean: true, root_only: true, default: false
add_setting :outgoing_email_default_name, root_only: true
add_setting :external_notification_warning, boolean: true, root_only: true, default: false
# Terms of Use and Privacy Policy settings for the root account
add_setting :terms_changed_at, root_only: true
add_setting :account_terms_required, root_only: true, boolean: true, default: true
# When a user is invited to a course, do we let them see a preview of the
# course even without registering? This is part of the free-for-teacher
# account perks, since anyone can invite anyone to join any course, and it'd
# be nice to be able to see the course first if you weren't expecting the
# invitation.
add_setting :allow_invitation_previews, boolean: true, root_only: true, default: false
add_setting :large_course_rosters, boolean: true, root_only: true, default: false
add_setting :edit_institution_email, boolean: true, root_only: true, default: true
add_setting :js_kaltura_uploader, boolean: true, root_only: true, default: false
add_setting :google_docs_domain, root_only: true
add_setting :dashboard_url, root_only: true
add_setting :product_name, root_only: true
add_setting :author_email_in_notifications, boolean: true, root_only: true, default: false
add_setting :include_students_in_global_survey, boolean: true, root_only: true, default: false
add_setting :trusted_referers, root_only: true
add_setting :app_center_access_token
add_setting :enable_offline_web_export, boolean: true, default: false, inheritable: true
add_setting :disable_rce_media_uploads, boolean: true, default: false, inheritable: true
add_setting :allow_gradebook_show_first_last_names, boolean: true, default: false
add_setting :strict_sis_check, boolean: true, root_only: true, default: false
add_setting :lock_all_announcements, default: false, boolean: true, inheritable: true
add_setting :enable_gravatar, boolean: true, root_only: true, default: true
# For setting the default dashboard (e.g. Student Planner/List View, Activity Stream, Dashboard Cards)
add_setting :default_dashboard_view, inheritable: true
add_setting :require_confirmed_email, boolean: true, root_only: true, default: false
add_setting :enable_course_catalog, boolean: true, root_only: true, default: false
add_setting :usage_rights_required, boolean: true, default: false, inheritable: true
add_setting :limit_parent_app_web_access, boolean: true, default: false, root_only: true
add_setting :kill_joy, boolean: true, default: false, root_only: true
add_setting :smart_alerts_threshold, default: 36, root_only: true
add_setting :disable_post_to_sis_when_grading_period_closed, boolean: true, root_only: true, default: false
# privacy settings for root accounts
add_setting :enable_fullstory, boolean: true, root_only: true, default: true
add_setting :enable_google_analytics, boolean: true, root_only: true, default: true
add_setting :rce_favorite_tool_ids, inheritable: true
add_setting :enable_as_k5_account, boolean: true, default: false, inheritable: true
# Allow accounts with strict data residency requirements to turn off mobile
# push notifications which may be routed through US datacenters by Google/Apple
add_setting :enable_push_notifications, boolean: true, root_only: true, default: true
add_setting :allow_last_page_on_course_users, boolean: true, root_only: true, default: false
add_setting :allow_last_page_on_account_courses, boolean: true, root_only: true, default: false
add_setting :allow_last_page_on_users, boolean: true, root_only: true, default: false
add_setting :emoji_deny_list, root_only: true
add_setting :default_due_time, inheritable: true
add_setting :conditional_release, default: false, boolean: true, inheritable: true
def settings=(hash)
if hash.is_a?(Hash) || hash.is_a?(ActionController::Parameters)
hash.each do |key, val|
key = key.to_sym
if account_settings_options && (opts = account_settings_options[key])
if (opts[:root_only] && !root_account?) || (opts[:condition] && !send("#{opts[:condition]}?".to_sym))
settings.delete key
elsif opts[:hash]
new_hash = {}
if val.is_a?(Hash) || val.is_a?(ActionController::Parameters)
val.each do |inner_key, inner_val|
inner_key = inner_key.to_sym
next unless opts[:values].include?(inner_key)
new_hash[inner_key] = if opts[:inheritable] && (inner_key == :locked || (inner_key == :value && opts[:boolean]))
Canvas::Plugin.value_to_boolean(inner_val)
else
inner_val.to_s.presence
end
end
end
settings[key] = new_hash.empty? ? nil : new_hash
elsif opts[:boolean]
settings[key] = Canvas::Plugin.value_to_boolean(val)
else
settings[key] = val.to_s.presence
end
end
end
end
# prune nil or "" hash values to save space in the DB.
settings.reject! { |_, value| value.nil? || value == { value: nil } || value == { value: nil, locked: false } }
settings
end
def product_name
settings[:product_name] || t("#product_name", "Canvas")
end
def usage_rights_required?
usage_rights_required[:value]
end
def allow_global_includes?
if root_account?
global_includes?
else
root_account.try(:sub_account_includes?) && root_account.try(:allow_global_includes?)
end
end
def pronouns
return [] unless settings[:can_add_pronouns]
settings[:pronouns]&.map { |p| translate_pronouns(p) } || Pronouns.default_pronouns
end
def pronouns=(pronouns)
settings[:pronouns] = pronouns&.map { |p| untranslate_pronouns(p) }&.reject(&:blank?)
end
def mfa_settings
settings[:mfa_settings].try(:to_sym) || :disabled
end
def non_canvas_auth_configured?
authentication_providers.active.where("auth_type<>'canvas'").exists?
end
def canvas_authentication_provider
@canvas_ap ||= authentication_providers.active.where(auth_type: "canvas").first
end
def canvas_authentication?
!!canvas_authentication_provider
end
def enable_canvas_authentication
return unless root_account?
# for migrations creating a new db
return unless Account.connection.data_source_exists?("authentication_providers")
return if authentication_providers.active.where(auth_type: "canvas").exists?
authentication_providers.create!(auth_type: "canvas")
end
def enable_offline_web_export?
enable_offline_web_export[:value]
end
def disable_rce_media_uploads?
disable_rce_media_uploads[:value]
end
def enable_as_k5_account?
enable_as_k5_account[:value]
end
def enable_as_k5_account!
settings[:enable_as_k5_account] = { value: true }
save!
end
def conditional_release?
conditional_release[:value]
end
def update_conditional_release(conditional_release_params = conditional_release)
# We can optionally pass in a hash of conditional_release_params that are being used to update the account to
# properly trigger events during account updates or controller actions. Without the hash we default to the
# current settings values
enabled = Canvas::Plugin.value_to_boolean(conditional_release_params[:value])
courses.find_each(&:disable_conditional_release) unless enabled
# We need to have the subaccounts update their conditional release statuses as well because of the inheritance
# from the root account can change the state of the subaccount
sub_accounts.find_each do |sub_account|
sub_account.delay_if_production(priority: Delayed::LOW_PRIORITY).update_conditional_release
end
end
def open_registration?
!!settings[:open_registration] && canvas_authentication?
end
def self_registration?
canvas_authentication_provider.try(:jit_provisioning?)
end
def self_registration_type
canvas_authentication_provider.try(:self_registration)
end
def self_registration_captcha?
canvas_authentication_provider.try(:enable_captcha)
end
def self_registration_allowed_for?(type)
return false unless self_registration?
return false if self_registration_type != "all" && type != self_registration_type
true
end
def enable_self_registration
canvas_authentication_provider.update_attribute(:self_registration, true)
end
def terms_required?
terms = TermsOfService.ensure_terms_for_account(root_account)
!(terms.terms_type == "no_terms" || terms.passive)
end
def require_acceptance_of_terms?(user)
return false unless terms_required?
return true if user.nil? || user.new_record?
soc2_start_date = Setting.get("SOC2_start_date", Time.new(2015, 5, 16, 0, 0, 0).utc).to_datetime
return false if user.created_at < soc2_start_date
terms_changed_at = root_account.terms_of_service.terms_of_service_content&.terms_updated_at || settings[:terms_changed_at]
last_accepted = user.preferences[:accepted_terms]
return false if last_accepted && (terms_changed_at.nil? || last_accepted > terms_changed_at)
true
end
def ip_filters=(params)
filters = {}
require "ipaddr"
params.each do |key, str|
ips = []
vals = str.split(",")
vals.each do |val|
ip = IPAddr.new(val) rescue nil
# right now the ip_filter column on quizzes is just a string,
# so it has a max length. I figure whatever we set it to this
# setter should at the very least limit stored values to that
# length.
ips << val if ip && val.length <= 255
end
filters[key] = ips.join(",") unless ips.empty?
end
settings[:ip_filters] = filters
end
def enable_sis_imports
self.allow_sis_import = true
end
def ensure_defaults
name&.delete!("\r")
self.uuid ||= CanvasSlug.generate_securish_uuid if has_attribute?(:uuid)
self.lti_guid ||= "#{self.uuid}:#{INSTANCE_GUID_SUFFIX}" if has_attribute?(:lti_guid)
self.root_account_id ||= parent_account.root_account_id if parent_account && !parent_account.root_account?
self.root_account_id ||= parent_account_id
self.parent_account_id ||= self.root_account_id unless root_account?
unless root_account_id
Account.ensure_dummy_root_account
self.root_account_id = 0
end
true
end
def verify_unique_sis_source_id
return true unless has_attribute?(:sis_source_id)
return true unless sis_source_id
return true if !root_account_id_changed? && !sis_source_id_changed?
if root_account?
errors.add(:sis_source_id, t("#account.root_account_cant_have_sis_id", "SIS IDs cannot be set on root accounts"))
throw :abort
end
scope = root_account.all_accounts.where(sis_source_id: sis_source_id)
scope = scope.where("id<>?", self) unless new_record?
return true unless scope.exists?
errors.add(:sis_source_id, t("#account.sis_id_in_use", "SIS ID \"%{sis_id}\" is already in use", sis_id: sis_source_id))
throw :abort
end
def update_account_associations_if_changed
# if the account structure changed, but this is _not_ a new object
if (saved_change_to_parent_account_id? || saved_change_to_root_account_id?) &&
!saved_change_to_id?
shard.activate do
delay_if_production.update_account_associations
end
end
end
def check_downstream_caches
# dummy account has no downstream
return if dummy?
return if ActiveRecord::Base.in_migration
keys_to_clear = []
keys_to_clear << :account_chain if saved_change_to_parent_account_id? || saved_change_to_root_account_id?
if saved_change_to_brand_config_md5? || (@old_settings && @old_settings[:sub_account_includes] != settings[:sub_account_includes])
keys_to_clear << :brand_config
end
keys_to_clear << :default_locale if saved_change_to_default_locale?
if keys_to_clear.any?
shard.activate do
self.class.connection.after_transaction_commit do
delay_if_production(singleton: "Account#clear_downstream_caches/#{global_id}")
.clear_downstream_caches(*keys_to_clear, xlog_location: self.class.current_xlog_location)
end
end
end
end
def clear_downstream_caches(*key_types, xlog_location: nil, is_retry: false)
shard.activate do
if xlog_location
timeout = Setting.get("account_cache_clear_replication_timeout", "60").to_i.seconds
unless self.class.wait_for_replication(start: xlog_location, timeout: timeout)
delay(run_at: Time.now + timeout, singleton: "Account#clear_downstream_caches/#{global_id}")
.clear_downstream_caches(*keys_to_clear, xlog_location: xlog_location, is_retry: true)
# we still clear, but only the first time; after that we just keep waiting
return if is_retry
end
end
Account.clear_cache_keys([id] + Account.sub_account_ids_recursive(id), *key_types)
end
end
def equella_settings
endpoint = settings[:equella_endpoint] || equella_endpoint
if endpoint.blank?
nil
else
OpenObject.new({
endpoint: endpoint,
default_action: settings[:equella_action] || "selectOrAdd",
teaser: settings[:equella_teaser]
})
end
end
def settings
# If the settings attribute is not loaded because it's an old cached object or something, return an empty blob that is read-only
unless has_attribute?(:settings)
return SettingsWrapper.new(self, {}.freeze)
end
result = self[:settings]
if result
@old_settings ||= result.dup
return SettingsWrapper.new(self, result)
end
unless frozen?
self[:settings] = {}
return SettingsWrapper.new(self, self[:settings])
end
SettingsWrapper.new(self, {}.freeze)
end
def domain(current_host = nil)
HostUrl.context_host(self, current_host)
end
def self.find_by_domain(domain)
default if HostUrl.default_host == domain
end
def root_account?
root_account_id.nil? || local_root_account_id.zero?
end
def primary_settings_root_account?
root_account?
end
def root_account
return self if root_account?
super
end
def root_account=(value)
return if value == self && root_account?
raise ArgumentError, "cannot change the root account of a root account" if root_account? && persisted?
super
end
def resolved_root_account_id
root_account? ? id : root_account_id
end
def sub_accounts_as_options(indent = 0, preloaded_accounts = nil)
unless preloaded_accounts
preloaded_accounts = {}
root_account.all_accounts.active.each do |account|
(preloaded_accounts[account.parent_account_id] ||= []) << account
end
end
res = [[(" " * indent).html_safe + name, id]]
preloaded_accounts[id]&.each do |account|
res += account.sub_accounts_as_options(indent + 1, preloaded_accounts)
end
res
end
def users_visible_to(user)
grants_right?(user, :read) ? all_users : all_users.none
end
def users_name_like(query = "")
@cached_users_name_like ||= {}
@cached_users_name_like[query] ||= fast_all_users.name_like(query)
end
def associated_courses(opts = {})
if root_account?
all_courses
else
shard.activate do
if opts[:include_crosslisted_courses]
Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self)
.where("course_id=courses.id"))
else
Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self, course_section_id: nil)
.where("course_id=courses.id"))
end
end
end
end
def associated_user?(user)
user_account_associations.where(user_id: user).exists?
end
def fast_course_base(opts = {})
opts[:order] ||= Course.best_unicode_collation_key("courses.name").asc
columns = "courses.id, courses.name, courses.workflow_state, courses.course_code, courses.sis_source_id, courses.enrollment_term_id"
associated_courses = self.associated_courses(
include_crosslisted_courses: opts[:include_crosslisted_courses]
)
associated_courses = associated_courses.active.order(opts[:order])
associated_courses = associated_courses.with_enrollments if opts[:hide_enrollmentless_courses]
associated_courses = associated_courses.master_courses if opts[:only_master_courses]
associated_courses = associated_courses.for_term(opts[:term]) if opts[:term].present?
associated_courses = yield associated_courses if block_given?
associated_courses.limit(opts[:limit]).active_first.select(columns).to_a
end
def fast_all_courses(opts = {})
@cached_fast_all_courses ||= {}
@cached_fast_all_courses[opts] ||= fast_course_base(opts)
end
def all_users(limit = 250)
@cached_all_users ||= {}
@cached_all_users[limit] ||= User.of_account(self).limit(limit)
end
def fast_all_users(limit = nil)
@cached_fast_all_users ||= {}
@cached_fast_all_users[limit] ||= all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name
end
def users_not_in_groups(groups, opts = {})
scope = User.active.joins(:user_account_associations)
.where(user_account_associations: { account_id: self })
.where(Group.not_in_group_sql_fragment(groups.map(&:id)))
.select("users.id, users.name")
scope = scope.select(opts[:order]).order(opts[:order]) if opts[:order]
scope
end
def courses_name_like(query = "", opts = {})
opts[:limit] ||= 200
@cached_courses_name_like ||= {}
@cached_courses_name_like[[query, opts]] ||= fast_course_base(opts) { |q| q.name_like(query) }
end
def self_enrollment_course_for(code)
all_courses
.where(self_enrollment_code: code)
.first
end
def file_namespace
if Shard.current == Shard.birth
"account_#{root_account.local_id}"
else
root_account.global_asset_string
end
end
def self.account_lookup_cache_key(id)
["_account_lookup5", id].cache_key
end
def self.invalidate_cache(id)
return unless id
default_id = Shard.relative_id_for(id, Shard.current, Shard.default)
Shard.default.activate do
MultiCache.delete(account_lookup_cache_key(default_id)) if default_id
end
rescue
nil
end
def setup_cache_invalidation
@invalidations = []
unless new_record?
invalidate_all = parent_account_id_changed?
# apparently, the try_rescues are because these columns don't exist on old migrations
@invalidations += ["default_storage_quota", "current_quota"] if invalidate_all || try_rescue(:default_storage_quota_changed?)
@invalidations << "default_group_storage_quota" if invalidate_all || try_rescue(:default_group_storage_quota_changed?)
end
end
def invalidate_caches_if_changed
if saved_changes?
shard.activate do
self.class.connection.after_transaction_commit do
if root_account?
Account.invalidate_cache(id)
else
Rails.cache.delete(["account2", id].cache_key)
end
end
end
end
@invalidations ||= []
if saved_change_to_parent_account_id?
@invalidations += Account.inheritable_settings # invalidate all of them
elsif @old_settings
Account.inheritable_settings.each do |key|
@invalidations << key if @old_settings[key] != settings[key] # only invalidate if needed
end
@old_settings = nil
end
if @invalidations.present?
shard.activate do
self.class.connection.after_transaction_commit do
@invalidations.each do |key|
Rails.cache.delete([key, global_id].cache_key)
end
Account.delay_if_production(singleton: "Account.invalidate_inherited_caches_#{global_id}")
.invalidate_inherited_caches(self, @invalidations)
end
end
end
end
def self.invalidate_inherited_caches(parent_account, keys)
parent_account.shard.activate do
account_ids = Account.sub_account_ids_recursive(parent_account.id)
account_ids.each do |id|
global_id = Shard.global_id_for(id)
keys.each do |key|
Rails.cache.delete([key, global_id].cache_key)
end
end
access_keys = keys & [:restrict_student_future_view, :restrict_student_past_view]
if access_keys.any?
EnrollmentState.invalidate_access_for_accounts([parent_account.id] + account_ids, access_keys)
end
end
end
def self.default_storage_quota
Setting.get("account_default_quota", 500.megabytes.to_s).to_i
end
def quota
return storage_quota if read_attribute(:storage_quote)
return self.class.default_storage_quota if root_account?
shard.activate do
Rails.cache.fetch(["current_quota", global_id].cache_key) do
parent_account.default_storage_quota
end
end
end
def default_storage_quota
return super if read_attribute(:default_storage_quota)
return self.class.default_storage_quota if root_account?
shard.activate do
@default_storage_quota ||= Rails.cache.fetch(["default_storage_quota", global_id].cache_key) do
parent_account.default_storage_quota
end
end
end
def default_storage_quota_mb
default_storage_quota / 1.megabyte
end
def default_storage_quota_mb=(val)
self.default_storage_quota = val.try(:to_i).try(:megabytes)
end
def default_storage_quota=(val)
val = val.to_f
val = nil if val <= 0
# If the value is the same as the inherited value, then go
# ahead and blank it so it keeps using the inherited value
if parent_account && parent_account.default_storage_quota == val
val = nil
end
write_attribute(:default_storage_quota, val)
end
def default_user_storage_quota
read_attribute(:default_user_storage_quota) ||
User.default_storage_quota
end
def default_user_storage_quota=(val)
val = val.to_i
val = nil if val == User.default_storage_quota || val <= 0
write_attribute(:default_user_storage_quota, val)
end
def default_user_storage_quota_mb
default_user_storage_quota / 1.megabyte
end
def default_user_storage_quota_mb=(val)
self.default_user_storage_quota = val.try(:to_i).try(:megabytes)
end
def default_group_storage_quota
return super if read_attribute(:default_group_storage_quota)
return Group.default_storage_quota if root_account?
shard.activate do
Rails.cache.fetch(["default_group_storage_quota", global_id].cache_key) do
parent_account.default_group_storage_quota
end
end
end
def default_group_storage_quota=(val)
val = val.to_i
if (val == Group.default_storage_quota) || (val <= 0) ||
(parent_account && parent_account.default_group_storage_quota == val)
val = nil
end
write_attribute(:default_group_storage_quota, val)
end
def default_group_storage_quota_mb
default_group_storage_quota / 1.megabyte
end
def default_group_storage_quota_mb=(val)
self.default_group_storage_quota = val.try(:to_i).try(:megabytes)
end
def turnitin_shared_secret=(secret)
return if secret.blank?
self.turnitin_crypted_secret, self.turnitin_salt = Canvas::Security.encrypt_password(secret, "instructure_turnitin_secret_shared")
end
def turnitin_shared_secret
return nil unless turnitin_salt && turnitin_crypted_secret
Canvas::Security.decrypt_password(turnitin_crypted_secret, turnitin_salt, "instructure_turnitin_secret_shared")
end
def self.account_chain(starting_account_id)
chain = []
if starting_account_id.is_a?(Account)
chain << starting_account_id
starting_account_id = starting_account_id.parent_account_id
end