Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Contains classes, functions and constants used during the tracking
  19   * of activity completion for users.
  20   *
  21   * Completion top-level options (admin setting enablecompletion)
  22   *
  23   * @package core_completion
  24   * @category completion
  25   * @copyright 1999 onwards Martin Dougiamas   {@link http://moodle.com}
  26   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  27   */
  28  
  29  use core_completion\activity_custom_completion;
  30  use core_courseformat\base as course_format;
  31  
  32  defined('MOODLE_INTERNAL') || die();
  33  
  34  /**
  35   * Include the required completion libraries
  36   */
  37  require_once $CFG->dirroot.'/completion/completion_aggregation.php';
  38  require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
  39  require_once $CFG->dirroot.'/completion/completion_completion.php';
  40  require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
  41  
  42  
  43  /**
  44   * The completion system is enabled in this site/course
  45   */
  46  define('COMPLETION_ENABLED', 1);
  47  /**
  48   * The completion system is not enabled in this site/course
  49   */
  50  define('COMPLETION_DISABLED', 0);
  51  
  52  /**
  53   * Completion tracking is disabled for this activity
  54   * This is a completion tracking option per-activity  (course_modules/completion)
  55   */
  56  define('COMPLETION_TRACKING_NONE', 0);
  57  
  58  /**
  59   * Manual completion tracking (user ticks box) is enabled for this activity
  60   * This is a completion tracking option per-activity  (course_modules/completion)
  61   */
  62  define('COMPLETION_TRACKING_MANUAL', 1);
  63  /**
  64   * Automatic completion tracking (system ticks box) is enabled for this activity
  65   * This is a completion tracking option per-activity  (course_modules/completion)
  66   */
  67  define('COMPLETION_TRACKING_AUTOMATIC', 2);
  68  
  69  /**
  70   * The user has not completed this activity.
  71   * This is a completion state value (course_modules_completion/completionstate)
  72   */
  73  define('COMPLETION_INCOMPLETE', 0);
  74  /**
  75   * The user has completed this activity. It is not specified whether they have
  76   * passed or failed it.
  77   * This is a completion state value (course_modules_completion/completionstate)
  78   */
  79  define('COMPLETION_COMPLETE', 1);
  80  /**
  81   * The user has completed this activity with a grade above the pass mark.
  82   * This is a completion state value (course_modules_completion/completionstate)
  83   */
  84  define('COMPLETION_COMPLETE_PASS', 2);
  85  /**
  86   * The user has completed this activity but their grade is less than the pass mark
  87   * This is a completion state value (course_modules_completion/completionstate)
  88   */
  89  define('COMPLETION_COMPLETE_FAIL', 3);
  90  
  91  /**
  92   * Indicates that the user has received a failing grade for a hidden grade item.
  93   */
  94  define('COMPLETION_COMPLETE_FAIL_HIDDEN', 4);
  95  
  96  /**
  97   * The effect of this change to completion status is unknown.
  98   * A completion effect changes (used only in update_state)
  99   */
 100  define('COMPLETION_UNKNOWN', -1);
 101  /**
 102   * The user's grade has changed, so their new state might be
 103   * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
 104   * A completion effect changes (used only in update_state)
 105   */
 106  define('COMPLETION_GRADECHANGE', -2);
 107  
 108  /**
 109   * User must view this activity.
 110   * Whether view is required to create an activity (course_modules/completionview)
 111   */
 112  define('COMPLETION_VIEW_REQUIRED', 1);
 113  /**
 114   * User does not need to view this activity
 115   * Whether view is required to create an activity (course_modules/completionview)
 116   */
 117  define('COMPLETION_VIEW_NOT_REQUIRED', 0);
 118  
 119  /**
 120   * User has viewed this activity.
 121   * Completion viewed state (course_modules_completion/viewed)
 122   */
 123  define('COMPLETION_VIEWED', 1);
 124  /**
 125   * User has not viewed this activity.
 126   * Completion viewed state (course_modules_completion/viewed)
 127   */
 128  define('COMPLETION_NOT_VIEWED', 0);
 129  
 130  /**
 131   * Completion details should be ORed together and you should return false if
 132   * none apply.
 133   */
 134  define('COMPLETION_OR', false);
 135  /**
 136   * Completion details should be ANDed together and you should return true if
 137   * none apply
 138   */
 139  define('COMPLETION_AND', true);
 140  
 141  /**
 142   * Course completion criteria aggregation method.
 143   */
 144  define('COMPLETION_AGGREGATION_ALL', 1);
 145  /**
 146   * Course completion criteria aggregation method.
 147   */
 148  define('COMPLETION_AGGREGATION_ANY', 2);
 149  
 150  /**
 151   * Completion conditions will be displayed to user.
 152   */
 153  define('COMPLETION_SHOW_CONDITIONS', 1);
 154  
 155  /**
 156   * Completion conditions will be hidden from user.
 157   */
 158  define('COMPLETION_HIDE_CONDITIONS', 0);
 159  
 160  /**
 161   * Utility function for checking if the logged in user can view
 162   * another's completion data for a particular course
 163   *
 164   * @access  public
 165   * @param   int         $userid     Completion data's owner
 166   * @param   mixed       $course     Course object or Course ID (optional)
 167   * @return  boolean
 168   */
 169  function completion_can_view_data($userid, $course = null) {
 170      global $USER;
 171  
 172      if (!isloggedin()) {
 173          return false;
 174      }
 175  
 176      if (!is_object($course)) {
 177          $cid = $course;
 178          $course = new stdClass();
 179          $course->id = $cid;
 180      }
 181  
 182      // Check if this is the site course
 183      if ($course->id == SITEID) {
 184          $course = null;
 185      }
 186  
 187      // Check if completion is enabled
 188      if ($course) {
 189          $cinfo = new completion_info($course);
 190          if (!$cinfo->is_enabled()) {
 191              return false;
 192          }
 193      } else {
 194          if (!completion_info::is_enabled_for_site()) {
 195              return false;
 196          }
 197      }
 198  
 199      // Is own user's data?
 200      if ($USER->id == $userid) {
 201          return true;
 202      }
 203  
 204      // Check capabilities
 205      $personalcontext = context_user::instance($userid);
 206  
 207      if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
 208          return true;
 209      } elseif (has_capability('report/completion:view', $personalcontext)) {
 210          return true;
 211      }
 212  
 213      if ($course->id) {
 214          $coursecontext = context_course::instance($course->id);
 215      } else {
 216          $coursecontext = context_system::instance();
 217      }
 218  
 219      if (has_capability('report/completion:view', $coursecontext)) {
 220          return true;
 221      }
 222  
 223      return false;
 224  }
 225  
 226  
 227  /**
 228   * Class represents completion information for a course.
 229   *
 230   * Does not contain any data, so you can safely construct it multiple times
 231   * without causing any problems.
 232   *
 233   * @package core
 234   * @category completion
 235   * @copyright 2008 Sam Marshall
 236   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 237   */
 238  class completion_info {
 239  
 240      /* @var stdClass Course object passed during construction */
 241      private $course;
 242  
 243      /* @var int Course id */
 244      public $course_id;
 245  
 246      /* @var array Completion criteria {@link completion_info::get_criteria()}  */
 247      private $criteria;
 248  
 249      /**
 250       * Return array of aggregation methods
 251       * @return array
 252       */
 253      public static function get_aggregation_methods() {
 254          return array(
 255              COMPLETION_AGGREGATION_ALL => get_string('all'),
 256              COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
 257          );
 258      }
 259  
 260      /**
 261       * Constructs with course details.
 262       *
 263       * When instantiating a new completion info object you must provide a course
 264       * object with at least id, and enablecompletion properties. Property
 265       * cacherev is needed if you check completion of the current user since
 266       * it is used for cache validation.
 267       *
 268       * @param stdClass $course Moodle course object.
 269       */
 270      public function __construct($course) {
 271          $this->course = $course;
 272          $this->course_id = $course->id;
 273      }
 274  
 275      /**
 276       * Determines whether completion is enabled across entire site.
 277       *
 278       * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
 279       *     COMPLETION_DISABLED (false) if it's complete
 280       */
 281      public static function is_enabled_for_site() {
 282          global $CFG;
 283          return !empty($CFG->enablecompletion);
 284      }
 285  
 286      /**
 287       * Checks whether completion is enabled in a particular course and possibly
 288       * activity.
 289       *
 290       * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
 291       *   completion enable state.
 292       * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
 293       *   site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
 294       *   for a course-module.
 295       */
 296      public function is_enabled($cm = null) {
 297          global $CFG, $DB;
 298  
 299          // First check global completion
 300          if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
 301              return COMPLETION_DISABLED;
 302          }
 303  
 304          // Load data if we do not have enough
 305          if (!isset($this->course->enablecompletion)) {
 306              $this->course = get_course($this->course_id);
 307          }
 308  
 309          // Check course completion
 310          if ($this->course->enablecompletion == COMPLETION_DISABLED) {
 311              return COMPLETION_DISABLED;
 312          }
 313  
 314          // If there was no $cm and we got this far, then it's enabled
 315          if (!$cm) {
 316              return COMPLETION_ENABLED;
 317          }
 318  
 319          // Return course-module completion value
 320          return $cm->completion;
 321      }
 322  
 323      /**
 324       * Displays the 'Your progress' help icon, if completion tracking is enabled.
 325       * Just prints the result of display_help_icon().
 326       *
 327       * @deprecated since Moodle 2.0 - Use display_help_icon instead.
 328       */
 329      public function print_help_icon() {
 330          debugging('The function print_help_icon() is deprecated, please do not use it anymore.',
 331              DEBUG_DEVELOPER);
 332          print $this->display_help_icon();
 333      }
 334  
 335      /**
 336       * Returns the 'Your progress' help icon, if completion tracking is enabled.
 337       *
 338       * @return string HTML code for help icon, or blank if not needed
 339       * @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
 340       */
 341      public function display_help_icon() {
 342          global $PAGE, $OUTPUT, $USER;
 343          debugging('The function display_help_icon() is deprecated, please do not use it anymore.',
 344          DEBUG_DEVELOPER);
 345          $result = '';
 346          if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
 347                  !isguestuser()) {
 348              $result .= html_writer::tag('div', get_string('yourprogress','completion') .
 349                      $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
 350                      'class' => 'completionprogress'));
 351          }
 352          return $result;
 353      }
 354  
 355      /**
 356       * Get a course completion for a user
 357       *
 358       * @param int $user_id User id
 359       * @param int $criteriatype Specific criteria type to return
 360       * @return bool|completion_criteria_completion returns false on fail
 361       */
 362      public function get_completion($user_id, $criteriatype) {
 363          $completions = $this->get_completions($user_id, $criteriatype);
 364  
 365          if (empty($completions)) {
 366              return false;
 367          } elseif (count($completions) > 1) {
 368              throw new \moodle_exception('multipleselfcompletioncriteria', 'completion');
 369          }
 370  
 371          return $completions[0];
 372      }
 373  
 374      /**
 375       * Get all course criteria's completion objects for a user
 376       *
 377       * @param int $user_id User id
 378       * @param int $criteriatype Specific criteria type to return (optional)
 379       * @return array
 380       */
 381      public function get_completions($user_id, $criteriatype = null) {
 382          $criteria = $this->get_criteria($criteriatype);
 383  
 384          $completions = array();
 385  
 386          foreach ($criteria as $criterion) {
 387              $params = array(
 388                  'course'        => $this->course_id,
 389                  'userid'        => $user_id,
 390                  'criteriaid'    => $criterion->id
 391              );
 392  
 393              $completion = new completion_criteria_completion($params);
 394              $completion->attach_criteria($criterion);
 395  
 396              $completions[] = $completion;
 397          }
 398  
 399          return $completions;
 400      }
 401  
 402      /**
 403       * Get completion object for a user and a criteria
 404       *
 405       * @param int $user_id User id
 406       * @param completion_criteria $criteria Criteria object
 407       * @return completion_criteria_completion
 408       */
 409      public function get_user_completion($user_id, $criteria) {
 410          $params = array(
 411              'course'        => $this->course_id,
 412              'userid'        => $user_id,
 413              'criteriaid'    => $criteria->id,
 414          );
 415  
 416          $completion = new completion_criteria_completion($params);
 417          return $completion;
 418      }
 419  
 420      /**
 421       * Check if course has completion criteria set
 422       *
 423       * @return bool Returns true if there are criteria
 424       */
 425      public function has_criteria() {
 426          $criteria = $this->get_criteria();
 427  
 428          return (bool) count($criteria);
 429      }
 430  
 431      /**
 432       * Get course completion criteria
 433       *
 434       * @param int $criteriatype Specific criteria type to return (optional)
 435       */
 436      public function get_criteria($criteriatype = null) {
 437  
 438          // Fill cache if empty
 439          if (!is_array($this->criteria)) {
 440              global $DB;
 441  
 442              $params = array(
 443                  'course'    => $this->course->id
 444              );
 445  
 446              // Load criteria from database
 447              $records = (array)$DB->get_records('course_completion_criteria', $params);
 448  
 449              // Order records so activities are in the same order as they appear on the course view page.
 450              if ($records) {
 451                  $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
 452                  usort($records, function ($a, $b) use ($activitiesorder) {
 453                      $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
 454                          array_search($a->moduleinstance, $activitiesorder) : false;
 455                      $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
 456                          array_search($b->moduleinstance, $activitiesorder) : false;
 457                      if ($aidx === false || $bidx === false || $aidx == $bidx) {
 458                          return 0;
 459                      }
 460                      return ($aidx < $bidx) ? -1 : 1;
 461                  });
 462              }
 463  
 464              // Build array of criteria objects
 465              $this->criteria = array();
 466              foreach ($records as $record) {
 467                  $this->criteria[$record->id] = completion_criteria::factory((array)$record);
 468              }
 469          }
 470  
 471          // If after all criteria
 472          if ($criteriatype === null) {
 473              return $this->criteria;
 474          }
 475  
 476          // If we are only after a specific criteria type
 477          $criteria = array();
 478          foreach ($this->criteria as $criterion) {
 479  
 480              if ($criterion->criteriatype != $criteriatype) {
 481                  continue;
 482              }
 483  
 484              $criteria[$criterion->id] = $criterion;
 485          }
 486  
 487          return $criteria;
 488      }
 489  
 490      /**
 491       * Get aggregation method
 492       *
 493       * @param int $criteriatype If none supplied, get overall aggregation method (optional)
 494       * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
 495       */
 496      public function get_aggregation_method($criteriatype = null) {
 497          $params = array(
 498              'course'        => $this->course_id,
 499              'criteriatype'  => $criteriatype
 500          );
 501  
 502          $aggregation = new completion_aggregation($params);
 503  
 504          if (!$aggregation->id) {
 505              $aggregation->method = COMPLETION_AGGREGATION_ALL;
 506          }
 507  
 508          return $aggregation->method;
 509      }
 510  
 511      /**
 512       * @deprecated since Moodle 2.8 MDL-46290.
 513       */
 514      public function get_incomplete_criteria() {
 515          throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
 516      }
 517  
 518      /**
 519       * Clear old course completion criteria
 520       */
 521      public function clear_criteria() {
 522          global $DB;
 523  
 524          // Remove completion criteria records for the course itself, and any records that refer to the course.
 525          $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
 526          $params = [
 527              'course' => $this->course_id,
 528              'type' => COMPLETION_CRITERIA_TYPE_COURSE,
 529              'courseinstance' => $this->course_id,
 530          ];
 531  
 532          $DB->delete_records_select('course_completion_criteria', $select, $params);
 533          $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
 534  
 535          $this->delete_course_completion_data();
 536      }
 537  
 538      /**
 539       * Has the supplied user completed this course
 540       *
 541       * @param int $user_id User's id
 542       * @return boolean
 543       */
 544      public function is_course_complete($user_id) {
 545          $params = array(
 546              'userid'    => $user_id,
 547              'course'  => $this->course_id
 548          );
 549  
 550          $ccompletion = new completion_completion($params);
 551          return $ccompletion->is_complete();
 552      }
 553  
 554      /**
 555       * Check whether the supplied user can override the activity completion statuses within the current course.
 556       *
 557       * @param stdClass $user The user object.
 558       * @return bool True if the user can override, false otherwise.
 559       */
 560      public function user_can_override_completion($user) {
 561          return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
 562      }
 563  
 564      /**
 565       * Updates (if necessary) the completion state of activity $cm for the given
 566       * user.
 567       *
 568       * For manual completion, this function is called when completion is toggled
 569       * with $possibleresult set to the target state.
 570       *
 571       * For automatic completion, this function should be called every time a module
 572       * does something which might influence a user's completion state. For example,
 573       * if a forum provides options for marking itself 'completed' once a user makes
 574       * N posts, this function should be called every time a user makes a new post.
 575       * [After the post has been saved to the database]. When calling, you do not
 576       * need to pass in the new completion state. Instead this function carries out completion
 577       * calculation by checking grades and viewed state itself, and calling the involved module
 578       * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
 579       * check module-specific conditions.
 580       *
 581       * @param stdClass|cm_info $cm Course-module
 582       * @param int $possibleresult Expected completion result. If the event that
 583       *   has just occurred (e.g. add post) can only result in making the activity
 584       *   complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
 585       *   has just occurred (e.g. delete post) can only result in making the activity
 586       *   not complete when it was previously complete, use COMPLETION_INCOMPLETE.
 587       *   Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
 588       *   COMPLETION_UNKNOWN significantly improves performance because it will abandon
 589       *   processing early if the user's completion state already matches the expected
 590       *   result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
 591       *   must be used; these directly set the specified state.
 592       * @param int $userid User ID to be updated. Default 0 = current user
 593       * @param bool $override Whether manually overriding the existing completion state.
 594       * @param bool $isbulkupdate If bulk grade update is happening.
 595       * @return void
 596       * @throws moodle_exception if trying to override without permission.
 597       */
 598      public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
 599              $override = false, $isbulkupdate = false) {
 600          global $USER;
 601  
 602          // Do nothing if completion is not enabled for that activity
 603          if (!$this->is_enabled($cm)) {
 604              return;
 605          }
 606  
 607          // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
 608          if ($override) {
 609              if (!$this->user_can_override_completion($USER)) {
 610                  throw new required_capability_exception(context_course::instance($this->course_id),
 611                                                          'moodle/course:overridecompletion', 'nopermission', '');
 612              }
 613          }
 614  
 615          // Default to current user if one is not provided.
 616          if ($userid == 0) {
 617              $userid = $USER->id;
 618          }
 619  
 620          // Delete the cm's cached completion data for this user if automatic completion is enabled.
 621          // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
 622          if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
 623              $completioncache = cache::make('core', 'completion');
 624              $completionkey = $userid . '_' . $this->course->id;
 625              $completiondata = $completioncache->get($completionkey);
 626  
 627              if ($completiondata !== false) {
 628                  unset($completiondata[$cm->id]);
 629                  $completioncache->set($completionkey, $completiondata);
 630              }
 631          }
 632  
 633          // Get current value of completion state and do nothing if it's same as
 634          // the possible result of this change. If the change is to COMPLETE and the
 635          // current value is one of the COMPLETE_xx subtypes, ignore that as well
 636          $current = $this->get_data($cm, false, $userid);
 637          if ($possibleresult == $current->completionstate ||
 638              ($possibleresult == COMPLETION_COMPLETE &&
 639                  ($current->completionstate == COMPLETION_COMPLETE_PASS ||
 640                  $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
 641              return;
 642          }
 643  
 644          // The activity completion alters the course state cache for this particular user.
 645          $course = get_course($cm->course);
 646          if ($course) {
 647              course_format::session_cache_reset($course);
 648          }
 649  
 650          // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
 651          // unless processing another override.
 652          // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
 653          // overridden to INCOMPLETE to still be processed by normal completion triggers.
 654          if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
 655              && $current->completionstate == COMPLETION_COMPLETE && !$override) {
 656              return;
 657          }
 658  
 659          // For manual tracking, or if overriding the completion state, we set the state directly.
 660          if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
 661              switch($possibleresult) {
 662                  case COMPLETION_COMPLETE:
 663                  case COMPLETION_INCOMPLETE:
 664                      $newstate = $possibleresult;
 665                      break;
 666                  default:
 667                      $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
 668              }
 669  
 670          } else {
 671              $newstate = $this->internal_get_state($cm, $userid, $current);
 672          }
 673  
 674          // If the overall completion state has changed, update it in the cache.
 675          if ($newstate != $current->completionstate) {
 676              $current->completionstate = $newstate;
 677              $current->timemodified    = time();
 678              $current->overrideby      = $override ? $USER->id : null;
 679              $this->internal_set_data($cm, $current, $isbulkupdate);
 680          }
 681      }
 682  
 683      /**
 684       * Calculates the completion state for an activity and user.
 685       *
 686       * Internal function. Not private, so we can unit-test it.
 687       *
 688       * @param stdClass|cm_info $cm Activity
 689       * @param int $userid ID of user
 690       * @param stdClass $current Previous completion information from database
 691       * @return mixed
 692       */
 693      public function internal_get_state($cm, $userid, $current) {
 694          global $USER, $DB;
 695  
 696          // Get user ID
 697          if (!$userid) {
 698              $userid = $USER->id;
 699          }
 700  
 701          $newstate = COMPLETION_COMPLETE;
 702          if ($cm instanceof stdClass) {
 703              // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
 704              if (!isset($cm->modname)) {
 705                  $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
 706              }
 707              // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
 708              if (!isset($cm->course)) {
 709                  $cm->course = $this->course_id;
 710              }
 711          }
 712          // Make sure we're using a cm_info object.
 713          $cminfo = cm_info::create($cm, $userid);
 714          $completionstate = $this->get_core_completion_state($cminfo, $userid);
 715  
 716          if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
 717              $response = true;
 718              $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
 719              if ($cmcompletionclass) {
 720                  /** @var activity_custom_completion $cmcompletion */
 721                  $cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
 722                  $response = $cmcompletion->get_overall_completion_state() != COMPLETION_INCOMPLETE;
 723              } else {
 724                  // Fallback to the get_completion_state callback.
 725                  $cmcompletionclass = "mod_{$cminfo->modname}\\completion\\custom_completion";
 726                  $function = $cminfo->modname . '_get_completion_state';
 727                  if (!function_exists($function)) {
 728                      $this->internal_systemerror("Module {$cminfo->modname} claims to support FEATURE_COMPLETION_HAS_RULES " .
 729                          "but does not implement the custom completion class $cmcompletionclass which extends " .
 730                          "\core_completion\activity_custom_completion.");
 731                  }
 732                  debugging("*_get_completion_state() callback functions such as $function have been deprecated and should no " .
 733                      "longer be used. Please implement the custom completion class $cmcompletionclass which extends " .
 734                      "\core_completion\activity_custom_completion.", DEBUG_DEVELOPER);
 735                  $response = $function($this->course, $cm, $userid, COMPLETION_AND, $completionstate);
 736              }
 737  
 738              if (!$response) {
 739                  return COMPLETION_INCOMPLETE;
 740              }
 741          }
 742  
 743          if ($completionstate) {
 744              // We have allowed the plugins to do it's thing and run their own checks.
 745              // We have now reached a state where we need to AND all the calculated results.
 746              // Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
 747              $newstate = array_reduce($completionstate, function($carry, $value) {
 748                  if (in_array(COMPLETION_INCOMPLETE, [$carry, $value])) {
 749                      return COMPLETION_INCOMPLETE;
 750                  } else if (in_array(COMPLETION_COMPLETE_FAIL, [$carry, $value])) {
 751                      return COMPLETION_COMPLETE_FAIL;
 752                  } else {
 753                      return in_array(COMPLETION_COMPLETE_PASS, [$carry, $value]) ? COMPLETION_COMPLETE_PASS : $value;
 754                  }
 755  
 756              }, COMPLETION_COMPLETE);
 757          }
 758  
 759          return $newstate;
 760  
 761      }
 762  
 763      /**
 764       * Fetches the completion state for an activity completion's require grade completion requirement.
 765       *
 766       * @param cm_info $cm The course module information.
 767       * @param int $userid The user ID.
 768       * @return int The completion state.
 769       */
 770      public function get_grade_completion(cm_info $cm, int $userid): int {
 771          global $CFG;
 772  
 773          require_once($CFG->libdir . '/gradelib.php');
 774          $item = grade_item::fetch([
 775              'courseid' => $cm->course,
 776              'itemtype' => 'mod',
 777              'itemmodule' => $cm->modname,
 778              'iteminstance' => $cm->instance,
 779              'itemnumber' => $cm->completiongradeitemnumber
 780          ]);
 781          if ($item) {
 782              // Fetch 'grades' (will be one or none).
 783              $grades = grade_grade::fetch_users_grades($item, [$userid], false);
 784              if (empty($grades)) {
 785                  // No grade for user.
 786                  return COMPLETION_INCOMPLETE;
 787              }
 788              if (count($grades) > 1) {
 789                  $this->internal_systemerror("Unexpected result: multiple grades for
 790                          item '{$item->id}', user '{$userid}'");
 791              }
 792              $returnpassfail = !empty($cm->completionpassgrade);
 793              return self::internal_get_grade_state($item, reset($grades), $returnpassfail);
 794          }
 795  
 796          return COMPLETION_INCOMPLETE;
 797      }
 798  
 799      /**
 800       * Marks a module as viewed.
 801       *
 802       * Should be called whenever a module is 'viewed' (it is up to the module how to
 803       * determine that). Has no effect if viewing is not set as a completion condition.
 804       *
 805       * Note that this function must be called before you print the page header because
 806       * it is possible that the navigation block may depend on it. If you call it after
 807       * printing the header, it shows a developer debug warning.
 808       *
 809       * @param stdClass|cm_info $cm Activity
 810       * @param int $userid User ID or 0 (default) for current user
 811       * @return void
 812       */
 813      public function set_module_viewed($cm, $userid=0) {
 814          global $PAGE;
 815          if ($PAGE->headerprinted) {
 816              debugging('set_module_viewed must be called before header is printed',
 817                      DEBUG_DEVELOPER);
 818          }
 819  
 820          // Don't do anything if view condition is not turned on
 821          if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
 822              return;
 823          }
 824  
 825          // Get current completion state
 826          $data = $this->get_data($cm, false, $userid);
 827  
 828          // If we already viewed it, don't do anything unless the completion status is overridden.
 829          // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
 830          if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
 831              return;
 832          }
 833  
 834          // OK, change state, save it, and update completion
 835          $data->viewed = COMPLETION_VIEWED;
 836          $this->internal_set_data($cm, $data);
 837          $this->update_state($cm, COMPLETION_COMPLETE, $userid);
 838      }
 839  
 840      /**
 841       * Determines how much completion data exists for an activity. This is used when
 842       * deciding whether completion information should be 'locked' in the module
 843       * editing form.
 844       *
 845       * @param cm_info $cm Activity
 846       * @return int The number of users who have completion data stored for this
 847       *   activity, 0 if none
 848       */
 849      public function count_user_data($cm) {
 850          global $DB;
 851  
 852          return $DB->get_field_sql("
 853      SELECT
 854          COUNT(1)
 855      FROM
 856          {course_modules_completion}
 857      WHERE
 858          coursemoduleid=? AND completionstate<>0", array($cm->id));
 859      }
 860  
 861      /**
 862       * Determines how much course completion data exists for a course. This is used when
 863       * deciding whether completion information should be 'locked' in the completion
 864       * settings form and activity completion settings.
 865       *
 866       * @param int $user_id Optionally only get course completion data for a single user
 867       * @return int The number of users who have completion data stored for this
 868       *     course, 0 if none
 869       */
 870      public function count_course_user_data($user_id = null) {
 871          global $DB;
 872  
 873          $sql = '
 874      SELECT
 875          COUNT(1)
 876      FROM
 877          {course_completion_crit_compl}
 878      WHERE
 879          course = ?
 880          ';
 881  
 882          $params = array($this->course_id);
 883  
 884          // Limit data to a single user if an ID is supplied
 885          if ($user_id) {
 886              $sql .= ' AND userid = ?';
 887              $params[] = $user_id;
 888          }
 889  
 890          return $DB->get_field_sql($sql, $params);
 891      }
 892  
 893      /**
 894       * Check if this course's completion criteria should be locked
 895       *
 896       * @return boolean
 897       */
 898      public function is_course_locked() {
 899          return (bool) $this->count_course_user_data();
 900      }
 901  
 902      /**
 903       * Deletes all course completion completion data.
 904       *
 905       * Intended to be used when unlocking completion criteria settings.
 906       */
 907      public function delete_course_completion_data() {
 908          global $DB;
 909  
 910          $DB->delete_records('course_completions', array('course' => $this->course_id));
 911          $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
 912  
 913          // Difficult to find affected users, just purge all completion cache.
 914          cache::make('core', 'completion')->purge();
 915          cache::make('core', 'coursecompletion')->purge();
 916      }
 917  
 918      /**
 919       * Deletes all activity and course completion data for an entire course
 920       * (the below delete_all_state function does this for a single activity).
 921       *
 922       * Used by course reset page.
 923       */
 924      public function delete_all_completion_data() {
 925          global $DB;
 926  
 927          // Delete from database.
 928          $DB->delete_records_select('course_modules_completion',
 929                  'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
 930                  array($this->course_id));
 931          $DB->delete_records_select('course_modules_viewed',
 932              'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
 933              [$this->course_id]);
 934          // Wipe course completion data too.
 935          $this->delete_course_completion_data();
 936      }
 937  
 938      /**
 939       * Deletes completion state related to an activity for all users.
 940       *
 941       * Intended for use only when the activity itself is deleted.
 942       *
 943       * @param stdClass|cm_info $cm Activity
 944       */
 945      public function delete_all_state($cm) {
 946          global $DB;
 947  
 948          // Delete from database
 949          $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
 950  
 951          // Check if there is an associated course completion criteria
 952          $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
 953          $acriteria = false;
 954          foreach ($criteria as $criterion) {
 955              if ($criterion->moduleinstance == $cm->id) {
 956                  $acriteria = $criterion;
 957                  break;
 958              }
 959          }
 960  
 961          if ($acriteria) {
 962              // Delete all criteria completions relating to this activity
 963              $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
 964              $DB->delete_records('course_completions', array('course' => $this->course_id));
 965          }
 966  
 967          // Difficult to find affected users, just purge all completion cache.
 968          cache::make('core', 'completion')->purge();
 969          cache::make('core', 'coursecompletion')->purge();
 970      }
 971  
 972      /**
 973       * Recalculates completion state related to an activity for all users.
 974       *
 975       * Intended for use if completion conditions change. (This should be avoided
 976       * as it may cause some things to become incomplete when they were previously
 977       * complete, with the effect - for example - of hiding a later activity that
 978       * was previously available.)
 979       *
 980       * Resetting state of manual tickbox has same result as deleting state for
 981       * it.
 982       *
 983       * @param stcClass|cm_info $cm Activity
 984       */
 985      public function reset_all_state($cm) {
 986          global $DB;
 987  
 988          if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
 989              $this->delete_all_state($cm);
 990              return;
 991          }
 992          // Get current list of users with completion state
 993          $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
 994          $keepusers = array();
 995          foreach ($rs as $rec) {
 996              $keepusers[] = $rec->userid;
 997          }
 998          $rs->close();
 999  
1000          // Delete all existing state.
1001          $this->delete_all_state($cm);
1002  
1003          // Merge this with list of planned users (according to roles)
1004          $trackedusers = $this->get_tracked_users();
1005          foreach ($trackedusers as $trackeduser) {
1006              $keepusers[] = $trackeduser->id;
1007          }
1008          $keepusers = array_unique($keepusers);
1009  
1010          // Recalculate state for each kept user
1011          foreach ($keepusers as $keepuser) {
1012              $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
1013          }
1014      }
1015  
1016      /**
1017       * Obtains completion data for a particular activity and user (from the
1018       * completion cache if available, or by SQL query)
1019       *
1020       * @param stdClass|cm_info $cm Activity; only required field is ->id
1021       * @param bool $wholecourse If true (default false) then, when necessary to
1022       *   fill the cache, retrieves information from the entire course not just for
1023       *   this one activity
1024       * @param int $userid User ID or 0 (default) for current user
1025       * @param null $unused This parameter has been deprecated since 4.0 and should not be used anymore.
1026       * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
1027       *                  - Completion status for 'must-receive-grade' completion rule.
1028       *                  - Custom completion statuses defined by the activity module plugin.
1029       */
1030      public function get_data($cm, $wholecourse = false, $userid = 0, $unused = null) {
1031          global $USER, $DB;
1032  
1033          if ($unused !== null) {
1034              debugging('Deprecated argument passed to ' . __FUNCTION__, DEBUG_DEVELOPER);
1035          }
1036  
1037          $completioncache = cache::make('core', 'completion');
1038  
1039          // Get user ID
1040          if (!$userid) {
1041              $userid = $USER->id;
1042          }
1043  
1044          // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
1045          if ($cm instanceof stdClass && !isset($cm->course)) {
1046              $cm->course = $this->course_id;
1047          }
1048          // Make sure we're working on a cm_info object.
1049          $cminfo = cm_info::create($cm, $userid);
1050  
1051          // Create an anonymous function to remove the 'other_cm_completion_data_fetched' key.
1052          $returnfilteredvalue = function(array $value): stdClass {
1053              return (object) array_filter($value, function(string $key): bool {
1054                  return $key !== 'other_cm_completion_data_fetched';
1055              }, ARRAY_FILTER_USE_KEY);
1056          };
1057  
1058          // See if requested data is present in cache (use cache for current user only).
1059          $usecache = $userid == $USER->id;
1060          $cacheddata = array();
1061          if ($usecache) {
1062              $key = $userid . '_' . $this->course->id;
1063              if (!isset($this->course->cacherev)) {
1064                  $this->course = get_course($this->course_id);
1065              }
1066              if ($cacheddata = ($completioncache->get($key) ?: [])) {
1067                  if ($cacheddata['cacherev'] != $this->course->cacherev) {
1068                      // Course structure has been changed since the last caching, forget the cache.
1069                      $cacheddata = array();
1070                  } else if (isset($cacheddata[$cminfo->id])) {
1071                      $data = (array) $cacheddata[$cminfo->id];
1072                      if (empty($data['other_cm_completion_data_fetched'])) {
1073                          $data += $this->get_other_cm_completion_data($cminfo, $userid);
1074                          $data['other_cm_completion_data_fetched'] = true;
1075  
1076                          // Put in cache.
1077                          $cacheddata[$cminfo->id] = $data;
1078                          $completioncache->set($key, $cacheddata);
1079                      }
1080  
1081                      return $returnfilteredvalue($cacheddata[$cminfo->id]);
1082                  }
1083              }
1084          }
1085  
1086          // Default data to return when no completion data is found.
1087          $defaultdata = [
1088              'id' => 0,
1089              'coursemoduleid' => $cminfo->id,
1090              'userid' => $userid,
1091              'completionstate' => 0,
1092              'viewed' => 0,
1093              'overrideby' => null,
1094              'timemodified' => 0,
1095          ];
1096  
1097          // If cached completion data is not found, fetch via SQL.
1098          // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1099          // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1100          if ($usecache && $wholecourse) {
1101              // Get whole course data for cache.
1102              $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*,
1103                                                           CASE WHEN cmv.id IS NULL THEN 0 ELSE 1 END AS viewed
1104                                                      FROM {course_modules} cm
1105                                                 LEFT JOIN {course_modules_completion} cmc
1106                                                           ON cmc.coursemoduleid = cm.id  AND cmc.userid = ?
1107                                                 LEFT JOIN {course_modules_viewed} cmv
1108                                                           ON cmv.coursemoduleid = cm.id  AND cmv.userid = ?
1109                                                INNER JOIN {modules} m ON m.id = cm.module
1110                                                     WHERE m.visible = 1 AND cm.course = ?",
1111                  [$userid, $userid, $this->course->id]);
1112              $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();
1113  
1114              // Reindex by course module id.
1115              foreach ($alldatabycmc as $data) {
1116  
1117                  // Filter acitivites with no cm_info (missing plugins or other causes).
1118                  if (!isset($cminfos[$data->cmid])) {
1119                      continue;
1120                  }
1121  
1122                  if (empty($data->coursemoduleid)) {
1123                      $cacheddata[$data->cmid] = $defaultdata;
1124                      if ($data->viewed) {
1125                          $cacheddata[$data->cmid]['viewed'] = $data->viewed;
1126                      }
1127                      $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
1128                  } else {
1129                      unset($data->cmid);
1130                      $cacheddata[$data->coursemoduleid] = (array) $data;
1131                  }
1132              }
1133  
1134              if (!isset($cacheddata[$cminfo->id])) {
1135                  $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1136                  $this->internal_systemerror($errormessage);
1137              }
1138  
1139              $data = $cacheddata[$cminfo->id];
1140          } else {
1141              // Get single record
1142              $data = $this->get_completion_data($cminfo->id, $userid, $defaultdata);
1143              // Put in cache.
1144              $cacheddata[$cminfo->id] = $data;
1145          }
1146  
1147          // Fill the other completion data for this user in this module instance.
1148          $data += $this->get_other_cm_completion_data($cminfo, $userid);
1149          $data['other_cm_completion_data_fetched'] = true;
1150  
1151          // Put in cache
1152          $cacheddata[$cminfo->id] = $data;
1153  
1154          if ($usecache) {
1155              $cacheddata['cacherev'] = $this->course->cacherev;
1156              $completioncache->set($key, $cacheddata);
1157          }
1158  
1159          return $returnfilteredvalue($cacheddata[$cminfo->id]);
1160      }
1161  
1162      /**
1163       * Get the latest completion state for each criteria used in the module
1164       *
1165       * @param cm_info $cm The corresponding module's information
1166       * @param int $userid The id for the user we are calculating core completion state
1167       * @return array $data The individualised core completion state used in the module.
1168       *                      Consists of the following keys completiongrade, passgrade, viewed
1169       */
1170      public function get_core_completion_state(cm_info $cm, int $userid): array {
1171          global $DB;
1172          $data = [];
1173          // Include in the completion info the grade completion, if necessary.
1174          if (!is_null($cm->completiongradeitemnumber)) {
1175              $newstate = $this->get_grade_completion($cm, $userid);
1176              $data['completiongrade'] = $newstate;
1177  
1178              if ($cm->completionpassgrade) {
1179                  // If we are asking to use pass grade completion but haven't set it properly,
1180                  // then default to COMPLETION_COMPLETE_PASS.
1181                  if ($newstate == COMPLETION_COMPLETE) {
1182                      $newstate = COMPLETION_COMPLETE_PASS;
1183                  }
1184  
1185                  // No need to show failing status for the completiongrade condition when passing grade condition is set.
1186                  if (in_array($newstate, [COMPLETION_COMPLETE_FAIL, COMPLETION_COMPLETE_FAIL_HIDDEN])) {
1187                      $data['completiongrade'] = COMPLETION_COMPLETE;
1188  
1189                      // If the grade received by the user is a failing grade for a hidden grade item,
1190                      // the 'Require passing grade' criterion is considered incomplete.
1191                      if ($newstate == COMPLETION_COMPLETE_FAIL_HIDDEN) {
1192                          $newstate = COMPLETION_INCOMPLETE;
1193                      }
1194                  }
1195                  $data['passgrade'] = $newstate;
1196              }
1197          }
1198  
1199          // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1200          if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
1201              $data['viewed'] = COMPLETION_INCOMPLETE;
1202              $record = $DB->record_exists('course_modules_viewed', ['coursemoduleid' => $cm->id, 'userid' => $userid]);
1203              $data['viewed'] = $record ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE;
1204          }
1205  
1206          return $data;
1207      }
1208  
1209      /**
1210       * Adds the user's custom completion data on the given course module.
1211       *
1212       * @param cm_info $cm The course module information.
1213       * @param int $userid The user ID.
1214       * @return array The additional completion data.
1215       */
1216      protected function get_other_cm_completion_data(cm_info $cm, int $userid): array {
1217          $data = $this->get_core_completion_state($cm, $userid);
1218  
1219          // Custom activity module completion data.
1220  
1221          // Cast custom data to array before checking for custom completion rules.
1222          // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1223          // and we cannot call a getter from a getter in PHP.
1224          $customdata = (array) $cm->get_custom_data();
1225          // Return early if the plugin does not define custom completion rules.
1226          if (empty($customdata['customcompletionrules'])) {
1227              return $data;
1228          }
1229  
1230          // Return early if the activity modules doe not implement the activity_custom_completion class.
1231          $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cm->modname);
1232          if (!$cmcompletionclass) {
1233              return $data;
1234          }
1235  
1236          /** @var activity_custom_completion $customcmcompletion */
1237          $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1238          foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1239              if (!$enabled) {
1240                  // Skip inactive completion rules.
1241                  continue;
1242              }
1243              // Get this custom completion rule's completion state.
1244              $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1245          }
1246  
1247          return $data;
1248      }
1249  
1250      /**
1251       * Updates completion data for a particular coursemodule and user (user is
1252       * determined from $data).
1253       *
1254       * (Internal function. Not private, so we can unit-test it.)
1255       *
1256       * @param stdClass|cm_info $cm Activity
1257       * @param stdClass $data Data about completion for that user
1258       * @param bool $isbulkupdate If bulk grade update is happening.
1259       */
1260      public function internal_set_data($cm, $data, $isbulkupdate = false) {
1261          global $USER, $DB, $CFG;
1262          require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
1263  
1264          $transaction = $DB->start_delegated_transaction();
1265          if (!$data->id) {
1266              // Check there isn't really a row
1267              $data->id = $DB->get_field('course_modules_completion', 'id',
1268                      array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1269          }
1270          if (!$data->id) {
1271              // Didn't exist before, needs creating
1272              $data->id = $DB->insert_record('course_modules_completion', $data);
1273          } else {
1274              // Has real (nonzero) id meaning that a database row exists, update
1275              $DB->update_record('course_modules_completion', $data);
1276          }
1277          $dataview = new stdClass();
1278          $dataview->coursemoduleid = $data->coursemoduleid;
1279          $dataview->userid = $data->userid;
1280          $dataview->id = $DB->get_field('course_modules_viewed', 'id',
1281              ['coursemoduleid' => $dataview->coursemoduleid, 'userid' => $dataview->userid]);
1282          if (!$data->viewed && $dataview->id) {
1283              $DB->delete_records('course_modules_viewed', ['id' => $dataview->id]);
1284          }
1285  
1286          if (!$dataview->id && $data->viewed) {
1287              $dataview->timecreated = time();
1288              $dataview->id = $DB->insert_record('course_modules_viewed', $dataview);
1289          }
1290          $transaction->allow_commit();
1291  
1292          $cmcontext = context_module::instance($data->coursemoduleid);
1293  
1294          $completioncache = cache::make('core', 'completion');
1295          $cachekey = "{$data->userid}_{$cm->course}";
1296          if ($data->userid == $USER->id) {
1297              // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1298              $cminfo = cm_info::create($cm, $data->userid); // Make sure we're working on a cm_info object.
1299              $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid);
1300              foreach ($otherdata as $key => $value) {
1301                  $data->$key = $value;
1302              }
1303  
1304              // Update module completion in user's cache.
1305              if (!($cachedata = $completioncache->get($cachekey))
1306                      || $cachedata['cacherev'] != $this->course->cacherev) {
1307                  $cachedata = array('cacherev' => $this->course->cacherev);
1308              }
1309              $cachedata[$cm->id] = (array) $data;
1310              $cachedata[$cm->id]['other_cm_completion_data_fetched'] = true;
1311              $completioncache->set($cachekey, $cachedata);
1312  
1313              // reset modinfo for user (no need to call rebuild_course_cache())
1314              get_fast_modinfo($cm->course, 0, true);
1315          } else {
1316              // Remove another user's completion cache for this course.
1317              $completioncache->delete($cachekey);
1318          }
1319  
1320          // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1321          if ($isbulkupdate) {
1322              return;
1323          } else {
1324              $userdata = ['userid' => $data->userid, 'courseid' => $this->course_id];
1325              $coursecompletionid = \core_completion\api::mark_course_completions_activity_criteria($userdata);
1326              if ($coursecompletionid) {
1327                  aggregate_completions($coursecompletionid);
1328              }
1329          }
1330  
1331          // Trigger an event for course module completion changed.
1332          $event = \core\event\course_module_completion_updated::create(array(
1333              'objectid' => $data->id,
1334              'context' => $cmcontext,
1335              'relateduserid' => $data->userid,
1336              'other' => array(
1337                  'relateduserid' => $data->userid,
1338                  'overrideby' => $data->overrideby,
1339                  'completionstate' => $data->completionstate
1340              )
1341          ));
1342          $event->add_record_snapshot('course_modules_completion', $data);
1343          $event->trigger();
1344      }
1345  
1346       /**
1347       * Return whether or not the course has activities with completion enabled.
1348       *
1349       * @return boolean true when there is at least one activity with completion enabled.
1350       */
1351      public function has_activities() {
1352          $modinfo = get_fast_modinfo($this->course);
1353          foreach ($modinfo->get_cms() as $cm) {
1354              if ($cm->completion != COMPLETION_TRACKING_NONE) {
1355                  return true;
1356              }
1357          }
1358          return false;
1359      }
1360  
1361      /**
1362       * Obtains a list of activities for which completion is enabled on the
1363       * course. The list is ordered by the section order of those activities.
1364       *
1365       * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1366       *   empty array if none
1367       */
1368      public function get_activities() {
1369          $modinfo = get_fast_modinfo($this->course);
1370          $result = array();
1371          foreach ($modinfo->get_cms() as $cm) {
1372              if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1373                  $result[$cm->id] = $cm;
1374              }
1375          }
1376          return $result;
1377      }
1378  
1379      /**
1380       * Checks to see if the userid supplied has a tracked role in
1381       * this course
1382       *
1383       * @param int $userid User id
1384       * @return bool
1385       */
1386      public function is_tracked_user($userid) {
1387          return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1388      }
1389  
1390      /**
1391       * Returns the number of users whose progress is tracked in this course.
1392       *
1393       * Optionally supply a search's where clause, or a group id.
1394       *
1395       * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1396       * @param array $whereparams Where clause params
1397       * @param int $groupid Group id
1398       * @return int Number of tracked users
1399       */
1400      public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1401          global $DB;
1402  
1403          list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1404                  context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1405          $sql  = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1406          if ($where) {
1407              $sql .= " WHERE $where";
1408          }
1409  
1410          $params = array_merge($enrolledparams, $whereparams);
1411          return $DB->count_records_sql($sql, $params);
1412      }
1413  
1414      /**
1415       * Return array of users whose progress is tracked in this course.
1416       *
1417       * Optionally supply a search's where clause, group id, sorting, paging.
1418       *
1419       * @param string $where Where clause sql, referring to 'u.' fields (optional)
1420       * @param array $whereparams Where clause params (optional)
1421       * @param int $groupid Group ID to restrict to (optional)
1422       * @param string $sort Order by clause (optional)
1423       * @param int $limitfrom Result start (optional)
1424       * @param int $limitnum Result max size (optional)
1425       * @param context $extracontext If set, includes extra user information fields
1426       *   as appropriate to display for current user in this context
1427       * @return array Array of user objects with user fields (including all identity fields)
1428       */
1429      public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1430               $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1431  
1432          global $DB;
1433  
1434          list($enrolledsql, $params) = get_enrolled_sql(
1435                  context_course::instance($this->course->id),
1436                  'moodle/course:isincompletionreports', $groupid, true);
1437  
1438          $userfieldsapi = \core_user\fields::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1439          $fieldssql = $userfieldsapi->get_sql('u', true);
1440          $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
1441          $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1442  
1443          if ($where) {
1444              $sql .= " AND $where";
1445              $params = array_merge($params, $whereparams);
1446          }
1447  
1448          $sql .= $fieldssql->joins;
1449          $params = array_merge($params, $fieldssql->params);
1450  
1451          if ($sort) {
1452              $sql .= " ORDER BY $sort";
1453          }
1454  
1455          return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1456      }
1457  
1458      /**
1459       * Obtains progress information across a course for all users on that course, or
1460       * for all users in a specific group. Intended for use when displaying progress.
1461       *
1462       * This includes only users who, in course context, have one of the roles for
1463       * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1464       *
1465       * Users are included (in the first array) even if they do not have
1466       * completion progress for any course-module.
1467       *
1468       * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1469       *   last name
1470       * @param string $where Where clause sql (optional)
1471       * @param array $where_params Where clause params (optional)
1472       * @param int $groupid Group ID or 0 (default)/false for all groups
1473       * @param int $pagesize Number of users to actually return (optional)
1474       * @param int $start User to start at if paging (optional)
1475       * @param context $extracontext If set, includes extra user information fields
1476       *   as appropriate to display for current user in this context
1477       * @return stdClass with ->total and ->start (same as $start) and ->users;
1478       *   an array of user objects (like mdl_user id, firstname, lastname)
1479       *   containing an additional ->progress array of coursemoduleid => completionstate
1480       */
1481      public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1482              $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1483          global $CFG, $DB;
1484  
1485          // Get list of applicable users
1486          $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1487                  $start, $pagesize, $extracontext);
1488  
1489          // Get progress information for these users in groups of 1, 000 (if needed)
1490          // to avoid making the SQL IN too long
1491          $results = array();
1492          $userids = array();
1493          foreach ($users as $user) {
1494              $userids[] = $user->id;
1495              $results[$user->id] = $user;
1496              $results[$user->id]->progress = array();
1497          }
1498  
1499          for($i=0; $i<count($userids); $i+=1000) {
1500              $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1501  
1502              list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1503              array_splice($params, 0, 0, array($this->course->id));
1504              $rs = $DB->get_recordset_sql("
1505                  SELECT
1506                      cmc.*
1507                  FROM
1508                      {course_modules} cm
1509                      INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1510                  WHERE
1511                      cm.course=? AND cmc.userid $insql", $params);
1512              foreach ($rs as $progress) {
1513                  $progress = (object)$progress;
1514                  $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1515              }
1516              $rs->close();
1517          }
1518  
1519          return $results;
1520      }
1521  
1522      /**
1523       * Called by grade code to inform the completion system when a grade has
1524       * been changed. If the changed grade is used to determine completion for
1525       * the course-module, then the completion status will be updated.
1526       *
1527       * @param stdClass|cm_info $cm Course-module for item that owns grade
1528       * @param grade_item $item Grade item
1529       * @param stdClass $grade
1530       * @param bool $deleted
1531       * @param bool $isbulkupdate If bulk grade update is happening.
1532       */
1533      public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1534          // Bail out now if completion is not enabled for course-module, it is enabled
1535          // but is set to manual, grade is not used to compute completion, or this
1536          // is a different numbered grade
1537          if (!$this->is_enabled($cm) ||
1538              $cm->completion == COMPLETION_TRACKING_MANUAL ||
1539              is_null($cm->completiongradeitemnumber) ||
1540              $item->itemnumber != $cm->completiongradeitemnumber) {
1541              return;
1542          }
1543  
1544          // What is the expected result based on this grade?
1545          if ($deleted) {
1546              // Grade being deleted, so only change could be to make it incomplete
1547              $possibleresult = COMPLETION_INCOMPLETE;
1548          } else {
1549              $possibleresult = self::internal_get_grade_state($item, $grade);
1550          }
1551  
1552          // OK, let's update state based on this
1553          $this->update_state($cm, $possibleresult, $grade->userid, false, $isbulkupdate);
1554      }
1555  
1556      /**
1557       * Calculates the completion state that would result from a graded item
1558       * (where grade-based completion is turned on) based on the actual grade
1559       * and settings.
1560       *
1561       * Internal function. Not private, so we can unit-test it.
1562       *
1563       * @param grade_item $item an instance of grade_item
1564       * @param grade_grade $grade an instance of grade_grade
1565       * @param bool $returnpassfail If course module has pass grade completion criteria
1566       * @return int Completion state e.g. COMPLETION_INCOMPLETE
1567       */
1568      public static function internal_get_grade_state($item, $grade, bool $returnpassfail = false) {
1569          // If no grade is supplied or the grade doesn't have an actual value, then
1570          // this is not complete.
1571          if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1572              return COMPLETION_INCOMPLETE;
1573          }
1574  
1575          // Conditions to show pass/fail:
1576          // a) Completion criteria to achieve pass grade is enabled
1577          // or
1578          // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1579          // b) Grade is visible (neither hidden nor hidden-until)
1580          if ($item->gradepass && $item->gradepass > 0.000009 && ($returnpassfail || !$item->hidden)) {
1581              // Use final grade if set otherwise raw grade
1582              $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1583  
1584              // We are displaying and tracking pass/fail
1585              if ($score >= $item->gradepass) {
1586                  return COMPLETION_COMPLETE_PASS;
1587              } else if ($item->hidden) {
1588                  return COMPLETION_COMPLETE_FAIL_HIDDEN;
1589              } else {
1590                  return COMPLETION_COMPLETE_FAIL;
1591              }
1592          } else {
1593              // Not displaying pass/fail, so just if there is a grade
1594              if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1595                  // Grade exists, so maybe complete now
1596                  return COMPLETION_COMPLETE;
1597              } else {
1598                  // Grade does not exist, so maybe incomplete now
1599                  return COMPLETION_INCOMPLETE;
1600              }
1601          }
1602      }
1603  
1604      /**
1605       * Aggregate activity completion state
1606       *
1607       * @param   int     $type   Aggregation type (COMPLETION_* constant)
1608       * @param   bool    $old    Old state
1609       * @param   bool    $new    New state
1610       * @return  bool
1611       */
1612      public static function aggregate_completion_states($type, $old, $new) {
1613          if ($type == COMPLETION_AND) {
1614              return $old && $new;
1615          } else {
1616              return $old || $new;
1617          }
1618      }
1619  
1620      /**
1621       * This is to be used only for system errors (things that shouldn't happen)
1622       * and not user-level errors.
1623       *
1624       * @global type $CFG
1625       * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1626       * @throws moodle_exception Exception with the error string as debug info
1627       */
1628      public function internal_systemerror($error) {
1629          global $CFG;
1630          throw new moodle_exception('err_system','completion',
1631              $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1632      }
1633  
1634      /**
1635       * Get completion data include viewed field.
1636       *
1637       * @param int $coursemoduleid The course module id.
1638       * @param int $userid The User ID.
1639       * @param array $defaultdata Default data completion.
1640       * @return array Data completion retrieved.
1641       */
1642      public function get_completion_data(int $coursemoduleid, int $userid, array $defaultdata): array {
1643          global $DB;
1644  
1645          // MySQL doesn't support FULL JOIN syntax, so we use UNION in the below SQL to help MySQL.
1646          $sql = "SELECT cmc.*, cmv.coursemoduleid as cmvcoursemoduleid, cmv.userid as cmvuserid
1647                    FROM {course_modules_completion} cmc
1648               LEFT JOIN {course_modules_viewed} cmv ON cmc.coursemoduleid = cmv.coursemoduleid AND cmc.userid = cmv.userid
1649                   WHERE cmc.coursemoduleid = :cmccoursemoduleid AND cmc.userid = :cmcuserid
1650                  UNION
1651                  SELECT cmc2.*, cmv2.coursemoduleid as cmvcoursemoduleid, cmv2.userid as cmvuserid
1652                    FROM {course_modules_completion} cmc2
1653              RIGHT JOIN {course_modules_viewed} cmv2
1654                      ON cmc2.coursemoduleid = cmv2.coursemoduleid AND cmc2.userid = cmv2.userid
1655                   WHERE cmv2.coursemoduleid = :cmvcoursemoduleid AND cmv2.userid = :cmvuserid";
1656  
1657          $data = $DB->get_record_sql($sql, ['cmccoursemoduleid' => $coursemoduleid, 'cmcuserid' => $userid,
1658              'cmvcoursemoduleid' => $coursemoduleid, 'cmvuserid' => $userid]);
1659  
1660          if (!$data) {
1661              $data = $defaultdata;
1662          } else {
1663              if (empty($data->coursemoduleid) && empty($data->userid)) {
1664                  $data->coursemoduleid = $data->cmvcoursemoduleid;
1665                  $data->userid = $data->cmvuserid;
1666              }
1667              unset($data->cmvcoursemoduleid);
1668              unset($data->cmvuserid);
1669  
1670              // When reseting all state in the completion, we need to keep current view state.
1671              $data->viewed = 1;
1672          }
1673  
1674          return (array)$data;
1675      }
1676  }
1677  
1678  /**
1679   * Aggregate criteria status's as per configured aggregation method.
1680   *
1681   * @param int $method COMPLETION_AGGREGATION_* constant.
1682   * @param bool $data Criteria completion status.
1683   * @param bool|null $state Aggregation state.
1684   */
1685  function completion_cron_aggregate($method, $data, &$state) {
1686      if ($method == COMPLETION_AGGREGATION_ALL) {
1687          if ($data && $state !== false) {
1688              $state = true;
1689          } else {
1690              $state = false;
1691          }
1692      } else if ($method == COMPLETION_AGGREGATION_ANY) {
1693          if ($data) {
1694              $state = true;
1695          } else if (!$data && $state === null) {
1696              $state = false;
1697          }
1698      }
1699  }
1700  
1701  /**
1702   * Aggregate courses completions. This function is called when activity completion status is updated
1703   * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1704   *
1705   * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1706   * @param bool $mtraceprogress To output debug info
1707   * @since Moodle 4.0
1708   */
1709  function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1710      global $DB;
1711  
1712      if (!$coursecompletionid && $mtraceprogress) {
1713          mtrace('Aggregating completions');
1714      }
1715      // Save time started.
1716      $timestarted = time();
1717  
1718      // Grab all criteria and their associated criteria completions.
1719      $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1720                         FROM {course_completion_criteria} cr
1721                   INNER JOIN {course} c ON cr.course = c.id
1722                   INNER JOIN {course_completions} cco ON cco.course = c.id
1723                    LEFT JOIN {course_completion_crit_compl} ccocr
1724                           ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1725                        WHERE c.enablecompletion = 1
1726                          AND cco.timecompleted IS NULL
1727                          AND cco.reaggregate > 0";
1728  
1729      if ($coursecompletionid) {
1730          $sql .= " AND cco.id = ?";
1731          $param = $coursecompletionid;
1732      } else {
1733          $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1734          $param = $timestarted;
1735      }
1736      $rs = $DB->get_recordset_sql($sql, [$param]);
1737  
1738      // Check if result is empty.
1739      if (!$rs->valid()) {
1740          $rs->close();
1741          return;
1742      }
1743  
1744      $currentuser = null;
1745      $currentcourse = null;
1746      $completions = [];
1747      while (1) {
1748          // Grab records for current user/course.
1749          foreach ($rs as $record) {
1750              // If we are still grabbing the same users completions.
1751              if ($record->userid === $currentuser && $record->courseid === $currentcourse) {
1752                  $completions[$record->criteriaid] = $record;
1753              } else {
1754                  break;
1755              }
1756          }
1757  
1758          // Aggregate.
1759          if (!empty($completions)) {
1760              if (!$coursecompletionid && $mtraceprogress) {
1761                  mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1762              }
1763  
1764              // Get course info object.
1765              $info = new \completion_info((object)['id' => $currentcourse]);
1766  
1767              // Setup aggregation.
1768              $overall = $info->get_aggregation_method();
1769              $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
1770              $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
1771              $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
1772  
1773              $overallstatus = null;
1774              $activitystatus = null;
1775              $prerequisitestatus = null;
1776              $rolestatus = null;
1777  
1778              // Get latest timecompleted.
1779              $timecompleted = null;
1780  
1781              // Check each of the criteria.
1782              foreach ($completions as $params) {
1783                  $timecompleted = max($timecompleted, $params->timecompleted);
1784                  $completion = new \completion_criteria_completion((array)$params, false);
1785  
1786                  // Handle aggregation special cases.
1787                  if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
1788                      completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1789                  } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
1790                      completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1791                  } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
1792                      completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1793                  } else {
1794                      completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1795                  }
1796              }
1797  
1798              // Include role criteria aggregation in overall aggregation.
1799              if ($rolestatus !== null) {
1800                  completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1801              }
1802  
1803              // Include activity criteria aggregation in overall aggregation.
1804              if ($activitystatus !== null) {
1805                  completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1806              }
1807  
1808              // Include prerequisite criteria aggregation in overall aggregation.
1809              if ($prerequisitestatus !== null) {
1810                  completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1811              }
1812  
1813              // If aggregation status is true, mark course complete for user.
1814              if ($overallstatus) {
1815                  if (!$coursecompletionid && $mtraceprogress) {
1816                      mtrace('Marking complete');
1817                  }
1818  
1819                  $ccompletion = new \completion_completion([
1820                      'course' => $params->courseid,
1821                      'userid' => $params->userid
1822                  ]);
1823                  $ccompletion->mark_complete($timecompleted);
1824              }
1825          }
1826  
1827          // If this is the end of the recordset, break the loop.
1828          if (!$rs->valid()) {
1829              $rs->close();
1830              break;
1831          }
1832  
1833          // New/next user, update user details, reset completions.
1834          $currentuser = $record->userid;
1835          $currentcourse = $record->courseid;
1836          $completions = [];
1837          $completions[$record->criteriaid] = $record;
1838      }
1839  
1840      // Mark all users as aggregated.
1841      if ($coursecompletionid) {
1842          $select = "reaggregate > 0 AND id = ?";
1843          $param = $coursecompletionid;
1844      } else {
1845          $select = "reaggregate > 0 AND reaggregate < ?";
1846          $param = $timestarted;
1847          if (PHPUNIT_TEST) {
1848              // MDL-33320: for instant completions we need aggregate to work in a single run.
1849              $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1850          }
1851      }
1852      $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);
1853  }