-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
utils.py
2354 lines (1974 loc) · 92.1 KB
/
utils.py
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
"""
Common utility functions useful throughout the contentstore
"""
from __future__ import annotations
import configparser
import html
import logging
import re
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime, timezone
from urllib.parse import quote_plus, urlencode, urlunparse, urlparse
from uuid import uuid4
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils import translation
from django.utils.text import Truncator
from django.utils.translation import gettext as _
from eventtracking import tracker
from help_tokens.core import HelpUrlExpert
from lti_consumer.models import CourseAllowPIISharingInLTIFlag
from opaque_keys.edx.keys import CourseKey, UsageKey
from opaque_keys.edx.locator import LibraryLocator
from openedx.core.lib.teams_config import CONTENT_GROUPS_FOR_TEAMS, TEAM_SCHEME
from openedx_events.content_authoring.data import DuplicatedXBlockData
from openedx_events.content_authoring.signals import XBLOCK_DUPLICATED
from openedx_events.learning.data import CourseNotificationData
from openedx_events.learning.signals import COURSE_NOTIFICATION_REQUESTED
from milestones import api as milestones_api
from pytz import UTC
from xblock.fields import Scope
from cms.djangoapps.contentstore.toggles import (
exam_setting_view_enabled,
libraries_v1_enabled,
libraries_v2_enabled,
split_library_view_on_dashboard,
use_new_advanced_settings_page,
use_new_course_outline_page,
use_new_certificates_page,
use_new_export_page,
use_new_files_uploads_page,
use_new_grading_page,
use_new_group_configurations_page,
use_new_course_team_page,
use_new_home_page,
use_new_import_page,
use_new_schedule_details_page,
use_new_text_editor,
use_new_textbooks_page,
use_new_unit_page,
use_new_updates_page,
use_new_video_editor,
use_new_video_uploads_page,
use_new_custom_pages,
)
from cms.djangoapps.models.settings.course_grading import CourseGradingModel
from cms.djangoapps.models.settings.course_metadata import CourseMetadata
from common.djangoapps.course_action_state.models import CourseRerunUIStateManager, CourseRerunState
from common.djangoapps.course_action_state.managers import CourseActionStateItemNotFoundError
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.edxmako.services import MakoService
from common.djangoapps.student import auth
from common.djangoapps.student.auth import has_studio_read_access, has_studio_write_access, STUDIO_EDIT_ROLES
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.roles import (
CourseInstructorRole,
CourseStaffRole,
GlobalStaff,
)
from common.djangoapps.track import contexts
from common.djangoapps.util.course import get_link_for_about_page
from common.djangoapps.util.milestones_helpers import (
is_prerequisite_courses_enabled,
is_valid_course_key,
remove_prerequisite_course,
set_prerequisite_courses,
get_namespace_choices,
generate_milestone_namespace
)
from common.djangoapps.util.date_utils import get_default_time_display
from common.djangoapps.xblock_django.api import deprecated_xblocks
from common.djangoapps.xblock_django.user_service import DjangoXBlockUserService
from openedx.core import toggles as core_toggles
from openedx.core.djangoapps.content_tagging.toggles import is_tagging_feature_disabled
from openedx.core.djangoapps.credit.api import get_credit_requirements, is_credit_course
from openedx.core.djangoapps.discussions.config.waffle import ENABLE_PAGES_AND_RESOURCES_MICROFRONTEND
from openedx.core.djangoapps.discussions.models import DiscussionsConfiguration
from openedx.core.djangoapps.django_comment_common.models import assign_default_role
from openedx.core.djangoapps.django_comment_common.utils import seed_permissions_roles
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.site_configuration.models import SiteConfiguration
from openedx.core.djangoapps.models.course_details import CourseDetails
from openedx.core.lib.courses import course_image_url
from openedx.core.lib.html_to_text import html_to_text
from openedx.features.content_type_gating.models import ContentTypeGatingConfig
from openedx.features.content_type_gating.partitions import CONTENT_TYPE_GATING_SCHEME
from openedx.features.course_experience.waffle import ENABLE_COURSE_ABOUT_SIDEBAR_HTML
from xmodule.library_tools import LegacyLibraryToolsService
from xmodule.course_block import DEFAULT_START_DATE # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.data import CertificatesDisplayBehaviors
from xmodule.modulestore import ModuleStoreEnum # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.modulestore.django import modulestore # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.modulestore.exceptions import ItemNotFoundError # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.partitions.partitions_service import get_all_partitions_for_course # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.services import SettingsService, ConfigurationService, TeamsConfigurationService
IMPORTABLE_FILE_TYPES = ('.tar.gz', '.zip')
log = logging.getLogger(__name__)
def add_instructor(course_key, requesting_user, new_instructor):
"""
Adds given user as instructor and staff to the given course,
after verifying that the requesting_user has permission to do so.
"""
# can't use auth.add_users here b/c it requires user to already have Instructor perms in this course
CourseInstructorRole(course_key).add_users(new_instructor)
auth.add_users(requesting_user, CourseStaffRole(course_key), new_instructor)
def initialize_permissions(course_key, user_who_created_course):
"""
Initializes a new course by enrolling the course creator as a student,
and initializing Forum by seeding its permissions and assigning default roles.
"""
# seed the forums
seed_permissions_roles(course_key)
# auto-enroll the course creator in the course so that "View Live" will work.
CourseEnrollment.enroll(user_who_created_course, course_key)
# set default forum roles (assign 'Student' role)
assign_default_role(course_key, user_who_created_course)
def remove_all_instructors(course_key):
"""
Removes all instructor and staff users from the given course.
"""
staff_role = CourseStaffRole(course_key)
staff_role.remove_users(*staff_role.users_with_role())
instructor_role = CourseInstructorRole(course_key)
instructor_role.remove_users(*instructor_role.users_with_role())
def delete_course(course_key, user_id, keep_instructors=False):
"""
Delete course from module store and if specified remove user and
groups permissions from course.
"""
_delete_course_from_modulestore(course_key, user_id)
if not keep_instructors:
_remove_instructors(course_key)
def _delete_course_from_modulestore(course_key, user_id):
"""
Delete course from MongoDB. Deleting course will fire a signal which will result into
deletion of the courseware associated with a course_key.
"""
module_store = modulestore()
with module_store.bulk_operations(course_key):
module_store.delete_course(course_key, user_id)
def _remove_instructors(course_key):
"""
In the django layer, remove all the user/groups permissions associated with this course
"""
print('removing User permissions from course....')
try:
remove_all_instructors(course_key)
except Exception as err: # lint-amnesty, pylint: disable=broad-except
log.error(f"Error in deleting course groups for {course_key}: {err}")
def get_lms_link_for_item(location, preview=False):
"""
Returns an LMS link to the course with a jump_to to the provided location.
:param location: the location to jump to
:param preview: True if the preview version of LMS should be returned. Default value is false.
"""
assert isinstance(location, UsageKey)
# checks LMS_ROOT_URL value in site configuration for the given course_org_filter(org)
# if not found returns settings.LMS_ROOT_URL
lms_base = SiteConfiguration.get_value_for_org(
location.org,
"LMS_ROOT_URL",
settings.LMS_ROOT_URL
)
query_string = ''
if lms_base is None:
return None
if preview:
params = {'preview': '1'}
query_string = urlencode(params)
url_parts = list(urlparse(lms_base))
url_parts[2] = '/courses/{course_key}/jump_to/{location}'.format(
course_key=str(location.course_key),
location=str(location),
)
url_parts[4] = query_string
return urlunparse(url_parts)
def get_lms_link_for_certificate_web_view(course_key, mode):
"""
Returns the url to the certificate web view.
"""
assert isinstance(course_key, CourseKey)
# checks LMS_BASE value in SiteConfiguration against course_org_filter if not found returns settings.LMS_BASE
lms_base = SiteConfiguration.get_value_for_org(course_key.org, "LMS_BASE", settings.LMS_BASE)
if lms_base is None:
return None
return "//{certificate_web_base}/certificates/course/{course_id}?preview={mode}".format(
certificate_web_base=lms_base,
course_id=str(course_key),
mode=mode
)
def get_course_authoring_url(course_locator):
"""
Gets course authoring microfrontend URL
"""
return configuration_helpers.get_value_for_org(
course_locator.org,
'COURSE_AUTHORING_MICROFRONTEND_URL',
settings.COURSE_AUTHORING_MICROFRONTEND_URL
)
def get_pages_and_resources_url(course_locator):
"""
Gets course authoring microfrontend URL for Pages and Resources view.
"""
pages_and_resources_url = None
if ENABLE_PAGES_AND_RESOURCES_MICROFRONTEND.is_enabled(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
if mfe_base_url:
pages_and_resources_url = f'{mfe_base_url}/course/{course_locator}/pages-and-resources'
return pages_and_resources_url
def get_proctored_exam_settings_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for links to proctored exam settings page
"""
proctored_exam_settings_url = ''
if exam_setting_view_enabled():
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}'
if mfe_base_url:
proctored_exam_settings_url = f'{course_mfe_url}/pages-and-resources/proctoring/settings'
return proctored_exam_settings_url
def get_editor_page_base_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for links to the new base editors
"""
editor_url = None
if use_new_text_editor() or use_new_video_editor():
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/editor'
if mfe_base_url:
editor_url = course_mfe_url
return editor_url
def get_studio_home_url():
"""
Gets course authoring microfrontend URL for Studio Home view.
"""
studio_home_url = None
if use_new_home_page():
mfe_base_url = settings.COURSE_AUTHORING_MICROFRONTEND_URL
if mfe_base_url:
studio_home_url = f'{mfe_base_url}/home'
return studio_home_url
def get_schedule_details_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for schedule and details pages view.
"""
schedule_details_url = None
if use_new_schedule_details_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/settings/details'
if mfe_base_url:
schedule_details_url = course_mfe_url
return schedule_details_url
def get_advanced_settings_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for advanced settings page view.
"""
advanced_settings_url = None
if use_new_advanced_settings_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/settings/advanced'
if mfe_base_url:
advanced_settings_url = course_mfe_url
return advanced_settings_url
def get_grading_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for grading page view.
"""
grading_url = None
if use_new_grading_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/settings/grading'
if mfe_base_url:
grading_url = course_mfe_url
return grading_url
def get_course_team_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for course team page view.
"""
course_team_url = None
if use_new_course_team_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/course_team'
if mfe_base_url:
course_team_url = course_mfe_url
return course_team_url
def get_updates_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for updates page view.
"""
updates_url = None
if use_new_updates_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/course_info'
if mfe_base_url:
updates_url = course_mfe_url
return updates_url
def get_import_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for import page view.
"""
import_url = None
if use_new_import_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/import'
if mfe_base_url:
import_url = course_mfe_url
return import_url
def get_export_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for export page view.
"""
export_url = None
if use_new_export_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/export'
if mfe_base_url:
export_url = course_mfe_url
return export_url
def get_files_uploads_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for files and uploads page view.
"""
files_uploads_url = None
if use_new_files_uploads_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/assets'
if mfe_base_url:
files_uploads_url = course_mfe_url
return files_uploads_url
def get_video_uploads_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for files and uploads page view.
"""
video_uploads_url = None
if use_new_video_uploads_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/videos/'
if mfe_base_url:
video_uploads_url = course_mfe_url
return video_uploads_url
def get_course_outline_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for course oultine page view.
"""
course_outline_url = None
if use_new_course_outline_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}'
if mfe_base_url:
course_outline_url = course_mfe_url
return course_outline_url
def get_library_content_picker_url(course_locator) -> str:
"""
Gets course authoring microfrontend library content picker URL for the given parent block.
"""
content_picker_url = None
if libraries_v2_enabled():
mfe_base_url = get_course_authoring_url(course_locator)
content_picker_url = f'{mfe_base_url}/component-picker?variant=published'
return content_picker_url
def get_unit_url(course_locator, unit_locator) -> str:
"""
Gets course authoring microfrontend URL for unit page view.
"""
unit_url = None
if use_new_unit_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/container/{unit_locator}'
if mfe_base_url:
unit_url = course_mfe_url
return unit_url
def get_certificates_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for certificates page view.
"""
certificates_url = None
if use_new_certificates_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/certificates'
if mfe_base_url:
certificates_url = course_mfe_url
return certificates_url
def get_textbooks_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for textbooks page view.
"""
textbooks_url = None
if use_new_textbooks_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/textbooks'
if mfe_base_url:
textbooks_url = course_mfe_url
return textbooks_url
def get_group_configurations_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for group configurations page view.
"""
group_configurations_url = None
if use_new_group_configurations_page(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/group_configurations'
if mfe_base_url:
group_configurations_url = course_mfe_url
return group_configurations_url
def get_custom_pages_url(course_locator) -> str:
"""
Gets course authoring microfrontend URL for custom pages view.
"""
custom_pages_url = None
if use_new_custom_pages(course_locator):
mfe_base_url = get_course_authoring_url(course_locator)
course_mfe_url = f'{mfe_base_url}/course/{course_locator}/custom-pages'
if mfe_base_url:
custom_pages_url = course_mfe_url
return custom_pages_url
def get_taxonomy_list_url() -> str | None:
"""
Gets course authoring microfrontend URL for taxonomy list page view.
"""
if is_tagging_feature_disabled():
return None
mfe_base_url = settings.COURSE_AUTHORING_MICROFRONTEND_URL
if not mfe_base_url:
return None
return f'{mfe_base_url}/taxonomies'
def get_taxonomy_tags_widget_url(course_locator=None) -> str | None:
"""
Gets course authoring microfrontend URL for taxonomy tags drawer widget view.
The `content_id` needs to be appended to the end of the URL when using it.
"""
if is_tagging_feature_disabled():
return None
if course_locator:
mfe_base_url = get_course_authoring_url(course_locator)
else:
mfe_base_url = settings.COURSE_AUTHORING_MICROFRONTEND_URL
if not mfe_base_url:
return None
return f'{mfe_base_url}/tagging/components/widget/'
def course_import_olx_validation_is_enabled():
"""
Check if course olx validation is enabled on course import.
"""
return settings.FEATURES.get('ENABLE_COURSE_OLX_VALIDATION', False)
# pylint: disable=invalid-name
def is_currently_visible_to_students(xblock):
"""
Returns true if there is a published version of the xblock that is currently visible to students.
This means that it has a release date in the past, and the xblock has not been set to staff only.
"""
try:
published = modulestore().get_item(xblock.location, revision=ModuleStoreEnum.RevisionOption.published_only)
# If there's no published version then the xblock is clearly not visible
except ItemNotFoundError:
return False
# If visible_to_staff_only is True, this xblock is not visible to students regardless of start date.
if published.visible_to_staff_only:
return False
# Check start date
if 'detached' not in published._class_tags and published.start is not None: # lint-amnesty, pylint: disable=protected-access
return datetime.now(UTC) > published.start
# No start date, so it's always visible
return True
def has_children_visible_to_specific_partition_groups(xblock):
"""
Returns True if this xblock has children that are limited to specific user partition groups.
Note that this method is not recursive (it does not check grandchildren).
"""
if not xblock.has_children:
return False
for child in xblock.get_children():
if is_visible_to_specific_partition_groups(child):
return True
return False
def is_visible_to_specific_partition_groups(xblock):
"""
Returns True if this xblock has visibility limited to specific user partition groups.
"""
if not xblock.group_access:
return False
for partition in get_user_partition_info(xblock):
if any(g["selected"] for g in partition["groups"]):
return True
return False
def find_release_date_source(xblock):
"""
Finds the ancestor of xblock that set its release date.
"""
# Stop searching at the section level
if xblock.category == 'chapter':
return xblock
parent_location = modulestore().get_parent_location(xblock.location,
revision=ModuleStoreEnum.RevisionOption.draft_preferred)
# Orphaned xblocks set their own release date
if not parent_location:
return xblock
parent = modulestore().get_item(parent_location)
if parent.start != xblock.start:
return xblock
else:
return find_release_date_source(parent)
def find_staff_lock_source(xblock):
"""
Returns the xblock responsible for setting this xblock's staff lock, or None if the xblock is not staff locked.
If this xblock is explicitly locked, return it, otherwise find the ancestor which sets this xblock's staff lock.
"""
# Stop searching if this xblock has explicitly set its own staff lock
if xblock.fields['visible_to_staff_only'].is_set_on(xblock):
return xblock
# Stop searching at the section level
if xblock.category == 'chapter':
return None
parent_location = modulestore().get_parent_location(xblock.location,
revision=ModuleStoreEnum.RevisionOption.draft_preferred)
# Orphaned xblocks set their own staff lock
if not parent_location:
return None
parent = modulestore().get_item(parent_location)
return find_staff_lock_source(parent)
def ancestor_has_staff_lock(xblock, parent_xblock=None):
"""
Returns True iff one of xblock's ancestors has staff lock.
Can avoid mongo query by passing in parent_xblock.
"""
if parent_xblock is None:
parent_location = modulestore().get_parent_location(xblock.location,
revision=ModuleStoreEnum.RevisionOption.draft_preferred)
if not parent_location:
return False
parent_xblock = modulestore().get_item(parent_location)
return parent_xblock.visible_to_staff_only
def get_sequence_usage_keys(course):
"""
Extracts a list of 'subsections' usage_keys
"""
return [str(subsection.location)
for section in course.get_children()
for subsection in section.get_children()]
def reverse_url(handler_name, key_name=None, key_value=None, kwargs=None):
"""
Creates the URL for the given handler.
The optional key_name and key_value are passed in as kwargs to the handler.
"""
kwargs_for_reverse = {key_name: str(key_value)} if key_name else None
if kwargs:
kwargs_for_reverse.update(kwargs)
return reverse(handler_name, kwargs=kwargs_for_reverse)
def reverse_course_url(handler_name, course_key, kwargs=None):
"""
Creates the URL for handlers that use course_keys as URL parameters.
"""
return reverse_url(handler_name, 'course_key_string', course_key, kwargs)
def reverse_library_url(handler_name, library_key, kwargs=None):
"""
Creates the URL for handlers that use library_keys as URL parameters.
"""
return reverse_url(handler_name, 'library_key_string', library_key, kwargs)
def reverse_usage_url(handler_name, usage_key, kwargs=None):
"""
Creates the URL for handlers that use usage_keys as URL parameters.
"""
return reverse_url(handler_name, 'usage_key_string', usage_key, kwargs)
def get_split_group_display_name(xblock, course):
"""
Returns group name if an xblock is found in user partition groups that are suitable for the split_test block.
Arguments:
xblock (XBlock): The courseware component.
course (XBlock): The course block.
Returns:
group name (String): Group name of the matching group xblock.
"""
for user_partition in get_user_partition_info(xblock, schemes=['random'], course=course):
for group in user_partition['groups']:
if 'Group ID {group_id}'.format(group_id=group['id']) == xblock.display_name_with_default:
return group['name']
def get_user_partition_info(xblock, schemes=None, course=None):
"""
Retrieve user partition information for an XBlock for display in editors.
* If a partition has been disabled, it will be excluded from the results.
* If a group within a partition is referenced by the XBlock, but the group has been deleted,
the group will be marked as deleted in the results.
Arguments:
xblock (XBlock): The courseware component being edited.
Keyword Arguments:
schemes (iterable of str): If provided, filter partitions to include only
schemes with the provided names.
course (XBlock): The course block. If provided, uses this to look up the user partitions
instead of loading the course. This is useful if we're calling this function multiple
times for the same course want to minimize queries to the modulestore.
Returns: list
Example Usage:
>>> get_user_partition_info(xblock, schemes=["cohort", "verification"])
[
{
"id": 12345,
"name": "Cohorts"
"scheme": "cohort",
"groups": [
{
"id": 7890,
"name": "Foo",
"selected": True,
"deleted": False,
}
]
},
{
"id": 7292,
"name": "Midterm A",
"scheme": "verification",
"groups": [
{
"id": 1,
"name": "Completed verification at Midterm A",
"selected": False,
"deleted": False
},
{
"id": 0,
"name": "Did not complete verification at Midterm A",
"selected": False,
"deleted": False,
}
]
}
]
"""
course = course or modulestore().get_course(xblock.location.course_key)
if course is None:
log.warning(
"Could not find course %s to retrieve user partition information",
xblock.location.course_key
)
return []
if schemes is not None:
schemes = set(schemes)
partitions = []
for p in sorted(get_all_partitions_for_course(course, active_only=True), key=lambda p: p.name):
# Exclude disabled partitions, partitions with no groups defined
# The exception to this case is when there is a selected group within that partition, which means there is
# a deleted group
# Also filter by scheme name if there's a filter defined.
selected_groups = set(xblock.group_access.get(p.id, []) or [])
if (p.groups or selected_groups) and (schemes is None or p.scheme.name in schemes):
# First, add groups defined by the partition
groups = []
for g in p.groups:
# Falsey group access for a partition mean that all groups
# are selected. In the UI, though, we don't show the particular
# groups selected, since there's a separate option for "all users".
groups.append({
"id": g.id,
"name": g.name,
"selected": g.id in selected_groups,
"deleted": False,
})
# Next, add any groups set on the XBlock that have been deleted
all_groups = {g.id for g in p.groups}
missing_group_ids = selected_groups - all_groups
for gid in missing_group_ids:
groups.append({
"id": gid,
"name": _("Deleted Group"),
"selected": True,
"deleted": True,
})
# Put together the entire partition dictionary
partitions.append({
"id": p.id,
"name": str(p.name), # Convert into a string in case ugettext_lazy was used
"scheme": p.scheme.name,
"groups": groups,
})
return partitions
def get_visibility_partition_info(xblock, course=None):
"""
Retrieve user partition information for the component visibility editor.
This pre-processes partition information to simplify the template.
Arguments:
xblock (XBlock): The component being edited.
course (XBlock): The course block. If provided, uses this to look up the user partitions
instead of loading the course. This is useful if we're calling this function multiple
times for the same course want to minimize queries to the modulestore.
Returns: dict
"""
selectable_partitions = []
# We wish to display enrollment partitions before cohort partitions.
enrollment_user_partitions = get_user_partition_info(xblock, schemes=["enrollment_track"], course=course)
# For enrollment partitions, we only show them if there is a selected group or
# or if the number of groups > 1.
for partition in enrollment_user_partitions:
if len(partition["groups"]) > 1 or any(group["selected"] for group in partition["groups"]):
selectable_partitions.append(partition)
team_user_partitions = get_user_partition_info(xblock, schemes=["team"], course=course)
selectable_partitions += team_user_partitions
course_key = xblock.scope_ids.usage_id.course_key
is_library = isinstance(course_key, LibraryLocator)
if not is_library and ContentTypeGatingConfig.current(course_key=course_key).studio_override_enabled:
selectable_partitions += get_user_partition_info(xblock, schemes=[CONTENT_TYPE_GATING_SCHEME], course=course)
# Now add the cohort user partitions.
selectable_partitions = selectable_partitions + get_user_partition_info(xblock, schemes=["cohort"], course=course)
# Find the first partition with a selected group. That will be the one initially enabled in the dialog
# (if the course has only been added in Studio, only one partition should have a selected group).
selected_partition_index = -1
# At the same time, build up all the selected groups as they are displayed in the dialog title.
selected_groups_label = ''
for index, partition in enumerate(selectable_partitions):
for group in partition["groups"]:
if group["selected"]:
if len(selected_groups_label) == 0:
selected_groups_label = group['name']
else:
# Translators: This is building up a list of groups. It is marked for translation because of the
# comma, which is used as a separator between each group.
selected_groups_label = _('{previous_groups}, {current_group}').format(
previous_groups=selected_groups_label,
current_group=group['name']
)
if selected_partition_index == -1:
selected_partition_index = index
return {
"selectable_partitions": selectable_partitions,
"selected_partition_index": selected_partition_index,
"selected_groups_label": selected_groups_label,
}
def get_xblock_aside_instance(usage_key):
"""
Returns: aside instance of a aside xblock
:param usage_key: Usage key of aside xblock
"""
try:
xblock = modulestore().get_item(usage_key.usage_key)
for aside in xblock.runtime.get_asides(xblock):
if aside.scope_ids.block_type == usage_key.aside_type:
return aside
except ItemNotFoundError:
log.warning('Unable to load item %s', usage_key.usage_key)
def is_self_paced(course):
"""
Returns True if course is self-paced, False otherwise.
"""
return course and course.self_paced
def get_sibling_urls(subsection, unit_location): # pylint: disable=too-many-statements
"""
Given a subsection, returns the urls for the next and previous units.
(the first unit of the next subsection or section, and
the last unit of the previous subsection/section)
"""
def get_unit_location(direction):
"""
Returns the desired location of the adjacent unit in a subsection.
"""
unit_index = subsection.children.index(unit_location)
try:
if direction == 'previous':
if unit_index > 0:
location = subsection.children[unit_index - 1]
else:
location = None
else:
location = subsection.children[unit_index + 1]
return location
except IndexError:
return None
def get_subsections_in_section():
"""
Returns subsections present in a section.
"""
try:
section_subsections = section.get_children()
return section_subsections
except AttributeError:
log.error("URL Retrieval Error: subsection {subsection} included in section {section}".format(
section=section.location,
subsection=subsection.location
))
return None
def get_sections_in_course():
"""
Returns sections present in course.
"""
try:
section_subsections = section.get_parent().get_children()
return section_subsections
except AttributeError:
log.error("URL Retrieval Error: In section {section} in course".format(
section=section.location,
))
return None
def get_subsection_location(section_subsections, current_subsection, direction):
"""
Returns the desired location of the adjacent subsections in a section.
"""
location = None
subsection_index = section_subsections.index(next(s for s in subsections if s.location ==
current_subsection.location))
try:
if direction == 'previous':
if subsection_index > 0:
prev_subsection = subsections[subsection_index - 1]
location = prev_subsection.get_children()[-1].location
else:
next_subsection = subsections[subsection_index + 1]
location = next_subsection.get_children()[0].location
return location
except IndexError:
return None
def get_section_location(course_sections, current_section, direction):
"""
Returns the desired location of the adjacent sections in a course.
"""