Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403] [Versions 39 and 310]

Contains class core_course_category responsible for course category operations

Copyright: 2013 Marina Glancy
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 3109 lines (126 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 1 class

core_course_category:: (92 methods):
  __set()
  __get()
  __isset()
  __unset()
  get_plugins_callback_function()
  getIterator()
  __construct()
  get()
  top()
  user_top()
  get_many()
  get_all()
  get_default()
  restore()
  create()
  update()
  is_uservisible()
  can_view_category()
  can_view_course_info()
  get_db_record()
  get_tree()
  get_cached_cat_tree()
  rebuild_coursecattree_cache_contents()
  count_all()
  is_simple_site()
  get_records()
  role_assignment_changed()
  user_enrolment_changed()
  preload_course_contacts()
  preload_custom_fields()
  ensure_users_enrolled()
  get_course_records()
  get_not_visible_children_ids()
  sort_records()
  get_children()
  get_all_children_ids()
  has_manage_capability_on_any()
  has_capability_on_any()
  can_resort_any()
  can_change_parent_any()
  get_children_count()
  has_children()
  has_courses()
  get_view_link()
  search_courses()
  search_courses_count()
  get_courses()
  get_courses_count()
  can_delete()
  can_delete_full()
  delete_full()
  move_content_targets_list()
  can_move_content_to()
  delete_move()
  can_change_parent()
  change_parent_raw()
  change_parent()
  hide_raw()
  hide()
  show_raw()
  show()
  get_formatted_name()
  get_nested_name()
  get_parents()
  make_categories_list()
  prepare_to_cache()
  wake_from_cache()
  can_create_top_level_category()
  get_context()
  has_manage_capability()
  parent_has_manage_capability()
  can_create_subcategory()
  can_resort_subcategories()
  can_resort_courses()
  can_change_sortorder()
  can_create_course()
  can_edit()
  can_review_roles()
  can_review_permissions()
  can_review_cohorts()
  can_review_filters()
  can_change_visibility()
  can_move_courses_out_of()
  can_move_courses_into()
  can_restore_courses_into()
  resort_subcategories()
  resort_categories_cleanup()
  resort_courses()
  change_sortorder_by_one()
  get_parent_coursecat()
  can_request_course()
  can_approve_course_requests()


Class: core_course_category  - X-Ref

Class to store, cache, render and manage course category

__set($name, $value)   X-Ref
Magic setter method, we do not want anybody to modify properties from the outside

param: string $name
param: mixed $value

__get($name)   X-Ref
Magic method getter, redirects to read only values. Queries from DB the fields that were not cached

param: string $name
return: mixed

__isset($name)   X-Ref
Full support for isset on our magic read only properties.

param: string $name
return: bool

__unset($name)   X-Ref
All properties are read only, sorry.

param: string $name

get_plugins_callback_function(string $name)   X-Ref
Get list of plugin callback functions.

param: string $name Callback function name.
return: [callable] $pluginfunctions

getIterator()   X-Ref
Create an iterator because magic vars can't be seen by 'foreach'.

implementing method from interface IteratorAggregate

return: ArrayIterator

__construct(stdClass $record, $fromcache = false)   X-Ref
Constructor

Constructor is protected, use core_course_category::get($id) to retrieve category

param: stdClass $record record from DB (may not contain all fields)
param: bool $fromcache whether it is being restored from cache

get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false, $user = null)   X-Ref
Returns coursecat object for requested category

If category is not visible to the given user, it is treated as non existing
unless $alwaysreturnhidden is set to true

If id is 0, the pseudo object for root category is returned (convenient
for calling other functions such as get_children())

param: int $id category id
param: int $strictness whether to throw an exception (MUST_EXIST) or
param: bool $alwaysreturnhidden set to true if you want an object to be
param: int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
return: null|self

top()   X-Ref
Returns the pseudo-category representing the whole system (id=0, context_system)

return: core_course_category

user_top()   X-Ref
Returns the top-most category for the current user

Examples:
1. User can browse courses everywhere - return self::top() - pseudo-category with id=0
2. User does not have capability to browse courses on the system level but
has it in ONE course category - return this course category
3. User has capability to browse courses in two course categories - return self::top()

return: core_course_category|null

get_many(array $ids)   X-Ref
Load many core_course_category objects.

param: array $ids An array of category ID's to load.
return: core_course_category[]

