public static function add_item_tag($component, $itemtype, $itemid, context $context, $tagname, $tiuserid = 0) {
        global $DB;

        if (static::is_enabled($component, $itemtype) === false) {
            // Tagging area is properly defined but not enabled - do nothing.
            return null;
        }

        $rawname = clean_param($tagname, PARAM_TAG);
        $normalisedname = core_text::strtolower($rawname);
        $tagcollid = core_tag_area::get_collection($component, $itemtype);

        $usersql = $tiuserid ? " AND ti.tiuserid = :tiuserid " : "";
        $sql = 'SELECT t.*, ti.id AS taginstanceid
                FROM {tag} t
                LEFT JOIN {tag_instance} ti ON ti.tagid = t.id AND ti.itemtype = :itemtype '.
                $usersql .
                'AND ti.itemid = :itemid AND ti.component = :component
                WHERE t.name = :name AND t.tagcollid = :tagcollid';
        $params = array('name' => $normalisedname, 'tagcollid' => $tagcollid, 'itemtype' => $itemtype,
            'itemid' => $itemid, 'component' => $component, 'tiuserid' => $tiuserid);
        $record = $DB->get_record_sql($sql, $params);
        if ($record) {
            if ($record->taginstanceid) {
                // Tag was already added to the item, nothing to do here.
                return $record->taginstanceid;
            }
            $tag = new static($record);
        } else {
            // The tag does not exist yet, create it.
            $tags = static::add($tagcollid, array($tagname));
            $tag = reset($tags);
        }

        $ordering = $DB->get_field_sql('SELECT MAX(ordering) FROM {tag_instance} ti
                WHERE ti.itemtype = :itemtype AND ti.itemid = :itemid AND
                ti.component = :component' . $usersql, $params);

        return $tag->add_instance($component, $itemtype, $itemid, $context, $ordering + 1, $tiuserid);
    }