Link a user evidence with a competency.

@param  user_evidence|int $userevidenceorid User evidence or its ID.
@param  int $competencyid Competency ID.
@return user_evidence_competency
333810
public static function create_user_evidence_competency($userevidenceorid, $competencyid) {
        global $USER;
        static::require_enabled();

        $userevidence = $userevidenceorid;
        if (!is_object($userevidence)) {
            $userevidence = self::read_user_evidence($userevidence);
        }

        // Perform user evidence capability checks.
        if (!$userevidence->can_manage()) {
            $context = $userevidence->get_context();
            throw new required_capability_exception($context, 'moodle/competency:userevidencemanage', 'nopermissions', '');
        }

        // Perform competency capability checks.
        $competency = self::read_competency($competencyid);

        // Get (and create) the relation.
        $relation = user_evidence_competency::get_relation($userevidence->get('id'), $competency->get('id'));
        if (!$relation->get('id')) {
            $relation->create();

            $link = url::user_evidence($userevidence->get('id'));
            self::add_evidence(
                $userevidence->get('userid'),
                $competency,
                $userevidence->get_context(),
                evidence::ACTION_LOG,
                'evidence_evidenceofpriorlearninglinked',
                'core_competency',
                $userevidence->get('name'),
                false,
                $link->out(false),
                null,
                $USER->id
            );
        }

        return $relation;
    }
931395
public static function can_read_user($evidenceuserid) {
        $context = context_user::instance($evidenceuserid);

        $capabilities = array('moodle/competency:userevidenceview');

        return has_any_capability($capabilities, $context) || self::can_manage_user($evidenceuserid);
    }
811677
public static function remove_competency_from_template($templateid, $competencyid) {
        static::require_enabled();
        // First we do a permissions check.
        $template = new template($templateid);
        if (!$template->can_manage()) {
            throw new required_capability_exception($template->get_context(), 'moodle/competency:templatemanage',
                'nopermissions', '');
        }

        $record = new stdClass();
        $record->templateid = $templateid;
        $record->competencyid = $competencyid;

        $competency = new competency($competencyid);

        $exists = template_competency::get_records(array('templateid' => $templateid, 'competencyid' => $competencyid));
        if ($exists) {
            $link = array_pop($exists);
            return $link->delete();
        }
        return false;
    }
397077
public static function list_user_competencies_in_course($courseid, $userid) {
        static::require_enabled();
        // First we do a permissions check.
        $context = context_course::instance($courseid);
        $onlyvisible = 1;

        $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
        if (!has_any_capability($capabilities, $context)) {
            throw new required_capability_exception($context, 'moodle/competency:coursecompetencyview', 'nopermissions', '');
        } else if (!user_competency::can_read_user_in_course($userid, $courseid)) {
            throw new required_capability_exception($context, 'moodle/competency:usercompetencyview', 'nopermissions', '');
        }

        // OK - all set.
        $competencylist = course_competency::list_competencies($courseid, false);

        $existing = user_competency_course::get_multiple($userid, $courseid, $competencylist);
        // Create missing.
        $orderedusercompetencycourses = array();

        $somemissing = false;
        foreach ($competencylist as $coursecompetency) {
            $found = false;
            foreach ($existing as $usercompetencycourse) {
                if ($usercompetencycourse->get('competencyid') == $coursecompetency->get('id')) {
                    $found = true;
                    $orderedusercompetencycourses[$usercompetencycourse->get('id')] = $usercompetencycourse;
                    break;
                }
            }
            if (!$found) {
                $ucc = user_competency_course::create_relation($userid, $coursecompetency->get('id'), $courseid);
                $ucc->create();
                $orderedusercompetencycourses[$ucc->get('id')] = $ucc;
            }
        }

        return $orderedusercompetencycourses;
    }
773978
public static function data_for_user_competency_summary($userid, $competencyid) {
        global $PAGE;
        $params = self::validate_parameters(self::data_for_user_competency_summary_parameters(), array(
            'userid' => $userid,
            'competencyid' => $competencyid,
        ));

        $uc = api::get_user_competency($params['userid'], $params['competencyid']);
        self::validate_context($uc->get_context());
        $output = $PAGE->get_renderer('tool_lp');

        $renderable = new \tool_lp\output\user_competency_summary($uc);
        return $renderable->export_for_template($output);
    }
