protected static function duplicate_competency_tree($frameworkid, $tree, $oldparent = 0, $newparent = 0) {
        $matchids = array();
        foreach ($tree as $node) {
            if ($node->competency->get('parentid') == $oldparent) {
                $parentid = $node->competency->get('id');

                // Create the competency.
                $competency = new competency(0, $node->competency->to_record());
                $competency->set('competencyframeworkid', $frameworkid);
                $competency->set('parentid', $newparent);
                $competency->set('path', '');
                $competency->set('id', 0);
                $competency->reset_rule();
                $competency->create();

                // Trigger the created event competency.
                \core\event\competency_created::create_from_competency($competency)->trigger();

                // Match the old id with the new one.
                $matchids[$parentid] = $competency;

                if (!empty($node->children)) {
                    // Duplicate children competency.
                    $childrenids = self::duplicate_competency_tree($frameworkid, $node->children, $parentid, $competency->get('id'));
                    // Array_merge does not keep keys when merging so we use the + operator.
                    $matchids = $matchids + $childrenids;
                }
            }
        }
        return $matchids;
    }