get_all($options = [])   X-Ref
Load all core_course_category objects.

param: array $options Options:
return: core_course_category[]

get_default()   X-Ref
Returns the first found category

Note that if there are no categories visible to the current user on the first level,
the invisible category may be returned

return: core_course_category

restore()   X-Ref
Restores the object after it has been externally modified in DB for example
during {@link fix_course_sortorder()}


create($data, $editoroptions = null)   X-Ref
Creates a new category either from form data or from raw data

Please note that this function does not verify access control.

Exception is thrown if name is missing or idnumber is duplicating another one in the system.

Category visibility is inherited from parent unless $data->visible = 0 is specified

param: array|stdClass $data
param: array $editoroptions if specified, the data is considered to be
return: core_course_category

update($data, $editoroptions = null)   X-Ref
Updates the record with either form data or raw data

Please note that this function does not verify access control.

This function calls core_course_category::change_parent_raw if field 'parent' is updated.
It also calls core_course_category::hide_raw or core_course_category::show_raw if 'visible' is updated.
Visibility is changed first and then parent is changed. This means that
if parent category is hidden, the current category will become hidden
too and it may overwrite whatever was set in field 'visible'.

Note that fields 'path' and 'depth' can not be updated manually
Also core_course_category::update() can not directly update the field 'sortoder'

param: array|stdClass $data
param: array $editoroptions if specified, the data is considered to be

is_uservisible($user = null)   X-Ref
Checks if this course category is visible to a user.

Please note that methods core_course_category::get (without 3rd argumet),
core_course_category::get_children(), etc. return only visible categories so it is
usually not needed to call this function outside of this class

param: int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
return: bool

can_view_category($category, $user = null)   X-Ref
Checks if current user has access to the category

param: stdClass|core_course_category $category
param: int|stdClass $user The user id or object. By default (null) checks access for the current user.
return: bool

can_view_course_info($course, $user = null)   X-Ref
Checks if current user can view course information or enrolment page.

This method does not check if user is already enrolled in the course

param: stdClass $course course object (must have 'id', 'visible' and 'category' fields)
param: null|stdClass $user The user id or object. By default (null) checks access for the current user.

get_db_record()   X-Ref
Returns the complete corresponding record from DB table course_categories

Mostly used in deprecated functions

return: stdClass

get_tree($id)   X-Ref
Returns the entry from categories tree and makes sure the application-level tree cache is built

The following keys can be requested:

'countall' - total number of categories in the system (always present)
0 - array of ids of top-level categories (always present)
'0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
$id (int) - array of ids of categories that are direct children of category with id $id. If
category with id $id does not exist, or category has no children, returns empty array
$id.'i' - array of ids of children categories that have visible=0

param: int|string $id
return: mixed

get_cached_cat_tree()   X-Ref
Return the course category tree.

Returns the category tree array, from the cache if available or rebuilding the cache
if required. Uses locking to prevent the cache being rebuilt by multiple requests at once.

return: array|null The tree as an array, or null if rebuilding the tree failed due to a lock timeout.

rebuild_coursecattree_cache_contents()   X-Ref
Rebuild the course category tree as an array, including an extra "countall" field.

return: array

count_all()   X-Ref
Returns number of ALL categories in the system regardless if
they are visible to current user or not

return: int

is_simple_site()   X-Ref
Checks if the site has only one category and it is visible and available.

In many situations we won't show this category at all
return: bool

get_records($whereclause, $params)   X-Ref
Retrieves number of records from course_categories table

Only cached fields are retrieved. Records are ready for preloading context

param: string $whereclause
param: array $params
return: array array of stdClass objects

role_assignment_changed($roleid, $context)   X-Ref
Resets course contact caches when role assignments were changed

param: int $roleid role id that was given or taken away
param: context $context context where role assignment has been changed

user_enrolment_changed($courseid, $userid,$status, $timestart = null, $timeend = null)   X-Ref
Executed when user enrolment was changed to check if course
contacts cache needs to be cleared

param: int $courseid course id
param: int $userid user id
param: int $status new enrolment status (0 - active, 1 - suspended)
param: int $timestart new enrolment time start
param: int $timeend new enrolment time end

preload_course_contacts(&$courses)   X-Ref
Given list of DB records from table course populates each record with list of users with course contact roles

This function fills the courses with raw information as {@link get_role_users()} would do.
See also {@link core_course_list_element::get_course_contacts()} for more readable return

