PageRenderTime 1261ms CodeModel.GetById 35ms RepoModel.GetById 2ms app.codeStats 1ms

/course/lib.php

https://bitbucket.org/moodle/moodle
PHP | 5132 lines | 3085 code | 601 blank | 1446 comment | 634 complexity | 3a0059cea7d8c7feec8b0a9ea43804a9 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  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. * Library of useful functions
  18. *
  19. * @copyright 1999 Martin Dougiamas http://dougiamas.com
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. * @package core_course
  22. */
  23. defined('MOODLE_INTERNAL') || die;
  24. use core_courseformat\base as course_format;
  25. require_once($CFG->libdir.'/completionlib.php');
  26. require_once($CFG->libdir.'/filelib.php');
  27. require_once($CFG->libdir.'/datalib.php');
  28. require_once($CFG->dirroot.'/course/format/lib.php');
  29. define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
  30. define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
  31. /**
  32. * Number of courses to display when summaries are included.
  33. * @var int
  34. * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
  35. */
  36. define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
  37. // Max courses in log dropdown before switching to optional.
  38. define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
  39. // Max users in log dropdown before switching to optional.
  40. define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
  41. define('FRONTPAGENEWS', '0');
  42. define('FRONTPAGECATEGORYNAMES', '2');
  43. define('FRONTPAGECATEGORYCOMBO', '4');
  44. define('FRONTPAGEENROLLEDCOURSELIST', '5');
  45. define('FRONTPAGEALLCOURSELIST', '6');
  46. define('FRONTPAGECOURSESEARCH', '7');
  47. // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
  48. define('EXCELROWS', 65535);
  49. define('FIRSTUSEDEXCELROW', 3);
  50. define('MOD_CLASS_ACTIVITY', 0);
  51. define('MOD_CLASS_RESOURCE', 1);
  52. define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
  53. define('COURSE_TIMELINE_ALL', 'all');
  54. define('COURSE_TIMELINE_PAST', 'past');
  55. define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
  56. define('COURSE_TIMELINE_FUTURE', 'future');
  57. define('COURSE_TIMELINE_SEARCH', 'search');
  58. define('COURSE_FAVOURITES', 'favourites');
  59. define('COURSE_TIMELINE_HIDDEN', 'hidden');
  60. define('COURSE_CUSTOMFIELD', 'customfield');
  61. define('COURSE_DB_QUERY_LIMIT', 1000);
  62. /** Searching for all courses that have no value for the specified custom field. */
  63. define('COURSE_CUSTOMFIELD_EMPTY', -1);
  64. // Course activity chooser footer default display option.
  65. define('COURSE_CHOOSER_FOOTER_NONE', 'hidden');
  66. // Download course content options.
  67. define('DOWNLOAD_COURSE_CONTENT_DISABLED', 0);
  68. define('DOWNLOAD_COURSE_CONTENT_ENABLED', 1);
  69. define('DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT', 2);
  70. function make_log_url($module, $url) {
  71. switch ($module) {
  72. case 'course':
  73. if (strpos($url, 'report/') === 0) {
  74. // there is only one report type, course reports are deprecated
  75. $url = "/$url";
  76. break;
  77. }
  78. case 'file':
  79. case 'login':
  80. case 'lib':
  81. case 'admin':
  82. case 'category':
  83. case 'mnet course':
  84. if (strpos($url, '../') === 0) {
  85. $url = ltrim($url, '.');
  86. } else {
  87. $url = "/course/$url";
  88. }
  89. break;
  90. case 'calendar':
  91. $url = "/calendar/$url";
  92. break;
  93. case 'user':
  94. case 'blog':
  95. $url = "/$module/$url";
  96. break;
  97. case 'upload':
  98. $url = $url;
  99. break;
  100. case 'coursetags':
  101. $url = '/'.$url;
  102. break;
  103. case 'library':
  104. case '':
  105. $url = '/';
  106. break;
  107. case 'message':
  108. $url = "/message/$url";
  109. break;
  110. case 'notes':
  111. $url = "/notes/$url";
  112. break;
  113. case 'tag':
  114. $url = "/tag/$url";
  115. break;
  116. case 'role':
  117. $url = '/'.$url;
  118. break;
  119. case 'grade':
  120. $url = "/grade/$url";
  121. break;
  122. default:
  123. $url = "/mod/$module/$url";
  124. break;
  125. }
  126. //now let's sanitise urls - there might be some ugly nasties:-(
  127. $parts = explode('?', $url);
  128. $script = array_shift($parts);
  129. if (strpos($script, 'http') === 0) {
  130. $script = clean_param($script, PARAM_URL);
  131. } else {
  132. $script = clean_param($script, PARAM_PATH);
  133. }
  134. $query = '';
  135. if ($parts) {
  136. $query = implode('', $parts);
  137. $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
  138. $parts = explode('&', $query);
  139. $eq = urlencode('=');
  140. foreach ($parts as $key=>$part) {
  141. $part = urlencode(urldecode($part));
  142. $part = str_replace($eq, '=', $part);
  143. $parts[$key] = $part;
  144. }
  145. $query = '?'.implode('&amp;', $parts);
  146. }
  147. return $script.$query;
  148. }
  149. function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
  150. $modname="", $modid=0, $modaction="", $groupid=0) {
  151. global $CFG, $DB;
  152. // It is assumed that $date is the GMT time of midnight for that day,
  153. // and so the next 86400 seconds worth of logs are printed.
  154. /// Setup for group handling.
  155. // TODO: I don't understand group/context/etc. enough to be able to do
  156. // something interesting with it here
  157. // What is the context of a remote course?
  158. /// If the group mode is separate, and this user does not have editing privileges,
  159. /// then only the user's group can be viewed.
  160. //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
  161. // $groupid = get_current_group($course->id);
  162. //}
  163. /// If this course doesn't have groups, no groupid can be specified.
  164. //else if (!$course->groupmode) {
  165. // $groupid = 0;
  166. //}
  167. $groupid = 0;
  168. $joins = array();
  169. $where = '';
  170. $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
  171. FROM {mnet_log} l
  172. LEFT JOIN {user} u ON l.userid = u.id
  173. WHERE ";
  174. $params = array();
  175. $where .= "l.hostid = :hostid";
  176. $params['hostid'] = $hostid;
  177. // TODO: Is 1 really a magic number referring to the sitename?
  178. if ($course != SITEID || $modid != 0) {
  179. $where .= " AND l.course=:courseid";
  180. $params['courseid'] = $course;
  181. }
  182. if ($modname) {
  183. $where .= " AND l.module = :modname";
  184. $params['modname'] = $modname;
  185. }
  186. if ('site_errors' === $modid) {
  187. $where .= " AND ( l.action='error' OR l.action='infected' )";
  188. } else if ($modid) {
  189. //TODO: This assumes that modids are the same across sites... probably
  190. //not true
  191. $where .= " AND l.cmid = :modid";
  192. $params['modid'] = $modid;
  193. }
  194. if ($modaction) {
  195. $firstletter = substr($modaction, 0, 1);
  196. if ($firstletter == '-') {
  197. $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
  198. $params['modaction'] = '%'.substr($modaction, 1).'%';
  199. } else {
  200. $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
  201. $params['modaction'] = '%'.$modaction.'%';
  202. }
  203. }
  204. if ($user) {
  205. $where .= " AND l.userid = :user";
  206. $params['user'] = $user;
  207. }
  208. if ($date) {
  209. $enddate = $date + 86400;
  210. $where .= " AND l.time > :date AND l.time < :enddate";
  211. $params['date'] = $date;
  212. $params['enddate'] = $enddate;
  213. }
  214. $result = array();
  215. $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
  216. if(!empty($result['totalcount'])) {
  217. $where .= " ORDER BY $order";
  218. $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
  219. } else {
  220. $result['logs'] = array();
  221. }
  222. return $result;
  223. }
  224. /**
  225. * Checks the integrity of the course data.
  226. *
  227. * In summary - compares course_sections.sequence and course_modules.section.
  228. *
  229. * More detailed, checks that:
  230. * - course_sections.sequence contains each module id not more than once in the course
  231. * - for each moduleid from course_sections.sequence the field course_modules.section
  232. * refers to the same section id (this means course_sections.sequence is more
  233. * important if they are different)
  234. * - ($fullcheck only) each module in the course is present in one of
  235. * course_sections.sequence
  236. * - ($fullcheck only) removes non-existing course modules from section sequences
  237. *
  238. * If there are any mismatches, the changes are made and records are updated in DB.
  239. *
  240. * Course cache is NOT rebuilt if there are any errors!
  241. *
  242. * This function is used each time when course cache is being rebuilt with $fullcheck = false
  243. * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
  244. *
  245. * @param int $courseid id of the course
  246. * @param array $rawmods result of funciton {@link get_course_mods()} - containst
  247. * the list of enabled course modules in the course. Retrieved from DB if not specified.
  248. * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
  249. * @param array $sections records from course_sections table for this course.
  250. * Retrieved from DB if not specified
  251. * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
  252. * course modules from sequences. Only to be used in site maintenance mode when we are
  253. * sure that another user is not in the middle of the process of moving/removing a module.
  254. * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
  255. * @return array array of messages with found problems. Empty output means everything is ok
  256. */
  257. function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
  258. global $DB;
  259. $messages = array();
  260. if ($sections === null) {
  261. $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
  262. }
  263. if ($fullcheck) {
  264. // Retrieve all records from course_modules regardless of module type visibility.
  265. $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
  266. }
  267. if ($rawmods === null) {
  268. $rawmods = get_course_mods($courseid);
  269. }
  270. if (!$fullcheck && (empty($sections) || empty($rawmods))) {
  271. // If either of the arrays is empty, no modules are displayed anyway.
  272. return true;
  273. }
  274. $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
  275. // First make sure that each module id appears in section sequences only once.
  276. // If it appears in several section sequences the last section wins.
  277. // If it appears twice in one section sequence, the first occurence wins.
  278. $modsection = array();
  279. foreach ($sections as $sectionid => $section) {
  280. $sections[$sectionid]->newsequence = $section->sequence;
  281. if (!empty($section->sequence)) {
  282. $sequence = explode(",", $section->sequence);
  283. $sequenceunique = array_unique($sequence);
  284. if (count($sequenceunique) != count($sequence)) {
  285. // Some course module id appears in this section sequence more than once.
  286. ksort($sequenceunique); // Preserve initial order of modules.
  287. $sequence = array_values($sequenceunique);
  288. $sections[$sectionid]->newsequence = join(',', $sequence);
  289. $messages[] = $debuggingprefix.'Sequence for course section ['.
  290. $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
  291. }
  292. foreach ($sequence as $cmid) {
  293. if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
  294. // Some course module id appears to be in more than one section's sequences.
  295. $wrongsectionid = $modsection[$cmid];
  296. $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
  297. $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
  298. $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
  299. }
  300. $modsection[$cmid] = $sectionid;
  301. }
  302. }
  303. }
  304. // Add orphaned modules to their sections if they exist or to section 0 otherwise.
  305. if ($fullcheck) {
  306. foreach ($rawmods as $cmid => $mod) {
  307. if (!isset($modsection[$cmid])) {
  308. // This is a module that is not mentioned in course_section.sequence at all.
  309. // Add it to the section $mod->section or to the last available section.
  310. if ($mod->section && isset($sections[$mod->section])) {
  311. $modsection[$cmid] = $mod->section;
  312. } else {
  313. $firstsection = reset($sections);
  314. $modsection[$cmid] = $firstsection->id;
  315. }
  316. $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
  317. $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
  318. $modsection[$cmid].']';
  319. }
  320. }
  321. foreach ($modsection as $cmid => $sectionid) {
  322. if (!isset($rawmods[$cmid])) {
  323. // Section $sectionid refers to module id that does not exist.
  324. $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
  325. $messages[] = $debuggingprefix.'Course module ['.$cmid.
  326. '] does not exist but is present in the sequence of section ['.$sectionid.']';
  327. }
  328. }
  329. }
  330. // Update changed sections.
  331. if (!$checkonly && !empty($messages)) {
  332. foreach ($sections as $sectionid => $section) {
  333. if ($section->newsequence !== $section->sequence) {
  334. $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
  335. }
  336. }
  337. }
  338. // Now make sure that all modules point to the correct sections.
  339. foreach ($rawmods as $cmid => $mod) {
  340. if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
  341. if (!$checkonly) {
  342. $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
  343. }
  344. $messages[] = $debuggingprefix.'Course module ['.$cmid.
  345. '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
  346. }
  347. }
  348. return $messages;
  349. }
  350. /**
  351. * For a given course, returns an array of course activity objects
  352. * Each item in the array contains he following properties:
  353. */
  354. function get_array_of_activities($courseid) {
  355. // cm - course module id
  356. // mod - name of the module (eg forum)
  357. // section - the number of the section (eg week or topic)
  358. // name - the name of the instance
  359. // visible - is the instance visible or not
  360. // groupingid - grouping id
  361. // extra - contains extra string to include in any link
  362. global $CFG, $DB;
  363. $course = $DB->get_record('course', array('id'=>$courseid));
  364. if (empty($course)) {
  365. throw new moodle_exception('courseidnotfound');
  366. }
  367. $mod = array();
  368. $rawmods = get_course_mods($courseid);
  369. if (empty($rawmods)) {
  370. return $mod; // always return array
  371. }
  372. $courseformat = course_get_format($course);
  373. if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
  374. 'section ASC', 'id,section,sequence,visible')) {
  375. // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
  376. if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
  377. debugging(join('<br>', $errormessages));
  378. $rawmods = get_course_mods($courseid);
  379. $sections = $DB->get_records('course_sections', array('course' => $courseid),
  380. 'section ASC', 'id,section,sequence,visible');
  381. }
  382. // Build array of activities.
  383. foreach ($sections as $section) {
  384. if (!empty($section->sequence)) {
  385. $sequence = explode(",", $section->sequence);
  386. foreach ($sequence as $seq) {
  387. if (empty($rawmods[$seq])) {
  388. continue;
  389. }
  390. // Adjust visibleoncoursepage, value in DB may not respect format availability.
  391. $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
  392. || $rawmods[$seq]->visibleoncoursepage
  393. || empty($CFG->allowstealth)
  394. || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
  395. // Create an object that will be cached.
  396. $mod[$seq] = new stdClass();
  397. $mod[$seq]->id = $rawmods[$seq]->instance;
  398. $mod[$seq]->cm = $rawmods[$seq]->id;
  399. $mod[$seq]->mod = $rawmods[$seq]->modname;
  400. // Oh dear. Inconsistent names left here for backward compatibility.
  401. $mod[$seq]->section = $section->section;
  402. $mod[$seq]->sectionid = $rawmods[$seq]->section;
  403. $mod[$seq]->module = $rawmods[$seq]->module;
  404. $mod[$seq]->added = $rawmods[$seq]->added;
  405. $mod[$seq]->score = $rawmods[$seq]->score;
  406. $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
  407. $mod[$seq]->visible = $rawmods[$seq]->visible;
  408. $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
  409. $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
  410. $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
  411. $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
  412. $mod[$seq]->indent = $rawmods[$seq]->indent;
  413. $mod[$seq]->completion = $rawmods[$seq]->completion;
  414. $mod[$seq]->extra = "";
  415. $mod[$seq]->completiongradeitemnumber =
  416. $rawmods[$seq]->completiongradeitemnumber;
  417. $mod[$seq]->completionpassgrade = $rawmods[$seq]->completionpassgrade;
  418. $mod[$seq]->completionview = $rawmods[$seq]->completionview;
  419. $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
  420. $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
  421. $mod[$seq]->availability = $rawmods[$seq]->availability;
  422. $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
  423. $modname = $mod[$seq]->mod;
  424. $functionname = $modname."_get_coursemodule_info";
  425. if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
  426. continue;
  427. }
  428. include_once("$CFG->dirroot/mod/$modname/lib.php");
  429. if ($hasfunction = function_exists($functionname)) {
  430. if ($info = $functionname($rawmods[$seq])) {
  431. if (!empty($info->icon)) {
  432. $mod[$seq]->icon = $info->icon;
  433. }
  434. if (!empty($info->iconcomponent)) {
  435. $mod[$seq]->iconcomponent = $info->iconcomponent;
  436. }
  437. if (!empty($info->name)) {
  438. $mod[$seq]->name = $info->name;
  439. }
  440. if ($info instanceof cached_cm_info) {
  441. // When using cached_cm_info you can include three new fields
  442. // that aren't available for legacy code
  443. if (!empty($info->content)) {
  444. $mod[$seq]->content = $info->content;
  445. }
  446. if (!empty($info->extraclasses)) {
  447. $mod[$seq]->extraclasses = $info->extraclasses;
  448. }
  449. if (!empty($info->iconurl)) {
  450. // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
  451. $url = new moodle_url($info->iconurl);
  452. $mod[$seq]->iconurl = $url->out(false);
  453. }
  454. if (!empty($info->onclick)) {
  455. $mod[$seq]->onclick = $info->onclick;
  456. }
  457. if (!empty($info->customdata)) {
  458. $mod[$seq]->customdata = $info->customdata;
  459. }
  460. } else {
  461. // When using a stdclass, the (horrible) deprecated ->extra field
  462. // is available for BC
  463. if (!empty($info->extra)) {
  464. $mod[$seq]->extra = $info->extra;
  465. }
  466. }
  467. }
  468. }
  469. // When there is no modname_get_coursemodule_info function,
  470. // but showdescriptions is enabled, then we use the 'intro'
  471. // and 'introformat' fields in the module table
  472. if (!$hasfunction && $rawmods[$seq]->showdescription) {
  473. if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
  474. array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
  475. // Set content from intro and introformat. Filters are disabled
  476. // because we filter it with format_text at display time
  477. $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
  478. $modvalues, $rawmods[$seq]->id, false);
  479. // To save making another query just below, put name in here
  480. $mod[$seq]->name = $modvalues->name;
  481. }
  482. }
  483. if (!isset($mod[$seq]->name)) {
  484. $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
  485. }
  486. // Minimise the database size by unsetting default options when they are
  487. // 'empty'. This list corresponds to code in the cm_info constructor.
  488. foreach (array('idnumber', 'groupmode', 'groupingid',
  489. 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
  490. 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
  491. 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
  492. if (property_exists($mod[$seq], $property) &&
  493. empty($mod[$seq]->{$property})) {
  494. unset($mod[$seq]->{$property});
  495. }
  496. }
  497. // Special case: this value is usually set to null, but may be 0
  498. if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
  499. is_null($mod[$seq]->completiongradeitemnumber)) {
  500. unset($mod[$seq]->completiongradeitemnumber);
  501. }
  502. }
  503. }
  504. }
  505. }
  506. return $mod;
  507. }
  508. /**
  509. * Returns the localised human-readable names of all used modules
  510. *
  511. * @param bool $plural if true returns the plural forms of the names
  512. * @return array where key is the module name (component name without 'mod_') and
  513. * the value is the human-readable string. Array sorted alphabetically by value
  514. */
  515. function get_module_types_names($plural = false) {
  516. static $modnames = null;
  517. global $DB, $CFG;
  518. if ($modnames === null) {
  519. $modnames = array(0 => array(), 1 => array());
  520. if ($allmods = $DB->get_records("modules")) {
  521. foreach ($allmods as $mod) {
  522. if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
  523. $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
  524. $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
  525. }
  526. }
  527. }
  528. }
  529. return $modnames[(int)$plural];
  530. }
  531. /**
  532. * Set highlighted section. Only one section can be highlighted at the time.
  533. *
  534. * @param int $courseid course id
  535. * @param int $marker highlight section with this number, 0 means remove higlightin
  536. * @return void
  537. */
  538. function course_set_marker($courseid, $marker) {
  539. global $DB, $COURSE;
  540. $DB->set_field("course", "marker", $marker, array('id' => $courseid));
  541. if ($COURSE && $COURSE->id == $courseid) {
  542. $COURSE->marker = $marker;
  543. }
  544. core_courseformat\base::reset_course_cache($courseid);
  545. course_modinfo::clear_instance_cache($courseid);
  546. }
  547. /**
  548. * For a given course section, marks it visible or hidden,
  549. * and does the same for every activity in that section
  550. *
  551. * @param int $courseid course id
  552. * @param int $sectionnumber The section number to adjust
  553. * @param int $visibility The new visibility
  554. * @return array A list of resources which were hidden in the section
  555. */
  556. function set_section_visible($courseid, $sectionnumber, $visibility) {
  557. global $DB;
  558. $resourcestotoggle = array();
  559. if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
  560. course_update_section($courseid, $section, array('visible' => $visibility));
  561. // Determine which modules are visible for AJAX update
  562. $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
  563. if (!empty($modules)) {
  564. list($insql, $params) = $DB->get_in_or_equal($modules);
  565. $select = 'id ' . $insql . ' AND visible = ?';
  566. array_push($params, $visibility);
  567. if (!$visibility) {
  568. $select .= ' AND visibleold = 1';
  569. }
  570. $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
  571. }
  572. }
  573. return $resourcestotoggle;
  574. }
  575. /**
  576. * Return the course category context for the category with id $categoryid, except
  577. * that if $categoryid is 0, return the system context.
  578. *
  579. * @param integer $categoryid a category id or 0.
  580. * @return context the corresponding context
  581. */
  582. function get_category_or_system_context($categoryid) {
  583. if ($categoryid) {
  584. return context_coursecat::instance($categoryid, IGNORE_MISSING);
  585. } else {
  586. return context_system::instance();
  587. }
  588. }
  589. /**
  590. * Print the buttons relating to course requests.
  591. *
  592. * @param context $context current page context.
  593. */
  594. function print_course_request_buttons($context) {
  595. global $CFG, $DB, $OUTPUT;
  596. if (empty($CFG->enablecourserequests)) {
  597. return;
  598. }
  599. if (course_request::can_request($context)) {
  600. // Print a button to request a new course.
  601. $params = [];
  602. if ($context instanceof context_coursecat) {
  603. $params['category'] = $context->instanceid;
  604. }
  605. echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
  606. get_string('requestcourse'), 'get');
  607. }
  608. /// Print a button to manage pending requests
  609. if (has_capability('moodle/site:approvecourse', $context)) {
  610. $disabled = !$DB->record_exists('course_request', array());
  611. echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
  612. }
  613. }
  614. /**
  615. * Does the user have permission to edit things in this category?
  616. *
  617. * @param integer $categoryid The id of the category we are showing, or 0 for system context.
  618. * @return boolean has_any_capability(array(...), ...); in the appropriate context.
  619. */
  620. function can_edit_in_category($categoryid = 0) {
  621. $context = get_category_or_system_context($categoryid);
  622. return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
  623. }
  624. /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
  625. function add_course_module($mod) {
  626. global $DB;
  627. $mod->added = time();
  628. unset($mod->id);
  629. $cmid = $DB->insert_record("course_modules", $mod);
  630. rebuild_course_cache($mod->course, true);
  631. return $cmid;
  632. }
  633. /**
  634. * Creates a course section and adds it to the specified position
  635. *
  636. * @param int|stdClass $courseorid course id or course object
  637. * @param int $position position to add to, 0 means to the end. If position is greater than
  638. * number of existing secitons, the section is added to the end. This will become sectionnum of the
  639. * new section. All existing sections at this or bigger position will be shifted down.
  640. * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
  641. * @return stdClass created section object
  642. */
  643. function course_create_section($courseorid, $position = 0, $skipcheck = false) {
  644. global $DB;
  645. $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
  646. // Find the last sectionnum among existing sections.
  647. if ($skipcheck) {
  648. $lastsection = $position - 1;
  649. } else {
  650. $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
  651. }
  652. // First add section to the end.
  653. $cw = new stdClass();
  654. $cw->course = $courseid;
  655. $cw->section = $lastsection + 1;
  656. $cw->summary = '';
  657. $cw->summaryformat = FORMAT_HTML;
  658. $cw->sequence = '';
  659. $cw->name = null;
  660. $cw->visible = 1;
  661. $cw->availability = null;
  662. $cw->timemodified = time();
  663. $cw->id = $DB->insert_record("course_sections", $cw);
  664. // Now move it to the specified position.
  665. if ($position > 0 && $position <= $lastsection) {
  666. $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
  667. move_section_to($course, $cw->section, $position, true);
  668. $cw->section = $position;
  669. }
  670. core\event\course_section_created::create_from_section($cw)->trigger();
  671. rebuild_course_cache($courseid, true);
  672. return $cw;
  673. }
  674. /**
  675. * Creates missing course section(s) and rebuilds course cache
  676. *
  677. * @param int|stdClass $courseorid course id or course object
  678. * @param int|array $sections list of relative section numbers to create
  679. * @return bool if there were any sections created
  680. */
  681. function course_create_sections_if_missing($courseorid, $sections) {
  682. if (!is_array($sections)) {
  683. $sections = array($sections);
  684. }
  685. $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
  686. if ($newsections = array_diff($sections, $existing)) {
  687. foreach ($newsections as $sectionnum) {
  688. course_create_section($courseorid, $sectionnum, true);
  689. }
  690. return true;
  691. }
  692. return false;
  693. }
  694. /**
  695. * Adds an existing module to the section
  696. *
  697. * Updates both tables {course_sections} and {course_modules}
  698. *
  699. * Note: This function does not use modinfo PROVIDED that the section you are
  700. * adding the module to already exists. If the section does not exist, it will
  701. * build modinfo if necessary and create the section.
  702. *
  703. * @param int|stdClass $courseorid course id or course object
  704. * @param int $cmid id of the module already existing in course_modules table
  705. * @param int $sectionnum relative number of the section (field course_sections.section)
  706. * If section does not exist it will be created
  707. * @param int|stdClass $beforemod id or object with field id corresponding to the module
  708. * before which the module needs to be included. Null for inserting in the
  709. * end of the section
  710. * @return int The course_sections ID where the module is inserted
  711. */
  712. function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
  713. global $DB, $COURSE;
  714. if (is_object($beforemod)) {
  715. $beforemod = $beforemod->id;
  716. }
  717. if (is_object($courseorid)) {
  718. $courseid = $courseorid->id;
  719. } else {
  720. $courseid = $courseorid;
  721. }
  722. // Do not try to use modinfo here, there is no guarantee it is valid!
  723. $section = $DB->get_record('course_sections',
  724. array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
  725. if (!$section) {
  726. // This function call requires modinfo.
  727. course_create_sections_if_missing($courseorid, $sectionnum);
  728. $section = $DB->get_record('course_sections',
  729. array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
  730. }
  731. $modarray = explode(",", trim($section->sequence));
  732. if (empty($section->sequence)) {
  733. $newsequence = "$cmid";
  734. } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
  735. $insertarray = array($cmid, $beforemod);
  736. array_splice($modarray, $key[0], 1, $insertarray);
  737. $newsequence = implode(",", $modarray);
  738. } else {
  739. $newsequence = "$section->sequence,$cmid";
  740. }
  741. $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
  742. $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
  743. if (is_object($courseorid)) {
  744. rebuild_course_cache($courseorid->id, true);
  745. } else {
  746. rebuild_course_cache($courseorid, true);
  747. }
  748. return $section->id; // Return course_sections ID that was used.
  749. }
  750. /**
  751. * Change the group mode of a course module.
  752. *
  753. * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
  754. * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
  755. *
  756. * @param int $id course module ID.
  757. * @param int $groupmode the new groupmode value.
  758. * @return bool True if the $groupmode was updated.
  759. */
  760. function set_coursemodule_groupmode($id, $groupmode) {
  761. global $DB;
  762. $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
  763. if ($cm->groupmode != $groupmode) {
  764. $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
  765. rebuild_course_cache($cm->course, true);
  766. }
  767. return ($cm->groupmode != $groupmode);
  768. }
  769. function set_coursemodule_idnumber($id, $idnumber) {
  770. global $DB;
  771. $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
  772. if ($cm->idnumber != $idnumber) {
  773. $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
  774. rebuild_course_cache($cm->course, true);
  775. }
  776. return ($cm->idnumber != $idnumber);
  777. }
  778. /**
  779. * Set the visibility of a module and inherent properties.
  780. *
  781. * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
  782. * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
  783. *
  784. * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
  785. * has been moved to {@link set_section_visible()} which was the only place from which
  786. * the parameter was used.
  787. *
  788. * @param int $id of the module
  789. * @param int $visible state of the module
  790. * @param int $visibleoncoursepage state of the module on the course page
  791. * @return bool false when the module was not found, true otherwise
  792. */
  793. function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
  794. global $DB, $CFG;
  795. require_once($CFG->libdir.'/gradelib.php');
  796. require_once($CFG->dirroot.'/calendar/lib.php');
  797. if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
  798. return false;
  799. }
  800. // Create events and propagate visibility to associated grade items if the value has changed.
  801. // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
  802. if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
  803. return true;
  804. }
  805. if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
  806. return false;
  807. }
  808. if (($cm->visible != $visible) &&
  809. ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
  810. foreach($events as $event) {
  811. if ($visible) {
  812. $event = new calendar_event($event);
  813. $event->toggle_visibility(true);
  814. } else {
  815. $event = new calendar_event($event);
  816. $event->toggle_visibility(false);
  817. }
  818. }
  819. }
  820. // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
  821. // affect visibleold to allow for an original visibility restore. See set_section_visible().
  822. $cminfo = new stdClass();
  823. $cminfo->id = $id;
  824. $cminfo->visible = $visible;
  825. $cminfo->visibleoncoursepage = $visibleoncoursepage;
  826. $cminfo->visibleold = $visible;
  827. $DB->update_record('course_modules', $cminfo);
  828. // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
  829. // Note that this must be done after updating the row in course_modules, in case
  830. // the modules grade_item_update function needs to access $cm->visible.
  831. if ($cm->visible != $visible &&
  832. plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
  833. component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
  834. $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
  835. component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
  836. } else if ($cm->visible != $visible) {
  837. $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
  838. if ($grade_items) {
  839. foreach ($grade_items as $grade_item) {
  840. $grade_item->set_hidden(!$visible);
  841. }
  842. }
  843. }
  844. rebuild_course_cache($cm->course, true);
  845. return true;
  846. }
  847. /**
  848. * Changes the course module name
  849. *
  850. * @param int $id course module id
  851. * @param string $name new value for a name
  852. * @return bool whether a change was made
  853. */
  854. function set_coursemodule_name($id, $name) {
  855. global $CFG, $DB;
  856. require_once($CFG->libdir . '/gradelib.php');
  857. $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
  858. $module = new \stdClass();
  859. $module->id = $cm->instance;
  860. // Escape strings as they would be by mform.
  861. if (!empty($CFG->formatstringstriptags)) {
  862. $module->name = clean_param($name, PARAM_TEXT);
  863. } else {
  864. $module->name = clean_param($name, PARAM_CLEANHTML);
  865. }
  866. if ($module->name === $cm->name || strval($module->name) === '') {
  867. return false;
  868. }
  869. if (\core_text::strlen($module->name) > 255) {
  870. throw new \moodle_exception('maximumchars', 'moodle', '', 255);
  871. }
  872. $module->timemodified = time();
  873. $DB->update_record($cm->modname, $module);
  874. $cm->name = $module->name;
  875. \core\event\course_module_updated::create_from_cm($cm)->trigger();
  876. rebuild_course_cache($cm->course, true);
  877. // Attempt to update the grade item if relevant.
  878. $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
  879. $grademodule->cmidnumber = $cm->idnumber;
  880. $grademodule->modname = $cm->modname;
  881. grade_update_mod_grades($grademodule);
  882. // Update calendar events with the new name.
  883. course_module_update_calendar_events($cm->modname, $grademodule, $cm);
  884. return true;
  885. }
  886. /**
  887. * This function will handle the whole deletion process of a module. This includes calling
  888. * the modules delete_instance function, deleting files, events, grades, conditional data,
  889. * the data in the course_module and course_sections table and adding a module deletion
  890. * event to the DB.
  891. *
  892. * @param int $cmid the course module id
  893. * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
  894. * @throws moodle_exception
  895. * @since Moodle 2.5
  896. */
  897. function course_delete_module($cmid, $async = false) {
  898. // Check the 'course_module_background_deletion_recommended' hook first.
  899. // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
  900. // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
  901. // It's up to plugins to handle things like whether or not they are enabled.
  902. if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
  903. foreach ($pluginsfunction as $plugintype => $plugins) {
  904. foreach ($plugins as $pluginfunction) {
  905. if ($pluginfunction()) {
  906. return course_module_flag_for_async_deletion($cmid);
  907. }
  908. }
  909. }
  910. }
  911. global $CFG, $DB;
  912. require_once($CFG->libdir.'/gradelib.php');
  913. require_once($CFG->libdir.'/questionlib.php');
  914. require_once($CFG->dirroot.'/blog/lib.php');
  915. require_once($CFG->dirroot.'/calendar/lib.php');
  916. // Get the course module.
  917. if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
  918. return true;
  919. }
  920. // Get the module context.
  921. $modcontext = context_module::instance($cm->id);
  922. // Get the course module name.
  923. $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
  924. // Get the file location of the delete_instance function for this module.
  925. $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
  926. // Include the file required to call the delete_instance function for this module.
  927. if (file_exists($modlib)) {
  928. require_once($modlib);
  929. } else {
  930. throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
  931. "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
  932. }
  933. $deleteinstancefunction = $modulename . '_delete_instance';
  934. // Ensure the delete_instance function exists for this module.
  935. if (!function_exists($deleteinstancefunction)) {
  936. throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
  937. "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
  938. }
  939. // Allow plugins to use this course module before we completely delete it.
  940. if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
  941. foreach ($pluginsfunction as $plugintype => $plugins) {
  942. foreach ($plugins as $pluginfunction) {
  943. $pluginfunction($cm);
  944. }
  945. }
  946. }
  947. question_delete_activity($cm);
  948. // Call the delete_instance function, if it returns false throw an exception.
  949. if (!$deleteinstancefunction($cm->instance)) {
  950. throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
  951. "Cannot delete the module $modulename (instance).");
  952. }
  953. // Remove all module files in case modules forget to do that.
  954. $fs = get_file_storage();
  955. $fs->delete_area_files($modcontext->id);
  956. // Delete events from calendar.
  957. if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
  958. $coursecontext = context_course::instance($cm->course);
  959. foreach($events as $event) {
  960. $event->context = $coursecontext;
  961. $calendarevent = calendar_event::load($event);
  962. $calendarevent->delete();
  963. }
  964. }
  965. // Delete grade items, outcome items and grades attached to modules.
  966. if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
  967. 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
  968. foreach ($grade_items as $grade_item) {
  969. $grade_item->delete('moddelete');
  970. }
  971. }
  972. // Delete associated blogs and blog tag instances.
  973. blog_remove_associations_for_module($modcontext->id);
  974. // Delete completion and availability data; it is better to do this even if the
  975. // features are not turned on, in case they were turned on previously (these will be
  976. // very quick on an empty table).
  977. $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
  978. $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
  979. 'course' => $cm->course,
  980. 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
  981. // Delete all tag instances associated with the instance of this module.
  982. core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
  983. core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
  984. // Notify the competency subsystem.
  985. \core_competency\api::hook_course_module_deleted($cm);
  986. // Delete the context.
  987. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  988. // Delete the module from the course_modules table.
  989. $DB->delete_records('course_modules', array('id' => $cm->id));
  990. // Delete module from that section.
  991. if (!delete_mod_from_section($cm->id, $cm->section)) {
  992. throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
  993. "Cannot delete the module $modulename (instance) from section.");
  994. }
  995. // Trigger event for course module delete action.
  996. $event = \core\event\course_module_deleted::create(array(
  997. 'courseid' => $cm->course,
  998. 'context' => $modcontext,
  999. 'objectid' => $cm->id,
  1000. 'other' => array(
  1001. 'modulename' => $modulename,
  1002. 'instanceid' => $cm->instance,
  1003. )
  1004. ));
  1005. $event->add_record_snapshot('course_modules', $cm);
  1006. $event->trigger();
  1007. rebuild_course_cache($cm->course, true);
  1008. }
  1009. /**
  1010. * Schedule a course module for deletion in the background using an adhoc task.
  1011. *
  1012. * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
  1013. * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
  1014. *
  1015. * @param int $cmid the course module id.
  1016. * @return bool whether the module was successfully scheduled for deletion.
  1017. * @throws \moodle_exception
  1018. */
  1019. function course_module_flag_for_async_deletion($cmid) {
  1020. global $CFG, $DB, $USER;
  1021. require_once($CFG->libdir.'/gradelib.php');
  1022. require_once($CFG->libdir.'/questionlib.php');
  1023. require_once($CFG->dirroot.'/blog/lib.php');
  1024. require_once($CFG->dirroot.'/calendar/lib.php');
  1025. // Get the course module.
  1026. if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
  1027. return true;
  1028. }
  1029. // We need to be reasonably certain the deletion is going to succeed before we background the process.
  1030. // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
  1031. // Get the course module name.
  1032. $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
  1033. // Get the file location of the delete_instance function for this module.
  1034. $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
  1035. // Include the file required to call the delete_instance function for this module.
  1036. if (file_exists($modlib)) {
  1037. require_once($modlib);
  1038. } else {
  1039. throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
  1040. "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
  1041. }
  1042. $deleteinstancefunction = $modulename . '_delete_instance';
  1043. // Ensure the delete_instance function exists for this module.
  1044. if (!function_exists($deleteinstancefunction)) {
  1045. throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
  1046. "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
  1047. }
  1048. // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
  1049. $cm->deletioninprogress = '1';
  1050. $DB->update_record('course_modules', $cm);
  1051. // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
  1052. $removaltask = new \core_course\task\course_delete_modules();
  1053. $removaltask->set_custom_data(array(
  1054. 'cms' => array($cm),
  1055. 'userid' => $USER->id,
  1056. 'realuserid' => \core\session\manager::get_realuser()->id
  1057. ));
  1058. // Queue the task for the next run.
  1059. \core\task\manager::queue_adhoc_task($removaltask);
  1060. // Reset the course cache to hide the module.
  1061. rebuild_course_cache($cm->course, true);
  1062. }
  1063. /**
  1064. * Checks whether the given course has any course modules scheduled for adhoc deletion.
  1065. *
  1066. * @param int $courseid the id of the course.
  1067. * @param bool $onlygradable whether to check only gradable modules or all modules.
  1068. * @return bool true if the course contains any modules pending deletion, false otherwise.
  1069. */
  1070. function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
  1071. if (empty($courseid)) {
  1072. return false;
  1073. }
  1074. if ($onlygradable) {
  1075. // Fetch modules with grade items.
  1076. if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
  1077. // Return early when there is none.
  1078. return false;
  1079. }
  1080. }
  1081. $modinfo = get_fast_modinfo($courseid);
  1082. foreach ($modinfo->get_cms() as $module) {
  1083. if ($module->deletioninprogress == '1') {
  1084. if ($onlygradable) {
  1085. // Check if the module being deleted is in the list of course modules with grade items.
  1086. foreach ($coursegradeitems as $coursegradeitem) {
  1087. if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
  1088. // The module being deleted is within the gradable modules.
  1089. return true;
  1090. }
  1091. }
  1092. } else {
  1093. return true;
  1094. }
  1095. }
  1096. }
  1097. return false;
  1098. }
  1099. /**
  1100. * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
  1101. *
  1102. * @param int $courseid the course id.
  1103. * @param string $modulename the module name. E.g. 'assign', 'book', etc.
  1104. * @param int $instanceid the module instance id.
  1105. * @return bool true if the course module is pending deletion, false otherwise.
  1106. */
  1107. function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
  1108. if (empty($courseid) || empty($modulename) || empty($instanceid)) {
  1109. return false;
  1110. }
  1111. $modinfo = get_fast_modinfo($courseid);
  1112. $instances = $modinfo->get_instances_of($modulename);
  1113. return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
  1114. }
  1115. function delete_mod_from_section($modid, $sectionid) {
  1116. global $DB;
  1117. if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
  1118. $modarray = explode(",", $section->sequence);
  1119. if ($key = array_keys ($modarray, $modid)) {
  1120. array_splice($modarray, $key[0], 1);
  1121. $newsequence = implode(",", $modarray);
  1122. $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
  1123. rebuild_course_cache($section->course, true);
  1124. return true;
  1125. } else {
  1126. return false;
  1127. }
  1128. }
  1129. return false;
  1130. }
  1131. /**
  1132. * This function updates the calendar events from the information stored in the module table and the course
  1133. * module table.
  1134. *
  1135. * @param string $modulename Module name
  1136. * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
  1137. * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
  1138. * @return bool Returns true if calendar events are updated.
  1139. * @since Moodle 3.3.4
  1140. */
  1141. function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
  1142. global $DB;
  1143. if (isset($instance) || isset($cm)) {
  1144. if (!isset($instance)) {
  1145. $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
  1146. }
  1147. if (!isset($cm)) {
  1148. $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
  1149. }
  1150. if (!empty($cm)) {
  1151. course_module_calendar_event_update_process($instance, $cm);
  1152. }
  1153. return true;
  1154. }
  1155. return false;
  1156. }
  1157. /**
  1158. * Update all instances through out the site or in a course.
  1159. *
  1160. * @param string $modulename Module type to update.
  1161. * @param integer $courseid Course id to update events. 0 for the whole site.
  1162. * @return bool Returns True if the update was successful.
  1163. * @since Moodle 3.3.4
  1164. */
  1165. function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
  1166. global $DB;
  1167. $instances = null;
  1168. if ($courseid) {
  1169. if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
  1170. return false;
  1171. }
  1172. } else {
  1173. if (!$instances = $DB->get_records($modulename)) {
  1174. return false;
  1175. }
  1176. }
  1177. foreach ($instances as $instance) {
  1178. if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
  1179. course_module_calendar_event_update_process($instance, $cm);
  1180. }
  1181. }
  1182. return true;
  1183. }
  1184. /**
  1185. * Calendar events for a module instance are updated.
  1186. *
  1187. * @param stdClass $instance Module instance object.
  1188. * @param stdClass $cm Course Module object.
  1189. * @since Moodle 3.3.4
  1190. */
  1191. function course_module_calendar_event_update_process($instance, $cm) {
  1192. // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
  1193. // will remove the completion events.
  1194. $refresheventsfunction = $cm->modname . '_refresh_events';
  1195. if (function_exists($refresheventsfunction)) {
  1196. call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
  1197. }
  1198. $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
  1199. \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
  1200. }
  1201. /**
  1202. * Moves a section within a course, from a position to another.
  1203. * Be very careful: $section and $destination refer to section number,
  1204. * not id!.
  1205. *
  1206. * @param object $course
  1207. * @param int $section Section number (not id!!!)
  1208. * @param int $destination
  1209. * @param bool $ignorenumsections
  1210. * @return boolean Result
  1211. */
  1212. function move_section_to($course, $section, $destination, $ignorenumsections = false) {
  1213. /// Moves a whole course section up and down within the course
  1214. global $USER, $DB;
  1215. if (!$destination && $destination != 0) {
  1216. return true;
  1217. }
  1218. // compartibility with course formats using field 'numsections'
  1219. $courseformatoptions = course_get_format($course)->get_format_options();
  1220. if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
  1221. ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
  1222. return false;
  1223. }
  1224. // Get all sections for this course and re-order them (2 of them should now share the same section number)
  1225. if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
  1226. 'section ASC, id ASC', 'id, section')) {
  1227. return false;
  1228. }
  1229. $movedsections = reorder_sections($sections, $section, $destination);
  1230. // Update all sections. Do this in 2 steps to avoid breaking database
  1231. // uniqueness constraint
  1232. $transaction = $DB->start_delegated_transaction();
  1233. foreach ($movedsections as $id => $position) {
  1234. if ($sections[$id] !== $position) {
  1235. $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
  1236. }
  1237. }
  1238. foreach ($movedsections as $id => $position) {
  1239. if ($sections[$id] !== $position) {
  1240. $DB->set_field('course_sections', 'section', $position, array('id' => $id));
  1241. }
  1242. }
  1243. // If we move the highlighted section itself, then just highlight the destination.
  1244. // Adjust the higlighted section location if we move something over it either direction.
  1245. if ($section == $course->marker) {
  1246. course_set_marker($course->id, $destination);
  1247. } elseif ($section > $course->marker && $course->marker >= $destination) {
  1248. course_set_marker($course->id, $course->marker+1);
  1249. } elseif ($section < $course->marker && $course->marker <= $destination) {
  1250. course_set_marker($course->id, $course->marker-1);
  1251. }
  1252. $transaction->allow_commit();
  1253. rebuild_course_cache($course->id, true);
  1254. return true;
  1255. }
  1256. /**
  1257. * This method will delete a course section and may delete all modules inside it.
  1258. *
  1259. * No permissions are checked here, use {@link course_can_delete_section()} to
  1260. * check if section can actually be deleted.
  1261. *
  1262. * @param int|stdClass $course
  1263. * @param int|stdClass|section_info $section
  1264. * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
  1265. * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
  1266. * @return bool whether section was deleted
  1267. */
  1268. function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
  1269. global $DB;
  1270. // Prepare variables.
  1271. $courseid = (is_object($course)) ? $course->id : (int)$course;
  1272. $sectionnum = (is_object($section)) ? $section->section : (int)$section;
  1273. $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
  1274. if (!$section) {
  1275. // No section exists, can't proceed.
  1276. return false;
  1277. }
  1278. // Check the 'course_module_background_deletion_recommended' hook first.
  1279. // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
  1280. // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
  1281. // It's up to plugins to handle things like whether or not they are enabled.
  1282. if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
  1283. foreach ($pluginsfunction as $plugintype => $plugins) {
  1284. foreach ($plugins as $pluginfunction) {
  1285. if ($pluginfunction()) {
  1286. return course_delete_section_async($section, $forcedeleteifnotempty);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. $format = course_get_format($course);
  1292. $sectionname = $format->get_section_name($section);
  1293. // Delete section.
  1294. $result = $format->delete_section($section, $forcedeleteifnotempty);
  1295. // Trigger an event for course section deletion.
  1296. if ($result) {
  1297. $context = context_course::instance($courseid);
  1298. $event = \core\event\course_section_deleted::create(
  1299. array(
  1300. 'objectid' => $section->id,
  1301. 'courseid' => $courseid,
  1302. 'context' => $context,
  1303. 'other' => array(
  1304. 'sectionnum' => $section->section,
  1305. 'sectionname' => $sectionname,
  1306. )
  1307. )
  1308. );
  1309. $event->add_record_snapshot('course_sections', $section);
  1310. $event->trigger();
  1311. }
  1312. return $result;
  1313. }
  1314. /**
  1315. * Course section deletion, using an adhoc task for deletion of the modules it contains.
  1316. * 1. Schedule all modules within the section for adhoc removal.
  1317. * 2. Move all modules to course section 0.
  1318. * 3. Delete the resulting empty section.
  1319. *
  1320. * @param \stdClass $section the section to schedule for deletion.
  1321. * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
  1322. * @return bool true if the section was scheduled for deletion, false otherwise.
  1323. */
  1324. function course_delete_section_async($section, $forcedeleteifnotempty = true) {
  1325. global $DB, $USER;
  1326. // Objects only, and only valid ones.
  1327. if (!is_object($section) || empty($section->id)) {
  1328. return false;
  1329. }
  1330. // Does the object currently exist in the DB for removal (check for stale objects).
  1331. $section = $DB->get_record('course_sections', array('id' => $section->id));
  1332. if (!$section || !$section->section) {
  1333. // No section exists, or the section is 0. Can't proceed.
  1334. return false;
  1335. }
  1336. // Check whether the section can be removed.
  1337. if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
  1338. return false;
  1339. }
  1340. $format = course_get_format($section->course);
  1341. $sectionname = $format->get_section_name($section);
  1342. // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
  1343. // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
  1344. $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
  1345. [$section->course, $section->id, 1], '', 'id');
  1346. $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
  1347. // Move all modules to section 0.
  1348. $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
  1349. $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
  1350. foreach ($modules as $mod) {
  1351. moveto_module($mod, $sectionzero);
  1352. }
  1353. // Create and queue an adhoc task for the deletion of the modules.
  1354. $removaltask = new \core_course\task\course_delete_modules();
  1355. $data = array(
  1356. 'cms' => $affectedmods,
  1357. 'userid' => $USER->id,
  1358. 'realuserid' => \core\session\manager::get_realuser()->id
  1359. );
  1360. $removaltask->set_custom_data($data);
  1361. \core\task\manager::queue_adhoc_task($removaltask);
  1362. // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
  1363. // The refresh is needed because the section->sequence is now stale.
  1364. $result = $format->delete_section($section->section, $forcedeleteifnotempty);
  1365. // Trigger an event for course section deletion.
  1366. if ($result) {
  1367. $context = \context_course::instance($section->course);
  1368. $event = \core\event\course_section_deleted::create(
  1369. array(
  1370. 'objectid' => $section->id,
  1371. 'courseid' => $section->course,
  1372. 'context' => $context,
  1373. 'other' => array(
  1374. 'sectionnum' => $section->section,
  1375. 'sectionname' => $sectionname,
  1376. )
  1377. )
  1378. );
  1379. $event->add_record_snapshot('course_sections', $section);
  1380. $event->trigger();
  1381. }
  1382. rebuild_course_cache($section->course, true);
  1383. return $result;
  1384. }
  1385. /**
  1386. * Updates the course section
  1387. *
  1388. * This function does not check permissions or clean values - this has to be done prior to calling it.
  1389. *
  1390. * @param int|stdClass $course
  1391. * @param stdClass $section record from course_sections table - it will be updated with the new values
  1392. * @param array|stdClass $data
  1393. */
  1394. function course_update_section($course, $section, $data) {
  1395. global $DB;
  1396. $courseid = (is_object($course)) ? $course->id : (int)$course;
  1397. // Some fields can not be updated using this method.
  1398. $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
  1399. $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
  1400. if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
  1401. throw new moodle_exception('maximumchars', 'moodle', '', 255);
  1402. }
  1403. // Update record in the DB and course format options.
  1404. $data['id'] = $section->id;
  1405. $data['timemodified'] = time();
  1406. $DB->update_record('course_sections', $data);
  1407. rebuild_course_cache($courseid, true);
  1408. course_get_format($courseid)->update_section_format_options($data);
  1409. // Update fields of the $section object.
  1410. foreach ($data as $key => $value) {
  1411. if (property_exists($section, $key)) {
  1412. $section->$key = $value;
  1413. }
  1414. }
  1415. // Trigger an event for course section update.
  1416. $event = \core\event\course_section_updated::create(
  1417. array(
  1418. 'objectid' => $section->id,
  1419. 'courseid' => $courseid,
  1420. 'context' => context_course::instance($courseid),
  1421. 'other' => array('sectionnum' => $section->section)
  1422. )
  1423. );
  1424. $event->trigger();
  1425. // If section visibility was changed, hide the modules in this section too.
  1426. if ($changevisibility && !empty($section->sequence)) {
  1427. $modules = explode(',', $section->sequence);
  1428. foreach ($modules as $moduleid) {
  1429. if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
  1430. if ($data['visible']) {
  1431. // As we unhide the section, we use the previously saved visibility stored in visibleold.
  1432. set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
  1433. } else {
  1434. // We hide the section, so we hide the module but we store the original state in visibleold.
  1435. set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
  1436. $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
  1437. }
  1438. \core\event\course_module_updated::create_from_cm($cm)->trigger();
  1439. }
  1440. }
  1441. }
  1442. }
  1443. /**
  1444. * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
  1445. *
  1446. * @param int|stdClass $course
  1447. * @param int|stdClass|section_info $section
  1448. * @return bool
  1449. */
  1450. function course_can_delete_section($course, $section) {
  1451. if (is_object($section)) {
  1452. $section = $section->section;
  1453. }
  1454. if (!$section) {
  1455. // Not possible to delete 0-section.
  1456. return false;
  1457. }
  1458. // Course format should allow to delete sections.
  1459. if (!course_get_format($course)->can_delete_section($section)) {
  1460. return false;
  1461. }
  1462. // Make sure user has capability to update course and move sections.
  1463. $context = context_course::instance(is_object($course) ? $course->id : $course);
  1464. if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
  1465. return false;
  1466. }
  1467. // Make sure user has capability to delete each activity in this section.
  1468. $modinfo = get_fast_modinfo($course);
  1469. if (!empty($modinfo->sections[$section])) {
  1470. foreach ($modinfo->sections[$section] as $cmid) {
  1471. if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
  1472. return false;
  1473. }
  1474. }
  1475. }
  1476. return true;
  1477. }
  1478. /**
  1479. * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
  1480. * an original position number and a target position number, rebuilds the array so that the
  1481. * move is made without any duplication of section positions.
  1482. * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
  1483. * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
  1484. *
  1485. * @param array $sections
  1486. * @param int $origin_position
  1487. * @param int $target_position
  1488. * @return array
  1489. */
  1490. function reorder_sections($sections, $origin_position, $target_position) {
  1491. if (!is_array($sections)) {
  1492. return false;
  1493. }
  1494. // We can't move section position 0
  1495. if ($origin_position < 1) {
  1496. echo "We can't move section position 0";
  1497. return false;
  1498. }
  1499. // Locate origin section in sections array
  1500. if (!$origin_key = array_search($origin_position, $sections)) {
  1501. echo "searched position not in sections array";
  1502. return false; // searched position not in sections array
  1503. }
  1504. // Extract origin section
  1505. $origin_section = $sections[$origin_key];
  1506. unset($sections[$origin_key]);
  1507. // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
  1508. $found = false;
  1509. $append_array = array();
  1510. foreach ($sections as $id => $position) {
  1511. if ($found) {
  1512. $append_array[$id] = $position;
  1513. unset($sections[$id]);
  1514. }
  1515. if ($position == $target_position) {
  1516. if ($target_position < $origin_position) {
  1517. $append_array[$id] = $position;
  1518. unset($sections[$id]);
  1519. }
  1520. $found = true;
  1521. }
  1522. }
  1523. // Append moved section
  1524. $sections[$origin_key] = $origin_section;
  1525. // Append rest of array (if applicable)
  1526. if (!empty($append_array)) {
  1527. foreach ($append_array as $id => $position) {
  1528. $sections[$id] = $position;
  1529. }
  1530. }
  1531. // Renumber positions
  1532. $position = 0;
  1533. foreach ($sections as $id => $p) {
  1534. $sections[$id] = $position;
  1535. $position++;
  1536. }
  1537. return $sections;
  1538. }
  1539. /**
  1540. * Move the module object $mod to the specified $section
  1541. * If $beforemod exists then that is the module
  1542. * before which $modid should be inserted
  1543. *
  1544. * @param stdClass|cm_info $mod
  1545. * @param stdClass|section_info $section
  1546. * @param int|stdClass $beforemod id or object with field id corresponding to the module
  1547. * before which the module needs to be included. Null for inserting in the
  1548. * end of the section
  1549. * @return int new value for module visibility (0 or 1)
  1550. */
  1551. function moveto_module($mod, $section, $beforemod=NULL) {
  1552. global $OUTPUT, $DB;
  1553. // Current module visibility state - return value of this function.
  1554. $modvisible = $mod->visible;
  1555. // Remove original module from original section.
  1556. if (! delete_mod_from_section($mod->id, $mod->section)) {
  1557. echo $OUTPUT->notification("Could not delete module from existing section");
  1558. }
  1559. // If moving to a hidden section then hide module.
  1560. if ($mod->section != $section->id) {
  1561. if (!$section->visible && $mod->visible) {
  1562. // Module was visible but must become hidden after moving to hidden section.
  1563. $modvisible = 0;
  1564. set_coursemodule_visible($mod->id, 0);
  1565. // Set visibleold to 1 so module will be visible when section is made visible.
  1566. $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
  1567. }
  1568. if ($section->visible && !$mod->visible) {
  1569. // Hidden module was moved to the visible section, restore the module visibility from visibleold.
  1570. set_coursemodule_visible($mod->id, $mod->visibleold);
  1571. $modvisible = $mod->visibleold;
  1572. }
  1573. }
  1574. // Add the module into the new section.
  1575. course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
  1576. return $modvisible;
  1577. }
  1578. /**
  1579. * Returns the list of all editing actions that current user can perform on the module
  1580. *
  1581. * @param cm_info $mod The module to produce editing buttons for
  1582. * @param int $indent The current indenting (default -1 means no move left-right actions)
  1583. * @param int $sr The section to link back to (used for creating the links)
  1584. * @return array array of action_link or pix_icon objects
  1585. */
  1586. function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
  1587. global $COURSE, $SITE, $CFG;
  1588. static $str;
  1589. $coursecontext = context_course::instance($mod->course);
  1590. $modcontext = context_module::instance($mod->id);
  1591. $courseformat = course_get_format($mod->get_course());
  1592. $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
  1593. $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
  1594. // No permission to edit anything.
  1595. if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
  1596. return array();
  1597. }
  1598. $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
  1599. if (!isset($str)) {
  1600. $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
  1601. 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
  1602. $str->assign = get_string('assignroles', 'role');
  1603. $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
  1604. $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
  1605. $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
  1606. }
  1607. $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
  1608. if ($sr !== null) {
  1609. $baseurl->param('sr', $sr);
  1610. }
  1611. $actions = array();
  1612. // Update.
  1613. if ($hasmanageactivities) {
  1614. $actions['update'] = new action_menu_link_secondary(
  1615. new moodle_url($baseurl, array('update' => $mod->id)),
  1616. new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
  1617. $str->editsettings,
  1618. array('class' => 'editing_update', 'data-action' => 'update')
  1619. );
  1620. }
  1621. // Move (only for component compatible formats).
  1622. if ($courseformat->supports_components()) {
  1623. $actions['move'] = new action_menu_link_secondary(
  1624. new moodle_url($baseurl, [
  1625. 'sesskey' => sesskey(),
  1626. 'copy' => $mod->id,
  1627. ]),
  1628. new pix_icon('i/dragdrop', '', 'moodle', ['class' => 'iconsmall']),
  1629. $str->move,
  1630. [
  1631. 'class' => 'editing_movecm',
  1632. 'data-action' => 'moveCm',
  1633. 'data-id' => $mod->id,
  1634. ]
  1635. );
  1636. }
  1637. // Indent.
  1638. if ($hasmanageactivities && $indent >= 0) {
  1639. $indentlimits = new stdClass();
  1640. $indentlimits->min = 0;
  1641. $indentlimits->max = 16;
  1642. if (right_to_left()) { // Exchange arrows on RTL
  1643. $rightarrow = 't/left';
  1644. $leftarrow = 't/right';
  1645. } else {
  1646. $rightarrow = 't/right';
  1647. $leftarrow = 't/left';
  1648. }
  1649. if ($indent >= $indentlimits->max) {
  1650. $enabledclass = 'hidden';
  1651. } else {
  1652. $enabledclass = '';
  1653. }
  1654. $actions['moveright'] = new action_menu_link_secondary(
  1655. new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
  1656. new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
  1657. $str->moveright,
  1658. array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
  1659. 'data-keepopen' => true, 'data-sectionreturn' => $sr)
  1660. );
  1661. if ($indent <= $indentlimits->min) {
  1662. $enabledclass = 'hidden';
  1663. } else {
  1664. $enabledclass = '';
  1665. }
  1666. $actions['moveleft'] = new action_menu_link_secondary(
  1667. new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
  1668. new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
  1669. $str->moveleft,
  1670. array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
  1671. 'data-keepopen' => true, 'data-sectionreturn' => $sr)
  1672. );
  1673. }
  1674. // Hide/Show/Available/Unavailable.
  1675. if (has_capability('moodle/course:activityvisibility', $modcontext)) {
  1676. $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
  1677. $sectionvisible = $mod->get_section_info()->visible;
  1678. // The module on the course page may be in one of the following states:
  1679. // - Available and displayed on the course page ($displayedoncoursepage);
  1680. // - Not available and not displayed on the course page ($unavailable);
  1681. // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
  1682. $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
  1683. $unavailable = !$mod->visible;
  1684. $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
  1685. if ($displayedoncoursepage) {
  1686. $actions['hide'] = new action_menu_link_secondary(
  1687. new moodle_url($baseurl, array('hide' => $mod->id)),
  1688. new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
  1689. $str->modhide,
  1690. array('class' => 'editing_hide', 'data-action' => 'hide')
  1691. );
  1692. } else if (!$displayedoncoursepage && $sectionvisible) {
  1693. // Offer to "show" only if the section is visible.
  1694. $actions['show'] = new action_menu_link_secondary(
  1695. new moodle_url($baseurl, array('show' => $mod->id)),
  1696. new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
  1697. $str->modshow,
  1698. array('class' => 'editing_show', 'data-action' => 'show')
  1699. );
  1700. }
  1701. if ($stealth) {
  1702. // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
  1703. $actions['hide'] = new action_menu_link_secondary(
  1704. new moodle_url($baseurl, array('hide' => $mod->id)),
  1705. new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
  1706. $str->makeunavailable,
  1707. array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
  1708. );
  1709. } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
  1710. // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
  1711. // When the section is hidden it is an equivalent of "showing" the module.
  1712. // Activities without the link (i.e. labels) can not be made available but hidden on course page.
  1713. $action = $sectionvisible ? 'stealth' : 'show';
  1714. $actions[$action] = new action_menu_link_secondary(
  1715. new moodle_url($baseurl, array($action => $mod->id)),
  1716. new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
  1717. $str->makeavailable,
  1718. array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
  1719. );
  1720. }
  1721. }
  1722. // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
  1723. if (has_all_capabilities($dupecaps, $coursecontext) &&
  1724. plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
  1725. course_allowed_module($mod->get_course(), $mod->modname)) {
  1726. $actions['duplicate'] = new action_menu_link_secondary(
  1727. new moodle_url($baseurl, array('duplicate' => $mod->id)),
  1728. new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
  1729. $str->duplicate,
  1730. array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
  1731. );
  1732. }
  1733. // Groupmode.
  1734. if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
  1735. if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
  1736. if ($mod->effectivegroupmode == SEPARATEGROUPS) {
  1737. $nextgroupmode = VISIBLEGROUPS;
  1738. $grouptitle = $str->groupsseparate;
  1739. $actionname = 'groupsseparate';
  1740. $nextactionname = 'groupsvisible';
  1741. $groupimage = 'i/groups';
  1742. } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
  1743. $nextgroupmode = NOGROUPS;
  1744. $grouptitle = $str->groupsvisible;
  1745. $actionname = 'groupsvisible';
  1746. $nextactionname = 'groupsnone';
  1747. $groupimage = 'i/groupv';
  1748. } else {
  1749. $nextgroupmode = SEPARATEGROUPS;
  1750. $grouptitle = $str->groupsnone;
  1751. $actionname = 'groupsnone';
  1752. $nextactionname = 'groupsseparate';
  1753. $groupimage = 'i/groupn';
  1754. }
  1755. $actions[$actionname] = new action_menu_link_primary(
  1756. new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
  1757. new pix_icon($groupimage, '', 'moodle', array('class' => 'iconsmall')),
  1758. $grouptitle,
  1759. array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
  1760. 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
  1761. );
  1762. } else {
  1763. $actions['nogroupsupport'] = new action_menu_filler();
  1764. }
  1765. }
  1766. // Assign.
  1767. if (has_capability('moodle/role:assign', $modcontext)){
  1768. $actions['assign'] = new action_menu_link_secondary(
  1769. new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
  1770. new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
  1771. $str->assign,
  1772. array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
  1773. );
  1774. }
  1775. // Delete.
  1776. if ($hasmanageactivities) {
  1777. $actions['delete'] = new action_menu_link_secondary(
  1778. new moodle_url($baseurl, array('delete' => $mod->id)),
  1779. new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
  1780. $str->delete,
  1781. array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
  1782. );
  1783. }
  1784. return $actions;
  1785. }
  1786. /**
  1787. * Returns the move action.
  1788. *
  1789. * @param cm_info $mod The module to produce a move button for
  1790. * @param int $sr The section to link back to (used for creating the links)
  1791. * @return The markup for the move action, or an empty string if not available.
  1792. */
  1793. function course_get_cm_move(cm_info $mod, $sr = null) {
  1794. global $OUTPUT;
  1795. static $str;
  1796. static $baseurl;
  1797. $modcontext = context_module::instance($mod->id);
  1798. $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
  1799. if (!isset($str)) {
  1800. $str = get_strings(array('move'));
  1801. }
  1802. if (!isset($baseurl)) {
  1803. $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
  1804. if ($sr !== null) {
  1805. $baseurl->param('sr', $sr);
  1806. }
  1807. }
  1808. if ($hasmanageactivities) {
  1809. $pixicon = 'i/dragdrop';
  1810. if (!course_ajax_enabled($mod->get_course())) {
  1811. // Override for course frontpage until we get drag/drop working there.
  1812. $pixicon = 't/move';
  1813. }
  1814. $attributes = [
  1815. 'class' => 'editing_move',
  1816. 'data-action' => 'move',
  1817. 'data-sectionreturn' => $sr,
  1818. 'title' => $str->move,
  1819. 'aria-label' => $str->move,
  1820. ];
  1821. return html_writer::link(
  1822. new moodle_url($baseurl, ['copy' => $mod->id]),
  1823. $OUTPUT->pix_icon($pixicon, '', 'moodle', ['class' => 'iconsmall']),
  1824. $attributes
  1825. );
  1826. }
  1827. return '';
  1828. }
  1829. /**
  1830. * given a course object with shortname & fullname, this function will
  1831. * truncate the the number of chars allowed and add ... if it was too long
  1832. */
  1833. function course_format_name ($course,$max=100) {
  1834. $context = context_course::instance($course->id);
  1835. $shortname = format_string($course->shortname, true, array('context' => $context));
  1836. $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
  1837. $str = $shortname.': '. $fullname;
  1838. if (core_text::strlen($str) <= $max) {
  1839. return $str;
  1840. }
  1841. else {
  1842. return core_text::substr($str,0,$max-3).'...';
  1843. }
  1844. }
  1845. /**
  1846. * Is the user allowed to add this type of module to this course?
  1847. * @param object $course the course settings. Only $course->id is used.
  1848. * @param string $modname the module name. E.g. 'forum' or 'quiz'.
  1849. * @param \stdClass $user the user to check, defaults to the global user if not provided.
  1850. * @return bool whether the current user is allowed to add this type of module to this course.
  1851. */
  1852. function course_allowed_module($course, $modname, \stdClass $user = null) {
  1853. global $USER;
  1854. $user = $user ?? $USER;
  1855. if (is_numeric($modname)) {
  1856. throw new coding_exception('Function course_allowed_module no longer
  1857. supports numeric module ids. Please update your code to pass the module name.');
  1858. }
  1859. $capability = 'mod/' . $modname . ':addinstance';
  1860. if (!get_capability_info($capability)) {
  1861. // Debug warning that the capability does not exist, but no more than once per page.
  1862. static $warned = array();
  1863. $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
  1864. if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
  1865. debugging('The module ' . $modname . ' does not define the standard capability ' .
  1866. $capability , DEBUG_DEVELOPER);
  1867. $warned[$modname] = 1;
  1868. }
  1869. // If the capability does not exist, the module can always be added.
  1870. return true;
  1871. }
  1872. $coursecontext = context_course::instance($course->id);
  1873. return has_capability($capability, $coursecontext, $user);
  1874. }
  1875. /**
  1876. * Efficiently moves many courses around while maintaining
  1877. * sortorder in order.
  1878. *
  1879. * @param array $courseids is an array of course ids
  1880. * @param int $categoryid
  1881. * @return bool success
  1882. */
  1883. function move_courses($courseids, $categoryid) {
  1884. global $DB;
  1885. if (empty($courseids)) {
  1886. // Nothing to do.
  1887. return false;
  1888. }
  1889. if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
  1890. return false;
  1891. }
  1892. $courseids = array_reverse($courseids);
  1893. $newparent = context_coursecat::instance($category->id);
  1894. $i = 1;
  1895. list($where, $params) = $DB->get_in_or_equal($courseids);
  1896. $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
  1897. foreach ($dbcourses as $dbcourse) {
  1898. $course = new stdClass();
  1899. $course->id = $dbcourse->id;
  1900. $course->timemodified = time();
  1901. $course->category = $category->id;
  1902. $course->sortorder = $category->sortorder + get_max_courses_in_category() - $i++;
  1903. if ($category->visible == 0) {
  1904. // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
  1905. // to previous state if somebody unhides the category.
  1906. $course->visible = 0;
  1907. }
  1908. $DB->update_record('course', $course);
  1909. // Update context, so it can be passed to event.
  1910. $context = context_course::instance($course->id);
  1911. $context->update_moved($newparent);
  1912. // Trigger a course updated event.
  1913. $event = \core\event\course_updated::create(array(
  1914. 'objectid' => $course->id,
  1915. 'context' => context_course::instance($course->id),
  1916. 'other' => array('shortname' => $dbcourse->shortname,
  1917. 'fullname' => $dbcourse->fullname,
  1918. 'updatedfields' => array('category' => $category->id))
  1919. ));
  1920. $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
  1921. $event->trigger();
  1922. }
  1923. fix_course_sortorder();
  1924. cache_helper::purge_by_event('changesincourse');
  1925. return true;
  1926. }
  1927. /**
  1928. * Returns the display name of the given section that the course prefers
  1929. *
  1930. * Implementation of this function is provided by course format
  1931. * @see core_courseformat\base::get_section_name()
  1932. *
  1933. * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
  1934. * @param int|stdClass $section Section object from database or just field course_sections.section
  1935. * @return string Display name that the course format prefers, e.g. "Week 2"
  1936. */
  1937. function get_section_name($courseorid, $section) {
  1938. return course_get_format($courseorid)->get_section_name($section);
  1939. }
  1940. /**
  1941. * Tells if current course format uses sections
  1942. *
  1943. * @param string $format Course format ID e.g. 'weeks' $course->format
  1944. * @return bool
  1945. */
  1946. function course_format_uses_sections($format) {
  1947. $course = new stdClass();
  1948. $course->format = $format;
  1949. return course_get_format($course)->uses_sections();
  1950. }
  1951. /**
  1952. * Returns the information about the ajax support in the given source format
  1953. *
  1954. * The returned object's property (boolean)capable indicates that
  1955. * the course format supports Moodle course ajax features.
  1956. *
  1957. * @param string $format
  1958. * @return stdClass
  1959. */
  1960. function course_format_ajax_support($format) {
  1961. $course = new stdClass();
  1962. $course->format = $format;
  1963. return course_get_format($course)->supports_ajax();
  1964. }
  1965. /**
  1966. * Can the current user delete this course?
  1967. * Course creators have exception,
  1968. * 1 day after the creation they can sill delete the course.
  1969. * @param int $courseid
  1970. * @return boolean
  1971. */
  1972. function can_delete_course($courseid) {
  1973. global $USER;
  1974. $context = context_course::instance($courseid);
  1975. if (has_capability('moodle/course:delete', $context)) {
  1976. return true;
  1977. }
  1978. // hack: now try to find out if creator created this course recently (1 day)
  1979. if (!has_capability('moodle/course:create', $context)) {
  1980. return false;
  1981. }
  1982. $since = time() - 60*60*24;
  1983. $course = get_course($courseid);
  1984. if ($course->timecreated < $since) {
  1985. return false; // Return if the course was not created in last 24 hours.
  1986. }
  1987. $logmanger = get_log_manager();
  1988. $readers = $logmanger->get_readers('\core\log\sql_reader');
  1989. $reader = reset($readers);
  1990. if (empty($reader)) {
  1991. return false; // No log reader found.
  1992. }
  1993. // A proper reader.
  1994. $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
  1995. $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
  1996. return (bool)$reader->get_events_select_count($select, $params);
  1997. }
  1998. /**
  1999. * Save the Your name for 'Some role' strings.
  2000. *
  2001. * @param integer $courseid the id of this course.
  2002. * @param array $data the data that came from the course settings form.
  2003. */
  2004. function save_local_role_names($courseid, $data) {
  2005. global $DB;
  2006. $context = context_course::instance($courseid);
  2007. foreach ($data as $fieldname => $value) {
  2008. if (strpos($fieldname, 'role_') !== 0) {
  2009. continue;
  2010. }
  2011. list($ignored, $roleid) = explode('_', $fieldname);
  2012. // make up our mind whether we want to delete, update or insert
  2013. if (!$value) {
  2014. $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
  2015. } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
  2016. $rolename->name = $value;
  2017. $DB->update_record('role_names', $rolename);
  2018. } else {
  2019. $rolename = new stdClass;
  2020. $rolename->contextid = $context->id;
  2021. $rolename->roleid = $roleid;
  2022. $rolename->name = $value;
  2023. $DB->insert_record('role_names', $rolename);
  2024. }
  2025. // This will ensure the course contacts cache is purged..
  2026. core_course_category::role_assignment_changed($roleid, $context);
  2027. }
  2028. }
  2029. /**
  2030. * Returns options to use in course overviewfiles filemanager
  2031. *
  2032. * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
  2033. * may be empty if course does not exist yet (course create form)
  2034. * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
  2035. * or null if overviewfiles are disabled
  2036. */
  2037. function course_overviewfiles_options($course) {
  2038. global $CFG;
  2039. if (empty($CFG->courseoverviewfileslimit)) {
  2040. return null;
  2041. }
  2042. // Create accepted file types based on config value, falling back to default all.
  2043. $acceptedtypes = (new \core_form\filetypes_util)->normalize_file_types($CFG->courseoverviewfilesext);
  2044. if (in_array('*', $acceptedtypes) || empty($acceptedtypes)) {
  2045. $acceptedtypes = '*';
  2046. }
  2047. $options = array(
  2048. 'maxfiles' => $CFG->courseoverviewfileslimit,
  2049. 'maxbytes' => $CFG->maxbytes,
  2050. 'subdirs' => 0,
  2051. 'accepted_types' => $acceptedtypes
  2052. );
  2053. if (!empty($course->id)) {
  2054. $options['context'] = context_course::instance($course->id);
  2055. } else if (is_int($course) && $course > 0) {
  2056. $options['context'] = context_course::instance($course);
  2057. }
  2058. return $options;
  2059. }
  2060. /**
  2061. * Create a course and either return a $course object
  2062. *
  2063. * Please note this functions does not verify any access control,
  2064. * the calling code is responsible for all validation (usually it is the form definition).
  2065. *
  2066. * @param array $editoroptions course description editor options
  2067. * @param object $data - all the data needed for an entry in the 'course' table
  2068. * @return object new course instance
  2069. */
  2070. function create_course($data, $editoroptions = NULL) {
  2071. global $DB, $CFG;
  2072. //check the categoryid - must be given for all new courses
  2073. $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
  2074. // Check if the shortname already exists.
  2075. if (!empty($data->shortname)) {
  2076. if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
  2077. throw new moodle_exception('shortnametaken', '', '', $data->shortname);
  2078. }
  2079. }
  2080. // Check if the idnumber already exists.
  2081. if (!empty($data->idnumber)) {
  2082. if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
  2083. throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
  2084. }
  2085. }
  2086. if (empty($CFG->enablecourserelativedates)) {
  2087. // Make sure we're not setting the relative dates mode when the setting is disabled.
  2088. unset($data->relativedatesmode);
  2089. }
  2090. if ($errorcode = course_validate_dates((array)$data)) {
  2091. throw new moodle_exception($errorcode);
  2092. }
  2093. // Check if timecreated is given.
  2094. $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
  2095. $data->timemodified = $data->timecreated;
  2096. // place at beginning of any category
  2097. $data->sortorder = 0;
  2098. if ($editoroptions) {
  2099. // summary text is updated later, we need context to store the files first
  2100. $data->summary = '';
  2101. $data->summary_format = FORMAT_HTML;
  2102. }
  2103. // Get default completion settings as a fallback in case the enablecompletion field is not set.
  2104. $courseconfig = get_config('moodlecourse');
  2105. $defaultcompletion = !empty($CFG->enablecompletion) ? $courseconfig->enablecompletion : COMPLETION_DISABLED;
  2106. $enablecompletion = $data->enablecompletion ?? $defaultcompletion;
  2107. // Unset showcompletionconditions when completion tracking is not enabled for the course.
  2108. if ($enablecompletion == COMPLETION_DISABLED) {
  2109. unset($data->showcompletionconditions);
  2110. } else if (!isset($data->showcompletionconditions)) {
  2111. // Show completion conditions should have a default value when completion is enabled. Set it to the site defaults.
  2112. // This scenario can happen when a course is created through data generators or through a web service.
  2113. $data->showcompletionconditions = $courseconfig->showcompletionconditions;
  2114. }
  2115. if (!isset($data->visible)) {
  2116. // data not from form, add missing visibility info
  2117. $data->visible = $category->visible;
  2118. }
  2119. $data->visibleold = $data->visible;
  2120. $newcourseid = $DB->insert_record('course', $data);
  2121. $context = context_course::instance($newcourseid, MUST_EXIST);
  2122. if ($editoroptions) {
  2123. // Save the files used in the summary editor and store
  2124. $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
  2125. $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
  2126. $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
  2127. }
  2128. if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
  2129. // Save the course overviewfiles
  2130. $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
  2131. }
  2132. // update course format options
  2133. course_get_format($newcourseid)->update_course_format_options($data);
  2134. $course = course_get_format($newcourseid)->get_course();
  2135. fix_course_sortorder();
  2136. // purge appropriate caches in case fix_course_sortorder() did not change anything
  2137. cache_helper::purge_by_event('changesincourse');
  2138. // Trigger a course created event.
  2139. $event = \core\event\course_created::create(array(
  2140. 'objectid' => $course->id,
  2141. 'context' => context_course::instance($course->id),
  2142. 'other' => array('shortname' => $course->shortname,
  2143. 'fullname' => $course->fullname)
  2144. ));
  2145. $event->trigger();
  2146. // Setup the blocks
  2147. blocks_add_default_course_blocks($course);
  2148. // Create default section and initial sections if specified (unless they've already been created earlier).
  2149. // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
  2150. $numsections = isset($data->numsections) ? $data->numsections : 0;
  2151. $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
  2152. $newsections = array_diff(range(0, $numsections), $existingsections);
  2153. foreach ($newsections as $sectionnum) {
  2154. course_create_section($newcourseid, $sectionnum, true);
  2155. }
  2156. // Save any custom role names.
  2157. save_local_role_names($course->id, (array)$data);
  2158. // set up enrolments
  2159. enrol_course_updated(true, $course, $data);
  2160. // Update course tags.
  2161. if (isset($data->tags)) {
  2162. core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
  2163. }
  2164. // Save custom fields if there are any of them in the form.
  2165. $handler = core_course\customfield\course_handler::create();
  2166. // Make sure to set the handler's parent context first.
  2167. $coursecatcontext = context_coursecat::instance($category->id);
  2168. $handler->set_parent_context($coursecatcontext);
  2169. // Save the custom field data.
  2170. $data->id = $course->id;
  2171. $handler->instance_form_save($data, true);
  2172. return $course;
  2173. }
  2174. /**
  2175. * Update a course.
  2176. *
  2177. * Please note this functions does not verify any access control,
  2178. * the calling code is responsible for all validation (usually it is the form definition).
  2179. *
  2180. * @param object $data - all the data needed for an entry in the 'course' table
  2181. * @param array $editoroptions course description editor options
  2182. * @return void
  2183. */
  2184. function update_course($data, $editoroptions = NULL) {
  2185. global $DB, $CFG;
  2186. // Prevent changes on front page course.
  2187. if ($data->id == SITEID) {
  2188. throw new moodle_exception('invalidcourse', 'error');
  2189. }
  2190. $oldcourse = course_get_format($data->id)->get_course();
  2191. $context = context_course::instance($oldcourse->id);
  2192. // Make sure we're not changing whatever the course's relativedatesmode setting is.
  2193. unset($data->relativedatesmode);
  2194. // Capture the updated fields for the log data.
  2195. $updatedfields = [];
  2196. foreach (get_object_vars($oldcourse) as $field => $value) {
  2197. if ($field == 'summary_editor') {
  2198. if (($data->$field)['text'] !== $value['text']) {
  2199. // The summary might be very long, we don't wan't to fill up the log record with the full text.
  2200. $updatedfields[$field] = '(updated)';
  2201. }
  2202. } else if ($field == 'tags' && isset($data->tags)) {
  2203. // Tags might not have the same array keys, just check the values.
  2204. if (array_values($data->$field) !== array_values($value)) {
  2205. $updatedfields[$field] = $data->$field;
  2206. }
  2207. } else {
  2208. if (isset($data->$field) && $data->$field != $value) {
  2209. $updatedfields[$field] = $data->$field;
  2210. }
  2211. }
  2212. }
  2213. $data->timemodified = time();
  2214. if ($editoroptions) {
  2215. $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
  2216. }
  2217. if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
  2218. $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
  2219. }
  2220. // Check we don't have a duplicate shortname.
  2221. if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
  2222. if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
  2223. throw new moodle_exception('shortnametaken', '', '', $data->shortname);
  2224. }
  2225. }
  2226. // Check we don't have a duplicate idnumber.
  2227. if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
  2228. if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
  2229. throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
  2230. }
  2231. }
  2232. if ($errorcode = course_validate_dates((array)$data)) {
  2233. throw new moodle_exception($errorcode);
  2234. }
  2235. if (!isset($data->category) or empty($data->category)) {
  2236. // prevent nulls and 0 in category field
  2237. unset($data->category);
  2238. }
  2239. $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
  2240. if (!isset($data->visible)) {
  2241. // data not from form, add missing visibility info
  2242. $data->visible = $oldcourse->visible;
  2243. }
  2244. if ($data->visible != $oldcourse->visible) {
  2245. // reset the visibleold flag when manually hiding/unhiding course
  2246. $data->visibleold = $data->visible;
  2247. $changesincoursecat = true;
  2248. } else {
  2249. if ($movecat) {
  2250. $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
  2251. if (empty($newcategory->visible)) {
  2252. // make sure when moving into hidden category the course is hidden automatically
  2253. $data->visible = 0;
  2254. }
  2255. }
  2256. }
  2257. // Set newsitems to 0 if format does not support announcements.
  2258. if (isset($data->format)) {
  2259. $newcourseformat = course_get_format((object)['format' => $data->format]);
  2260. if (!$newcourseformat->supports_news()) {
  2261. $data->newsitems = 0;
  2262. }
  2263. }
  2264. // Set showcompletionconditions to null when completion tracking has been disabled for the course.
  2265. if (isset($data->enablecompletion) && $data->enablecompletion == COMPLETION_DISABLED) {
  2266. $data->showcompletionconditions = null;
  2267. }
  2268. // Update custom fields if there are any of them in the form.
  2269. $handler = core_course\customfield\course_handler::create();
  2270. $handler->instance_form_save($data);
  2271. // Update with the new data
  2272. $DB->update_record('course', $data);
  2273. // make sure the modinfo cache is reset
  2274. rebuild_course_cache($data->id);
  2275. // Purge course image cache in case if course image has been updated.
  2276. \cache::make('core', 'course_image')->delete($data->id);
  2277. // update course format options with full course data
  2278. course_get_format($data->id)->update_course_format_options($data, $oldcourse);
  2279. $course = $DB->get_record('course', array('id'=>$data->id));
  2280. if ($movecat) {
  2281. $newparent = context_coursecat::instance($course->category);
  2282. $context->update_moved($newparent);
  2283. }
  2284. $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
  2285. if ($fixcoursesortorder) {
  2286. fix_course_sortorder();
  2287. }
  2288. // purge appropriate caches in case fix_course_sortorder() did not change anything
  2289. cache_helper::purge_by_event('changesincourse');
  2290. if ($changesincoursecat) {
  2291. cache_helper::purge_by_event('changesincoursecat');
  2292. }
  2293. // Test for and remove blocks which aren't appropriate anymore
  2294. blocks_remove_inappropriate($course);
  2295. // Save any custom role names.
  2296. save_local_role_names($course->id, $data);
  2297. // update enrol settings
  2298. enrol_course_updated(false, $course, $data);
  2299. // Update course tags.
  2300. if (isset($data->tags)) {
  2301. core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
  2302. }
  2303. // Trigger a course updated event.
  2304. $event = \core\event\course_updated::create(array(
  2305. 'objectid' => $course->id,
  2306. 'context' => context_course::instance($course->id),
  2307. 'other' => array('shortname' => $course->shortname,
  2308. 'fullname' => $course->fullname,
  2309. 'updatedfields' => $updatedfields)
  2310. ));
  2311. $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
  2312. $event->trigger();
  2313. if ($oldcourse->format !== $course->format) {
  2314. // Remove all options stored for the previous format
  2315. // We assume that new course format migrated everything it needed watching trigger
  2316. // 'course_updated' and in method format_XXX::update_course_format_options()
  2317. $DB->delete_records('course_format_options',
  2318. array('courseid' => $course->id, 'format' => $oldcourse->format));
  2319. }
  2320. }
  2321. /**
  2322. * Calculate the average number of enrolled participants per course.
  2323. *
  2324. * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
  2325. * Front page enrolments are excluded.
  2326. *
  2327. * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
  2328. * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
  2329. * @return float
  2330. */
  2331. function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
  2332. global $DB;
  2333. $params = [
  2334. 'siteid' => SITEID,
  2335. ];
  2336. $sql = "SELECT DISTINCT ue.userid, e.courseid
  2337. FROM {user_enrolments} ue
  2338. JOIN {enrol} e ON e.id = ue.enrolid
  2339. JOIN {course} c ON c.id = e.courseid ";
  2340. if ($onlyactive || $lastloginsince) {
  2341. $sql .= "JOIN {user} u ON u.id = ue.userid ";
  2342. }
  2343. $sql .= "WHERE e.courseid <> :siteid
  2344. AND c.visible = 1 ";
  2345. if ($onlyactive) {
  2346. $sql .= "AND ue.status = :active
  2347. AND e.status = :enabled
  2348. AND ue.timestart < :now1
  2349. AND (ue.timeend = 0 OR ue.timeend > :now2) ";
  2350. // Same as in the enrollib - the rounding should help caching in the database.
  2351. $now = round(time(), -2);
  2352. $params += [
  2353. 'active' => ENROL_USER_ACTIVE,
  2354. 'enabled' => ENROL_INSTANCE_ENABLED,
  2355. 'now1' => $now,
  2356. 'now2' => $now,
  2357. ];
  2358. }
  2359. if ($lastloginsince) {
  2360. $sql .= "AND u.lastlogin > :lastlogin ";
  2361. $params['lastlogin'] = $lastloginsince;
  2362. }
  2363. $sql = "SELECT COUNT(*)
  2364. FROM ($sql) total";
  2365. $enrolmenttotal = $DB->count_records_sql($sql, $params);
  2366. // Get the number of visible courses (exclude the front page).
  2367. $coursetotal = $DB->count_records('course', ['visible' => 1]);
  2368. $coursetotal = $coursetotal - 1;
  2369. if (empty($coursetotal)) {
  2370. $participantaverage = 0;
  2371. } else {
  2372. $participantaverage = $enrolmenttotal / $coursetotal;
  2373. }
  2374. return $participantaverage;
  2375. }
  2376. /**
  2377. * Average number of course modules
  2378. * @return integer
  2379. */
  2380. function average_number_of_courses_modules() {
  2381. global $DB, $SITE;
  2382. //count total of visible course module (except front page)
  2383. $sql = 'SELECT COUNT(*) FROM (
  2384. SELECT cm.course, cm.module
  2385. FROM {course} c, {course_modules} cm
  2386. WHERE c.id = cm.course
  2387. AND c.id <> :siteid
  2388. AND cm.visible = 1
  2389. AND c.visible = 1) total';
  2390. $params = array('siteid' => $SITE->id);
  2391. $moduletotal = $DB->count_records_sql($sql, $params);
  2392. //count total of visible courses (minus front page)
  2393. $coursetotal = $DB->count_records('course', array('visible' => 1));
  2394. $coursetotal = $coursetotal - 1 ;
  2395. //average of course module
  2396. if (empty($coursetotal)) {
  2397. $coursemoduleaverage = 0;
  2398. } else {
  2399. $coursemoduleaverage = $moduletotal / $coursetotal;
  2400. }
  2401. return $coursemoduleaverage;
  2402. }
  2403. /**
  2404. * This class pertains to course requests and contains methods associated with
  2405. * create, approving, and removing course requests.
  2406. *
  2407. * Please note we do not allow embedded images here because there is no context
  2408. * to store them with proper access control.
  2409. *
  2410. * @copyright 2009 Sam Hemelryk
  2411. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2412. * @since Moodle 2.0
  2413. *
  2414. * @property-read int $id
  2415. * @property-read string $fullname
  2416. * @property-read string $shortname
  2417. * @property-read string $summary
  2418. * @property-read int $summaryformat
  2419. * @property-read int $summarytrust
  2420. * @property-read string $reason
  2421. * @property-read int $requester
  2422. */
  2423. class course_request {
  2424. /**
  2425. * This is the stdClass that stores the properties for the course request
  2426. * and is externally accessed through the __get magic method
  2427. * @var stdClass
  2428. */
  2429. protected $properties;
  2430. /**
  2431. * An array of options for the summary editor used by course request forms.
  2432. * This is initially set by {@link summary_editor_options()}
  2433. * @var array
  2434. * @static
  2435. */
  2436. protected static $summaryeditoroptions;
  2437. /**
  2438. * Static function to prepare the summary editor for working with a course
  2439. * request.
  2440. *
  2441. * @static
  2442. * @param null|stdClass $data Optional, an object containing the default values
  2443. * for the form, these may be modified when preparing the
  2444. * editor so this should be called before creating the form
  2445. * @return stdClass An object that can be used to set the default values for
  2446. * an mforms form
  2447. */
  2448. public static function prepare($data=null) {
  2449. if ($data === null) {
  2450. $data = new stdClass;
  2451. }
  2452. $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
  2453. return $data;
  2454. }
  2455. /**
  2456. * Static function to create a new course request when passed an array of properties
  2457. * for it.
  2458. *
  2459. * This function also handles saving any files that may have been used in the editor
  2460. *
  2461. * @static
  2462. * @param stdClass $data
  2463. * @return course_request The newly created course request
  2464. */
  2465. public static function create($data) {
  2466. global $USER, $DB, $CFG;
  2467. $data->requester = $USER->id;
  2468. // Setting the default category if none set.
  2469. if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
  2470. $data->category = $CFG->defaultrequestcategory;
  2471. }
  2472. // Summary is a required field so copy the text over
  2473. $data->summary = $data->summary_editor['text'];
  2474. $data->summaryformat = $data->summary_editor['format'];
  2475. $data->id = $DB->insert_record('course_request', $data);
  2476. // Create a new course_request object and return it
  2477. $request = new course_request($data);
  2478. // Notify the admin if required.
  2479. if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
  2480. $a = new stdClass;
  2481. $a->link = "$CFG->wwwroot/course/pending.php";
  2482. $a->user = fullname($USER);
  2483. $subject = get_string('courserequest');
  2484. $message = get_string('courserequestnotifyemail', 'admin', $a);
  2485. foreach ($users as $user) {
  2486. $request->notify($user, $USER, 'courserequested', $subject, $message);
  2487. }
  2488. }
  2489. return $request;
  2490. }
  2491. /**
  2492. * Returns an array of options to use with a summary editor
  2493. *
  2494. * @uses course_request::$summaryeditoroptions
  2495. * @return array An array of options to use with the editor
  2496. */
  2497. public static function summary_editor_options() {
  2498. global $CFG;
  2499. if (self::$summaryeditoroptions === null) {
  2500. self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
  2501. }
  2502. return self::$summaryeditoroptions;
  2503. }
  2504. /**
  2505. * Loads the properties for this course request object. Id is required and if
  2506. * only id is provided then we load the rest of the properties from the database
  2507. *
  2508. * @param stdClass|int $properties Either an object containing properties
  2509. * or the course_request id to load
  2510. */
  2511. public function __construct($properties) {
  2512. global $DB;
  2513. if (empty($properties->id)) {
  2514. if (empty($properties)) {
  2515. throw new coding_exception('You must provide a course request id when creating a course_request object');
  2516. }
  2517. $id = $properties;
  2518. $properties = new stdClass;
  2519. $properties->id = (int)$id;
  2520. unset($id);
  2521. }
  2522. if (empty($properties->requester)) {
  2523. if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
  2524. print_error('unknowncourserequest');
  2525. }
  2526. } else {
  2527. $this->properties = $properties;
  2528. }
  2529. $this->properties->collision = null;
  2530. }
  2531. /**
  2532. * Returns the requested property
  2533. *
  2534. * @param string $key
  2535. * @return mixed
  2536. */
  2537. public function __get($key) {
  2538. return $this->properties->$key;
  2539. }
  2540. /**
  2541. * Override this to ensure empty($request->blah) calls return a reliable answer...
  2542. *
  2543. * This is required because we define the __get method
  2544. *
  2545. * @param mixed $key
  2546. * @return bool True is it not empty, false otherwise
  2547. */
  2548. public function __isset($key) {
  2549. return (!empty($this->properties->$key));
  2550. }
  2551. /**
  2552. * Returns the user who requested this course
  2553. *
  2554. * Uses a static var to cache the results and cut down the number of db queries
  2555. *
  2556. * @staticvar array $requesters An array of cached users
  2557. * @return stdClass The user who requested the course
  2558. */
  2559. public function get_requester() {
  2560. global $DB;
  2561. static $requesters= array();
  2562. if (!array_key_exists($this->properties->requester, $requesters)) {
  2563. $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
  2564. }
  2565. return $requesters[$this->properties->requester];
  2566. }
  2567. /**
  2568. * Checks that the shortname used by the course does not conflict with any other
  2569. * courses that exist
  2570. *
  2571. * @param string|null $shortnamemark The string to append to the requests shortname
  2572. * should a conflict be found
  2573. * @return bool true is there is a conflict, false otherwise
  2574. */
  2575. public function check_shortname_collision($shortnamemark = '[*]') {
  2576. global $DB;
  2577. if ($this->properties->collision !== null) {
  2578. return $this->properties->collision;
  2579. }
  2580. if (empty($this->properties->shortname)) {
  2581. debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
  2582. $this->properties->collision = false;
  2583. } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
  2584. if (!empty($shortnamemark)) {
  2585. $this->properties->shortname .= ' '.$shortnamemark;
  2586. }
  2587. $this->properties->collision = true;
  2588. } else {
  2589. $this->properties->collision = false;
  2590. }
  2591. return $this->properties->collision;
  2592. }
  2593. /**
  2594. * Checks user capability to approve a requested course
  2595. *
  2596. * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
  2597. * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
  2598. *
  2599. * @return bool
  2600. */
  2601. public function can_approve() {
  2602. global $CFG;
  2603. $category = null;
  2604. if ($this->properties->category) {
  2605. $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
  2606. } else if ($CFG->defaultrequestcategory) {
  2607. $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
  2608. }
  2609. if ($category) {
  2610. return has_capability('moodle/site:approvecourse', $category->get_context());
  2611. }
  2612. // We can not determine the context where the course should be created. The approver should have
  2613. // both capabilities to approve courses and change course category in the system context.
  2614. return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
  2615. }
  2616. /**
  2617. * Returns the category where this course request should be created
  2618. *
  2619. * Note that we don't check here that user has a capability to view
  2620. * hidden categories if he has capabilities 'moodle/site:approvecourse' and
  2621. * 'moodle/course:changecategory'
  2622. *
  2623. * @return core_course_category
  2624. */
  2625. public function get_category() {
  2626. global $CFG;
  2627. if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
  2628. return $category;
  2629. } else if ($CFG->defaultrequestcategory &&
  2630. ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
  2631. return $category;
  2632. } else {
  2633. return core_course_category::get_default();
  2634. }
  2635. }
  2636. /**
  2637. * This function approves the request turning it into a course
  2638. *
  2639. * This function converts the course request into a course, at the same time
  2640. * transferring any files used in the summary to the new course and then removing
  2641. * the course request and the files associated with it.
  2642. *
  2643. * @return int The id of the course that was created from this request
  2644. */
  2645. public function approve() {
  2646. global $CFG, $DB, $USER;
  2647. require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
  2648. $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
  2649. $courseconfig = get_config('moodlecourse');
  2650. // Transfer appropriate settings
  2651. $data = clone($this->properties);
  2652. unset($data->id);
  2653. unset($data->reason);
  2654. unset($data->requester);
  2655. // Set category
  2656. $category = $this->get_category();
  2657. $data->category = $category->id;
  2658. // Set misc settings
  2659. $data->requested = 1;
  2660. // Apply course default settings
  2661. $data->format = $courseconfig->format;
  2662. $data->newsitems = $courseconfig->newsitems;
  2663. $data->showgrades = $courseconfig->showgrades;
  2664. $data->showreports = $courseconfig->showreports;
  2665. $data->maxbytes = $courseconfig->maxbytes;
  2666. $data->groupmode = $courseconfig->groupmode;
  2667. $data->groupmodeforce = $courseconfig->groupmodeforce;
  2668. $data->visible = $courseconfig->visible;
  2669. $data->visibleold = $data->visible;
  2670. $data->lang = $courseconfig->lang;
  2671. $data->enablecompletion = $courseconfig->enablecompletion;
  2672. $data->numsections = $courseconfig->numsections;
  2673. $data->startdate = usergetmidnight(time());
  2674. if ($courseconfig->courseenddateenabled) {
  2675. $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
  2676. }
  2677. list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
  2678. $course = create_course($data);
  2679. $context = context_course::instance($course->id, MUST_EXIST);
  2680. // add enrol instances
  2681. if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
  2682. if ($manual = enrol_get_plugin('manual')) {
  2683. $manual->add_default_instance($course);
  2684. }
  2685. }
  2686. // enrol the requester as teacher if necessary
  2687. if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
  2688. enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
  2689. }
  2690. $this->delete();
  2691. $a = new stdClass();
  2692. $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
  2693. $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
  2694. $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
  2695. return $course->id;
  2696. }
  2697. /**
  2698. * Reject a course request
  2699. *
  2700. * This function rejects a course request, emailing the requesting user the
  2701. * provided notice and then removing the request from the database
  2702. *
  2703. * @param string $notice The message to display to the user
  2704. */
  2705. public function reject($notice) {
  2706. global $USER, $DB;
  2707. $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
  2708. $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
  2709. $this->delete();
  2710. }
  2711. /**
  2712. * Deletes the course request and any associated files
  2713. */
  2714. public function delete() {
  2715. global $DB;
  2716. $DB->delete_records('course_request', array('id' => $this->properties->id));
  2717. }
  2718. /**
  2719. * Send a message from one user to another using events_trigger
  2720. *
  2721. * @param object $touser
  2722. * @param object $fromuser
  2723. * @param string $name
  2724. * @param string $subject
  2725. * @param string $message
  2726. * @param int|null $courseid
  2727. */
  2728. protected function notify($touser, $fromuser, $name, $subject, $message, $courseid = null) {
  2729. $eventdata = new \core\message\message();
  2730. $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
  2731. $eventdata->component = 'moodle';
  2732. $eventdata->name = $name;
  2733. $eventdata->userfrom = $fromuser;
  2734. $eventdata->userto = $touser;
  2735. $eventdata->subject = $subject;
  2736. $eventdata->fullmessage = $message;
  2737. $eventdata->fullmessageformat = FORMAT_PLAIN;
  2738. $eventdata->fullmessagehtml = '';
  2739. $eventdata->smallmessage = '';
  2740. $eventdata->notification = 1;
  2741. message_send($eventdata);
  2742. }
  2743. /**
  2744. * Checks if current user can request a course in this context
  2745. *
  2746. * @param context $context
  2747. * @return bool
  2748. */
  2749. public static function can_request(context $context) {
  2750. global $CFG;
  2751. if (empty($CFG->enablecourserequests)) {
  2752. return false;
  2753. }
  2754. if (has_capability('moodle/course:create', $context)) {
  2755. return false;
  2756. }
  2757. if ($context instanceof context_system) {
  2758. $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
  2759. return $defaultcontext &&
  2760. has_capability('moodle/course:request', $defaultcontext);
  2761. } else if ($context instanceof context_coursecat) {
  2762. if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
  2763. return has_capability('moodle/course:request', $context);
  2764. }
  2765. }
  2766. return false;
  2767. }
  2768. }
  2769. /**
  2770. * Return a list of page types
  2771. * @param string $pagetype current page type
  2772. * @param context $parentcontext Block's parent context
  2773. * @param context $currentcontext Current context of block
  2774. * @return array array of page types
  2775. */
  2776. function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
  2777. if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
  2778. // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
  2779. $pagetypes = array('*' => get_string('page-x', 'pagetype'),
  2780. 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
  2781. );
  2782. } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
  2783. // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
  2784. $pagetypes = array('*' => get_string('page-x', 'pagetype'));
  2785. } else {
  2786. // Otherwise consider it a page inside a course even if $currentcontext is null
  2787. $pagetypes = array('*' => get_string('page-x', 'pagetype'),
  2788. 'course-*' => get_string('page-course-x', 'pagetype'),
  2789. 'course-view-*' => get_string('page-course-view-x', 'pagetype')
  2790. );
  2791. }
  2792. return $pagetypes;
  2793. }
  2794. /**
  2795. * Determine whether course ajax should be enabled for the specified course
  2796. *
  2797. * @param stdClass $course The course to test against
  2798. * @return boolean Whether course ajax is enabled or note
  2799. */
  2800. function course_ajax_enabled($course) {
  2801. global $CFG, $PAGE, $SITE;
  2802. // The user must be editing for AJAX to be included
  2803. if (!$PAGE->user_is_editing()) {
  2804. return false;
  2805. }
  2806. // Check that the theme suports
  2807. if (!$PAGE->theme->enablecourseajax) {
  2808. return false;
  2809. }
  2810. // Check that the course format supports ajax functionality
  2811. // The site 'format' doesn't have information on course format support
  2812. if ($SITE->id !== $course->id) {
  2813. $courseformatajaxsupport = course_format_ajax_support($course->format);
  2814. if (!$courseformatajaxsupport->capable) {
  2815. return false;
  2816. }
  2817. }
  2818. // All conditions have been met so course ajax should be enabled
  2819. return true;
  2820. }
  2821. /**
  2822. * Include the relevant javascript and language strings for the resource
  2823. * toolbox YUI module
  2824. *
  2825. * @param integer $id The ID of the course being applied to
  2826. * @param array $usedmodules An array containing the names of the modules in use on the page
  2827. * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
  2828. * @param stdClass $config An object containing configuration parameters for ajax modules including:
  2829. * * resourceurl The URL to post changes to for resource changes
  2830. * * sectionurl The URL to post changes to for section changes
  2831. * * pageparams Additional parameters to pass through in the post
  2832. * @return bool
  2833. */
  2834. function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
  2835. global $CFG, $PAGE, $SITE;
  2836. // Init the course editor module to support UI components.
  2837. $format = course_get_format($course);
  2838. include_course_editor($format);
  2839. // Ensure that ajax should be included
  2840. if (!course_ajax_enabled($course)) {
  2841. return false;
  2842. }
  2843. // Component based formats don't use YUI drag and drop anymore.
  2844. if (!$format->supports_components() && course_format_uses_sections($course->format)) {
  2845. if (!$config) {
  2846. $config = new stdClass();
  2847. }
  2848. // The URL to use for resource changes.
  2849. if (!isset($config->resourceurl)) {
  2850. $config->resourceurl = '/course/rest.php';
  2851. }
  2852. // The URL to use for section changes.
  2853. if (!isset($config->sectionurl)) {
  2854. $config->sectionurl = '/course/rest.php';
  2855. }
  2856. // Any additional parameters which need to be included on page submission.
  2857. if (!isset($config->pageparams)) {
  2858. $config->pageparams = array();
  2859. }
  2860. $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
  2861. array(array(
  2862. 'courseid' => $course->id,
  2863. 'ajaxurl' => $config->sectionurl,
  2864. 'config' => $config,
  2865. )), null, true);
  2866. $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
  2867. array(array(
  2868. 'courseid' => $course->id,
  2869. 'ajaxurl' => $config->resourceurl,
  2870. 'config' => $config,
  2871. )), null, true);
  2872. }
  2873. // Require various strings for the command toolbox
  2874. $PAGE->requires->strings_for_js(array(
  2875. 'moveleft',
  2876. 'deletechecktype',
  2877. 'deletechecktypename',
  2878. 'edittitle',
  2879. 'edittitleinstructions',
  2880. 'show',
  2881. 'hide',
  2882. 'highlight',
  2883. 'highlightoff',
  2884. 'groupsnone',
  2885. 'groupsvisible',
  2886. 'groupsseparate',
  2887. 'clicktochangeinbrackets',
  2888. 'markthistopic',
  2889. 'markedthistopic',
  2890. 'movesection',
  2891. 'movecoursemodule',
  2892. 'movecoursesection',
  2893. 'movecontent',
  2894. 'tocontent',
  2895. 'emptydragdropregion',
  2896. 'afterresource',
  2897. 'aftersection',
  2898. 'totopofsection',
  2899. ), 'moodle');
  2900. // Include section-specific strings for formats which support sections.
  2901. if (course_format_uses_sections($course->format)) {
  2902. $PAGE->requires->strings_for_js(array(
  2903. 'showfromothers',
  2904. 'hidefromothers',
  2905. ), 'format_' . $course->format);
  2906. }
  2907. // For confirming resource deletion we need the name of the module in question
  2908. foreach ($usedmodules as $module => $modname) {
  2909. $PAGE->requires->string_for_js('pluginname', $module);
  2910. }
  2911. // Load drag and drop upload AJAX.
  2912. require_once($CFG->dirroot.'/course/dnduploadlib.php');
  2913. dndupload_add_to_course($course, $enabledmodules);
  2914. $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
  2915. return true;
  2916. }
  2917. /**
  2918. * Include and configure the course editor modules.
  2919. *
  2920. * @param course_format $format the course format instance.
  2921. */
  2922. function include_course_editor(course_format $format) {
  2923. global $PAGE, $SITE;
  2924. $course = $format->get_course();
  2925. if ($SITE->id === $course->id) {
  2926. return;
  2927. }
  2928. // Edition mode and some format specs must be passed to the init method.
  2929. $setup = (object)[
  2930. 'editing' => $format->show_editor(),
  2931. 'supportscomponents' => $format->supports_components(),
  2932. ];
  2933. // All the new editor elements will be loaded after the course is presented and
  2934. // the initial course state will be generated using core_course_get_state webservice.
  2935. $PAGE->requires->js_call_amd('core_courseformat/courseeditor', 'setViewFormat', [$course->id, $setup]);
  2936. }
  2937. /**
  2938. * Returns the sorted list of available course formats, filtered by enabled if necessary
  2939. *
  2940. * @param bool $enabledonly return only formats that are enabled
  2941. * @return array array of sorted format names
  2942. */
  2943. function get_sorted_course_formats($enabledonly = false) {
  2944. global $CFG;
  2945. $formats = core_component::get_plugin_list('format');
  2946. if (!empty($CFG->format_plugins_sortorder)) {
  2947. $order = explode(',', $CFG->format_plugins_sortorder);
  2948. $order = array_merge(array_intersect($order, array_keys($formats)),
  2949. array_diff(array_keys($formats), $order));
  2950. } else {
  2951. $order = array_keys($formats);
  2952. }
  2953. if (!$enabledonly) {
  2954. return $order;
  2955. }
  2956. $sortedformats = array();
  2957. foreach ($order as $formatname) {
  2958. if (!get_config('format_'.$formatname, 'disabled')) {
  2959. $sortedformats[] = $formatname;
  2960. }
  2961. }
  2962. return $sortedformats;
  2963. }
  2964. /**
  2965. * The URL to use for the specified course (with section)
  2966. *
  2967. * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
  2968. * @param int|stdClass $section Section object from database or just field course_sections.section
  2969. * if omitted the course view page is returned
  2970. * @param array $options options for view URL. At the moment core uses:
  2971. * 'navigation' (bool) if true and section has no separate page, the function returns null
  2972. * 'sr' (int) used by multipage formats to specify to which section to return
  2973. * @return moodle_url The url of course
  2974. */
  2975. function course_get_url($courseorid, $section = null, $options = array()) {
  2976. return course_get_format($courseorid)->get_view_url($section, $options);
  2977. }
  2978. /**
  2979. * Create a module.
  2980. *
  2981. * It includes:
  2982. * - capability checks and other checks
  2983. * - create the module from the module info
  2984. *
  2985. * @param object $module
  2986. * @return object the created module info
  2987. * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
  2988. */
  2989. function create_module($moduleinfo) {
  2990. global $DB, $CFG;
  2991. require_once($CFG->dirroot . '/course/modlib.php');
  2992. // Check manadatory attributs.
  2993. $mandatoryfields = array('modulename', 'course', 'section', 'visible');
  2994. if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
  2995. $mandatoryfields[] = 'introeditor';
  2996. }
  2997. foreach($mandatoryfields as $mandatoryfield) {
  2998. if (!isset($moduleinfo->{$mandatoryfield})) {
  2999. throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
  3000. }
  3001. }
  3002. // Some additional checks (capability / existing instances).
  3003. $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
  3004. list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
  3005. // Add the module.
  3006. $moduleinfo->module = $module->id;
  3007. $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
  3008. return $moduleinfo;
  3009. }
  3010. /**
  3011. * Update a module.
  3012. *
  3013. * It includes:
  3014. * - capability and other checks
  3015. * - update the module
  3016. *
  3017. * @param object $module
  3018. * @return object the updated module info
  3019. * @throws moodle_exception if current user is not allowed to update the module
  3020. */
  3021. function update_module($moduleinfo) {
  3022. global $DB, $CFG;
  3023. require_once($CFG->dirroot . '/course/modlib.php');
  3024. // Check the course module exists.
  3025. $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
  3026. // Check the course exists.
  3027. $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
  3028. // Some checks (capaibility / existing instances).
  3029. list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
  3030. // Retrieve few information needed by update_moduleinfo.
  3031. $moduleinfo->modulename = $cm->modname;
  3032. if (!isset($moduleinfo->scale)) {
  3033. $moduleinfo->scale = 0;
  3034. }
  3035. $moduleinfo->type = 'mod';
  3036. // Update the module.
  3037. list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
  3038. return $moduleinfo;
  3039. }
  3040. /**
  3041. * Duplicate a module on the course for ajax.
  3042. *
  3043. * @see mod_duplicate_module()
  3044. * @param object $course The course
  3045. * @param object $cm The course module to duplicate
  3046. * @param int $sr The section to link back to (used for creating the links)
  3047. * @throws moodle_exception if the plugin doesn't support duplication
  3048. * @return Object containing:
  3049. * - fullcontent: The HTML markup for the created CM
  3050. * - cmid: The CMID of the newly created CM
  3051. * - redirect: Whether to trigger a redirect following this change
  3052. */
  3053. function mod_duplicate_activity($course, $cm, $sr = null) {
  3054. global $PAGE;
  3055. $newcm = duplicate_module($course, $cm);
  3056. $resp = new stdClass();
  3057. if ($newcm) {
  3058. $format = course_get_format($course);
  3059. $renderer = $format->get_renderer($PAGE);
  3060. $modinfo = $format->get_modinfo();
  3061. $section = $modinfo->get_section_info($newcm->sectionnum);
  3062. // Get the new element html content.
  3063. $resp->fullcontent = $renderer->course_section_updated_cm_item($format, $section, $newcm);
  3064. $resp->cmid = $newcm->id;
  3065. } else {
  3066. // Trigger a redirect.
  3067. $resp->redirect = true;
  3068. }
  3069. return $resp;
  3070. }
  3071. /**
  3072. * Api to duplicate a module.
  3073. *
  3074. * @param object $course course object.
  3075. * @param object $cm course module object to be duplicated.
  3076. * @since Moodle 2.8
  3077. *
  3078. * @throws Exception
  3079. * @throws coding_exception
  3080. * @throws moodle_exception
  3081. * @throws restore_controller_exception
  3082. *
  3083. * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
  3084. */
  3085. function duplicate_module($course, $cm) {
  3086. global $CFG, $DB, $USER;
  3087. require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
  3088. require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
  3089. require_once($CFG->libdir . '/filelib.php');
  3090. $a = new stdClass();
  3091. $a->modtype = get_string('modulename', $cm->modname);
  3092. $a->modname = format_string($cm->name);
  3093. if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
  3094. throw new moodle_exception('duplicatenosupport', 'error', '', $a);
  3095. }
  3096. // Backup the activity.
  3097. $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
  3098. backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
  3099. $backupid = $bc->get_backupid();
  3100. $backupbasepath = $bc->get_plan()->get_basepath();
  3101. $bc->execute_plan();
  3102. $bc->destroy();
  3103. // Restore the backup immediately.
  3104. $rc = new restore_controller($backupid, $course->id,
  3105. backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
  3106. // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
  3107. $plan = $rc->get_plan();
  3108. $groupsetting = $plan->get_setting('groups');
  3109. if (empty($groupsetting->get_value())) {
  3110. $groupsetting->set_value(true);
  3111. }
  3112. $cmcontext = context_module::instance($cm->id);
  3113. if (!$rc->execute_precheck()) {
  3114. $precheckresults = $rc->get_precheck_results();
  3115. if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
  3116. if (empty($CFG->keeptempdirectoriesonbackup)) {
  3117. fulldelete($backupbasepath);
  3118. }
  3119. }
  3120. }
  3121. $rc->execute_plan();
  3122. // Now a bit hacky part follows - we try to get the cmid of the newly
  3123. // restored copy of the module.
  3124. $newcmid = null;
  3125. $tasks = $rc->get_plan()->get_tasks();
  3126. foreach ($tasks as $task) {
  3127. if (is_subclass_of($task, 'restore_activity_task')) {
  3128. if ($task->get_old_contextid() == $cmcontext->id) {
  3129. $newcmid = $task->get_moduleid();
  3130. break;
  3131. }
  3132. }
  3133. }
  3134. $rc->destroy();
  3135. if (empty($CFG->keeptempdirectoriesonbackup)) {
  3136. fulldelete($backupbasepath);
  3137. }
  3138. // If we know the cmid of the new course module, let us move it
  3139. // right below the original one. otherwise it will stay at the
  3140. // end of the section.
  3141. if ($newcmid) {
  3142. // Proceed with activity renaming before everything else. We don't use APIs here to avoid
  3143. // triggering a lot of create/update duplicated events.
  3144. $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
  3145. // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
  3146. // from original name that was valid, so the copy should be too.
  3147. $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
  3148. $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
  3149. $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
  3150. $modarray = explode(",", trim($section->sequence));
  3151. $cmindex = array_search($cm->id, $modarray);
  3152. if ($cmindex !== false && $cmindex < count($modarray) - 1) {
  3153. moveto_module($newcm, $section, $modarray[$cmindex + 1]);
  3154. }
  3155. // Update calendar events with the duplicated module.
  3156. // The following line is to be removed in MDL-58906.
  3157. course_module_update_calendar_events($newcm->modname, null, $newcm);
  3158. // Trigger course module created event. We can trigger the event only if we know the newcmid.
  3159. $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
  3160. $event = \core\event\course_module_created::create_from_cm($newcm);
  3161. $event->trigger();
  3162. }
  3163. return isset($newcm) ? $newcm : null;
  3164. }
  3165. /**
  3166. * Compare two objects to find out their correct order based on timestamp (to be used by usort).
  3167. * Sorts by descending order of time.
  3168. *
  3169. * @param stdClass $a First object
  3170. * @param stdClass $b Second object
  3171. * @return int 0,1,-1 representing the order
  3172. */
  3173. function compare_activities_by_time_desc($a, $b) {
  3174. // Make sure the activities actually have a timestamp property.
  3175. if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
  3176. return 0;
  3177. }
  3178. // We treat instances without timestamp as if they have a timestamp of 0.
  3179. if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
  3180. return 1;
  3181. }
  3182. if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
  3183. return -1;
  3184. }
  3185. if ($a->timestamp == $b->timestamp) {
  3186. return 0;
  3187. }
  3188. return ($a->timestamp > $b->timestamp) ? -1 : 1;
  3189. }
  3190. /**
  3191. * Compare two objects to find out their correct order based on timestamp (to be used by usort).
  3192. * Sorts by ascending order of time.
  3193. *
  3194. * @param stdClass $a First object
  3195. * @param stdClass $b Second object
  3196. * @return int 0,1,-1 representing the order
  3197. */
  3198. function compare_activities_by_time_asc($a, $b) {
  3199. // Make sure the activities actually have a timestamp property.
  3200. if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
  3201. return 0;
  3202. }
  3203. // We treat instances without timestamp as if they have a timestamp of 0.
  3204. if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
  3205. return -1;
  3206. }
  3207. if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
  3208. return 1;
  3209. }
  3210. if ($a->timestamp == $b->timestamp) {
  3211. return 0;
  3212. }
  3213. return ($a->timestamp < $b->timestamp) ? -1 : 1;
  3214. }
  3215. /**
  3216. * Changes the visibility of a course.
  3217. *
  3218. * @param int $courseid The course to change.
  3219. * @param bool $show True to make it visible, false otherwise.
  3220. * @return bool
  3221. */
  3222. function course_change_visibility($courseid, $show = true) {
  3223. $course = new stdClass;
  3224. $course->id = $courseid;
  3225. $course->visible = ($show) ? '1' : '0';
  3226. $course->visibleold = $course->visible;
  3227. update_course($course);
  3228. return true;
  3229. }
  3230. /**
  3231. * Changes the course sortorder by one, moving it up or down one in respect to sort order.
  3232. *
  3233. * @param stdClass|core_course_list_element $course
  3234. * @param bool $up If set to true the course will be moved up one. Otherwise down one.
  3235. * @return bool
  3236. */
  3237. function course_change_sortorder_by_one($course, $up) {
  3238. global $DB;
  3239. $params = array($course->sortorder, $course->category);
  3240. if ($up) {
  3241. $select = 'sortorder < ? AND category = ?';
  3242. $sort = 'sortorder DESC';
  3243. } else {
  3244. $select = 'sortorder > ? AND category = ?';
  3245. $sort = 'sortorder ASC';
  3246. }
  3247. fix_course_sortorder();
  3248. $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
  3249. if ($swapcourse) {
  3250. $swapcourse = reset($swapcourse);
  3251. $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
  3252. $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
  3253. // Finally reorder courses.
  3254. fix_course_sortorder();
  3255. cache_helper::purge_by_event('changesincourse');
  3256. return true;
  3257. }
  3258. return false;
  3259. }
  3260. /**
  3261. * Changes the sort order of courses in a category so that the first course appears after the second.
  3262. *
  3263. * @param int|stdClass $courseorid The course to focus on.
  3264. * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
  3265. * @return bool
  3266. */
  3267. function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
  3268. global $DB;
  3269. if (!is_object($courseorid)) {
  3270. $course = get_course($courseorid);
  3271. } else {
  3272. $course = $courseorid;
  3273. }
  3274. if ((int)$moveaftercourseid === 0) {
  3275. // We've moving the course to the start of the queue.
  3276. $sql = 'SELECT sortorder
  3277. FROM {course}
  3278. WHERE category = :categoryid
  3279. ORDER BY sortorder';
  3280. $params = array(
  3281. 'categoryid' => $course->category
  3282. );
  3283. $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
  3284. $sql = 'UPDATE {course}
  3285. SET sortorder = sortorder + 1
  3286. WHERE category = :categoryid
  3287. AND id <> :id';
  3288. $params = array(
  3289. 'categoryid' => $course->category,
  3290. 'id' => $course->id,
  3291. );
  3292. $DB->execute($sql, $params);
  3293. $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
  3294. } else if ($course->id === $moveaftercourseid) {
  3295. // They're the same - moronic.
  3296. debugging("Invalid move after course given.", DEBUG_DEVELOPER);
  3297. return false;
  3298. } else {
  3299. // Moving this course after the given course. It could be before it could be after.
  3300. $moveaftercourse = get_course($moveaftercourseid);
  3301. if ($course->category !== $moveaftercourse->category) {
  3302. debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
  3303. return false;
  3304. }
  3305. // Increment all courses in the same category that are ordered after the moveafter course.
  3306. // This makes a space for the course we're moving.
  3307. $sql = 'UPDATE {course}
  3308. SET sortorder = sortorder + 1
  3309. WHERE category = :categoryid
  3310. AND sortorder > :sortorder';
  3311. $params = array(
  3312. 'categoryid' => $moveaftercourse->category,
  3313. 'sortorder' => $moveaftercourse->sortorder
  3314. );
  3315. $DB->execute($sql, $params);
  3316. $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
  3317. }
  3318. fix_course_sortorder();
  3319. cache_helper::purge_by_event('changesincourse');
  3320. return true;
  3321. }
  3322. /**
  3323. * Trigger course viewed event. This API function is used when course view actions happens,
  3324. * usually in course/view.php but also in external functions.
  3325. *
  3326. * @param stdClass $context course context object
  3327. * @param int $sectionnumber section number
  3328. * @since Moodle 2.9
  3329. */
  3330. function course_view($context, $sectionnumber = 0) {
  3331. $eventdata = array('context' => $context);
  3332. if (!empty($sectionnumber)) {
  3333. $eventdata['other']['coursesectionnumber'] = $sectionnumber;
  3334. }
  3335. $event = \core\event\course_viewed::create($eventdata);
  3336. $event->trigger();
  3337. user_accesstime_log($context->instanceid);
  3338. }
  3339. /**
  3340. * Returns courses tagged with a specified tag.
  3341. *
  3342. * @param core_tag_tag $tag
  3343. * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
  3344. * are displayed on the page and the per-page limit may be bigger
  3345. * @param int $fromctx context id where the link was displayed, may be used by callbacks
  3346. * to display items in the same context first
  3347. * @param int $ctx context id where to search for records
  3348. * @param bool $rec search in subcontexts as well
  3349. * @param int $page 0-based number of page being displayed
  3350. * @return \core_tag\output\tagindex
  3351. */
  3352. function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
  3353. global $CFG, $PAGE;
  3354. $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
  3355. $displayoptions = array(
  3356. 'limit' => $perpage,
  3357. 'offset' => $page * $perpage,
  3358. 'viewmoreurl' => null,
  3359. );
  3360. $courserenderer = $PAGE->get_renderer('core', 'course');
  3361. $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
  3362. $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
  3363. $totalpages = ceil($totalcount / $perpage);
  3364. return new core_tag\output\tagindex($tag, 'core', 'course', $content,
  3365. $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
  3366. }
  3367. /**
  3368. * Implements callback inplace_editable() allowing to edit values in-place
  3369. *
  3370. * @param string $itemtype
  3371. * @param int $itemid
  3372. * @param mixed $newvalue
  3373. * @return \core\output\inplace_editable
  3374. */
  3375. function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
  3376. if ($itemtype === 'activityname') {
  3377. return \core_courseformat\output\local\content\cm\cmname::update($itemid, $newvalue);
  3378. }
  3379. }
  3380. /**
  3381. * This function calculates the minimum and maximum cutoff values for the timestart of
  3382. * the given event.
  3383. *
  3384. * It will return an array with two values, the first being the minimum cutoff value and
  3385. * the second being the maximum cutoff value. Either or both values can be null, which
  3386. * indicates there is no minimum or maximum, respectively.
  3387. *
  3388. * If a cutoff is required then the function must return an array containing the cutoff
  3389. * timestamp and error string to display to the user if the cutoff value is violated.
  3390. *
  3391. * A minimum and maximum cutoff return value will look like:
  3392. * [
  3393. * [1505704373, 'The date must be after this date'],
  3394. * [1506741172, 'The date must be before this date']
  3395. * ]
  3396. *
  3397. * @param calendar_event $event The calendar event to get the time range for
  3398. * @param stdClass $course The course object to get the range from
  3399. * @return array Returns an array with min and max date.
  3400. */
  3401. function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
  3402. $mindate = null;
  3403. $maxdate = null;
  3404. if ($course->startdate) {
  3405. $mindate = [
  3406. $course->startdate,
  3407. get_string('errorbeforecoursestart', 'calendar')
  3408. ];
  3409. }
  3410. return [$mindate, $maxdate];
  3411. }
  3412. /**
  3413. * Render the message drawer to be included in the top of the body of each page.
  3414. *
  3415. * @return string HTML
  3416. */
  3417. function core_course_drawer(): string {
  3418. global $PAGE;
  3419. $format = course_get_format($PAGE->course);
  3420. // Only course and modules are able to render course index.
  3421. $ismod = strpos($PAGE->pagetype, 'mod-') === 0;
  3422. if ($ismod || $PAGE->pagetype == 'course-view-' . $format->get_format()) {
  3423. $renderer = $format->get_renderer($PAGE);
  3424. if (method_exists($renderer, 'course_index_drawer')) {
  3425. return $renderer->course_index_drawer($format);
  3426. }
  3427. }
  3428. return '';
  3429. }
  3430. /**
  3431. * Returns course modules tagged with a specified tag ready for output on tag/index.php page
  3432. *
  3433. * This is a callback used by the tag area core/course_modules to search for course modules
  3434. * tagged with a specific tag.
  3435. *
  3436. * @param core_tag_tag $tag
  3437. * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
  3438. * are displayed on the page and the per-page limit may be bigger
  3439. * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
  3440. * to display items in the same context first
  3441. * @param int $contextid context id where to search for records
  3442. * @param bool $recursivecontext search in subcontexts as well
  3443. * @param int $page 0-based number of page being displayed
  3444. * @return \core_tag\output\tagindex
  3445. */
  3446. function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
  3447. $recursivecontext = 1, $page = 0) {
  3448. global $OUTPUT;
  3449. $perpage = $exclusivemode ? 20 : 5;
  3450. // Build select query.
  3451. $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
  3452. $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
  3453. FROM {course_modules} cm
  3454. JOIN {tag_instance} tt ON cm.id = tt.itemid
  3455. JOIN {course} c ON cm.course = c.id
  3456. JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
  3457. WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
  3458. AND cm.deletioninprogress = 0
  3459. AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
  3460. $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
  3461. 'coursemodulecontextlevel' => CONTEXT_MODULE);
  3462. if ($contextid) {
  3463. $context = context::instance_by_id($contextid);
  3464. $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
  3465. $params['contextid'] = $context->id;
  3466. $params['path'] = $context->path.'/%';
  3467. }
  3468. $query .= ' ORDER BY';
  3469. if ($fromcontextid) {
  3470. // In order-clause specify that modules from inside "fromctx" context should be returned first.
  3471. $fromcontext = context::instance_by_id($fromcontextid);
  3472. $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
  3473. $params['fromcontextid'] = $fromcontext->id;
  3474. $params['frompath'] = $fromcontext->path.'/%';
  3475. }
  3476. $query .= ' c.sortorder, cm.id';
  3477. $totalpages = $page + 1;
  3478. // Use core_tag_index_builder to build and filter the list of items.
  3479. // Request one item more than we need so we know if next page exists.
  3480. $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
  3481. while ($item = $builder->has_item_that_needs_access_check()) {
  3482. context_helper::preload_from_record($item);
  3483. $courseid = $item->courseid;
  3484. if (!$builder->can_access_course($courseid)) {
  3485. $builder->set_accessible($item, false);
  3486. continue;
  3487. }
  3488. $modinfo = get_fast_modinfo($builder->get_course($courseid));
  3489. // Set accessibility of this item and all other items in the same course.
  3490. $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
  3491. if ($taggeditem->courseid == $courseid) {
  3492. $cm = $modinfo->get_cm($taggeditem->cmid);
  3493. $builder->set_accessible($taggeditem, $cm->uservisible);
  3494. }
  3495. });
  3496. }
  3497. $items = $builder->get_items();
  3498. if (count($items) > $perpage) {
  3499. $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
  3500. array_pop($items);
  3501. }
  3502. // Build the display contents.
  3503. if ($items) {
  3504. $tagfeed = new core_tag\output\tagfeed();
  3505. foreach ($items as $item) {
  3506. context_helper::preload_from_record($item);
  3507. $course = $builder->get_course($item->courseid);
  3508. $modinfo = get_fast_modinfo($course);
  3509. $cm = $modinfo->get_cm($item->cmid);
  3510. $courseurl = course_get_url($item->courseid, $cm->sectionnum);
  3511. $cmname = $cm->get_formatted_name();
  3512. if (!$exclusivemode) {
  3513. $cmname = shorten_text($cmname, 100);
  3514. }
  3515. $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
  3516. $coursename = format_string($course->fullname, true,
  3517. array('context' => context_course::instance($item->courseid)));
  3518. $coursename = html_writer::link($courseurl, $coursename);
  3519. $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
  3520. $tagfeed->add($icon, $cmname, $coursename);
  3521. }
  3522. $content = $OUTPUT->render_from_template('core_tag/tagfeed',
  3523. $tagfeed->export_for_template($OUTPUT));
  3524. return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
  3525. $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
  3526. }
  3527. }
  3528. /**
  3529. * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
  3530. * This function also handles the frontpage course.
  3531. *
  3532. * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
  3533. * @param stdClass $course the course where the settings are being rendered
  3534. * @return stdClass the navigation options in a course and their availability status
  3535. * @since Moodle 3.2
  3536. */
  3537. function course_get_user_navigation_options($context, $course = null) {
  3538. global $CFG;
  3539. $isloggedin = isloggedin();
  3540. $isguestuser = isguestuser();
  3541. $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
  3542. if ($isfrontpage) {
  3543. $sitecontext = $context;
  3544. } else {
  3545. $sitecontext = context_system::instance();
  3546. }
  3547. // Sets defaults for all options.
  3548. $options = (object) [
  3549. 'badges' => false,
  3550. 'blogs' => false,
  3551. 'calendar' => false,
  3552. 'competencies' => false,
  3553. 'grades' => false,
  3554. 'notes' => false,
  3555. 'participants' => false,
  3556. 'search' => false,
  3557. 'tags' => false,
  3558. ];
  3559. $options->blogs = !empty($CFG->enableblogs) &&
  3560. ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
  3561. ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
  3562. && has_capability('moodle/blog:view', $sitecontext);
  3563. $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
  3564. // Frontpage settings?
  3565. if ($isfrontpage) {
  3566. // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
  3567. $options->participants = course_can_view_participants($sitecontext);
  3568. $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
  3569. $options->tags = !empty($CFG->usetags) && $isloggedin;
  3570. $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
  3571. $options->calendar = $isloggedin;
  3572. } else {
  3573. // We are in a course, so make sure we use the proper capability (course:viewparticipants).
  3574. $options->participants = course_can_view_participants($context);
  3575. $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
  3576. has_capability('moodle/badges:viewbadges', $context);
  3577. // Add view grade report is permitted.
  3578. $grades = false;
  3579. if (has_capability('moodle/grade:viewall', $context)) {
  3580. $grades = true;
  3581. } else if (!empty($course->showgrades)) {
  3582. $reports = core_component::get_plugin_list('gradereport');
  3583. if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
  3584. arsort($reports); // User is last, we want to test it first.
  3585. foreach ($reports as $plugin => $plugindir) {
  3586. if (has_capability('gradereport/'.$plugin.':view', $context)) {
  3587. // Stop when the first visible plugin is found.
  3588. $grades = true;
  3589. break;
  3590. }
  3591. }
  3592. }
  3593. }
  3594. $options->grades = $grades;
  3595. }
  3596. if (\core_competency\api::is_enabled()) {
  3597. $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
  3598. $options->competencies = has_any_capability($capabilities, $context);
  3599. }
  3600. return $options;
  3601. }
  3602. /**
  3603. * Return an object with the list of administration options in a course that are available or not for the current user.
  3604. * This function also handles the frontpage settings.
  3605. *
  3606. * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
  3607. * @param stdClass $context context object (course context)
  3608. * @return stdClass the administration options in a course and their availability status
  3609. * @since Moodle 3.2
  3610. */
  3611. function course_get_user_administration_options($course, $context) {
  3612. global $CFG;
  3613. $isfrontpage = $course->id == SITEID;
  3614. $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
  3615. $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
  3616. $options = new stdClass;
  3617. $options->update = has_capability('moodle/course:update', $context);
  3618. $options->editcompletion = $CFG->enablecompletion &&
  3619. $course->enablecompletion &&
  3620. ($options->update || $hascompletiontabs);
  3621. $options->filters = has_capability('moodle/filter:manage', $context) &&
  3622. count(filter_get_available_in_context($context)) > 0;
  3623. $options->reports = has_capability('moodle/site:viewreports', $context);
  3624. $options->backup = has_capability('moodle/backup:backupcourse', $context);
  3625. $options->restore = has_capability('moodle/restore:restorecourse', $context);
  3626. $options->copy = \core_course\management\helper::can_copy_course($course->id);
  3627. $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
  3628. if (!$isfrontpage) {
  3629. $options->tags = has_capability('moodle/course:tag', $context);
  3630. $options->gradebook = has_capability('moodle/grade:manage', $context);
  3631. $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
  3632. $options->badges = !empty($CFG->enablebadges);
  3633. $options->import = has_capability('moodle/restore:restoretargetimport', $context);
  3634. $options->reset = has_capability('moodle/course:reset', $context);
  3635. $options->roles = has_capability('moodle/role:switchroles', $context);
  3636. } else {
  3637. // Set default options to false.
  3638. $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
  3639. foreach ($listofoptions as $option) {
  3640. $options->$option = false;
  3641. }
  3642. }
  3643. return $options;
  3644. }
  3645. /**
  3646. * Validates course start and end dates.
  3647. *
  3648. * Checks that the end course date is not greater than the start course date.
  3649. *
  3650. * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
  3651. *
  3652. * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
  3653. * @return mixed False if everything alright, error codes otherwise.
  3654. */
  3655. function course_validate_dates($coursedata) {
  3656. // If both start and end dates are set end date should be later than the start date.
  3657. if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
  3658. ($coursedata['enddate'] < $coursedata['startdate'])) {
  3659. return 'enddatebeforestartdate';
  3660. }
  3661. // If start date is not set end date can not be set.
  3662. if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
  3663. return 'nostartdatenoenddate';
  3664. }
  3665. return false;
  3666. }
  3667. /**
  3668. * Check for course updates in the given context level instances (only modules supported right Now)
  3669. *
  3670. * @param stdClass $course course object
  3671. * @param array $tocheck instances to check for updates
  3672. * @param array $filter check only for updates in these areas
  3673. * @return array list of warnings and instances with updates information
  3674. * @since Moodle 3.2
  3675. */
  3676. function course_check_updates($course, $tocheck, $filter = array()) {
  3677. global $CFG, $DB;
  3678. $instances = array();
  3679. $warnings = array();
  3680. $modulescallbacksupport = array();
  3681. $modinfo = get_fast_modinfo($course);
  3682. $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
  3683. // Check instances.
  3684. foreach ($tocheck as $instance) {
  3685. if ($instance['contextlevel'] == 'module') {
  3686. // Check module visibility.
  3687. try {
  3688. $cm = $modinfo->get_cm($instance['id']);
  3689. } catch (Exception $e) {
  3690. $warnings[] = array(
  3691. 'item' => 'module',
  3692. 'itemid' => $instance['id'],
  3693. 'warningcode' => 'cmidnotincourse',
  3694. 'message' => 'This module id does not belong to this course.'
  3695. );
  3696. continue;
  3697. }
  3698. if (!$cm->uservisible) {
  3699. $warnings[] = array(
  3700. 'item' => 'module',
  3701. 'itemid' => $instance['id'],
  3702. 'warningcode' => 'nonuservisible',
  3703. 'message' => 'You don\'t have access to this module.'
  3704. );
  3705. continue;
  3706. }
  3707. if (empty($supportedplugins['mod_' . $cm->modname])) {
  3708. $warnings[] = array(
  3709. 'item' => 'module',
  3710. 'itemid' => $instance['id'],
  3711. 'warningcode' => 'missingcallback',
  3712. 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
  3713. );
  3714. continue;
  3715. }
  3716. // Retrieve the module instance.
  3717. $instances[] = array(
  3718. 'contextlevel' => $instance['contextlevel'],
  3719. 'id' => $instance['id'],
  3720. 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
  3721. );
  3722. } else {
  3723. $warnings[] = array(
  3724. 'item' => 'contextlevel',
  3725. 'itemid' => $instance['id'],
  3726. 'warningcode' => 'contextlevelnotsupported',
  3727. 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
  3728. );
  3729. }
  3730. }
  3731. return array($instances, $warnings);
  3732. }
  3733. /**
  3734. * This function classifies a course as past, in progress or future.
  3735. *
  3736. * This function may incur a DB hit to calculate course completion.
  3737. * @param stdClass $course Course record
  3738. * @param stdClass $user User record (optional - defaults to $USER).
  3739. * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
  3740. * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
  3741. */
  3742. function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
  3743. global $USER;
  3744. if ($user == null) {
  3745. $user = $USER;
  3746. }
  3747. $today = time();
  3748. // End date past.
  3749. if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
  3750. return COURSE_TIMELINE_PAST;
  3751. }
  3752. if ($completioninfo == null) {
  3753. $completioninfo = new completion_info($course);
  3754. }
  3755. // Course was completed.
  3756. if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
  3757. return COURSE_TIMELINE_PAST;
  3758. }
  3759. // Start date not reached.
  3760. if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
  3761. return COURSE_TIMELINE_FUTURE;
  3762. }
  3763. // Everything else is in progress.
  3764. return COURSE_TIMELINE_INPROGRESS;
  3765. }
  3766. /**
  3767. * This function calculates the end date to use for display classification purposes,
  3768. * incorporating the grace period, if any.
  3769. *
  3770. * @param stdClass $course The course record.
  3771. * @return int The new enddate.
  3772. */
  3773. function course_classify_end_date($course) {
  3774. global $CFG;
  3775. $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
  3776. $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
  3777. return $enddate->getTimestamp();
  3778. }
  3779. /**
  3780. * This function calculates the start date to use for display classification purposes,
  3781. * incorporating the grace period, if any.
  3782. *
  3783. * @param stdClass $course The course record.
  3784. * @return int The new startdate.
  3785. */
  3786. function course_classify_start_date($course) {
  3787. global $CFG;
  3788. $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
  3789. $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
  3790. return $startdate->getTimestamp();
  3791. }
  3792. /**
  3793. * Group a list of courses into either past, future, or in progress.
  3794. *
  3795. * The return value will be an array indexed by the COURSE_TIMELINE_* constants
  3796. * with each value being an array of courses in that group.
  3797. * E.g.
  3798. * [
  3799. * COURSE_TIMELINE_PAST => [... list of past courses ...],
  3800. * COURSE_TIMELINE_FUTURE => [],
  3801. * COURSE_TIMELINE_INPROGRESS => []
  3802. * ]
  3803. *
  3804. * @param array $courses List of courses to be grouped.
  3805. * @return array
  3806. */
  3807. function course_classify_courses_for_timeline(array $courses) {
  3808. return array_reduce($courses, function($carry, $course) {
  3809. $classification = course_classify_for_timeline($course);
  3810. array_push($carry[$classification], $course);
  3811. return $carry;
  3812. }, [
  3813. COURSE_TIMELINE_PAST => [],
  3814. COURSE_TIMELINE_FUTURE => [],
  3815. COURSE_TIMELINE_INPROGRESS => []
  3816. ]);
  3817. }
  3818. /**
  3819. * Get the list of enrolled courses for the current user.
  3820. *
  3821. * This function returns a Generator. The courses will be loaded from the database
  3822. * in chunks rather than a single query.
  3823. *
  3824. * @param int $limit Restrict result set to this amount
  3825. * @param int $offset Skip this number of records from the start of the result set
  3826. * @param string|null $sort SQL string for sorting
  3827. * @param string|null $fields SQL string for fields to be returned
  3828. * @param int $dbquerylimit The number of records to load per DB request
  3829. * @param array $includecourses courses ids to be restricted
  3830. * @param array $hiddencourses courses ids to be excluded
  3831. * @return Generator
  3832. */
  3833. function course_get_enrolled_courses_for_logged_in_user(
  3834. int $limit = 0,
  3835. int $offset = 0,
  3836. string $sort = null,
  3837. string $fields = null,
  3838. int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
  3839. array $includecourses = [],
  3840. array $hiddencourses = []
  3841. ) : Generator {
  3842. $haslimit = !empty($limit);
  3843. $recordsloaded = 0;
  3844. $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
  3845. while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
  3846. yield from $courses;
  3847. $recordsloaded += $querylimit;
  3848. if (count($courses) < $querylimit) {
  3849. break;
  3850. }
  3851. if ($haslimit && $recordsloaded >= $limit) {
  3852. break;
  3853. }
  3854. $offset += $querylimit;
  3855. }
  3856. }
  3857. /**
  3858. * Get the list of enrolled courses the current user searched for.
  3859. *
  3860. * This function returns a Generator. The courses will be loaded from the database
  3861. * in chunks rather than a single query.
  3862. *
  3863. * @param int $limit Restrict result set to this amount
  3864. * @param int $offset Skip this number of records from the start of the result set
  3865. * @param string|null $sort SQL string for sorting
  3866. * @param string|null $fields SQL string for fields to be returned
  3867. * @param int $dbquerylimit The number of records to load per DB request
  3868. * @param array $searchcriteria contains search criteria
  3869. * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
  3870. * search is always category-independent
  3871. * @return Generator
  3872. */
  3873. function course_get_enrolled_courses_for_logged_in_user_from_search(
  3874. int $limit = 0,
  3875. int $offset = 0,
  3876. string $sort = null,
  3877. string $fields = null,
  3878. int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
  3879. array $searchcriteria = [],
  3880. array $options = []
  3881. ) : Generator {
  3882. $haslimit = !empty($limit);
  3883. $recordsloaded = 0;
  3884. $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
  3885. $ids = core_course_category::search_courses($searchcriteria, $options);
  3886. // If no courses were found matching the criteria return back.
  3887. if (empty($ids)) {
  3888. return;
  3889. }
  3890. while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $ids, false, $offset)) {
  3891. yield from $courses;
  3892. $recordsloaded += $querylimit;
  3893. if (count($courses) < $querylimit) {
  3894. break;
  3895. }
  3896. if ($haslimit && $recordsloaded >= $limit) {
  3897. break;
  3898. }
  3899. $offset += $querylimit;
  3900. }
  3901. }
  3902. /**
  3903. * Search the given $courses for any that match the given $classification up to the specified
  3904. * $limit.
  3905. *
  3906. * This function will return the subset of courses that match the classification as well as the
  3907. * number of courses it had to process to build that subset.
  3908. *
  3909. * It is recommended that for larger sets of courses this function is given a Generator that loads
  3910. * the courses from the database in chunks.
  3911. *
  3912. * @param array|Traversable $courses List of courses to process
  3913. * @param string $classification One of the COURSE_TIMELINE_* constants
  3914. * @param int $limit Limit the number of results to this amount
  3915. * @return array First value is the filtered courses, second value is the number of courses processed
  3916. */
  3917. function course_filter_courses_by_timeline_classification(
  3918. $courses,
  3919. string $classification,
  3920. int $limit = 0
  3921. ) : array {
  3922. if (!in_array($classification,
  3923. [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
  3924. COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN, COURSE_TIMELINE_SEARCH])) {
  3925. $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
  3926. . 'COURSE_TIMELINE_INPROGRESS, COURSE_TIMELINE_SEARCH or COURSE_TIMELINE_FUTURE';
  3927. throw new moodle_exception($message);
  3928. }
  3929. $filteredcourses = [];
  3930. $numberofcoursesprocessed = 0;
  3931. $filtermatches = 0;
  3932. foreach ($courses as $course) {
  3933. $numberofcoursesprocessed++;
  3934. $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
  3935. // Added as of MDL-63457 toggle viewability for each user.
  3936. if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
  3937. $classification == COURSE_TIMELINE_SEARCH||
  3938. (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
  3939. $filteredcourses[] = $course;
  3940. $filtermatches++;
  3941. }
  3942. if ($limit && $filtermatches >= $limit) {
  3943. // We've found the number of requested courses. No need to continue searching.
  3944. break;
  3945. }
  3946. }
  3947. // Return the number of filtered courses as well as the number of courses that were searched
  3948. // in order to find the matching courses. This allows the calling code to do some kind of
  3949. // pagination.
  3950. return [$filteredcourses, $numberofcoursesprocessed];
  3951. }
  3952. /**
  3953. * Search the given $courses for any that match the given $classification up to the specified
  3954. * $limit.
  3955. *
  3956. * This function will return the subset of courses that are favourites as well as the
  3957. * number of courses it had to process to build that subset.
  3958. *
  3959. * It is recommended that for larger sets of courses this function is given a Generator that loads
  3960. * the courses from the database in chunks.
  3961. *
  3962. * @param array|Traversable $courses List of courses to process
  3963. * @param array $favouritecourseids Array of favourite courses.
  3964. * @param int $limit Limit the number of results to this amount
  3965. * @return array First value is the filtered courses, second value is the number of courses processed
  3966. */
  3967. function course_filter_courses_by_favourites(
  3968. $courses,
  3969. $favouritecourseids,
  3970. int $limit = 0
  3971. ) : array {
  3972. $filteredcourses = [];
  3973. $numberofcoursesprocessed = 0;
  3974. $filtermatches = 0;
  3975. foreach ($courses as $course) {
  3976. $numberofcoursesprocessed++;
  3977. if (in_array($course->id, $favouritecourseids)) {
  3978. $filteredcourses[] = $course;
  3979. $filtermatches++;
  3980. }
  3981. if ($limit && $filtermatches >= $limit) {
  3982. // We've found the number of requested courses. No need to continue searching.
  3983. break;
  3984. }
  3985. }
  3986. // Return the number of filtered courses as well as the number of courses that were searched
  3987. // in order to find the matching courses. This allows the calling code to do some kind of
  3988. // pagination.
  3989. return [$filteredcourses, $numberofcoursesprocessed];
  3990. }
  3991. /**
  3992. * Search the given $courses for any that have a $customfieldname value that matches the given
  3993. * $customfieldvalue, up to the specified $limit.
  3994. *
  3995. * This function will return the subset of courses that matches the value as well as the
  3996. * number of courses it had to process to build that subset.
  3997. *
  3998. * It is recommended that for larger sets of courses this function is given a Generator that loads
  3999. * the courses from the database in chunks.
  4000. *
  4001. * @param array|Traversable $courses List of courses to process
  4002. * @param string $customfieldname the shortname of the custom field to match against
  4003. * @param string $customfieldvalue the value this custom field needs to match
  4004. * @param int $limit Limit the number of results to this amount
  4005. * @return array First value is the filtered courses, second value is the number of courses processed
  4006. */
  4007. function course_filter_courses_by_customfield(
  4008. $courses,
  4009. $customfieldname,
  4010. $customfieldvalue,
  4011. int $limit = 0
  4012. ) : array {
  4013. global $DB;
  4014. if (!$courses) {
  4015. return [[], 0];
  4016. }
  4017. // Prepare the list of courses to search through.
  4018. $coursesbyid = [];
  4019. foreach ($courses as $course) {
  4020. $coursesbyid[$course->id] = $course;
  4021. }
  4022. if (!$coursesbyid) {
  4023. return [[], 0];
  4024. }
  4025. list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
  4026. // Get the id of the custom field.
  4027. $sql = "
  4028. SELECT f.id
  4029. FROM {customfield_field} f
  4030. JOIN {customfield_category} cat ON cat.id = f.categoryid
  4031. WHERE f.shortname = ?
  4032. AND cat.component = 'core_course'
  4033. AND cat.area = 'course'
  4034. ";
  4035. $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
  4036. if (!$fieldid) {
  4037. return [[], 0];
  4038. }
  4039. // Get a list of courseids that match that custom field value.
  4040. if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
  4041. $comparevalue = $DB->sql_compare_text('cd.value');
  4042. $sql = "
  4043. SELECT c.id
  4044. FROM {course} c
  4045. LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
  4046. WHERE c.id $csql
  4047. AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
  4048. ";
  4049. $params['fieldid'] = $fieldid;
  4050. $matchcourseids = $DB->get_fieldset_sql($sql, $params);
  4051. } else {
  4052. $comparevalue = $DB->sql_compare_text('value');
  4053. $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
  4054. $params['fieldid'] = $fieldid;
  4055. $params['customfieldvalue'] = $customfieldvalue;
  4056. $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
  4057. }
  4058. // Prepare the list of courses to return.
  4059. $filteredcourses = [];
  4060. $numberofcoursesprocessed = 0;
  4061. $filtermatches = 0;
  4062. foreach ($coursesbyid as $course) {
  4063. $numberofcoursesprocessed++;
  4064. if (in_array($course->id, $matchcourseids)) {
  4065. $filteredcourses[] = $course;
  4066. $filtermatches++;
  4067. }
  4068. if ($limit && $filtermatches >= $limit) {
  4069. // We've found the number of requested courses. No need to continue searching.
  4070. break;
  4071. }
  4072. }
  4073. // Return the number of filtered courses as well as the number of courses that were searched
  4074. // in order to find the matching courses. This allows the calling code to do some kind of
  4075. // pagination.
  4076. return [$filteredcourses, $numberofcoursesprocessed];
  4077. }
  4078. /**
  4079. * Check module updates since a given time.
  4080. * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
  4081. *
  4082. * @param cm_info $cm course module data
  4083. * @param int $from the time to check
  4084. * @param array $fileareas additional file ares to check
  4085. * @param array $filter if we need to filter and return only selected updates
  4086. * @return stdClass object with the different updates
  4087. * @since Moodle 3.2
  4088. */
  4089. function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
  4090. global $DB, $CFG, $USER;
  4091. $context = $cm->context;
  4092. $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
  4093. $updates = new stdClass();
  4094. $course = get_course($cm->course);
  4095. $component = 'mod_' . $cm->modname;
  4096. // Check changes in the module configuration.
  4097. if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
  4098. $updates->configuration = (object) array('updated' => false);
  4099. if ($updates->configuration->updated = $mod->timemodified > $from) {
  4100. $updates->configuration->timeupdated = $mod->timemodified;
  4101. }
  4102. }
  4103. // Check for updates in files.
  4104. if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
  4105. $fileareas[] = 'intro';
  4106. }
  4107. if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
  4108. $fs = get_file_storage();
  4109. $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
  4110. foreach ($fileareas as $filearea) {
  4111. $updates->{$filearea . 'files'} = (object) array('updated' => false);
  4112. }
  4113. foreach ($files as $file) {
  4114. $updates->{$file->get_filearea() . 'files'}->updated = true;
  4115. $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
  4116. }
  4117. }
  4118. // Check completion.
  4119. $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
  4120. $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
  4121. if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
  4122. $updates->completion = (object) array('updated' => false);
  4123. $completion = new completion_info($course);
  4124. // Use wholecourse to cache all the modules the first time.
  4125. $completiondata = $completion->get_data($cm, true);
  4126. if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
  4127. $updates->completion->timemodified = $completiondata->timemodified;
  4128. }
  4129. }
  4130. // Check grades.
  4131. $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
  4132. $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
  4133. if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
  4134. require_once($CFG->libdir . '/gradelib.php');
  4135. $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
  4136. if (empty($filter) or in_array('gradeitems', $filter)) {
  4137. $updates->gradeitems = (object) array('updated' => false);
  4138. foreach ($grades->items as $gradeitem) {
  4139. foreach ($gradeitem->grades as $grade) {
  4140. if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
  4141. $updates->gradeitems->updated = true;
  4142. $updates->gradeitems->itemids[] = $gradeitem->id;
  4143. }
  4144. }
  4145. }
  4146. }
  4147. if (empty($filter) or in_array('outcomes', $filter)) {
  4148. $updates->outcomes = (object) array('updated' => false);
  4149. foreach ($grades->outcomes as $outcome) {
  4150. foreach ($outcome->grades as $grade) {
  4151. if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
  4152. $updates->outcomes->updated = true;
  4153. $updates->outcomes->itemids[] = $outcome->id;
  4154. }
  4155. }
  4156. }
  4157. }
  4158. }
  4159. // Check comments.
  4160. if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
  4161. $updates->comments = (object) array('updated' => false);
  4162. require_once($CFG->dirroot . '/comment/lib.php');
  4163. require_once($CFG->dirroot . '/comment/locallib.php');
  4164. $manager = new comment_manager();
  4165. $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
  4166. if (!empty($comments)) {
  4167. $updates->comments->updated = true;
  4168. $updates->comments->itemids = array_keys($comments);
  4169. }
  4170. }
  4171. // Check ratings.
  4172. if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
  4173. $updates->ratings = (object) array('updated' => false);
  4174. require_once($CFG->dirroot . '/rating/lib.php');
  4175. $manager = new rating_manager();
  4176. $ratings = $manager->get_component_ratings_since($context, $component, $from);
  4177. if (!empty($ratings)) {
  4178. $updates->ratings->updated = true;
  4179. $updates->ratings->itemids = array_keys($ratings);
  4180. }
  4181. }
  4182. return $updates;
  4183. }
  4184. /**
  4185. * Returns true if the user can view the participant page, false otherwise,
  4186. *
  4187. * @param context $context The context we are checking.
  4188. * @return bool
  4189. */
  4190. function course_can_view_participants($context) {
  4191. $viewparticipantscap = 'moodle/course:viewparticipants';
  4192. if ($context->contextlevel == CONTEXT_SYSTEM) {
  4193. $viewparticipantscap = 'moodle/site:viewparticipants';
  4194. }
  4195. return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
  4196. }
  4197. /**
  4198. * Checks if a user can view the participant page, if not throws an exception.
  4199. *
  4200. * @param context $context The context we are checking.
  4201. * @throws required_capability_exception
  4202. */
  4203. function course_require_view_participants($context) {
  4204. if (!course_can_view_participants($context)) {
  4205. $viewparticipantscap = 'moodle/course:viewparticipants';
  4206. if ($context->contextlevel == CONTEXT_SYSTEM) {
  4207. $viewparticipantscap = 'moodle/site:viewparticipants';
  4208. }
  4209. throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
  4210. }
  4211. }
  4212. /**
  4213. * Return whether the user can download from the specified backup file area in the given context.
  4214. *
  4215. * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
  4216. * @param \context $context
  4217. * @param stdClass $user the user object. If not provided, the current user will be checked.
  4218. * @return bool true if the user is allowed to download in the context, false otherwise.
  4219. */
  4220. function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
  4221. $candownload = false;
  4222. switch ($filearea) {
  4223. case 'course':
  4224. case 'backup':
  4225. $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
  4226. break;
  4227. case 'automated':
  4228. // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
  4229. // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
  4230. // doesn't make sense here.
  4231. $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
  4232. has_capability('moodle/restore:userinfo', $context, $user);
  4233. break;
  4234. default:
  4235. break;
  4236. }
  4237. return $candownload;
  4238. }
  4239. /**
  4240. * Get a list of hidden courses
  4241. *
  4242. * @param int|object|null $user User override to get the filter from. Defaults to current user
  4243. * @return array $ids List of hidden courses
  4244. * @throws coding_exception
  4245. */
  4246. function get_hidden_courses_on_timeline($user = null) {
  4247. global $USER;
  4248. if (empty($user)) {
  4249. $user = $USER->id;
  4250. }
  4251. $preferences = get_user_preferences(null, null, $user);
  4252. $ids = [];
  4253. foreach ($preferences as $key => $value) {
  4254. if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
  4255. $id = preg_split('/block_myoverview_hidden_course_/', $key);
  4256. $ids[] = $id[1];
  4257. }
  4258. }
  4259. return $ids;
  4260. }
  4261. /**
  4262. * Returns a list of the most recently courses accessed by a user
  4263. *
  4264. * @param int $userid User id from which the courses will be obtained
  4265. * @param int $limit Restrict result set to this amount
  4266. * @param int $offset Skip this number of records from the start of the result set
  4267. * @param string|null $sort SQL string for sorting
  4268. * @return array
  4269. */
  4270. function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
  4271. global $CFG, $USER, $DB;
  4272. if (empty($userid)) {
  4273. $userid = $USER->id;
  4274. }
  4275. $basefields = [
  4276. 'id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
  4277. 'shortname', 'fullname', 'timeaccess', 'component', 'visible',
  4278. 'showactivitydates', 'showcompletionconditions',
  4279. ];
  4280. if (empty($sort)) {
  4281. $sort = 'timeaccess DESC';
  4282. } else {
  4283. // The SQL string for sorting can define sorting by multiple columns.
  4284. $rawsorts = explode(',', $sort);
  4285. $sorts = array();
  4286. // Validate and trim the sort parameters in the SQL string for sorting.
  4287. foreach ($rawsorts as $rawsort) {
  4288. $sort = trim($rawsort);
  4289. $sortparams = explode(' ', $sort);
  4290. // A valid sort statement can not have more than 2 params (ex. 'summary desc' or 'timeaccess').
  4291. if (count($sortparams) > 2) {
  4292. throw new invalid_parameter_exception(
  4293. 'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].');
  4294. }
  4295. $sortfield = trim($sortparams[0]);
  4296. // Validate the value which defines the field to sort by.
  4297. if (!in_array($sortfield, $basefields)) {
  4298. throw new invalid_parameter_exception('Invalid field in the sort parameter, allowed fields: ' .
  4299. implode(', ', $basefields) . '.');
  4300. }
  4301. $sortdirection = isset($sortparams[1]) ? trim($sortparams[1]) : '';
  4302. // Validate the value which defines the sort direction (if present).
  4303. $allowedsortdirections = ['asc', 'desc'];
  4304. if (!empty($sortdirection) && !in_array(strtolower($sortdirection), $allowedsortdirections)) {
  4305. throw new invalid_parameter_exception('Invalid sort direction in the sort parameter, allowed values: ' .
  4306. implode(', ', $allowedsortdirections) . '.');
  4307. }
  4308. $sorts[] = $sort;
  4309. }
  4310. $sort = implode(',', $sorts);
  4311. }
  4312. $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
  4313. $coursefields = 'c.' . join(',', $basefields);
  4314. // Ask the favourites service to give us the join SQL for favourited courses,
  4315. // so we can include favourite information in the query.
  4316. $usercontext = \context_user::instance($userid);
  4317. $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
  4318. list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
  4319. $sql = "SELECT $coursefields, $ctxfields
  4320. FROM {course} c
  4321. JOIN {context} ctx
  4322. ON ctx.contextlevel = :contextlevel
  4323. AND ctx.instanceid = c.id
  4324. JOIN {user_lastaccess} ul
  4325. ON ul.courseid = c.id
  4326. $favsql
  4327. LEFT JOIN {enrol} eg ON eg.courseid = c.id AND eg.status = :statusenrolg AND eg.enrol = :guestenrol
  4328. WHERE ul.userid = :userid
  4329. AND c.visible = :visible
  4330. AND (eg.id IS NOT NULL
  4331. OR EXISTS (SELECT e.id
  4332. FROM {enrol} e
  4333. JOIN {user_enrolments} ue ON ue.enrolid = e.id
  4334. WHERE e.courseid = c.id
  4335. AND e.status = :statusenrol
  4336. AND ue.status = :status
  4337. AND ue.userid = :userid2
  4338. AND ue.timestart < :now1
  4339. AND (ue.timeend = 0 OR ue.timeend > :now2)
  4340. ))
  4341. ORDER BY $sort";
  4342. $now = round(time(), -2); // Improves db caching.
  4343. $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
  4344. 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now,
  4345. 'userid2' => $userid, 'statusenrolg' => ENROL_INSTANCE_ENABLED] + $favparams;
  4346. $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
  4347. // Filter courses if last access field is hidden.
  4348. $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
  4349. if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
  4350. $recentcourses = array_filter($recentcourses, function($course) {
  4351. context_helper::preload_from_record($course);
  4352. $context = context_course::instance($course->id, IGNORE_MISSING);
  4353. // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
  4354. // fields.
  4355. return has_capability('moodle/course:viewhiddenuserfields', $context);
  4356. });
  4357. }
  4358. return $recentcourses;
  4359. }
  4360. /**
  4361. * Calculate the course start date and offset for the given user ids.
  4362. *
  4363. * If the course is a fixed date course then the course start date will be returned.
  4364. * If the course is a relative date course then the course date will be calculated and
  4365. * and offset provided.
  4366. *
  4367. * The dates are returned as an array with the index being the user id. The array
  4368. * contains the start date and start offset values for the user.
  4369. *
  4370. * If the user is not enrolled in the course then the course start date will be returned.
  4371. *
  4372. * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
  4373. * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
  4374. * return value would look like:
  4375. * [
  4376. * '123' => [
  4377. * 'start' => 1563244693,
  4378. * 'startoffset' => 693
  4379. * ],
  4380. * '456' => [
  4381. * 'start' => 1563244000,
  4382. * 'startoffset' => 0
  4383. * ]
  4384. * ]
  4385. *
  4386. * @param stdClass $course The course to fetch dates for.
  4387. * @param array $userids The list of user ids to get dates for.
  4388. * @return array
  4389. */
  4390. function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
  4391. if (empty($course->relativedatesmode)) {
  4392. // This course isn't set to relative dates so we can early return with the course
  4393. // start date.
  4394. return array_reduce($userids, function($carry, $userid) use ($course) {
  4395. $carry[$userid] = [
  4396. 'start' => $course->startdate,
  4397. 'startoffset' => 0
  4398. ];
  4399. return $carry;
  4400. }, []);
  4401. }
  4402. // We're dealing with a relative dates course now so we need to calculate some dates.
  4403. $cache = cache::make('core', 'course_user_dates');
  4404. $dates = [];
  4405. $uncacheduserids = [];
  4406. // Try fetching the values from the cache so that we don't need to do a DB request.
  4407. foreach ($userids as $userid) {
  4408. $cachekey = "{$course->id}_{$userid}";
  4409. $cachedvalue = $cache->get($cachekey);
  4410. if ($cachedvalue === false) {
  4411. // Looks like we haven't seen this user for this course before so we'll have
  4412. // to fetch it.
  4413. $uncacheduserids[] = $userid;
  4414. } else {
  4415. [$start, $startoffset] = $cachedvalue;
  4416. $dates[$userid] = [
  4417. 'start' => $start,
  4418. 'startoffset' => $startoffset
  4419. ];
  4420. }
  4421. }
  4422. if (!empty($uncacheduserids)) {
  4423. // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
  4424. // to false because it filters out users with enrolment start times in the future which
  4425. // we don't want.
  4426. $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
  4427. foreach ($uncacheduserids as $userid) {
  4428. // Find the user enrolment that has the earliest start date.
  4429. $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
  4430. // Only consider enrolments for this user if the user enrolment is active and the
  4431. // enrolment method is enabled.
  4432. if (
  4433. $enrolment->uestatus == ENROL_USER_ACTIVE &&
  4434. $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
  4435. $enrolment->id == $userid
  4436. ) {
  4437. if (is_null($carry)) {
  4438. // Haven't found an enrolment yet for this user so use the one we just found.
  4439. $carry = $enrolment;
  4440. } else {
  4441. // We've already found an enrolment for this user so let's use which ever one
  4442. // has the earliest start time.
  4443. $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
  4444. }
  4445. }
  4446. return $carry;
  4447. }, null);
  4448. if ($enrolment) {
  4449. // The course is in relative dates mode so we calculate the student's start
  4450. // date based on their enrolment start date.
  4451. $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
  4452. $startoffset = $start - $course->startdate;
  4453. } else {
  4454. // The user is not enrolled in the course so default back to the course start date.
  4455. $start = $course->startdate;
  4456. $startoffset = 0;
  4457. }
  4458. $dates[$userid] = [
  4459. 'start' => $start,
  4460. 'startoffset' => $startoffset
  4461. ];
  4462. $cachekey = "{$course->id}_{$userid}";
  4463. $cache->set($cachekey, [$start, $startoffset]);
  4464. }
  4465. }
  4466. return $dates;
  4467. }
  4468. /**
  4469. * Calculate the course start date and offset for the given user id.
  4470. *
  4471. * If the course is a fixed date course then the course start date will be returned.
  4472. * If the course is a relative date course then the course date will be calculated and
  4473. * and offset provided.
  4474. *
  4475. * The return array contains the start date and start offset values for the user.
  4476. *
  4477. * If the user is not enrolled in the course then the course start date will be returned.
  4478. *
  4479. * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
  4480. * then the return would be:
  4481. * [
  4482. * 'start' => 1563244693,
  4483. * 'startoffset' => 693
  4484. * ]
  4485. *
  4486. * If the use was not enrolled then the return would be:
  4487. * [
  4488. * 'start' => 1563244000,
  4489. * 'startoffset' => 0
  4490. * ]
  4491. *
  4492. * @param stdClass $course The course to fetch dates for.
  4493. * @param int $userid The user id to get dates for.
  4494. * @return array
  4495. */
  4496. function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
  4497. return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
  4498. }
  4499. /**
  4500. * Renders the course copy form for the modal on the course management screen.
  4501. *
  4502. * @param array $args
  4503. * @return string $o Form HTML.
  4504. */
  4505. function course_output_fragment_new_base_form($args) {
  4506. $serialiseddata = json_decode($args['jsonformdata'], true);
  4507. $formdata = [];
  4508. if (!empty($serialiseddata)) {
  4509. parse_str($serialiseddata, $formdata);
  4510. }
  4511. $context = context_course::instance($args['courseid']);
  4512. $copycaps = \core_course\management\helper::get_course_copy_capabilities();
  4513. require_all_capabilities($copycaps, $context);
  4514. $course = get_course($args['courseid']);
  4515. $mform = new \core_backup\output\copy_form(
  4516. null,
  4517. array('course' => $course, 'returnto' => '', 'returnurl' => ''),
  4518. 'post', '', ['class' => 'ignoredirty'], true, $formdata);
  4519. if (!empty($serialiseddata)) {
  4520. // If we were passed non-empty form data we want the mform to call validation functions and show errors.
  4521. $mform->is_validated();
  4522. }
  4523. ob_start();
  4524. $mform->display();
  4525. $o = ob_get_contents();
  4526. ob_end_clean();
  4527. return $o;
  4528. }