public static function reorder_template_competency($templateid, $competencyidfrom, $competencyidto) {
        static::require_enabled();
        $template = new template($templateid);

        // First we do a permissions check.
        if (!$template->can_manage()) {
            throw new required_capability_exception($template->get_context(), 'moodle/competency:templatemanage',
                'nopermissions', '');
        }

        $down = true;
        $matches = template_competency::get_records(array('templateid' => $templateid, 'competencyid' => $competencyidfrom));
        if (count($matches) == 0) {
            throw new coding_exception('The link does not exist');
        }

        $competencyfrom = array_pop($matches);
        $matches = template_competency::get_records(array('templateid' => $templateid, 'competencyid' => $competencyidto));
        if (count($matches) == 0) {
            throw new coding_exception('The link does not exist');
        }

        $competencyto = array_pop($matches);

        $all = template_competency::get_records(array('templateid' => $templateid), 'sortorder', 'ASC', 0, 0);

        if ($competencyfrom->get('sortorder') > $competencyto->get('sortorder')) {
            // We are moving up, so put it before the "to" item.
            $down = false;
        }

        foreach ($all as $id => $templatecompetency) {
            $sort = $templatecompetency->get('sortorder');
            if ($down && $sort > $competencyfrom->get('sortorder') && $sort <= $competencyto->get('sortorder')) {
                $templatecompetency->set('sortorder', $templatecompetency->get('sortorder') - 1);
                $templatecompetency->update();
            } else if (!$down && $sort >= $competencyto->get('sortorder') && $sort < $competencyfrom->get('sortorder')) {
                $templatecompetency->set('sortorder', $templatecompetency->get('sortorder') + 1);
                $templatecompetency->update();
            }
        }
        $competencyfrom->set('sortorder', $competencyto->get('sortorder'));
        return $competencyfrom->update();
    }