$courses[$i]->managers = array(
$roleassignmentid => $roleuser,
...
);

where $roleuser is an stdClass with the following properties:

$roleuser->raid - role assignment id
$roleuser->id - user id
$roleuser->username
$roleuser->firstname
$roleuser->lastname
$roleuser->rolecoursealias
$roleuser->rolename
$roleuser->sortorder - role sortorder
$roleuser->roleid
$roleuser->roleshortname

param: array $courses

preload_custom_fields(array &$records)   X-Ref
Preloads the custom fields values in bulk

param: array $records

ensure_users_enrolled($courseusers)   X-Ref
Verify user enrollments for multiple course-user combinations

param: array $courseusers array where keys are course ids and values are array
return: array same structure as input array but values list only users from input

get_course_records($whereclause, $params, $options, $checkvisibility = false)   X-Ref
Retrieves number of records from course table

Not all fields are retrieved. Records are ready for preloading context

param: string $whereclause
param: array $params
param: array $options may indicate that summary needs to be retrieved
param: bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
return: array array of stdClass objects

get_not_visible_children_ids()   X-Ref
Returns array of ids of children categories that current user can not see

This data is cached in user session cache

return: array

sort_records(&$records, $sortfields)   X-Ref
Sorts list of records by several fields

param: array $records array of stdClass objects
param: array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
return: int

