PageRenderTime 46ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/MoodleWebRole/lib/datalib.php

#
PHP | 2288 lines | 1290 code | 290 blank | 708 comment | 314 complexity | b929cdf5400bb2e31fc3e2a071b93b41 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, LGPL-2.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php // $Id$
  2. /**
  3. * Library of functions for database manipulation.
  4. *
  5. * Other main libraries:
  6. * - weblib.php - functions that produce web output
  7. * - moodlelib.php - general-purpose Moodle functions
  8. * @author Martin Dougiamas and many others
  9. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  10. * @package moodlecore
  11. */
  12. /// Some constants
  13. define('LASTACCESS_UPDATE_SECS', 60); /// Number of seconds to wait before
  14. /// updating lastaccess information in DB.
  15. /**
  16. * Escape all dangerous characters in a data record
  17. *
  18. * $dataobject is an object containing needed data
  19. * Run over each field exectuting addslashes() function
  20. * to escape SQL unfriendly characters (e.g. quotes)
  21. * Handy when writing back data read from the database
  22. *
  23. * @param $dataobject Object containing the database record
  24. * @return object Same object with neccessary characters escaped
  25. */
  26. function addslashes_object( $dataobject ) {
  27. $a = get_object_vars( $dataobject);
  28. foreach ($a as $key=>$value) {
  29. $a[$key] = addslashes( $value );
  30. }
  31. return (object)$a;
  32. }
  33. /// USER DATABASE ////////////////////////////////////////////////
  34. /**
  35. * Returns $user object of the main admin user
  36. * primary admin = admin with lowest role_assignment id among admins
  37. * @uses $CFG
  38. * @return object(admin) An associative array representing the admin user.
  39. */
  40. function get_admin () {
  41. static $myadmin;
  42. if (! isset($admin)) {
  43. if (! $admins = get_admins()) {
  44. return false;
  45. }
  46. $admin = reset($admins);//reset returns first element
  47. }
  48. return $admin;
  49. }
  50. /**
  51. * Returns list of all admins, using 1 DB query. It depends on DB schema v1.7
  52. * but does not depend on the v1.9 datastructures (context.path, etc).
  53. *
  54. * @uses $CFG
  55. * @return object
  56. */
  57. function get_admins() {
  58. global $CFG;
  59. $sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid
  60. FROM " . $CFG->prefix . "role_capabilities rc
  61. JOIN " . $CFG->prefix . "context ctx
  62. ON ctx.id=rc.contextid
  63. JOIN " . $CFG->prefix . "role_assignments ra
  64. ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
  65. WHERE ctx.contextlevel=10
  66. AND rc.capability IN ('moodle/site:config',
  67. 'moodle/legacy:admin',
  68. 'moodle/site:doanything')
  69. GROUP BY ra.userid
  70. HAVING SUM(rc.permission) > 0";
  71. $sql = "SELECT u.*, ra.adminid
  72. FROM " . $CFG->prefix . "user u
  73. JOIN ($sql) ra
  74. ON u.id=ra.userid
  75. ORDER BY ra.adminid ASC";
  76. return get_records_sql($sql);
  77. }
  78. function get_courses_in_metacourse($metacourseid) {
  79. global $CFG;
  80. $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
  81. AND mc.child_course = c.id ORDER BY c.shortname";
  82. return get_records_sql($sql);
  83. }
  84. function get_courses_notin_metacourse($metacourseid,$count=false) {
  85. global $CFG;
  86. if ($count) {
  87. $sql = "SELECT COUNT(c.id)";
  88. } else {
  89. $sql = "SELECT c.id,c.shortname,c.fullname";
  90. }
  91. $alreadycourses = get_courses_in_metacourse($metacourseid);
  92. $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
  93. AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
  94. return get_records_sql($sql);
  95. }
  96. function count_courses_notin_metacourse($metacourseid) {
  97. global $CFG;
  98. $alreadycourses = get_courses_in_metacourse($metacourseid);
  99. $sql = "SELECT COUNT(c.id) AS notin FROM {$CFG->prefix}course c
  100. WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
  101. AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1";
  102. if (!$count = get_record_sql($sql)) {
  103. return 0;
  104. }
  105. return $count->notin;
  106. }
  107. /**
  108. * Search through course users
  109. *
  110. * If $coursid specifies the site course then this function searches
  111. * through all undeleted and confirmed users
  112. *
  113. * @uses $CFG
  114. * @uses SITEID
  115. * @param int $courseid The course in question.
  116. * @param int $groupid The group in question.
  117. * @param string $searchtext ?
  118. * @param string $sort ?
  119. * @param string $exceptions ?
  120. * @return object
  121. */
  122. function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
  123. global $CFG;
  124. $LIKE = sql_ilike();
  125. $fullname = sql_fullname('u.firstname', 'u.lastname');
  126. if (!empty($exceptions)) {
  127. $except = ' AND u.id NOT IN ('. $exceptions .') ';
  128. } else {
  129. $except = '';
  130. }
  131. if (!empty($sort)) {
  132. $order = ' ORDER BY '. $sort;
  133. } else {
  134. $order = '';
  135. }
  136. $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
  137. if (!$courseid or $courseid == SITEID) {
  138. return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
  139. FROM {$CFG->prefix}user u
  140. WHERE $select
  141. AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
  142. $except $order");
  143. } else {
  144. if ($groupid) {
  145. //TODO:check. Remove group DB dependencies.
  146. return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
  147. FROM {$CFG->prefix}user u,
  148. {$CFG->prefix}groups_members gm
  149. WHERE $select AND gm.groupid = '$groupid' AND gm.userid = u.id
  150. AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
  151. $except $order");
  152. } else {
  153. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  154. $contextlists = get_related_contexts_string($context);
  155. $users = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
  156. FROM {$CFG->prefix}user u,
  157. {$CFG->prefix}role_assignments ra
  158. WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id
  159. AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
  160. $except $order");
  161. }
  162. return $users;
  163. }
  164. }
  165. /**
  166. * Returns a list of all site users
  167. * Obsolete, just calls get_course_users(SITEID)
  168. *
  169. * @uses SITEID
  170. * @deprecated Use {@link get_course_users()} instead.
  171. * @param string $fields A comma separated list of fields to be returned from the chosen table.
  172. * @param string $exceptions A comma separated list of user->id to be skiped in the result returned by the function
  173. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  174. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  175. * @return object|false {@link $USER} records or false if error.
  176. */
  177. function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='', $limitfrom='', $limitnum='') {
  178. return get_course_users(SITEID, $sort, $exceptions, $fields, $limitfrom, $limitnum);
  179. }
  180. /**
  181. * Returns a subset of users
  182. *
  183. * @uses $CFG
  184. * @param bool $get If false then only a count of the records is returned
  185. * @param string $search A simple string to search for
  186. * @param bool $confirmed A switch to allow/disallow unconfirmed users
  187. * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
  188. * @param string $sort A SQL snippet for the sorting criteria to use
  189. * @param string $firstinitial ?
  190. * @param string $lastinitial ?
  191. * @param string $page ?
  192. * @param string $recordsperpage ?
  193. * @param string $fields A comma separated list of fields to be returned from the chosen table.
  194. * @return object|false|int {@link $USER} records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.
  195. */
  196. function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
  197. $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='') {
  198. global $CFG;
  199. if ($get && !$recordsperpage) {
  200. debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
  201. 'On large installations, this will probably cause an out of memory error. ' .
  202. 'Please think again and change your code so that it does not try to ' .
  203. 'load so much data into memory.', DEBUG_DEVELOPER);
  204. }
  205. $LIKE = sql_ilike();
  206. $fullname = sql_fullname();
  207. $select = 'username <> \'guest\' AND deleted = 0';
  208. if (!empty($search)){
  209. $search = trim($search);
  210. $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
  211. }
  212. if ($confirmed) {
  213. $select .= ' AND confirmed = \'1\' ';
  214. }
  215. if ($exceptions) {
  216. $select .= ' AND id NOT IN ('. $exceptions .') ';
  217. }
  218. if ($firstinitial) {
  219. $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
  220. }
  221. if ($lastinitial) {
  222. $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
  223. }
  224. if ($extraselect) {
  225. $select .= " AND $extraselect ";
  226. }
  227. if ($get) {
  228. return get_records_select('user', $select, $sort, $fields, $page, $recordsperpage);
  229. } else {
  230. return count_records_select('user', $select);
  231. }
  232. }
  233. /**
  234. * shortdesc (optional)
  235. *
  236. * longdesc
  237. *
  238. * @uses $CFG
  239. * @param string $sort ?
  240. * @param string $dir ?
  241. * @param int $categoryid ?
  242. * @param int $categoryid ?
  243. * @param string $search ?
  244. * @param string $firstinitial ?
  245. * @param string $lastinitial ?
  246. * @returnobject {@link $USER} records
  247. * @todo Finish documenting this function
  248. */
  249. function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
  250. $search='', $firstinitial='', $lastinitial='', $extraselect='') {
  251. global $CFG;
  252. $LIKE = sql_ilike();
  253. $fullname = sql_fullname();
  254. $select = "deleted <> '1'";
  255. if (!empty($search)) {
  256. $search = trim($search);
  257. $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
  258. }
  259. if ($firstinitial) {
  260. $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
  261. }
  262. if ($lastinitial) {
  263. $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
  264. }
  265. if ($extraselect) {
  266. $select .= " AND $extraselect ";
  267. }
  268. if ($sort) {
  269. $sort = ' ORDER BY '. $sort .' '. $dir;
  270. }
  271. /// warning: will return UNCONFIRMED USERS
  272. return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
  273. FROM {$CFG->prefix}user
  274. WHERE $select $sort", $page, $recordsperpage);
  275. }
  276. /**
  277. * Full list of users that have confirmed their accounts.
  278. *
  279. * @uses $CFG
  280. * @return object
  281. */
  282. function get_users_confirmed() {
  283. global $CFG;
  284. return get_records_sql("SELECT *
  285. FROM {$CFG->prefix}user
  286. WHERE confirmed = 1
  287. AND deleted = 0
  288. AND username <> 'guest'");
  289. }
  290. /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
  291. /**
  292. * Returns $course object of the top-level site.
  293. *
  294. * @return course A {@link $COURSE} object for the site
  295. */
  296. function get_site() {
  297. global $SITE;
  298. if (!empty($SITE->id)) { // We already have a global to use, so return that
  299. return $SITE;
  300. }
  301. if ($course = get_record('course', 'category', 0)) {
  302. return $course;
  303. } else {
  304. return false;
  305. }
  306. }
  307. /**
  308. * Returns list of courses, for whole site, or category
  309. *
  310. * Returns list of courses, for whole site, or category
  311. * Important: Using c.* for fields is extremely expensive because
  312. * we are using distinct. You almost _NEVER_ need all the fields
  313. * in such a large SELECT
  314. *
  315. * @param type description
  316. *
  317. */
  318. function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
  319. global $USER, $CFG;
  320. if ($categoryid != "all" && is_numeric($categoryid)) {
  321. $categoryselect = "WHERE c.category = '$categoryid'";
  322. } else {
  323. $categoryselect = "";
  324. }
  325. if (empty($sort)) {
  326. $sortstatement = "";
  327. } else {
  328. $sortstatement = "ORDER BY $sort";
  329. }
  330. $visiblecourses = array();
  331. // pull out all course matching the cat
  332. if ($courses = get_records_sql("SELECT $fields,
  333. ctx.id AS ctxid, ctx.path AS ctxpath,
  334. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  335. FROM {$CFG->prefix}course c
  336. JOIN {$CFG->prefix}context ctx
  337. ON (c.id = ctx.instanceid
  338. AND ctx.contextlevel=".CONTEXT_COURSE.")
  339. $categoryselect
  340. $sortstatement")) {
  341. // loop throught them
  342. foreach ($courses as $course) {
  343. $course = make_context_subobj($course);
  344. if (isset($course->visible) && $course->visible <= 0) {
  345. // for hidden courses, require visibility check
  346. if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
  347. $visiblecourses [] = $course;
  348. }
  349. } else {
  350. $visiblecourses [] = $course;
  351. }
  352. }
  353. }
  354. return $visiblecourses;
  355. /*
  356. $teachertable = "";
  357. $visiblecourses = "";
  358. $sqland = "";
  359. if (!empty($categoryselect)) {
  360. $sqland = "AND ";
  361. }
  362. if (!empty($USER->id)) { // May need to check they are a teacher
  363. if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
  364. $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
  365. $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
  366. }
  367. } else {
  368. $visiblecourses = "$sqland c.visible > 0";
  369. }
  370. if ($categoryselect or $visiblecourses) {
  371. $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
  372. } else {
  373. $selectsql = "{$CFG->prefix}course c $teachertable";
  374. }
  375. $extrafield = str_replace('ASC','',$sort);
  376. $extrafield = str_replace('DESC','',$extrafield);
  377. $extrafield = trim($extrafield);
  378. if (!empty($extrafield)) {
  379. $extrafield = ','.$extrafield;
  380. }
  381. return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
  382. */
  383. }
  384. /**
  385. * Returns list of courses, for whole site, or category
  386. *
  387. * Similar to get_courses, but allows paging
  388. * Important: Using c.* for fields is extremely expensive because
  389. * we are using distinct. You almost _NEVER_ need all the fields
  390. * in such a large SELECT
  391. *
  392. * @param type description
  393. *
  394. */
  395. function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
  396. &$totalcount, $limitfrom="", $limitnum="") {
  397. global $USER, $CFG;
  398. $categoryselect = "";
  399. if ($categoryid != "all" && is_numeric($categoryid)) {
  400. $categoryselect = "WHERE c.category = '$categoryid'";
  401. } else {
  402. $categoryselect = "";
  403. }
  404. // pull out all course matching the cat
  405. $visiblecourses = array();
  406. if (!($rs = get_recordset_sql("SELECT $fields,
  407. ctx.id AS ctxid, ctx.path AS ctxpath,
  408. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  409. FROM {$CFG->prefix}course c
  410. JOIN {$CFG->prefix}context ctx
  411. ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  412. $categoryselect
  413. ORDER BY $sort"))) {
  414. return $visiblecourses;
  415. }
  416. $totalcount = 0;
  417. if (!$limitfrom) {
  418. $limitfrom = 0;
  419. }
  420. // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
  421. while ($course = rs_fetch_next_record($rs)) {
  422. $course = make_context_subobj($course);
  423. if ($course->visible <= 0) {
  424. // for hidden courses, require visibility check
  425. if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
  426. $totalcount++;
  427. if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
  428. $visiblecourses [] = $course;
  429. }
  430. }
  431. } else {
  432. $totalcount++;
  433. if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
  434. $visiblecourses [] = $course;
  435. }
  436. }
  437. }
  438. rs_close($rs);
  439. return $visiblecourses;
  440. /**
  441. $categoryselect = "";
  442. if ($categoryid != "all" && is_numeric($categoryid)) {
  443. $categoryselect = "c.category = '$categoryid'";
  444. }
  445. $teachertable = "";
  446. $visiblecourses = "";
  447. $sqland = "";
  448. if (!empty($categoryselect)) {
  449. $sqland = "AND ";
  450. }
  451. if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
  452. if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
  453. $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
  454. $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
  455. }
  456. } else {
  457. $visiblecourses = "$sqland c.visible > 0";
  458. }
  459. if ($limitfrom !== "") {
  460. $limit = sql_paging_limit($limitfrom, $limitnum);
  461. } else {
  462. $limit = "";
  463. }
  464. $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
  465. $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
  466. return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
  467. */
  468. }
  469. /*
  470. * Retrieve course records with the course managers and other related records
  471. * that we need for print_course(). This allows print_courses() to do its job
  472. * in a constant number of DB queries, regardless of the number of courses,
  473. * role assignments, etc.
  474. *
  475. * The returned array is indexed on c.id, and each course will have
  476. * - $course->context - a context obj
  477. * - $course->managers - array containing RA objects that include a $user obj
  478. * with the minimal fields needed for fullname()
  479. *
  480. */
  481. function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
  482. /*
  483. * The plan is to
  484. *
  485. * - Grab the courses JOINed w/context
  486. *
  487. * - Grab the interesting course-manager RAs
  488. * JOINed with a base user obj and add them to each course
  489. *
  490. * So as to do all the work in 2 DB queries. The RA+user JOIN
  491. * ends up being pretty expensive if it happens over _all_
  492. * courses on a large site. (Are we surprised!?)
  493. *
  494. * So this should _never_ get called with 'all' on a large site.
  495. *
  496. */
  497. global $USER, $CFG;
  498. $allcats = false; // bool flag
  499. if ($categoryid === 'all') {
  500. $categoryclause = '';
  501. $allcats = true;
  502. } elseif (is_numeric($categoryid)) {
  503. $categoryclause = "c.category = $categoryid";
  504. } else {
  505. debugging("Could not recognise categoryid = $categoryid");
  506. $categoryclause = '';
  507. }
  508. $basefields = array('id', 'category', 'sortorder',
  509. 'shortname', 'fullname', 'idnumber',
  510. 'teacher', 'teachers', 'student', 'students',
  511. 'guest', 'startdate', 'visible',
  512. 'newsitems', 'cost', 'enrol',
  513. 'groupmode', 'groupmodeforce');
  514. if (!is_null($fields) && is_string($fields)) {
  515. if (empty($fields)) {
  516. $fields = $basefields;
  517. } else {
  518. // turn the fields from a string to an array that
  519. // get_user_courses_bycap() will like...
  520. $fields = explode(',',$fields);
  521. $fields = array_map('trim', $fields);
  522. $fields = array_unique(array_merge($basefields, $fields));
  523. }
  524. } elseif (is_array($fields)) {
  525. $fields = array_merge($basefields,$fields);
  526. }
  527. $coursefields = 'c.' .join(',c.', $fields);
  528. if (empty($sort)) {
  529. $sortstatement = "";
  530. } else {
  531. $sortstatement = "ORDER BY $sort";
  532. }
  533. $where = 'WHERE c.id != ' . SITEID;
  534. if ($categoryclause !== ''){
  535. $where = "$where AND $categoryclause";
  536. }
  537. // pull out all courses matching the cat
  538. $sql = "SELECT $coursefields,
  539. ctx.id AS ctxid, ctx.path AS ctxpath,
  540. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  541. FROM {$CFG->prefix}course c
  542. JOIN {$CFG->prefix}context ctx
  543. ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  544. $where
  545. $sortstatement";
  546. $catpaths = array();
  547. $catpath = NULL;
  548. if ($courses = get_records_sql($sql)) {
  549. // loop on courses materialising
  550. // the context, and prepping data to fetch the
  551. // managers efficiently later...
  552. foreach ($courses as $k => $course) {
  553. $courses[$k] = make_context_subobj($courses[$k]);
  554. $courses[$k]->managers = array();
  555. if ($allcats === false) {
  556. // single cat, so take just the first one...
  557. if ($catpath === NULL) {
  558. $catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
  559. }
  560. } else {
  561. // chop off the contextid of the course itself
  562. // like dirname() does...
  563. $catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
  564. }
  565. }
  566. } else {
  567. return array(); // no courses!
  568. }
  569. $CFG->coursemanager = trim($CFG->coursemanager);
  570. if (empty($CFG->coursemanager)) {
  571. return $courses;
  572. }
  573. $managerroles = split(',', $CFG->coursemanager);
  574. $catctxids = '';
  575. if (count($managerroles)) {
  576. if ($allcats === true) {
  577. $catpaths = array_unique($catpaths);
  578. $ctxids = array();
  579. foreach ($catpaths as $cpath) {
  580. $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
  581. }
  582. $ctxids = array_unique($ctxids);
  583. $catctxids = implode( ',' , $ctxids);
  584. unset($catpaths);
  585. unset($cpath);
  586. } else {
  587. // take the ctx path from the first course
  588. // as all categories will be the same...
  589. $catpath = substr($catpath,1);
  590. $catpath = preg_replace(':/\d+$:','',$catpath);
  591. $catctxids = str_replace('/',',',$catpath);
  592. }
  593. if ($categoryclause !== '') {
  594. $categoryclause = "AND $categoryclause";
  595. }
  596. /*
  597. * Note: Here we use a LEFT OUTER JOIN that can
  598. * "optionally" match to avoid passing a ton of context
  599. * ids in an IN() clause. Perhaps a subselect is faster.
  600. *
  601. * In any case, this SQL is not-so-nice over large sets of
  602. * courses with no $categoryclause.
  603. *
  604. */
  605. $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
  606. ra.hidden,
  607. r.id AS roleid, r.name as rolename,
  608. u.id AS userid, u.firstname, u.lastname
  609. FROM {$CFG->prefix}role_assignments ra
  610. JOIN {$CFG->prefix}context ctx
  611. ON ra.contextid = ctx.id
  612. JOIN {$CFG->prefix}user u
  613. ON ra.userid = u.id
  614. JOIN {$CFG->prefix}role r
  615. ON ra.roleid = r.id
  616. LEFT OUTER JOIN {$CFG->prefix}course c
  617. ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
  618. WHERE ( c.id IS NOT NULL";
  619. // under certain conditions, $catctxids is NULL
  620. if($catctxids == NULL){
  621. $sql .= ") ";
  622. }else{
  623. $sql .= " OR ra.contextid IN ($catctxids) )";
  624. }
  625. $sql .= "AND ra.roleid IN ({$CFG->coursemanager})
  626. $categoryclause
  627. ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
  628. $rs = get_recordset_sql($sql);
  629. // This loop is fairly stupid as it stands - might get better
  630. // results doing an initial pass clustering RAs by path.
  631. while ($ra = rs_fetch_next_record($rs)) {
  632. $user = new StdClass;
  633. $user->id = $ra->userid; unset($ra->userid);
  634. $user->firstname = $ra->firstname; unset($ra->firstname);
  635. $user->lastname = $ra->lastname; unset($ra->lastname);
  636. $ra->user = $user;
  637. if ($ra->contextlevel == CONTEXT_SYSTEM) {
  638. foreach ($courses as $k => $course) {
  639. $courses[$k]->managers[] = $ra;
  640. }
  641. } elseif ($ra->contextlevel == CONTEXT_COURSECAT) {
  642. if ($allcats === false) {
  643. // It always applies
  644. foreach ($courses as $k => $course) {
  645. $courses[$k]->managers[] = $ra;
  646. }
  647. } else {
  648. foreach ($courses as $k => $course) {
  649. // Note that strpos() returns 0 as "matched at pos 0"
  650. if (strpos($course->context->path, $ra->path.'/')===0) {
  651. // Only add it to subpaths
  652. $courses[$k]->managers[] = $ra;
  653. }
  654. }
  655. }
  656. } else { // course-level
  657. if(!array_key_exists($ra->instanceid, $courses)) {
  658. //this course is not in a list, probably a frontpage course
  659. continue;
  660. }
  661. $courses[$ra->instanceid]->managers[] = $ra;
  662. }
  663. }
  664. rs_close($rs);
  665. }
  666. return $courses;
  667. }
  668. /**
  669. * Convenience function - lists courses that a user has access to view.
  670. *
  671. * For admins and others with access to "every" course in the system, we should
  672. * try to get courses with explicit RAs.
  673. *
  674. * NOTE: this function is heavily geared towards the perspective of the user
  675. * passed in $userid. So it will hide courses that the user cannot see
  676. * (for any reason) even if called from cron or from another $USER's
  677. * perspective.
  678. *
  679. * If you really want to know what courses are assigned to the user,
  680. * without any hiding or scheming, call the lower-level
  681. * get_user_courses_bycap().
  682. *
  683. *
  684. * Notes inherited from get_user_courses_bycap():
  685. *
  686. * - $fields is an array of fieldnames to ADD
  687. * so name the fields you really need, which will
  688. * be added and uniq'd
  689. *
  690. * - the course records have $c->context which is a fully
  691. * valid context object. Saves you a query per course!
  692. *
  693. * @uses $CFG,$USER
  694. * @param int $userid The user of interest
  695. * @param string $sort the sortorder in the course table
  696. * @param array $fields - names of _additional_ fields to return (also accepts a string)
  697. * @param bool $doanything True if using the doanything flag
  698. * @param int $limit Maximum number of records to return, or 0 for unlimited
  699. * @return array {@link $COURSE} of course objects
  700. */
  701. function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
  702. global $CFG,$USER;
  703. // Guest's do not have any courses
  704. $sitecontext = get_context_instance(CONTEXT_SYSTEM);
  705. if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
  706. return(array());
  707. }
  708. $basefields = array('id', 'category', 'sortorder',
  709. 'shortname', 'fullname', 'idnumber',
  710. 'teacher', 'teachers', 'student', 'students',
  711. 'guest', 'startdate', 'visible',
  712. 'newsitems', 'cost', 'enrol',
  713. 'groupmode', 'groupmodeforce');
  714. if (!is_null($fields) && is_string($fields)) {
  715. if (empty($fields)) {
  716. $fields = $basefields;
  717. } else {
  718. // turn the fields from a string to an array that
  719. // get_user_courses_bycap() will like...
  720. $fields = explode(',',$fields);
  721. $fields = array_map('trim', $fields);
  722. $fields = array_unique(array_merge($basefields, $fields));
  723. }
  724. } elseif (is_array($fields)) {
  725. $fields = array_unique(array_merge($basefields, $fields));
  726. } else {
  727. $fields = $basefields;
  728. }
  729. $orderby = '';
  730. $sort = trim($sort);
  731. if (!empty($sort)) {
  732. $rawsorts = explode(',', $sort);
  733. $sorts = array();
  734. foreach ($rawsorts as $rawsort) {
  735. $rawsort = trim($rawsort);
  736. if (strpos($rawsort, 'c.') === 0) {
  737. $rawsort = substr($rawsort, 2);
  738. }
  739. $sorts[] = trim($rawsort);
  740. }
  741. $sort = 'c.'.implode(',c.', $sorts);
  742. $orderby = "ORDER BY $sort";
  743. }
  744. //
  745. // Logged-in user - Check cached courses
  746. //
  747. // NOTE! it's a _string_ because
  748. // - it's all we'll ever use
  749. // - it serialises much more compact than an array
  750. // this a big concern here - cost of serialise
  751. // and unserialise gets huge as the session grows
  752. //
  753. // If the courses are too many - it won't be set
  754. // for large numbers of courses, caching in the session
  755. // has marginal benefits (costs too much, not
  756. // worthwhile...) and we may hit SQL parser limits
  757. // because we use IN()
  758. //
  759. if ($userid === $USER->id) {
  760. if (isset($USER->loginascontext)
  761. && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
  762. // list _only_ this course
  763. // anything else is asking for trouble...
  764. $courseids = $USER->loginascontext->instanceid;
  765. } elseif (isset($USER->mycourses)
  766. && is_string($USER->mycourses)) {
  767. if ($USER->mycourses === '') {
  768. // empty str means: user has no courses
  769. // ... so do the easy thing...
  770. return array();
  771. } else {
  772. $courseids = $USER->mycourses;
  773. }
  774. }
  775. if (isset($courseids)) {
  776. // The data massaging here MUST be kept in sync with
  777. // get_user_courses_bycap() so we return
  778. // the same...
  779. // (but here we don't need to check has_cap)
  780. $coursefields = 'c.' .join(',c.', $fields);
  781. $sql = "SELECT $coursefields,
  782. ctx.id AS ctxid, ctx.path AS ctxpath,
  783. ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
  784. cc.path AS categorypath
  785. FROM {$CFG->prefix}course c
  786. JOIN {$CFG->prefix}course_categories cc
  787. ON c.category=cc.id
  788. JOIN {$CFG->prefix}context ctx
  789. ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  790. WHERE c.id IN ($courseids)
  791. $orderby";
  792. $rs = get_recordset_sql($sql);
  793. $courses = array();
  794. $cc = 0; // keep count
  795. while ($c = rs_fetch_next_record($rs)) {
  796. // build the context obj
  797. $c = make_context_subobj($c);
  798. if ($limit > 0 && $cc >= $limit) {
  799. break;
  800. }
  801. $courses[$c->id] = $c;
  802. $cc++;
  803. }
  804. rs_close($rs);
  805. return $courses;
  806. }
  807. }
  808. // Non-cached - get accessinfo
  809. if ($userid === $USER->id && isset($USER->access)) {
  810. $accessinfo = $USER->access;
  811. } else {
  812. $accessinfo = get_user_access_sitewide($userid);
  813. }
  814. $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
  815. $doanything, $sort, $fields,
  816. $limit);
  817. $cats = NULL;
  818. // If we have to walk category visibility
  819. // to eval course visibility, get the categories
  820. if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
  821. $sql = "SELECT cc.id, cc.path, cc.visible,
  822. ctx.id AS ctxid, ctx.path AS ctxpath,
  823. ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
  824. FROM {$CFG->prefix}course_categories cc
  825. JOIN {$CFG->prefix}context ctx ON (cc.id = ctx.instanceid)
  826. WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
  827. ORDER BY cc.id";
  828. $rs = get_recordset_sql($sql);
  829. // Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
  830. $categories = array();
  831. while ($course_cat = rs_fetch_next_record($rs)) {
  832. // build the context obj
  833. $course_cat = make_context_subobj($course_cat);
  834. $categories[$course_cat->id] = $course_cat;
  835. }
  836. rs_close($rs);
  837. if (!empty($categories)) {
  838. $cats = $categories;
  839. }
  840. unset($course_cat);
  841. }
  842. //
  843. // Strangely, get_my_courses() is expected to return the
  844. // array keyed on id, which messes up the sorting
  845. // So do that, and also cache the ids in the session if appropriate
  846. //
  847. $kcourses = array();
  848. $courses_count = count($courses);
  849. $cacheids = NULL;
  850. $vcatpaths = array();
  851. if ($userid === $USER->id && $courses_count < 500) {
  852. $cacheids = array();
  853. }
  854. for ($n=0; $n<$courses_count; $n++) {
  855. //
  856. // Check whether $USER (not $userid) can _actually_ see them
  857. // Easy if $CFG->allowvisiblecoursesinhiddencategories
  858. // is set, and we don't have to care about categories.
  859. // Lots of work otherwise... (all in mem though!)
  860. //
  861. $cansee = false;
  862. if (is_null($cats)) { // easy rules!
  863. if ($courses[$n]->visible == true) {
  864. $cansee = true;
  865. } elseif (has_capability('moodle/course:viewhiddencourses',
  866. $courses[$n]->context, $USER->id)) {
  867. $cansee = true;
  868. }
  869. } else {
  870. //
  871. // Is the cat visible?
  872. // we have to assume it _is_ visible
  873. // so we can shortcut when we find a hidden one
  874. //
  875. $viscat = true;
  876. $cpath = $courses[$n]->categorypath;
  877. if (isset($vcatpaths[$cpath])) {
  878. $viscat = $vcatpaths[$cpath];
  879. } else {
  880. $cpath = substr($cpath,1); // kill leading slash
  881. $cpath = explode('/',$cpath);
  882. $ccct = count($cpath);
  883. for ($m=0;$m<$ccct;$m++) {
  884. $ccid = $cpath[$m];
  885. if ($cats[$ccid]->visible==false) {
  886. $viscat = false;
  887. break;
  888. }
  889. }
  890. $vcatpaths[$courses[$n]->categorypath] = $viscat;
  891. }
  892. //
  893. // Perhaps it's actually visible to $USER
  894. // check moodle/category:viewhiddencategories
  895. //
  896. // The name isn't obvious, but the description says
  897. // "See hidden categories" so the user shall see...
  898. // But also check if the allowvisiblecoursesinhiddencategories setting is true, and check for course visibility
  899. if ($viscat === false) {
  900. $catctx = $cats[$courses[$n]->category]->context;
  901. if (has_capability('moodle/category:viewhiddencategories', $catctx, $USER->id)) {
  902. $vcatpaths[$courses[$n]->categorypath] = true;
  903. $viscat = true;
  904. } elseif ($CFG->allowvisiblecoursesinhiddencategories && $courses[$n]->visible == true) {
  905. $viscat = true;
  906. }
  907. }
  908. //
  909. // Decision matrix
  910. //
  911. if ($viscat === true) {
  912. if ($courses[$n]->visible == true) {
  913. $cansee = true;
  914. } elseif (has_capability('moodle/course:viewhiddencourses',
  915. $courses[$n]->context, $USER->id)) {
  916. $cansee = true;
  917. }
  918. }
  919. }
  920. if ($cansee === true) {
  921. $kcourses[$courses[$n]->id] = $courses[$n];
  922. if (is_array($cacheids)) {
  923. $cacheids[] = $courses[$n]->id;
  924. }
  925. }
  926. }
  927. if (is_array($cacheids)) {
  928. // Only happens
  929. // - for the logged in user
  930. // - below the threshold (500)
  931. // empty string is _valid_
  932. $USER->mycourses = join(',',$cacheids);
  933. } elseif ($userid === $USER->id && isset($USER->mycourses)) {
  934. // cheap sanity check
  935. unset($USER->mycourses);
  936. }
  937. return $kcourses;
  938. }
  939. /**
  940. * A list of courses that match a search
  941. *
  942. * @uses $CFG
  943. * @param array $searchterms ?
  944. * @param string $sort ?
  945. * @param int $page ?
  946. * @param int $recordsperpage ?
  947. * @param int $totalcount Passed in by reference. ?
  948. * @return object {@link $COURSE} records
  949. */
  950. function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
  951. global $CFG;
  952. //to allow case-insensitive search for postgesql
  953. if ($CFG->dbfamily == 'postgres') {
  954. $LIKE = 'ILIKE';
  955. $NOTLIKE = 'NOT ILIKE'; // case-insensitive
  956. $REGEXP = '~*';
  957. $NOTREGEXP = '!~*';
  958. } else {
  959. $LIKE = 'LIKE';
  960. $NOTLIKE = 'NOT LIKE';
  961. $REGEXP = 'REGEXP';
  962. $NOTREGEXP = 'NOT REGEXP';
  963. }
  964. $fullnamesearch = '';
  965. $summarysearch = '';
  966. $idnumbersearch = '';
  967. $shortnamesearch = '';
  968. foreach ($searchterms as $searchterm) {
  969. $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
  970. /// will use it to simulate the "-" operator with LIKE clause
  971. /// Under Oracle and MSSQL, trim the + and - operators and perform
  972. /// simpler LIKE (or NOT LIKE) queries
  973. if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
  974. if (substr($searchterm, 0, 1) == '-') {
  975. $NOT = ' NOT ';
  976. }
  977. $searchterm = trim($searchterm, '+-');
  978. }
  979. if ($fullnamesearch) {
  980. $fullnamesearch .= ' AND ';
  981. }
  982. if ($summarysearch) {
  983. $summarysearch .= ' AND ';
  984. }
  985. if ($idnumbersearch) {
  986. $idnumbersearch .= ' AND ';
  987. }
  988. if ($shortnamesearch) {
  989. $shortnamesearch .= ' AND ';
  990. }
  991. if (substr($searchterm,0,1) == '+') {
  992. $searchterm = substr($searchterm,1);
  993. $summarysearch .= " c.summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  994. $fullnamesearch .= " c.fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  995. $idnumbersearch .= " c.idnumber $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  996. $shortnamesearch .= " c.shortname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  997. } else if (substr($searchterm,0,1) == "-") {
  998. $searchterm = substr($searchterm,1);
  999. $summarysearch .= " c.summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  1000. $fullnamesearch .= " c.fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  1001. $idnumbersearch .= " c.idnumber $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  1002. $shortnamesearch .= " c.shortname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
  1003. } else {
  1004. $summarysearch .= ' summary '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
  1005. $fullnamesearch .= ' fullname '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
  1006. $idnumbersearch .= ' idnumber '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
  1007. $shortnamesearch .= ' shortname '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
  1008. }
  1009. }
  1010. $sql = "SELECT c.*,
  1011. ctx.id AS ctxid, ctx.path AS ctxpath,
  1012. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  1013. FROM {$CFG->prefix}course c
  1014. JOIN {$CFG->prefix}context ctx
  1015. ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  1016. WHERE (( $fullnamesearch ) OR ( $summarysearch ) OR ( $idnumbersearch ) OR ( $shortnamesearch ))
  1017. AND category > 0
  1018. ORDER BY " . $sort;
  1019. $courses = array();
  1020. if ($rs = get_recordset_sql($sql)) {
  1021. // Tiki pagination
  1022. $limitfrom = $page * $recordsperpage;
  1023. $limitto = $limitfrom + $recordsperpage;
  1024. $c = 0; // counts how many visible courses we've seen
  1025. while ($course = rs_fetch_next_record($rs)) {
  1026. $course = make_context_subobj($course);
  1027. if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) {
  1028. // Don't exit this loop till the end
  1029. // we need to count all the visible courses
  1030. // to update $totalcount
  1031. if ($c >= $limitfrom && $c < $limitto) {
  1032. $courses[] = $course;
  1033. }
  1034. $c++;
  1035. }
  1036. }
  1037. }
  1038. // our caller expects 2 bits of data - our return
  1039. // array, and an updated $totalcount
  1040. $totalcount = $c;
  1041. return $courses;
  1042. }
  1043. /**
  1044. * Returns a sorted list of categories. Each category object has a context
  1045. * property that is a context object.
  1046. *
  1047. * When asking for $parent='none' it will return all the categories, regardless
  1048. * of depth. Wheen asking for a specific parent, the default is to return
  1049. * a "shallow" resultset. Pass false to $shallow and it will return all
  1050. * the child categories as well.
  1051. *
  1052. *
  1053. * @param string $parent The parent category if any
  1054. * @param string $sort the sortorder
  1055. * @param bool $shallow - set to false to get the children too
  1056. * @return array of categories
  1057. */
  1058. function get_categories($parent='none', $sort=NULL, $shallow=true) {
  1059. global $CFG;
  1060. if ($sort === NULL) {
  1061. $sort = 'ORDER BY cc.sortorder ASC';
  1062. } elseif ($sort ==='') {
  1063. // leave it as empty
  1064. } else {
  1065. $sort = "ORDER BY $sort";
  1066. }
  1067. if ($parent === 'none') {
  1068. $sql = "SELECT cc.*,
  1069. ctx.id AS ctxid, ctx.path AS ctxpath,
  1070. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  1071. FROM {$CFG->prefix}course_categories cc
  1072. JOIN {$CFG->prefix}context ctx
  1073. ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
  1074. $sort";
  1075. } elseif ($shallow) {
  1076. $parent = (int)$parent;
  1077. $sql = "SELECT cc.*,
  1078. ctx.id AS ctxid, ctx.path AS ctxpath,
  1079. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  1080. FROM {$CFG->prefix}course_categories cc
  1081. JOIN {$CFG->prefix}context ctx
  1082. ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
  1083. WHERE cc.parent=$parent
  1084. $sort";
  1085. } else {
  1086. $parent = (int)$parent;
  1087. $sql = "SELECT cc.*,
  1088. ctx.id AS ctxid, ctx.path AS ctxpath,
  1089. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  1090. FROM {$CFG->prefix}course_categories cc
  1091. JOIN {$CFG->prefix}context ctx
  1092. ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
  1093. JOIN {$CFG->prefix}course_categories ccp
  1094. ON (cc.path LIKE ".sql_concat('ccp.path',"'%'").")
  1095. WHERE ccp.id=$parent
  1096. $sort";
  1097. }
  1098. $categories = array();
  1099. if( $rs = get_recordset_sql($sql) ){
  1100. while ($cat = rs_fetch_next_record($rs)) {
  1101. $cat = make_context_subobj($cat);
  1102. if ($cat->visible || has_capability('moodle/category:viewhiddencategories',$cat->context)) {
  1103. $categories[$cat->id] = $cat;
  1104. }
  1105. }
  1106. }
  1107. return $categories;
  1108. }
  1109. /**
  1110. * Returns an array of category ids of all the subcategories for a given
  1111. * category.
  1112. * @param $catid - The id of the category whose subcategories we want to find.
  1113. * @return array of category ids.
  1114. */
  1115. function get_all_subcategories($catid) {
  1116. $subcats = array();
  1117. if ($categories = get_records('course_categories', 'parent', $catid)) {
  1118. foreach ($categories as $cat) {
  1119. array_push($subcats, $cat->id);
  1120. $subcats = array_merge($subcats, get_all_subcategories($cat->id));
  1121. }
  1122. }
  1123. return $subcats;
  1124. }
  1125. /**
  1126. * This recursive function makes sure that the courseorder is consecutive
  1127. *
  1128. * @param type description
  1129. *
  1130. * $n is the starting point, offered only for compatilibity -- will be ignored!
  1131. * $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
  1132. * safely from 1.4 to 1.5
  1133. */
  1134. function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
  1135. global $CFG;
  1136. $count = 0;
  1137. $catgap = 1000; // "standard" category gap
  1138. $tolerance = 200; // how "close" categories can get
  1139. if ($categoryid > 0){
  1140. // update depth and path
  1141. $cat = get_record('course_categories', 'id', $categoryid);
  1142. if ($cat->parent == 0) {
  1143. $depth = 0;
  1144. $path = '';
  1145. } else if ($depth == 0 ) { // doesn't make sense; get from DB
  1146. // this is only called if the $depth parameter looks dodgy
  1147. $parent = get_record('course_categories', 'id', $cat->parent);
  1148. $path = $parent->path;
  1149. $depth = $parent->depth;
  1150. }
  1151. $path = $path . '/' . $categoryid;
  1152. $depth = $depth + 1;
  1153. if ($cat->path !== $path) {
  1154. set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
  1155. }
  1156. if ($cat->depth != $depth) {
  1157. set_field('course_categories', 'depth', $depth, 'id', $categoryid);
  1158. }
  1159. }
  1160. // get some basic info about courses in the category
  1161. $info = get_record_sql('SELECT MIN(sortorder) AS min,
  1162. MAX(sortorder) AS max,
  1163. COUNT(sortorder) AS count
  1164. FROM ' . $CFG->prefix . 'course
  1165. WHERE category=' . $categoryid);
  1166. if (is_object($info)) { // no courses?
  1167. $max = $info->max;
  1168. $count = $info->count;
  1169. $min = $info->min;
  1170. unset($info);
  1171. }
  1172. if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
  1173. $n = $min;
  1174. }
  1175. // $hasgap flag indicates whether there's a gap in the sequence
  1176. $hasgap = false;
  1177. if ($max-$min+1 != $count) {
  1178. $hasgap = true;
  1179. }
  1180. // $mustshift indicates whether the sequence must be shifted to
  1181. // meet its range
  1182. $mustshift = false;
  1183. if ($min < $n-$tolerance || $min > $n+$tolerance+$catgap ) {
  1184. $mustshift = true;
  1185. }
  1186. // actually sort only if there are courses,
  1187. // and we meet one ofthe triggers:
  1188. // - safe flag
  1189. // - they are not in a continuos block
  1190. // - they are too close to the 'bottom'
  1191. if ($count && ( $safe || $hasgap || $mustshift ) ) {
  1192. // special, optimized case where all we need is to shift
  1193. if ( $mustshift && !$safe && !$hasgap) {
  1194. $shift = $n + $catgap - $min;
  1195. if ($shift < $count) {
  1196. $shift = $count + $catgap;
  1197. }
  1198. // UPDATE course SET sortorder=sortorder+$shift
  1199. execute_sql("UPDATE {$CFG->prefix}course
  1200. SET sortorder=sortorder+$shift
  1201. WHERE category=$categoryid", 0);
  1202. $n = $n + $catgap + $count;
  1203. } else { // do it slowly
  1204. $n = $n + $catgap;
  1205. // if the new sequence overlaps the current sequence, lack of transactions
  1206. // will stop us -- shift things aside for a moment...
  1207. if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
  1208. $shift = $max + $n + 1000;
  1209. execute_sql("UPDATE {$CFG->prefix}course
  1210. SET sortorder=sortorder+$shift
  1211. WHERE category=$categoryid", 0);
  1212. }
  1213. $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
  1214. begin_sql();
  1215. $tx = true; // transaction sanity
  1216. foreach ($courses as $course) {
  1217. if ($tx && $course->sortorder != $n ) { // save db traffic
  1218. $tx = $tx && set_field('course', 'sortorder', $n,
  1219. 'id', $course->id);
  1220. }
  1221. $n++;
  1222. }
  1223. if ($tx) {
  1224. commit_sql();
  1225. } else {
  1226. rollback

Large files files are truncated, but you can click here to view the full file