예제 #1
0
/**
 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
 *
 * @package core_tag
 * @access private
 * @param string $record_type the type of the record that will be tagged
 * @param int $record_id the id of the record that will be tagged
 * @param string $tagid the tag id to set on the record.
 * @param int $ordering the order of the instance for this record
 * @param int $userid (optional) only required for course tagging
 * @param string|null $component the component that was tagged
 * @param int|null $contextid the context id of where this tag was assigned
 * @return bool true on success, false otherwise
 */
function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null)
{
    global $DB;
    if ($component === null || $contextid === null) {
        debugging('You should specify the component and contextid of the item being tagged in your call to tag_assign.', DEBUG_DEVELOPER);
    }
    // Get the tag.
    $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
    if ($tag_instance_object = $DB->get_record('tag_instance', array('tagid' => $tagid, 'itemtype' => $record_type, 'itemid' => $record_id, 'tiuserid' => $userid), 'id')) {
        $tag_instance_object->ordering = $ordering;
        $tag_instance_object->timemodified = time();
        $DB->update_record('tag_instance', $tag_instance_object);
    } else {
        $tag_instance_object = new StdClass();
        $tag_instance_object->tagid = $tagid;
        $tag_instance_object->component = $component;
        $tag_instance_object->itemid = $record_id;
        $tag_instance_object->itemtype = $record_type;
        $tag_instance_object->contextid = $contextid;
        $tag_instance_object->ordering = $ordering;
        $tag_instance_object->timecreated = time();
        $tag_instance_object->timemodified = $tag_instance_object->timecreated;
        $tag_instance_object->tiuserid = $userid;
        $tag_instance_object->id = $DB->insert_record('tag_instance', $tag_instance_object);
    }
    // We can not fire an event with 'null' as the contextid.
    if (is_null($contextid)) {
        $contextid = context_system::instance()->id;
    }
    // Trigger tag added event.
    $event = \core\event\tag_added::create(array('objectid' => $tag_instance_object->id, 'contextid' => $contextid, 'other' => array('tagid' => $tagid, 'tagname' => $tag->name, 'tagrawname' => $tag->rawname, 'itemid' => $record_id, 'itemtype' => $record_type)));
    $event->trigger();
    return true;
}