get_children($options = array()   X-Ref
Returns array of children categories visible to the current user

param: array $options options for retrieving children
return: core_course_category[] Array of core_course_category objects indexed by category id

get_all_children_ids()   X-Ref
Returns an array of ids of categories that are (direct and indirect) children
of this category.

return: int[]

has_manage_capability_on_any()   X-Ref
Returns true if the user has the manage capability on any category.

This method uses the coursecat cache and an entry `has_manage_capability` to speed up
calls to this method.

return: bool

has_capability_on_any($capabilities)   X-Ref
Checks if the user has at least one of the given capabilities on any category.

param: array|string $capabilities One or more capabilities to check. Check made is an OR.
return: bool

can_resort_any()   X-Ref
Returns true if the user can resort any category.

return: bool

can_change_parent_any()   X-Ref
Returns true if the user can change the parent of any category.

return: bool

get_children_count()   X-Ref
Returns number of subcategories visible to the current user

return: int

has_children()   X-Ref
Returns true if the category has ANY children, including those not visible to the user

return: boolean

has_courses()   X-Ref
Returns true if the category has courses in it (count does not include courses
in child categories)

return: bool

get_view_link()   X-Ref
Get the link used to view this course category.

return: \moodle_url

search_courses($search, $options = array()   X-Ref
Searches courses

List of found course ids is cached for 10 minutes. Cache may be purged prior
to this when somebody edits courses or categories, however it is very
difficult to keep track of all possible changes that may affect list of courses.

param: array $search contains search criterias, such as:
param: array $options display options, same as in get_courses() except 'recursive' is ignored -
param: array $requiredcapabilities List of capabilities required to see return course.
return: core_course_list_element[]

search_courses_count($search, $options = array()   X-Ref
Returns number of courses in the search results

It is recommended to call this function after {@link core_course_category::search_courses()}
and not before because only course ids are cached. Otherwise search_courses() may
perform extra DB queries.

param: array $search search criteria, see method search_courses() for more details
param: array $options display options. They do not affect the result but
param: array $requiredcapabilities List of capabilities required to see return course.
return: int

get_courses($options = array()   X-Ref
Retrieves the list of courses accessible by user

Not all information is cached, try to avoid calling this method
twice in the same request.

The following fields are always retrieved:
- id, visible, fullname, shortname, idnumber, category, sortorder

If you plan to use properties/methods core_course_list_element::$summary and/or
core_course_list_element::get_course_contacts()
you can preload this information using appropriate 'options'. Otherwise
they will be retrieved from DB on demand and it may end with bigger DB load.

Note that method core_course_list_element::has_summary() will not perform additional
DB queries even if $options['summary'] is not specified

List of found course ids is cached for 10 minutes. Cache may be purged prior
to this when somebody edits courses or categories, however it is very
difficult to keep track of all possible changes that may affect list of courses.

param: array $options options for retrieving children
return: core_course_list_element[]

get_courses_count($options = array()   X-Ref
Returns number of courses visible to the user

param: array $options similar to get_courses() except some options do not affect
return: int

can_delete()   X-Ref
Returns true if the user is able to delete this category.

Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
{@link core_course_category::can_delete_full()} or {@link core_course_category::can_move_content_to()}
depending upon what the user wished to do.

return: boolean

can_delete_full()   X-Ref
Returns true if user can delete current category and all its contents

To be able to delete course category the user must have permission
'moodle/category:manage' in ALL child course categories AND
be able to delete all courses

return: bool

delete_full($showfeedback = true)   X-Ref
Recursively delete category including all subcategories and courses

Function {@link core_course_category::can_delete_full()} MUST be called prior
to calling this function because there is no capability check
inside this function

param: boolean $showfeedback display some notices
return: array return deleted courses

move_content_targets_list()   X-Ref
Checks if user can delete this category and move content (courses, subcategories and questions)
to another category. If yes returns the array of possible target categories names

If user can not manage this category or it is completely empty - empty array will be returned

return: array

can_move_content_to($newcatid)   X-Ref
Checks if user has capability to move all category content to the new parent before
removing this category

param: int $newcatid
return: bool

delete_move($newparentid, $showfeedback = false)   X-Ref
Deletes a category and moves all content (children, courses and questions) to the new parent

Note that this function does not check capabilities, {@link core_course_category::can_move_content_to()}
must be called prior

param: int $newparentid
param: bool $showfeedback
return: bool

can_change_parent($newparentcat)   X-Ref
Checks if user can move current category to the new parent

This checks if new parent category exists, user has manage cap there
and new parent is not a child of this category

param: int|stdClass|core_course_category $newparentcat
return: bool

change_parent_raw(core_course_category $newparentcat)   X-Ref
Moves the category under another parent category. All associated contexts are moved as well

This is protected function, use change_parent() or update() from outside of this class

param: core_course_category $newparentcat

change_parent($newparentcat)   X-Ref
Efficiently moves a category - NOTE that this can have
a huge impact access-control-wise...

Note that this function does not check capabilities.

Example of usage:
$coursecat = core_course_category::get($categoryid);
if ($coursecat->can_change_parent($newparentcatid)) {
$coursecat->change_parent($newparentcatid);
}

This function does not update field course_categories.timemodified
If you want to update timemodified, use
$coursecat->update(array('parent' => $newparentcat));

param: int|stdClass|core_course_category $newparentcat

hide_raw($visibleold = 0)   X-Ref
Hide course category and child course and subcategories

If this category has changed the parent and is moved under hidden
category we will want to store it's current visibility state in
the field 'visibleold'. If admin clicked 'hide' for this particular
category, the field 'visibleold' should become 0.

All subcategories and courses will have their current visibility in the field visibleold

This is protected function, use hide() or update() from outside of this class

param: int $visibleold value to set in field $visibleold for this category
return: bool whether changes have been made and caches need to be purged afterwards

hide()   X-Ref
Hide course category and child course and subcategories

Note that there is no capability check inside this function

This function does not update field course_categories.timemodified
If you want to update timemodified, use
$coursecat->update(array('visible' => 0));

show_raw()   X-Ref
Show course category and restores visibility for child course and subcategories

Note that there is no capability check inside this function

This is protected function, use show() or update() from outside of this class

return: bool whether changes have been made and caches need to be purged afterwards

show()   X-Ref
Show course category and restores visibility for child course and subcategories

Note that there is no capability check inside this function

This function does not update field course_categories.timemodified
If you want to update timemodified, use
$coursecat->update(array('visible' => 1));

get_formatted_name($options = array()   X-Ref
Returns name of the category formatted as a string

param: array $options formatting options other than context
return: string

get_nested_name($includelinks = true, $separator = ' / ', $options = [])   X-Ref
Get the nested name of this category, with all of it's parents.

param: bool    $includelinks Whether to wrap each name in the view link for that category.
param: string  $separator The string between each name.
param: array   $options Formatting options.
return: string

get_parents()   X-Ref
Returns ids of all parents of the category. Last element in the return array is the direct parent

For example, if you have a tree of categories like:
Miscellaneous (id = 1)
Subcategory (id = 2)
Sub-subcategory (id = 4)
Other category (id = 3)

core_course_category::get(1)->get_parents() == array()
core_course_category::get(2)->get_parents() == array(1)
core_course_category::get(4)->get_parents() == array(1, 2);

Note that this method does not check if all parents are accessible by current user

return: array of category ids

make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ')   X-Ref
This function returns a nice list representing category tree
for display or to use in a form <select> element

List is cached for 10 minutes

For example, if you have a tree of categories like:
Miscellaneous (id = 1)
Subcategory (id = 2)
Sub-subcategory (id = 4)
Other category (id = 3)
Then after calling this function you will have
array(1 => 'Miscellaneous',
2 => 'Miscellaneous / Subcategory',
4 => 'Miscellaneous / Subcategory / Sub-subcategory',
3 => 'Other category');

If you specify $requiredcapability, then only categories where the current
user has that capability will be added to $list.
If you only have $requiredcapability in a child category, not the parent,
then the child catgegory will still be included.

If you specify the option $excludeid, then that category, and all its children,
are omitted from the tree. This is useful when you are doing something like
moving categories, where you do not want to allow people to move a category
to be the child of itself.

param: string/array $requiredcapability if given, only categories where the current
param: integer $excludeid Exclude this category and its children from the lists built.
param: string $separator string to use as a separator between parent and child category. Default ' / '
return: array of strings

prepare_to_cache()   X-Ref
Prepares the object for caching. Works like the __sleep method.

implementing method from interface cacheable_object

return: array ready to be cached

wake_from_cache($a)   X-Ref
Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.

implementing method from interface cacheable_object

param: array $a
return: core_course_category

can_create_top_level_category()   X-Ref
Returns true if the user is able to create a top level category.

return: bool

get_context()   X-Ref
Returns the category context.

return: context_coursecat

has_manage_capability()   X-Ref
Returns true if the user is able to manage this category.

return: bool

parent_has_manage_capability()   X-Ref
Returns true if the user has the manage capability on the parent category.

return: bool

can_create_subcategory()   X-Ref
Returns true if the current user can create subcategories of this category.

return: bool

can_resort_subcategories()   X-Ref
Returns true if the user can resort this categories sub categories and courses.
Must have manage capability and be able to see all subcategories.

return: bool

can_resort_courses()   X-Ref
Returns true if the user can resort the courses within this category.
Must have manage capability and be able to see all courses.

return: bool

can_change_sortorder()   X-Ref
Returns true of the user can change the sortorder of this category (resort in the parent category)

return: bool

can_create_course()   X-Ref
Returns true if the current user can create a course within this category.

return: bool

can_edit()   X-Ref
Returns true if the current user can edit this categories settings.

return: bool

can_review_roles()   X-Ref
Returns true if the current user can review role assignments for this category.

return: bool

can_review_permissions()   X-Ref
Returns true if the current user can review permissions for this category.

return: bool

can_review_cohorts()   X-Ref
Returns true if the current user can review cohorts for this category.

return: bool

can_review_filters()   X-Ref
Returns true if the current user can review filter settings for this category.

return: bool

can_change_visibility()   X-Ref
Returns true if the current user is able to change the visbility of this category.

return: bool

can_move_courses_out_of()   X-Ref
Returns true if the user can move courses out of this category.

return: bool

can_move_courses_into()   X-Ref
Returns true if the user can move courses into this category.

return: bool

can_restore_courses_into()   X-Ref
Returns true if the user is able to restore a course into this category as a new course.

return: bool

resort_subcategories($field, $cleanup = true)   X-Ref
Resorts the sub categories of this category by the given field.

param: string $field One of name, idnumber or descending values of each (appended desc)
param: bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
return: bool True on success.

resort_categories_cleanup($includecourses = false)   X-Ref
Cleans things up after categories have been resorted.

param: bool $includecourses If set to true we know courses have been resorted as well.

resort_courses($field, $cleanup = true)   X-Ref
Resort the courses within this category by the given field.

param: string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
param: bool $cleanup
return: bool True for success.

change_sortorder_by_one($up)   X-Ref
Changes the sort order of this categories parent shifting this category up or down one.

param: bool $up If set to true the category is shifted up one spot, else its moved down.
return: bool True on success, false otherwise.

get_parent_coursecat()   X-Ref
Returns the parent core_course_category object for this category.

Only returns parent if it exists and is visible to the current user

return: core_course_category|null

can_request_course()   X-Ref
Returns true if the user is able to request a new course be created.

return: bool

can_approve_course_requests()   X-Ref
Returns true if the user can approve course requests.

return: bool