Merge branch 'MDL-74184' of https://github.com/timhunt/moodle
[moodle.git] / mod / label / lib.php
blob03c2f712584299be0b6c826f9d8af92fb94f5690
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library of functions and constants for module label
21 * @package mod_label
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die;
28 /** LABEL_MAX_NAME_LENGTH = 50 */
29 define("LABEL_MAX_NAME_LENGTH", 50);
31 /**
32 * @uses LABEL_MAX_NAME_LENGTH
33 * @param object $label
34 * @return string
36 function get_label_name($label) {
37 $name = strip_tags(format_string($label->intro,true));
38 if (core_text::strlen($name) > LABEL_MAX_NAME_LENGTH) {
39 $name = core_text::substr($name, 0, LABEL_MAX_NAME_LENGTH)."...";
42 if (empty($name)) {
43 // arbitrary name
44 $name = get_string('modulename','label');
47 return $name;
49 /**
50 * Given an object containing all the necessary data,
51 * (defined by the form in mod_form.php) this function
52 * will create a new instance and return the id number
53 * of the new instance.
55 * @global object
56 * @param object $label
57 * @return bool|int
59 function label_add_instance($label) {
60 global $DB;
62 $label->name = get_label_name($label);
63 $label->timemodified = time();
65 $id = $DB->insert_record("label", $label);
67 $completiontimeexpected = !empty($label->completionexpected) ? $label->completionexpected : null;
68 \core_completion\api::update_completion_date_event($label->coursemodule, 'label', $id, $completiontimeexpected);
70 return $id;
73 /**
74 * Sets the special label display on course page.
76 * @param cm_info $cm Course-module object
78 function label_cm_info_view(cm_info $cm) {
79 $cm->set_custom_cmlist_item(true);
82 /**
83 * Given an object containing all the necessary data,
84 * (defined by the form in mod_form.php) this function
85 * will update an existing instance with new data.
87 * @global object
88 * @param object $label
89 * @return bool
91 function label_update_instance($label) {
92 global $DB;
94 $label->name = get_label_name($label);
95 $label->timemodified = time();
96 $label->id = $label->instance;
98 $completiontimeexpected = !empty($label->completionexpected) ? $label->completionexpected : null;
99 \core_completion\api::update_completion_date_event($label->coursemodule, 'label', $label->id, $completiontimeexpected);
101 return $DB->update_record("label", $label);
105 * Given an ID of an instance of this module,
106 * this function will permanently delete the instance
107 * and any data that depends on it.
109 * @global object
110 * @param int $id
111 * @return bool
113 function label_delete_instance($id) {
114 global $DB;
116 if (! $label = $DB->get_record("label", array("id"=>$id))) {
117 return false;
120 $result = true;
122 $cm = get_coursemodule_from_instance('label', $id);
123 \core_completion\api::update_completion_date_event($cm->id, 'label', $label->id, null);
125 if (! $DB->delete_records("label", array("id"=>$label->id))) {
126 $result = false;
129 return $result;
133 * Given a course_module object, this function returns any
134 * "extra" information that may be needed when printing
135 * this activity in a course listing.
136 * See get_array_of_activities() in course/lib.php
138 * @global object
139 * @param object $coursemodule
140 * @return cached_cm_info|null
142 function label_get_coursemodule_info($coursemodule) {
143 global $DB;
145 if ($label = $DB->get_record('label', array('id'=>$coursemodule->instance), 'id, name, intro, introformat')) {
146 if (empty($label->name)) {
147 // label name missing, fix it
148 $label->name = "label{$label->id}";
149 $DB->set_field('label', 'name', $label->name, array('id'=>$label->id));
151 $info = new cached_cm_info();
152 // no filtering hre because this info is cached and filtered later
153 $info->content = format_module_intro('label', $label, $coursemodule->id, false);
154 $info->name = $label->name;
155 return $info;
156 } else {
157 return null;
162 * This function is used by the reset_course_userdata function in moodlelib.
164 * @param object $data the data submitted from the reset course.
165 * @return array status array
167 function label_reset_userdata($data) {
169 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
170 // See MDL-9367.
172 return array();
176 * @uses FEATURE_IDNUMBER
177 * @uses FEATURE_GROUPS
178 * @uses FEATURE_GROUPINGS
179 * @uses FEATURE_MOD_INTRO
180 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
181 * @uses FEATURE_GRADE_HAS_GRADE
182 * @uses FEATURE_GRADE_OUTCOMES
183 * @param string $feature FEATURE_xx constant for requested feature
184 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
186 function label_supports($feature) {
187 switch($feature) {
188 case FEATURE_IDNUMBER: return true;
189 case FEATURE_GROUPS: return false;
190 case FEATURE_GROUPINGS: return false;
191 case FEATURE_MOD_INTRO: return true;
192 case FEATURE_COMPLETION_TRACKS_VIEWS: return false;
193 case FEATURE_GRADE_HAS_GRADE: return false;
194 case FEATURE_GRADE_OUTCOMES: return false;
195 case FEATURE_MOD_ARCHETYPE: return MOD_ARCHETYPE_RESOURCE;
196 case FEATURE_BACKUP_MOODLE2: return true;
197 case FEATURE_NO_VIEW_LINK: return true;
198 case FEATURE_MOD_PURPOSE: return MOD_PURPOSE_CONTENT;
200 default: return null;
205 * Register the ability to handle drag and drop file uploads
206 * @return array containing details of the files / types the mod can handle
208 function label_dndupload_register() {
209 $strdnd = get_string('dnduploadlabel', 'mod_label');
210 if (get_config('label', 'dndmedia')) {
211 $mediaextensions = file_get_typegroup('extension', ['web_image', 'web_video', 'web_audio']);
212 $files = array();
213 foreach ($mediaextensions as $extn) {
214 $extn = trim($extn, '.');
215 $files[] = array('extension' => $extn, 'message' => $strdnd);
217 $ret = array('files' => $files);
218 } else {
219 $ret = array();
222 $strdndtext = get_string('dnduploadlabeltext', 'mod_label');
223 return array_merge($ret, array('types' => array(
224 array('identifier' => 'text/html', 'message' => $strdndtext, 'noname' => true),
225 array('identifier' => 'text', 'message' => $strdndtext, 'noname' => true)
226 )));
230 * Handle a file that has been uploaded
231 * @param object $uploadinfo details of the file / content that has been uploaded
232 * @return int instance id of the newly created mod
234 function label_dndupload_handle($uploadinfo) {
235 global $USER;
237 // Gather the required info.
238 $data = new stdClass();
239 $data->course = $uploadinfo->course->id;
240 $data->name = $uploadinfo->displayname;
241 $data->intro = '';
242 $data->introformat = FORMAT_HTML;
243 $data->coursemodule = $uploadinfo->coursemodule;
245 // Extract the first (and only) file from the file area and add it to the label as an img tag.
246 if (!empty($uploadinfo->draftitemid)) {
247 $fs = get_file_storage();
248 $draftcontext = context_user::instance($USER->id);
249 $context = context_module::instance($uploadinfo->coursemodule);
250 $files = $fs->get_area_files($draftcontext->id, 'user', 'draft', $uploadinfo->draftitemid, '', false);
251 if ($file = reset($files)) {
252 if (file_mimetype_in_typegroup($file->get_mimetype(), 'web_image')) {
253 // It is an image - resize it, if too big, then insert the img tag.
254 $config = get_config('label');
255 $data->intro = label_generate_resized_image($file, $config->dndresizewidth, $config->dndresizeheight);
256 } else {
257 // We aren't supposed to be supporting non-image types here, but fallback to adding a link, just in case.
258 $url = moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename());
259 $data->intro = html_writer::link($url, $file->get_filename());
261 $data->intro = file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_label', 'intro', 0,
262 null, $data->intro);
264 } else if (!empty($uploadinfo->content)) {
265 $data->intro = $uploadinfo->content;
266 if ($uploadinfo->type != 'text/html') {
267 $data->introformat = FORMAT_PLAIN;
271 return label_add_instance($data, null);
275 * Resize the image, if required, then generate an img tag and, if required, a link to the full-size image
276 * @param stored_file $file the image file to process
277 * @param int $maxwidth the maximum width allowed for the image
278 * @param int $maxheight the maximum height allowed for the image
279 * @return string HTML fragment to add to the label
281 function label_generate_resized_image(stored_file $file, $maxwidth, $maxheight) {
282 global $CFG;
284 $fullurl = moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename());
285 $link = null;
286 $attrib = array('alt' => $file->get_filename(), 'src' => $fullurl);
288 if ($imginfo = $file->get_imageinfo()) {
289 // Work out the new width / height, bounded by maxwidth / maxheight
290 $width = $imginfo['width'];
291 $height = $imginfo['height'];
292 if (!empty($maxwidth) && $width > $maxwidth) {
293 $height *= (float)$maxwidth / $width;
294 $width = $maxwidth;
296 if (!empty($maxheight) && $height > $maxheight) {
297 $width *= (float)$maxheight / $height;
298 $height = $maxheight;
301 $attrib['width'] = $width;
302 $attrib['height'] = $height;
304 // If the size has changed and the image is of a suitable mime type, generate a smaller version
305 if ($width != $imginfo['width']) {
306 $mimetype = $file->get_mimetype();
307 if ($mimetype === 'image/gif' or $mimetype === 'image/jpeg' or $mimetype === 'image/png') {
308 require_once($CFG->libdir.'/gdlib.php');
309 $data = $file->generate_image_thumbnail($width, $height);
311 if (!empty($data)) {
312 $fs = get_file_storage();
313 $record = array(
314 'contextid' => $file->get_contextid(),
315 'component' => $file->get_component(),
316 'filearea' => $file->get_filearea(),
317 'itemid' => $file->get_itemid(),
318 'filepath' => '/',
319 'filename' => 's_'.$file->get_filename(),
321 $smallfile = $fs->create_file_from_string($record, $data);
323 // Replace the image 'src' with the resized file and link to the original
324 $attrib['src'] = moodle_url::make_draftfile_url($smallfile->get_itemid(), $smallfile->get_filepath(),
325 $smallfile->get_filename());
326 $link = $fullurl;
331 } else {
332 // Assume this is an image type that get_imageinfo cannot handle (e.g. SVG)
333 $attrib['width'] = $maxwidth;
336 $attrib['class'] = "img-fluid";
337 $img = html_writer::empty_tag('img', $attrib);
338 if ($link) {
339 return html_writer::link($link, $img);
340 } else {
341 return $img;
346 * Check if the module has any update that affects the current user since a given time.
348 * @param cm_info $cm course module data
349 * @param int $from the time to check updates from
350 * @param array $filter if we need to check only specific updates
351 * @return stdClass an object with the different type of areas indicating if they were updated or not
352 * @since Moodle 3.2
354 function label_check_updates_since(cm_info $cm, $from, $filter = array()) {
355 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
356 return $updates;
360 * This function receives a calendar event and returns the action associated with it, or null if there is none.
362 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
363 * is not displayed on the block.
365 * @param calendar_event $event
366 * @param \core_calendar\action_factory $factory
367 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
368 * @return \core_calendar\local\event\entities\action_interface|null
370 function mod_label_core_calendar_provide_event_action(calendar_event $event,
371 \core_calendar\action_factory $factory,
372 int $userid = 0) {
373 $cm = get_fast_modinfo($event->courseid, $userid)->instances['label'][$event->instance];
375 if (!$cm->uservisible) {
376 // The module is not visible to the user for any reason.
377 return null;
380 $completion = new \completion_info($cm->get_course());
382 $completiondata = $completion->get_data($cm, false, $userid);
384 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
385 return null;
388 return $factory->create_instance(
389 get_string('view'),
390 new \moodle_url('/mod/label/view.php', ['id' => $cm->id]),
392 true