public static function unlink_plan_from_template($planorid) {
        global $DB;
        static::require_enabled();

        $plan = $planorid;
        if (!is_object($planorid)) {
            $plan = new plan($planorid);
        }

        // The user must be allowed to manage the plans of the user, nothing about the template.
        if (!$plan->can_manage()) {
            throw new required_capability_exception($plan->get_context(), 'moodle/competency:planmanage', 'nopermissions', '');
        }

        // Only plan with status DRAFT or ACTIVE can be unliked..
        if ($plan->get('status') == plan::STATUS_COMPLETE) {
            throw new coding_exception('Only draft or active plan can be unliked from a template');
        }

        // Early exit, it's already done...
        if (!$plan->is_based_on_template()) {
            return true;
        }

        // Fetch the template.
        $template = new template($plan->get('templateid'));

        // Now, proceed by copying all competencies to the plan, then update the plan.
        $transaction = $DB->start_delegated_transaction();
        $competencies = template_competency::list_competencies($template->get('id'), false);
        $i = 0;
        foreach ($competencies as $competency) {
            $record = (object) array(
                'planid' => $plan->get('id'),
                'competencyid' => $competency->get('id'),
                'sortorder' => $i++
            );
            $pc = new plan_competency(null, $record);
            $pc->create();
        }
        $plan->set('origtemplateid', $template->get('id'));
        $plan->set('templateid', null);
        $success = $plan->update();
        $transaction->allow_commit();

        // Trigger unlinked event.
        \core\event\competency_plan_unlinked::create_from_plan($plan)->trigger();

        return $success;
    }