1044409
protected static function archive_user_competencies_in_plan($plan) {

        // Check if the plan was already completed.
        if ($plan->get('status') == plan::STATUS_COMPLETE) {
            throw new coding_exception('The plan is already completed.');
        }

        $competencies = $plan->get_competencies();
        $usercompetencies = user_competency::get_multiple($plan->get('userid'), $competencies);

        $i = 0;
        foreach ($competencies as $competency) {
            $found = false;

            foreach ($usercompetencies as $uckey => $uc) {
                if ($uc->get('competencyid') == $competency->get('id')) {
                    $found = true;

                    $ucprecord = $uc->to_record();
                    $ucprecord->planid = $plan->get('id');
                    $ucprecord->sortorder = $i;
                    unset($ucprecord->id);
                    unset($ucprecord->status);
                    unset($ucprecord->reviewerid);

                    $usercompetencyplan = new user_competency_plan(0, $ucprecord);
                    $usercompetencyplan->create();

                    unset($usercompetencies[$uckey]);
                    break;
                }
            }

            // If the user competency doesn't exist, we create a new relation in user_competency_plan.
            if (!$found) {
                $usercompetencyplan = user_competency_plan::create_relation($plan->get('userid'), $competency->get('id'),
                        $plan->get('id'));
                $usercompetencyplan->set('sortorder', $i);
                $usercompetencyplan->create();
            }
            $i++;
        }
    }
40799
public function findByCompetencyAndUser(Competency $competency, User $user)
    {
        $groupQb = $this->_em->createQueryBuilder()
            ->select('g')
            ->from('Claroline\CoreBundle\Entity\Group', 'g')
            ->join('g.users', 'gu')
            ->where('gu = :user');

        return $this->createQueryBuilder('o')
            ->select('o')
            ->leftJoin('o.objectiveCompetencies', 'oc')
            ->leftJoin('o.users', 'ou')
            ->leftJoin('o.groups', 'og')
            ->where('oc.competency = :competency')
            ->andWhere($groupQb->expr()->orX(
                'ou = :user',
                $groupQb->expr()->in('og', $groupQb->getQuery()->getDQL())
            ))
            ->setParameters([
                'competency' => $competency,
                'user' => $user,
            ])
            ->distinct()
            ->getQuery()
            ->getResult();
    }
1161184
public static function count_courses_using_competency($competencyid) {
        $params = self::validate_parameters(self::count_courses_using_competency_parameters(), array(
            'id' => $competencyid,
        ));

        $competency = api::read_competency($params['id']);
        self::validate_context($competency->get_context());

        return api::count_courses_using_competency($params['id']);
    }
87623
protected static function export_user_data_learning_plans_related_to_me($userid, context_user $context) {
        global $DB;

        $path = [
            get_string('competencies', 'core_competency'),
            get_string('privacy:path:relatedtome', 'core_competency'),
            get_string('privacy:path:plans', 'core_competency'),
        ];
        $plans = [];
        $helper = new performance_helper();
        $pfields = plan::get_sql_fields('p', 'p_');
        $pcfields = plan_competency::get_sql_fields('pc', 'pc_');
        $cfields = competency::get_sql_fields('c', 'c_');
        $ucpfields = user_competency_plan::get_sql_fields('ucp', 'ucp_');

        // Function to initialise a plan record.
        $initplan = function($record) use ($context, $userid, &$plans) {
            $plan = new plan(null, plan::extract_record($record, 'p_'));
            $options = ['context' => $context];
            $plans[$plan->get('id')] = [
                'name' => format_string($plan->get('name'), true, $options),
                'reviewer_is_you' => transform::yesno($plan->get('reviewerid') == $userid),
                'timecreated' => transform::datetime($plan->get('timecreated')),
                'timemodified' => transform::datetime($plan->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno($plan->get('usermodified') == $userid),
                'competencies' => [],
            ];
        };

        $initcompetency = function($record, $planid) use (&$plans) {
            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $plans[$planid]['competencies'][$competency->get('id')] = static::transform_competency_brief($competency);
        };

        // Look for associations that were created.
        $sql = "
            SELECT $pfields, $pcfields, $cfields
              FROM {" . plan_competency::TABLE . "} pc
              JOIN {" . plan::TABLE . "} p
                ON p.id = pc.planid
              JOIN {" . competency::TABLE . "} c
                ON c.id = pc.competencyid
             WHERE p.userid = :targetuserid
               AND pc.usermodified = :userid
          ORDER BY p.id, c.id";
        $params = [
            'targetuserid' => $context->instanceid,
            'userid' => $userid,
        ];

        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $planid = $record->p_id;
            if (!isset($plans[$planid])) {
                $initplan($record);
            }

            $initcompetency($record, $planid);
            $pc = new plan_competency(null, plan_competency::extract_record($record, 'pc_'));
            $plans[$planid]['competencies'][$pc->get('competencyid')] = array_merge(
                $plans[$planid]['competencies'][$pc->get('competencyid')], [
                    'timemodified' => $pc->get('timemodified') ? transform::datetime($pc->get('timemodified')) : '-',
                    'timecreated' => $pc->get('timecreated') ? transform::datetime($pc->get('timecreated')) : '-',
                    'created_or_modified_by_you' => transform::yesno($pc->get('usermodified') == $userid),
                ]
            );
        }
        $recordset->close();

        // Look for final grades that were given.
        $sql = "
            SELECT $pfields, $ucpfields, $cfields
              FROM {" . user_competency_plan::TABLE . "} ucp
              JOIN {" . plan::TABLE . "} p
                ON p.id = ucp.planid
              JOIN {" . competency::TABLE . "} c
                ON c.id = ucp.competencyid
             WHERE p.userid = :targetuserid
               AND ucp.usermodified = :userid
          ORDER BY p.id, c.id";
        $params = [
            'targetuserid' => $context->instanceid,
            'userid' => $userid,
        ];

        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $planid = $record->p_id;
            $competencyid = $record->c_id;

            if (!isset($plans[$planid])) {
                $initplan($record);
            }

            if (!isset($plans[$planid]['competencies'][$competencyid])) {
                $initcompetency($record, $planid);
            }

            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $ucp = new user_competency_plan(null, user_competency_plan::extract_record($record, 'ucp_'));
            $plans[$planid]['competencies'][$competencyid]['rating'] = static::transform_user_competency($userid, $ucp,
                $competency, $helper);
        }
        $recordset->close();

        // Find the plans that were modified or reviewed.
        $insql = " > 0";
        $inparams = [];
        if (!empty($plans)) {
            list($insql, $inparams) = $DB->get_in_or_equal(array_keys($plans), SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $pfields
              FROM {" . plan::TABLE . "} p
         LEFT JOIN {comments} c
                ON c.contextid = :contextid
               AND c.commentarea = :planarea
               AND c.component = :competency
               AND c.itemid = p.id
             WHERE p.userid = :targetuserid
               AND (p.usermodified = :userid1
                OR p.reviewerid = :userid2
                OR c.userid = :userid3)
               AND p.id $insql
          ORDER BY p.id";
        $params = array_merge($inparams, [
            'targetuserid' => $context->instanceid,
            'userid1' => $userid,
            'userid2' => $userid,
            'userid3' => $userid,
            'contextid' => $context->id,
            'planarea' => 'plan',
            'competency' => 'competency'
        ]);

        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $planid = $record->p_id;
            if (!isset($plans[$planid])) {
                $initplan($record);
            }
        }
        $recordset->close();

        // Export each plan on its own.
        foreach ($plans as $planid => $plan) {
            $planpath = array_merge($path, ["{$plan['name']} ({$planid})"]);
            $plan['competencies'] = array_values($plan['competencies']);    // Drop the keys.

            writer::with_context($context)->export_data($planpath, (object) $plan);
            \core_comment\privacy\provider::export_comments($context, 'competency', 'plan', $planid, $planpath, true);
        }
    }
