public function set_related_tags($tagnames) {
        $context = context_system::instance();
        $tagobjects = $tagnames ? static::create_if_missing($this->tagcollid, $tagnames) : array();
        unset($tagobjects[$this->name]); // Never link to itself.

        $currenttags = static::get_item_tags('core', 'tag', $this->id);

        // For data coherence reasons, it's better to remove deleted tags
        // before adding new data: ordering could be duplicated.
        foreach ($currenttags as $currenttag) {
            if (!array_key_exists($currenttag->name, $tagobjects)) {
                $taginstance = (object)array('id' => $currenttag->taginstanceid,
                    'itemtype' => 'tag', 'itemid' => $this->id,
                    'contextid' => $context->id);
                $currenttag->delete_instance_as_record($taginstance, false);
                $this->delete_instance('core', 'tag', $currenttag->id);
            }
        }

        foreach ($tagobjects as $name => $tag) {
            foreach ($currenttags as $currenttag) {
                if ($currenttag->name === $name) {
                    continue 2;
                }
            }
            $this->add_instance('core', 'tag', $tag->id, $context, 0);
            $tag->add_instance('core', 'tag', $this->id, $context, 0);
            $currenttags[] = $tag;
        }
    }