You are here

function question_make_default_categories in Quiz 6.6

Same name and namespace in other branches
  1. 6.5 includes/moodle/lib/questionlib.php \question_make_default_categories()

Gets the default category in the most specific context. If no categories exist yet then default ones are created in all contexts.

Parameters

array $contexts The context objects for this context and all parent contexts.:

Return value

object The default category - the category in the course context

File

includes/moodle/lib/questionlib.php, line 1888

Code

function question_make_default_categories($contexts) {
  static $preferredlevels = array(
    CONTEXT_COURSE => 4,
    CONTEXT_MODULE => 3,
    CONTEXT_COURSECAT => 2,
    CONTEXT_SYSTEM => 1,
  );
  $toreturn = null;
  $preferredness = 0;

  // If it already exists, just return it.
  foreach ($contexts as $key => $context) {
    if (!($categoryrs = get_recordset_select("question_categories", "contextid = '{$context->id}'", 'sortorder, name', '*', '', 1))) {
      error('error getting category record');
    }
    else {
      if (!($category = rs_fetch_record($categoryrs))) {

        // Otherwise, we need to make one
        $category = new stdClass();
        $contextname = print_context_name($context, false, true);
        $category->name = addslashes(get_string('defaultfor', 'question', $contextname));
        $category->info = addslashes(get_string('defaultinfofor', 'question', $contextname));
        $category->contextid = $context->id;
        $category->parent = 0;
        $category->sortorder = 999;

        // By default, all categories get this number, and are sorted alphabetically.
        $category->stamp = make_unique_id_code();
        if (!($category->id = insert_record('question_categories', $category))) {
          error('Error creating a default category for context ' . print_context_name($context));
        }
      }
    }
    if ($preferredlevels[$context->contextlevel] > $preferredness && has_any_capability(array(
      'moodle/question:usemine',
      'moodle/question:useall',
    ), $context)) {
      $toreturn = $category;
      $preferredness = $preferredlevels[$context->contextlevel];
    }
  }
  if (!is_null($toreturn)) {
    $toreturn = clone $toreturn;
  }
  return $toreturn;
}