if (isset($_REQUEST['ref'])) {
    // A request for a brand new form
    $form = read_form_settings_by_ref($_REQUEST['ref']);
    if ($form === false) {
        echo get_string('invalid_data', 'local_obu_forms');
        die;
    }
    if (!is_manager($form) && (!$form->student && !$staff || !$form->visible)) {
        // User hasn't the capability to view a non-student or hidden form
        $message = get_string('form_unavailable', 'local_obu_forms');
    }
    if (isset($_REQUEST['version'])) {
        $template = read_form_template($form->id, $_REQUEST['version']);
    } else {
        // Get the relevant form template (include draft templates if an administrator)
        $template = get_form_template($form->id, is_siteadmin());
    }
    if (!$template) {
        echo get_string('invalid_data', 'local_obu_forms');
        die;
    }
} else {
    if (isset($_REQUEST['id'])) {
        // An existing form
        $data_id = $_REQUEST['id'];
        if ($data_id == 0) {
            redirect($home);
        }
        if (!load_form_data($data_id, $record, $fields)) {
            echo get_string('invalid_data', 'local_obu_forms');
            die;
function get_forms($manager, $staff, $pg_student, $ump_student)
{
    global $DB;
    if (!$manager && !$staff && !$pg_student && !$ump_student) {
        // Nothing for you here...
        return array();
    }
    // Firstly, get all the forms of the correct type
    $conditions = array();
    if (!$manager) {
        $conditions['visible'] = 1;
        if (!$pg_student && !$ump_student) {
            // Just staff forms
            $conditions['student'] = 0;
        } else {
            if ($pg_student && !$ump_student) {
                // Just PG forms
                $conditions['modular'] = 0;
            } else {
                if (!$pg_student && $ump_student) {
                    // Just UMP forms
                    $conditions['modular'] = 1;
                }
            }
            if (!$staff) {
                // Just student forms
                $conditions['student'] = 1;
            }
        }
    }
    $forms = $DB->get_records('local_obu_forms', $conditions);
    // Now, include and index those forms that have published templates
    $valid = array();
    $index = array();
    foreach ($forms as $form) {
        if ($manager || get_form_template($form->id) !== false) {
            // Only include unpublished forms for managers
            // If a forms manager, only include forms that they manage
            if (!$manager || is_manager($form)) {
                $valid[] = $form;
                $index[] = $form->formref;
            }
        }
    }
    // Sort the index and create an array of the valid forms
    natcasesort($index);
    $forms = array();
    foreach ($index as $key => $ref) {
        $forms[] = $valid[$key];
    }
    return $forms;
}