615800
public static final function create_from_user_evidence(user_evidence $userevidence) {
        if (!$userevidence->get('id')) {
            throw new \coding_exception('The evidence of prior learning ID must be set.');
        }
        $event = static::create(array(
            'contextid'  => $userevidence->get_context()->id,
            'objectid' => $userevidence->get('id'),
            'relateduserid' => $userevidence->get('userid')
        ));
        $event->add_record_snapshot(user_evidence::TABLE, $userevidence->to_record());
        return $event;
    }
425076
public function matches(user_competency $usercompetency) {
        global $DB;

        // TODO Improve performance here, perhaps the caller could already provide records.
        $children = competency::get_records(array('parentid' => $this->competency->get('id')));

        if (empty($children)) {
            // Leaves are not compatible with this rule.
            return false;
        }

        $ids = array();
        foreach ($children as $child) {
            $ids[] = $child->get('id');
        }

        list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
        $sql = "userid = :userid
            AND proficiency = :proficiency
            AND competencyid $insql";
        $params['userid'] = $usercompetency->get('userid');
        $params['proficiency'] = 1;

        // Is the user is marked as proficient in all children?
        return user_competency::count_records_select($sql, $params) === count($ids);
    }
402980
public static function get_user_competency($userid, $competencyid) {
        static::require_enabled();
        $existing = user_competency::get_multiple($userid, array($competencyid));
        $uc = array_pop($existing);

        if (!$uc) {
            $uc = user_competency::create_relation($userid, $competencyid);
            $uc->create();
        }

        if (!$uc->can_read()) {
            throw new required_capability_exception($uc->get_context(), 'moodle/competency:usercompetencyview',
                'nopermissions', '');
        }
        return $uc;
    }
239527
public static function add_related_competency($competencyid, $relatedcompetencyid) {
        $params = self::validate_parameters(self::add_related_competency_parameters(), array(
            'competencyid' => $competencyid,
            'relatedcompetencyid' => $relatedcompetencyid
        ));
        $competency = api::read_competency($params['competencyid']);
        self::validate_context($competency->get_context());

        return api::add_related_competency($params['competencyid'], $params['relatedcompetencyid']);
    }
