protected function apply_completion_cm(\cm_info $cm, $data, $updateinstance) {
        global $DB;

        $defaults = ['completion' => COMPLETION_DISABLED, 'completionview' => COMPLETION_VIEW_NOT_REQUIRED,
            'completionexpected' => 0, 'completiongradeitemnumber' => null];

        $data += ['completion' => $cm->completion,
            'completionexpected' => $cm->completionexpected,
            'completionview' => $cm->completionview];

        if ($cm->completion == $data['completion'] && $cm->completion == COMPLETION_TRACKING_NONE) {
            // If old and new completion are both "none" - no changes are needed.
            return false;
        }

        if ($cm->completion == $data['completion'] && $cm->completion == COMPLETION_TRACKING_NONE &&
                $cm->completionexpected == $data['completionexpected']) {
            // If old and new completion are both "manual" and completion expected date is not changed - no changes are needed.
            return false;
        }

        if (array_key_exists('completionusegrade', $data)) {
            // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
            $data['completiongradeitemnumber'] = !empty($data['completionusegrade']) ? 0 : null;
            unset($data['completionusegrade']);
        } else {
            $data['completiongradeitemnumber'] = $cm->completiongradeitemnumber;
        }

        // Update module instance table.
        if ($updateinstance) {
            $moddata = ['id' => $cm->instance, 'timemodified' => time()] + array_diff_key($data, $defaults);
            $DB->update_record($cm->modname, $moddata);
        }

        // Update course modules table.
        $cmdata = ['id' => $cm->id, 'timemodified' => time()] + array_intersect_key($data, $defaults);
        $DB->update_record('course_modules', $cmdata);

        \core\event\course_module_updated::create_from_cm($cm, $cm->context)->trigger();

        // We need to reset completion data for this activity.
        return true;
    }