1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
17
18/**
19 * Course selector field.
20 *
21 * Allows auto-complete ajax searching for courses and can restrict by enrolment, permissions, viewhidden...
22 *
23 * @package   core_form
24 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
25 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28global $CFG;
29require_once($CFG->libdir . '/form/autocomplete.php');
30
31/**
32 * Form field type for choosing a course.
33 *
34 * Allows auto-complete ajax searching for courses and can restrict by enrolment, permissions, viewhidden...
35 *
36 * @package   core_form
37 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
38 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40class MoodleQuickForm_course extends MoodleQuickForm_autocomplete {
41
42    /**
43     * @var array $exclude Exclude a list of courses from the list (e.g. the current course).
44     */
45    protected $exclude = array();
46
47    /**
48     * @var boolean $allowmultiple Allow selecting more than one course.
49     */
50    protected $multiple = false;
51
52    /**
53     * @var array $requiredcapabilities Array of extra capabilities to check at the course context.
54     */
55    protected $requiredcapabilities = array();
56
57    /**
58     * @var bool $limittoenrolled Only allow enrolled courses.
59     */
60    protected $limittoenrolled = false;
61
62    /**
63     * Constructor
64     *
65     * @param string $elementname Element name
66     * @param mixed $elementlabel Label(s) for an element
67     * @param mixed $attributes Array of typical HTML attributes plus additional options, such as:
68     *                       'multiple' - boolean multi select
69     *                       'exclude' - array or int, list of course ids to never show
70     *                       'requiredcapabilities' - array of capabilities. Uses ANY to combine them.
71     *                       'limittoenrolled' - boolean Limits to enrolled courses.
72     *                       'includefrontpage' - boolean Enables the frontpage to be selected.
73     *                       'onlywithcompletion' - boolean Limits to courses where completion is enabled.
74     */
75    public function __construct($elementname = null, $elementlabel = null, $attributes = array()) {
76        if (!is_array($attributes)) {
77            $attributes = [];
78        }
79        if (isset($attributes['multiple'])) {
80            $this->multiple = $attributes['multiple'];
81        }
82        if (isset($attributes['exclude'])) {
83            $this->exclude = $attributes['exclude'];
84            if (!is_array($this->exclude)) {
85                $this->exclude = array($this->exclude);
86            }
87            unset($attributes['exclude']);
88        }
89        if (isset($attributes['requiredcapabilities'])) {
90            $this->requiredcapabilities = $attributes['requiredcapabilities'];
91            unset($attributes['requiredcapabilities']);
92        }
93        if (isset($attributes['limittoenrolled'])) {
94            $this->limittoenrolled = $attributes['limittoenrolled'];
95            unset($attributes['limittoenrolled']);
96        }
97
98        $attributes += array(
99            'ajax' => 'core/form-course-selector',
100            'data-requiredcapabilities' => implode(',', $this->requiredcapabilities),
101            'data-exclude' => implode(',', $this->exclude),
102            'data-limittoenrolled' => (int)$this->limittoenrolled
103        );
104        if (!empty($attributes['includefrontpage'])) {
105            $attributes['data-includefrontpage'] = SITEID;
106            unset($attributes['includefrontpage']);
107        }
108        if (!empty($attributes['onlywithcompletion'])) {
109            $attributes['data-onlywithcompletion'] = 1;
110            unset($attributes['onlywithcompletion']);
111        }
112
113        parent::__construct($elementname, $elementlabel, array(), $attributes);
114    }
115
116    /**
117     * Set the value of this element. If values can be added or are unknown, we will
118     * make sure they exist in the options array.
119     * @param string|array $value The value to set.
120     * @return boolean
121     */
122    public function setValue($value) {
123        global $DB;
124        $values = (array) $value;
125        $coursestofetch = array();
126
127        foreach ($values as $onevalue) {
128            if ($onevalue && !$this->optionExists($onevalue) &&
129                    ($onevalue !== '_qf__force_multiselect_submission')) {
130                array_push($coursestofetch, $onevalue);
131            }
132        }
133
134        if (empty($coursestofetch)) {
135            return $this->setSelected($values);
136        }
137
138        // There is no API function to load a list of course from a list of ids.
139        $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
140        $fields = array('c.id', 'c.category', 'c.sortorder',
141                        'c.shortname', 'c.fullname', 'c.idnumber',
142                        'c.startdate', 'c.visible', 'c.cacherev');
143        list($whereclause, $params) = $DB->get_in_or_equal($coursestofetch, SQL_PARAMS_NAMED, 'id');
144
145        $sql = "SELECT ". join(',', $fields). ", $ctxselect
146                FROM {course} c
147                JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
148                WHERE c.id ". $whereclause." ORDER BY c.sortorder";
149        $list = $DB->get_records_sql($sql, array('contextcourse' => CONTEXT_COURSE) + $params);
150
151        $mycourses = enrol_get_my_courses(null, null, 0, array_keys($list));
152        $coursestoselect = array();
153        foreach ($list as $course) {
154            context_helper::preload_from_record($course);
155            $context = context_course::instance($course->id);
156            // Make sure we can see the course.
157            if (!array_key_exists($course->id, $mycourses) && !core_course_category::can_view_course_info($course)) {
158                continue;
159            }
160            $label = format_string(get_course_display_name_for_list($course), true, ['context' => $context]);
161            $this->addOption($label, $course->id);
162            array_push($coursestoselect, $course->id);
163        }
164
165        return $this->setSelected($values);
166    }
167}
168