367114
public static function user_competency_viewed_in_plan($competencyid, $userid, $planid) {
        $params = self::validate_parameters(self::user_competency_viewed_in_plan_parameters(), array(
            'competencyid' => $competencyid,
            'userid' => $userid,
            'planid' => $planid
        ));
        $pl = api::get_plan_competency($params['planid'], $params['competencyid']);
        $result = api::user_competency_viewed_in_plan($pl->usercompetency, $params['planid']);

        return $result;
    }
576874
public static function move_up_competency($competencyid) {
        $params = self::validate_parameters(self::move_up_competency_parameters(), array(
            'id' => $competencyid,
        ));

        $competency = api::read_competency($params['id']);
        self::validate_context($competency->get_context());

        return api::move_up_competency($params['id']);
    }
1334600
public static function grade_competency($userid, $competencyid, $grade, $note = null) {
        global $USER, $PAGE;
        $params = self::validate_parameters(self::grade_competency_parameters(), array(
            'userid' => $userid,
            'competencyid' => $competencyid,
            'grade' => $grade,
            'note' => $note
        ));

        $uc = api::get_user_competency($params['userid'], $params['competencyid']);
        self::validate_context($uc->get_context());

        $output = $PAGE->get_renderer('core');
        $evidence = api::grade_competency(
                $uc->get('userid'),
                $uc->get('competencyid'),
                $params['grade'],
                $params['note']
        );

        $scale = $uc->get_competency()->get_scale();
        $exporter = new evidence_exporter($evidence, [
            'actionuser' => $USER,
            'scale' => $scale,
            'usercompetency' => $uc,
            'usercompetencyplan' => null,
            'context' => $evidence->get_context()
        ]);
        return $exporter->export($output);
    }
696897
protected static function export_user_data_user_evidence_related_to_me($userid, context_user $context) {
        global $DB;

        $path = [
            get_string('competencies', 'core_competency'),
            get_string('privacy:path:relatedtome', 'core_competency'),
            get_string('privacy:path:userevidence', 'core_competency'),
        ];
        $evidence = [];
        $helper = new performance_helper();
        $cfields = competency::get_sql_fields('c', 'c_');
        $uecfields = user_evidence_competency::get_sql_fields('uec', 'uec_');
        $uefields = user_evidence::get_sql_fields('ue', 'ue_');

        $initevidence = function($record) use (&$evidence, $userid) {
            $ue = new user_evidence(null, user_evidence::extract_record($record, 'ue_'));
            $evidence[$ue->get('id')] = static::transform_user_evidence($userid, $ue);
        };

        // Look for evidence.
        $sql = "
            SELECT $uefields, $uecfields, $cfields
              FROM {" . user_evidence_competency::TABLE . "} uec
              JOIN {" . user_evidence::TABLE . "} ue
                ON ue.id = uec.userevidenceid
              JOIN {" . competency::TABLE . "} c
                ON c.id = uec.competencyid
             WHERE ue.userid = :targetuserid
               AND uec.usermodified = :userid
          ORDER BY ue.id, c.id";
        $params = [
            'targetuserid' => $context->instanceid,
            'userid' => $userid,
        ];
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $ueid = $record->ue_id;
            if (!isset($evidence[$ueid])) {
                $initevidence($record);
            }

            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $uec = new user_evidence_competency(null, user_evidence_competency::extract_record($record, 'uec_'));
            $evidence[$ueid]['competencies'][] = array_merge(static::transform_competency_brief($competency), [
                'timemodified' => $uec->get('timemodified') ? transform::datetime($uec->get('timemodified')) : '-',
                'timecreated' => $uec->get('timecreated') ? transform::datetime($uec->get('timecreated')) : '-',
                'created_or_modified_by_you' => transform::yesno($uec->get('usermodified'))
            ]);
        }
        $recordset->close();

        // Look for user evidence we modified or reviewed and didn't catch.
        $insql = ' > 0';
        $inparams = [];
        if (!empty($evidence)) {
            list($insql, $inparams) = $DB->get_in_or_equal(array_keys($evidence), SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $uefields
              FROM {" . user_evidence::TABLE . "} ue
             WHERE ue.userid = :targetuserid
               AND ue.usermodified = :userid
               AND ue.id $insql
          ORDER BY ue.id";
        $params = array_merge($inparams, [
            'targetuserid' => $context->instanceid,
            'userid' => $userid,
        ]);

        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $initevidence($record);
        }
        $recordset->close();

        // Export files, then content.
        foreach ($evidence as $ueid => $data) {
            $uepath = array_merge($path, ["{$data['name']} ({$ueid})"]);
            writer::with_context($context)->export_area_files($uepath, 'core_competency', 'userevidence', $ueid);
            writer::with_context($context)->export_data($uepath, (object) $data);
        }
    }