Пример #1
0
function question_cwqpfs_to_update($categories = null)
{
    global $CFG;
    $tofix = array();
    $result = true;
    //any cats with questions picking from subcats?
    if (!($cwqpfs = get_records_sql_menu("SELECT DISTINCT qc.id, 1 " . "FROM {$CFG->prefix}question q, {$CFG->prefix}question_categories qc " . "WHERE q.qtype='random' AND qc.id = q.category AND " . sql_compare_text('q.questiontext') . " = '1'"))) {
        return array();
    } else {
        if ($categories === null) {
            $categories = get_records('question_categories');
        }
        $categorychildparents = array();
        foreach ($categories as $id => $category) {
            $categorychildparents[$category->course][$id] = $category->parent;
        }
        foreach ($categories as $id => $category) {
            if (FALSE !== array_key_exists($category->parent, $categorychildparents[$category->course])) {
                //this is not a top level cat
                continue;
                //go to next category
            } else {
                $tofix += question_cwqpfs_check_children($id, $categories, $categorychildparents[$category->course], $cwqpfs);
            }
        }
    }
    return $tofix;
}
Пример #2
0
 /**
  * This function sets up options of otag select element. This is called from definition and also
  * after adding new official tags with the add tag button.
  *
  */
 function otags_select_setup()
 {
     global $CFG;
     $mform =& $this->_form;
     $otagsselect =& $mform->getElement('otags');
     $otagsselect->removeOptions();
     if ($otags = get_records_sql_menu('SELECT id, text from ' . $CFG->prefix . 'tags WHERE type=\'official\' ORDER by text ASC')) {
         $otagsselect->loadArray($otags);
     }
 }
Пример #3
0
function handle_individual($usersid)
{
    global $CFG;
    $sql = "SELECT id, path FROM {$CFG->prefix}block_student_person\n                        WHERE (path != 'NA' OR path != 0)\n                          AND usersid = {$usersid}";
    $assignments = get_records_sql_menu($sql);
    if ($assignments) {
        return handle_person($assignments);
    }
    return '';
}
Пример #4
0
 /**
  * This function sets up options of otag select element. This is called from definition and also
  * after adding new official tags with the add tag button.
  *
  */
 function otags_select_setup()
 {
     global $CFG;
     $mform =& $this->_form;
     if ($otagsselect =& $mform->getElement('otags')) {
         $otagsselect->removeOptions();
     }
     $namefield = empty($CFG->keeptagnamecase) ? 'name' : 'rawname';
     if ($otags = get_records_sql_menu('SELECT id, ' . $namefield . ' from ' . $CFG->prefix . 'tag WHERE tagtype=\'official\' ORDER by name ASC')) {
         $otagsselect->loadArray($otags);
     }
 }
Пример #5
0
 /**
  * This function sets up options of otag select element. This is called from definition and also
  * after adding new official tags with the add tag button.
  *
  */
 function otags_select_setup()
 {
     global $CFG;
     $mform =& $this->_form;
     if ($otagsselect =& $mform->getElement('otags')) {
         $otagsselect->removeOptions();
     }
     if ($otags = get_records_sql_menu('SELECT id, name from ' . $CFG->prefix . 'tag WHERE tagtype=\'official\' ORDER by name ASC')) {
         $otagsselect->loadArray($otags);
     } else {
         // removing this causes errors
         //$mform->removeElement('otags');
     }
 }
Пример #6
0
 function display_search_field($value = '')
 {
     global $CFG;
     $temp = get_records_sql_menu('SELECT id, content from ' . $CFG->prefix . 'data_content WHERE fieldid=' . $this->field->id . ' GROUP BY content ORDER BY content');
     $options = array();
     if (!empty($temp)) {
         $options[''] = '';
         //Make first index blank.
         foreach ($temp as $key) {
             $options[$key] = $key;
             //Build following indicies from the sql.
         }
     }
     return choose_from_menu($options, 'f_' . $this->field->id, $value, 'choose', '', 0, true);
 }
Пример #7
0
 function display_search_field($value = '')
 {
     global $CFG;
     $lats = get_records_sql_menu('SELECT id, content from ' . $CFG->prefix . 'data_content WHERE fieldid=' . $this->field->id . ' GROUP BY content ORDER BY content');
     $longs = get_records_sql_menu('SELECT id, content1 from ' . $CFG->prefix . 'data_content WHERE fieldid=' . $this->field->id . ' GROUP BY content ORDER BY content');
     $options = array();
     if (!empty($lats) && !empty($longs)) {
         $options[''] = '';
         // Make first index blank.
         foreach ($lats as $key => $temp) {
             $options[$temp . ',' . $longs[$key]] = $temp . ',' . $longs[$key];
         }
     }
     return choose_from_menu($options, 'f_' . $this->field->id, $value, 'choose', '', 0, true);
 }
Пример #8
0
 function init()
 {
     global $CFG;
     // All the years to choose from
     // All the colleges to choose from
     // All the majors to choose from
     $fields = array('years' => 'year', 'colleges' => 'college', 'majors' => 'classification');
     $fields = array_map('special_sql', $fields);
     $this->fields = $fields;
     // All the current assignments in this category
     $sql = "SELECT id, path\n                FROM {$CFG->prefix}block_student_academics\n                WHERE path != 'NA'\n                Group By path";
     $inter = get_records_sql_menu($sql);
     $assignments = array_values(array(0 => 'NA') + (!$inter ? array() : $inter));
     $assignments = array_combine($assignments, $assignments);
     $assignments['NA'] = 'NA/NA/NA';
     $this->current_assignments = $assignments;
 }
Пример #9
0
 function init()
 {
     global $CFG;
     // Get user capabilities
     $cap_sql = "SELECT rc.id, rc.capability\n                        FROM {$CFG->prefix}role_assignments ra,\n                             {$CFG->prefix}role_capabilities rc\n                        WHERE ra.userid = {$this->userid}\n                          AND ra.roleid = rc.roleid\n                          AND rc.capability IN ('" . implode("','", $this->user_caps) . "')";
     $capabilities = get_records_sql_menu($cap_sql);
     // Get all the internal assignments
     $map = create_function('$field', '
             return "SELECT DISTINCT(u.id), u.firstname, u.lastname
                 FROM ' . $CFG->prefix . 'user u,
                      ' . $CFG->prefix . 'block_student_{$field} a,
                      ' . $CFG->prefix . 'role_assignments ra,
                      ' . $CFG->prefix . 'role_capabilities rc
                 WHERE u.id = a.usersid
                   AND ra.userid = u.id
                   AND ra.roleid = rc.roleid
                   AND rc.capability IN (\'' . implode("','", array_values($capabilities)) . '\')
                 GROUP BY u.id";');
     $sql = implode(') UNION (', array_map($map, array('sports', 'academics', 'person')));
     $this->mentors = array_map('flatten_mentors', get_records_sql('(' . $sql . ') ORDER BY lastname'));
 }
Пример #10
0
function question_insert_c_and_q_ids_for_module($backup_unique_code, $course, $modulename, $instances)
{
    global $CFG;
    $status = true;
    // using 'dummykeyname' in sql because otherwise get_records_sql_menu returns an error
    // if two key names are the same.
    $cmcontexts = array();
    if (!empty($instances)) {
        $cmcontexts = get_records_sql_menu("SELECT c.id, c.id AS dummykeyname FROM {$CFG->prefix}modules m,\n                                                        {$CFG->prefix}course_modules cm,\n                                                        {$CFG->prefix}context c\n                               WHERE m.name = '{$modulename}' AND m.id = cm.module AND cm.id = c.instanceid\n                                    AND c.contextlevel = " . CONTEXT_MODULE . " AND cm.course = {$course}\n                                    AND cm.instance IN (" . implode(',', array_keys($instances)) . ")");
    }
    if ($cmcontexts) {
        $status = $status && execute_sql("INSERT INTO {$CFG->prefix}backup_ids\n                                       (backup_code, table_name, old_id, info)\n                                   SELECT '{$backup_unique_code}', 'question_categories', qc.id, '{$modulename}'\n                                   FROM {$CFG->prefix}question_categories qc\n                                   WHERE qc.contextid IN (" . join(array_keys($cmcontexts), ', ') . ")", false);
    }
    $status = $status && question_insert_q_ids($backup_unique_code, $modulename);
    return $status;
}
Пример #11
0
 function set_data_attempt(&$attempt, &$strftimedate, &$strftimetime, &$blank)
 {
     global $CFG;
     $records = get_records_sql_menu("\n\t\t\tSELECT userid, MAX(time) AS logintime\n\t\t\tFROM {$CFG->prefix}log\n\t\t\tWHERE userid={$attempt->userid} AND action='login' AND time<{$attempt->timestart}\n\t\t\tGROUP BY userid\n\t\t");
     if (empty($records)) {
         $logindate = $blank;
         $logintime = $blank;
     } else {
         $logintime = $records[$attempt->userid];
         $logindate = trim(userdate($logintime, $strftimedate));
         $logintime = trim(userdate($logintime, $strftimetime));
     }
     $records = get_records_sql_menu("\n\t\t\tSELECT userid, MIN(time) AS logouttime\n\t\t\tFROM {$CFG->prefix}log\n\t\t\tWHERE userid={$attempt->userid} AND action='logout' AND time>{$attempt->cr_timefinish}\n\t\t\tGROUP BY userid\n\t\t");
     if (empty($records)) {
         $logouttime = $blank;
     } else {
         $logouttime = $records[$attempt->userid];
         $logouttime = trim(userdate($logouttime, $strftimetime));
     }
     $this->data['attempt'] = array('logindate' => $logindate, 'logintime' => $logintime, 'logouttime' => $logouttime, 'number' => $attempt->attempt, 'start' => trim(userdate($attempt->timestart, $strftimetime)), 'finish' => trim(userdate($attempt->cr_timefinish, $strftimetime)));
 }
Пример #12
0
 function display($quiz, $cm, $course)
 {
     /// This function just displays the report
     global $CFG, $SESSION, $db, $QTYPES;
     $strnoquiz = get_string('noquiz', 'quiz');
     $strnoattempts = get_string('noattempts', 'quiz');
     /// Only print headers if not asked to download data
     $download = optional_param('download', NULL);
     if (!$download) {
         $this->print_header_and_tabs($cm, $course, $quiz, $reportmode = "analysis");
     }
     /// Construct the table for this particular report
     if (!$quiz->questions) {
         print_heading($strnoattempts);
         return true;
     }
     /// Check to see if groups are being used in this quiz
     if ($groupmode = groupmode($course, $cm)) {
         // Groups are being used
         if (!$download) {
             $currentgroup = setup_and_print_groups($course, $groupmode, "report.php?id={$cm->id}&amp;mode=analysis");
         } else {
             $currentgroup = get_and_set_current_group($course, $groupmode);
         }
     } else {
         $currentgroup = get_and_set_current_group($course, $groupmode);
     }
     // set Table and Analysis stats options
     if (!isset($SESSION->quiz_analysis_table)) {
         $SESSION->quiz_analysis_table = array('attemptselection' => 0, 'lowmarklimit' => 0, 'pagesize' => 10);
     }
     foreach ($SESSION->quiz_analysis_table as $option => $value) {
         $urlparam = optional_param($option, NULL);
         if ($urlparam === NULL) {
             ${$option} = $value;
         } else {
             ${$option} = $SESSION->quiz_analysis_table[$option] = $urlparam;
         }
     }
     $scorelimit = $quiz->sumgrades * $lowmarklimit / 100;
     // ULPGC ecastro DEBUG this is here to allow for different SQL to select attempts
     switch ($attemptselection) {
         case QUIZ_ALLATTEMPTS:
             $limit = '';
             $group = '';
             break;
         case QUIZ_HIGHESTATTEMPT:
             $limit = ', max(qa.sumgrades) ';
             $group = ' GROUP BY qa.userid ';
             break;
         case QUIZ_FIRSTATTEMPT:
             $limit = ', min(qa.timemodified) ';
             $group = ' GROUP BY qa.userid ';
             break;
         case QUIZ_LASTATTEMPT:
             $limit = ', max(qa.timemodified) ';
             $group = ' GROUP BY qa.userid ';
             break;
     }
     if ($attemptselection != QUIZ_ALLATTEMPTS) {
         $sql = 'SELECT qa.userid ' . $limit . 'FROM ' . $CFG->prefix . 'user u LEFT JOIN ' . $CFG->prefix . 'quiz_attempts qa ON u.id = qa.userid ' . 'WHERE qa.quiz = ' . $quiz->id . ' AND qa.preview = 0 ' . $group;
         $usermax = get_records_sql_menu($sql);
     }
     $groupmembers = '';
     $groupwhere = '';
     //Add this to the SQL to show only group users
     if ($currentgroup) {
         $groupmembers = ', ' . groups_members_from_sql();
         $groupwhere = ' AND ' . groups_members_where_sql($currentgroup, 'u.id');
     }
     $sql = 'SELECT  qa.* FROM ' . $CFG->prefix . 'quiz_attempts qa, ' . $CFG->prefix . 'user u ' . $groupmembers . 'WHERE u.id = qa.userid AND qa.quiz = ' . $quiz->id . ' AND qa.preview = 0 AND ( qa.sumgrades >= ' . $scorelimit . ' ) ' . $groupwhere;
     // ^^^^^^ es posible seleccionar aqu TODOS los quizzes, como quiere Jussi,
     // pero habra que llevar la cuenta ed cada quiz para restaura las preguntas (quizquestions, states)
     /// Fetch the attempts
     $attempts = get_records_sql($sql);
     if (empty($attempts)) {
         print_heading(get_string('nothingtodisplay'));
         $this->print_options_form($quiz, $cm, $attemptselection, $lowmarklimit, $pagesize);
         return true;
     }
     /// Here we rewiew all attempts and record data to construct the table
     $questions = array();
     $statstable = array();
     $questionarray = array();
     foreach ($attempts as $attempt) {
         $questionarray[] = quiz_questions_in_quiz($attempt->layout);
     }
     $questionlist = quiz_questions_in_quiz(implode(",", $questionarray));
     $questionarray = array_unique(explode(",", $questionlist));
     $questionlist = implode(",", $questionarray);
     unset($questionarray);
     foreach ($attempts as $attempt) {
         switch ($attemptselection) {
             case QUIZ_ALLATTEMPTS:
                 $userscore = 0;
                 // can be anything, not used
                 break;
             case QUIZ_HIGHESTATTEMPT:
                 $userscore = $attempt->sumgrades;
                 break;
             case QUIZ_FIRSTATTEMPT:
                 $userscore = $attempt->timemodified;
                 break;
             case QUIZ_LASTATTEMPT:
                 $userscore = $attempt->timemodified;
                 break;
         }
         if ($attemptselection == QUIZ_ALLATTEMPTS || $userscore == $usermax[$attempt->userid]) {
             $sql = "SELECT q.*, i.grade AS maxgrade, i.id AS instance" . "  FROM {$CFG->prefix}question q," . "       {$CFG->prefix}quiz_question_instances i" . " WHERE i.quiz = '{$quiz->id}' AND q.id = i.question" . "   AND q.id IN ({$questionlist})";
             if (!($quizquestions = get_records_sql($sql))) {
                 error('No questions found');
             }
             // Load the question type specific information
             if (!get_question_options($quizquestions)) {
                 error('Could not load question options');
             }
             // Restore the question sessions to their most recent states
             // creating new sessions where required
             if (!($states = get_question_states($quizquestions, $quiz, $attempt))) {
                 error('Could not restore question sessions');
             }
             $numbers = explode(',', $questionlist);
             $statsrow = array();
             foreach ($numbers as $i) {
                 if (!isset($quizquestions[$i]) or !isset($states[$i])) {
                     continue;
                 }
                 $qtype = $quizquestions[$i]->qtype == 'random' ? $states[$i]->options->question->qtype : $quizquestions[$i]->qtype;
                 $q = get_question_responses($quizquestions[$i], $states[$i]);
                 if (empty($q)) {
                     continue;
                 }
                 $qid = $q->id;
                 if (!isset($questions[$qid])) {
                     $questions[$qid]['id'] = $qid;
                     $questions[$qid]['qname'] = $quizquestions[$i]->name;
                     foreach ($q->responses as $answer => $r) {
                         $r->count = 0;
                         $questions[$qid]['responses'][$answer] = $r->answer;
                         $questions[$qid]['rcounts'][$answer] = 0;
                         $questions[$qid]['credits'][$answer] = $r->credit;
                         $statsrow[$qid] = 0;
                     }
                 }
                 $responses = get_question_actual_response($quizquestions[$i], $states[$i]);
                 foreach ($responses as $resp) {
                     if ($resp) {
                         if ($key = array_search($resp, $questions[$qid]['responses'])) {
                             $questions[$qid]['rcounts'][$key]++;
                         } else {
                             $test = new stdClass();
                             $test->responses = $QTYPES[$quizquestions[$i]->qtype]->get_correct_responses($quizquestions[$i], $states[$i]);
                             if ($key = $QTYPES[$quizquestions[$i]->qtype]->check_response($quizquestions[$i], $states[$i], $test)) {
                                 $questions[$qid]['rcounts'][$key]++;
                             } else {
                                 $questions[$qid]['responses'][] = $resp;
                                 $questions[$qid]['rcounts'][] = 1;
                                 $questions[$qid]['credits'][] = 0;
                             }
                         }
                     }
                 }
                 $statsrow[$qid] = get_question_fraction_grade($quizquestions[$i], $states[$i]);
             }
             $attemptscores[$attempt->id] = $attempt->sumgrades;
             $statstable[$attempt->id] = $statsrow;
         }
     }
     // Statistics Data table built
     unset($attempts);
     unset($quizquestions);
     unset($states);
     // now calculate statistics and set the values in the $questions array
     $top = max($attemptscores);
     $bottom = min($attemptscores);
     $gap = ($top - $bottom) / 3;
     $top -= $gap;
     $bottom += $gap;
     foreach ($questions as $qid => $q) {
         $questions[$qid] = $this->report_question_stats($q, $attemptscores, $statstable, $top, $bottom);
     }
     unset($attemptscores);
     unset($statstable);
     /// Now check if asked download of data
     if ($download = optional_param('download', NULL)) {
         $filename = clean_filename("{$course->shortname} " . format_string($quiz->name, true));
         switch ($download) {
             case "Excel":
                 $this->Export_Excel($questions, $filename);
                 break;
             case "ODS":
                 $this->Export_ODS($questions, $filename);
                 break;
             case "CSV":
                 $this->Export_CSV($questions, $filename);
                 break;
         }
     }
     /// Construct the table for this particular report
     $tablecolumns = array('id', 'qname', 'responses', 'credits', 'rcounts', 'rpercent', 'facility', 'qsd', 'disc_index', 'disc_coeff');
     $tableheaders = array(get_string('qidtitle', 'quiz_analysis'), get_string('qtexttitle', 'quiz_analysis'), get_string('responsestitle', 'quiz_analysis'), get_string('rfractiontitle', 'quiz_analysis'), get_string('rcounttitle', 'quiz_analysis'), get_string('rpercenttitle', 'quiz_analysis'), get_string('facilitytitle', 'quiz_analysis'), get_string('stddevtitle', 'quiz_analysis'), get_string('dicsindextitle', 'quiz_analysis'), get_string('disccoefftitle', 'quiz_analysis'));
     $table = new flexible_table('mod-quiz-report-itemanalysis');
     $table->define_columns($tablecolumns);
     $table->define_headers($tableheaders);
     $table->define_baseurl($CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id . '&amp;mode=analysis');
     $table->sortable(true);
     $table->no_sorting('rpercent');
     $table->collapsible(true);
     $table->initialbars(false);
     $table->column_class('id', 'numcol');
     $table->column_class('credits', 'numcol');
     $table->column_class('rcounts', 'numcol');
     $table->column_class('rpercent', 'numcol');
     $table->column_class('facility', 'numcol');
     $table->column_class('qsd', 'numcol');
     $table->column_class('disc_index', 'numcol');
     $table->column_class('disc_coeff', 'numcol');
     $table->column_suppress('id');
     $table->column_suppress('qname');
     $table->column_suppress('facility');
     $table->column_suppress('qsd');
     $table->column_suppress('disc_index');
     $table->column_suppress('disc_coeff');
     $table->set_attribute('cellspacing', '0');
     $table->set_attribute('id', 'itemanalysis');
     $table->set_attribute('class', 'generaltable generalbox');
     // Start working -- this is necessary as soon as the niceties are over
     $table->setup();
     $tablesort = $table->get_sql_sort();
     $sorts = explode(",", trim($tablesort));
     if ($tablesort and is_array($sorts)) {
         $sortindex = array();
         $sortorder = array();
         foreach ($sorts as $sort) {
             $data = explode(" ", trim($sort));
             $sortindex[] = trim($data[0]);
             $s = trim($data[1]);
             if ($s == "ASC") {
                 $sortorder[] = SORT_ASC;
             } else {
                 $sortorder[] = SORT_DESC;
             }
         }
         if (count($sortindex) > 0) {
             $sortindex[] = "id";
             $sortorder[] = SORT_ASC;
             foreach ($questions as $qid => $row) {
                 $index1[$qid] = $row[$sortindex[0]];
                 $index2[$qid] = $row[$sortindex[1]];
             }
             array_multisort($index1, $sortorder[0], $index2, $sortorder[1], $questions);
         }
     }
     $format_options = new stdClass();
     $format_options->para = false;
     $format_options->noclean = true;
     $format_options->newlines = false;
     // Now it is time to page the data, simply slice the keys in the array
     if (!isset($pagesize) || (int) $pagesize < 1) {
         $pagesize = 10;
     }
     $table->pagesize($pagesize, count($questions));
     $start = $table->get_page_start();
     $pagequestions = array_slice(array_keys($questions), $start, $pagesize);
     foreach ($pagequestions as $qnum) {
         $q = $questions[$qnum];
         $qid = $q['id'];
         $question = get_record('question', 'id', $qid);
         if (has_capability('moodle/question:manage', get_context_instance(CONTEXT_COURSE, $course->id))) {
             $qnumber = " (" . link_to_popup_window('/question/question.php?id=' . $qid, '&amp;cmid=' . $cm->id . 'editquestion', $qid, 450, 550, get_string('edit'), 'none', true) . ") ";
         } else {
             $qnumber = $qid;
         }
         $qname = '<div class="qname">' . format_text($question->name . " :  ", $question->questiontextformat, $format_options, $quiz->course) . '</div>';
         $qicon = print_question_icon($question, true);
         $qreview = quiz_question_preview_button($quiz, $question);
         $qtext = format_text($question->questiontext, $question->questiontextformat, $format_options, $quiz->course);
         $qquestion = $qname . "\n" . $qtext . "\n";
         $responses = array();
         foreach ($q['responses'] as $aid => $resp) {
             $response = new stdClass();
             if ($q['credits'][$aid] <= 0) {
                 $qclass = 'uncorrect';
             } elseif ($q['credits'][$aid] == 1) {
                 $qclass = 'correct';
             } else {
                 $qclass = 'partialcorrect';
             }
             $response->credit = '<span class="' . $qclass . '">(' . format_float($q['credits'][$aid], 2) . ') </span>';
             $response->text = '<span class="' . $qclass . '">' . format_text($resp, FORMAT_MOODLE, $format_options, $quiz->course) . ' </span>';
             $count = $q['rcounts'][$aid] . '/' . $q['count'];
             $response->rcount = $count;
             $response->rpercent = '(' . format_float($q['rcounts'][$aid] / $q['count'] * 100, 0) . '%)';
             $responses[] = $response;
         }
         $facility = format_float($q['facility'] * 100, 0) . "%";
         $qsd = format_float($q['qsd'], 3);
         $di = format_float($q['disc_index'], 2);
         $dc = format_float($q['disc_coeff'], 2);
         $response = array_shift($responses);
         $table->add_data(array($qnumber . "\n<br />" . $qicon . "\n " . $qreview, $qquestion, $response->text, $response->credit, $response->rcount, $response->rpercent, $facility, $qsd, $di, $dc));
         foreach ($responses as $response) {
             $table->add_data(array('', '', $response->text, $response->credit, $response->rcount, $response->rpercent, '', '', '', ''));
         }
     }
     print_heading_with_help(get_string("analysistitle", "quiz_analysis"), "itemanalysis", "quiz");
     echo '<div id="tablecontainer">';
     $table->print_html();
     echo '</div>';
     $this->print_options_form($quiz, $cm, $attemptselection, $lowmarklimit, $pagesize);
     return true;
 }
Пример #13
0
function glossary_filter($courseid, $text)
{
    global $CFG;
    // Trivial-cache - keyed on $cachedcourseid
    static $nothingtodo;
    static $conceptlist;
    static $cachedcourseid;
    if (empty($courseid)) {
        $courseid = SITEID;
    }
    // Initialise/invalidate our trivial cache if dealing with a different course
    if (!isset($cachedcourseid) || $cachedcourseid !== (int) $courseid) {
        $conceptlist = array();
        $nothingtodo = false;
    }
    $cachedcourseid = (int) $courseid;
    if ($nothingtodo === true) {
        return $text;
    }
    /// Create a list of all the concepts to search for.  It may be cached already.
    if (empty($conceptlist)) {
        /// Find all the glossaries we need to examine
        if (!($glossaries = get_records_sql_menu('SELECT g.id, g.name
                                                    FROM ' . $CFG->prefix . 'glossary g,
                                                         ' . $CFG->prefix . 'course_modules cm,
                                                         ' . $CFG->prefix . 'modules m
                                                    WHERE m.name = \'glossary\' AND
                                                          cm.module = m.id AND
                                                          cm.visible = 1 AND
                                                          g.id = cm.instance AND
                                                          g.usedynalink != 0 AND
                                                          (g.course = \'' . $courseid . '\' OR g.globalglossary = 1)
                                                    ORDER BY g.globalglossary, g.id'))) {
            $nothingtodo = true;
            return $text;
        }
        /// Make a list of glossary IDs for searching
        $glossarylist = '';
        foreach ($glossaries as $glossaryid => $glossaryname) {
            $glossarylist .= $glossaryid . ',';
        }
        $glossarylist = substr($glossarylist, 0, -1);
        /// Pull out all the raw data from the database for entries, categories and aliases
        $entries = get_records_select('glossary_entries', 'glossaryid IN (' . $glossarylist . ') AND usedynalink != 0 AND approved != 0 ', '', 'id,glossaryid, concept, casesensitive, 0 AS category, fullmatch');
        $categories = get_records_select('glossary_categories', 'glossaryid IN (' . $glossarylist . ') AND usedynalink != 0', '', 'id,glossaryid,name AS concept, 1 AS casesensitive, 1 AS category, 1 AS fullmatch');
        $aliases = get_records_sql('SELECT ga.id, ge.glossaryid, ga.alias as concept, ge.concept as originalconcept,
                                           casesensitive, 0 AS category, fullmatch
                                      FROM ' . $CFG->prefix . 'glossary_alias ga,
                                           ' . $CFG->prefix . 'glossary_entries ge
                                     WHERE ga.entryid = ge.id
                                       AND ge.glossaryid IN (' . $glossarylist . ')
                                       AND ge.usedynalink != 0
                                       AND ge.approved != 0');
        /// Combine them into one big list
        $concepts = array();
        if ($entries and $categories) {
            $concepts = array_merge($entries, $categories);
        } else {
            if ($categories) {
                $concepts = $categories;
            } else {
                if ($entries) {
                    $concepts = $entries;
                }
            }
        }
        if ($aliases) {
            $concepts = array_merge($concepts, $aliases);
        }
        if (!empty($concepts)) {
            foreach ($concepts as $key => $concept) {
                /// Trim empty or unlinkable concepts
                $currentconcept = trim(strip_tags($concept->concept));
                if (empty($currentconcept)) {
                    unset($concepts[$key]);
                    continue;
                } else {
                    $concepts[$key]->concept = $currentconcept;
                }
                /// Rule out any small integers.  See bug 1446
                $currentint = intval($currentconcept);
                if ($currentint && strval($currentint) == $currentconcept && $currentint < 1000) {
                    unset($concepts[$key]);
                }
            }
        }
        if (empty($concepts)) {
            $nothingtodo = true;
            return $text;
        }
        usort($concepts, 'glossary_sort_entries_by_length');
        $strcategory = get_string('category', 'glossary');
        /// Loop through all the concepts, setting up our data structure for the filter
        $conceptlist = array();
        /// We will store all the concepts here
        foreach ($concepts as $concept) {
            $glossaryname = $glossaries[$concept->glossaryid];
            if ($concept->category) {
                // Link to a category
                $title = strip_tags($glossaryname . ': ' . $strcategory . ' ' . $concept->concept);
                $href_tag_begin = '<a class="glossary autolink glossaryid' . $concept->glossaryid . '" title="' . $title . '" ' . 'href="' . $CFG->wwwroot . '/mod/glossary/view.php?g=' . $concept->glossaryid . '&amp;mode=cat&amp;hook=' . $concept->id . '">';
            } else {
                if (!empty($concept->originalconcept)) {
                    // We are dealing with an alias (so show original)
                    $encodedconcept = urlencode($concept->originalconcept);
                    $title = str_replace('"', "'", strip_tags($glossaryname . ': ' . $concept->originalconcept));
                } else {
                    $encodedconcept = urlencode($concept->concept);
                    $title = str_replace('"', "'", strip_tags($glossaryname . ': ' . $concept->concept));
                }
                $href_tag_begin = '<a class="glossary autolink glossaryid' . $concept->glossaryid . '" title="' . $title . '" ' . 'href="' . $CFG->wwwroot . '/mod/glossary/showentry.php?courseid=' . $courseid . '&amp;concept=' . $encodedconcept . '" ' . 'onclick="return openpopup(\'/mod/glossary/showentry.php?courseid=' . $courseid . '\\&amp;concept=' . $encodedconcept . '\', \'entry\', ' . '\'menubar=0,location=0,scrollbars,resizable,width=600,height=450\', 0);">';
            }
            $conceptlist[] = new filterobject($concept->concept, $href_tag_begin, '</a>', $concept->casesensitive, $concept->fullmatch);
        }
        $conceptlist = filter_remove_duplicates($conceptlist);
    }
    return filter_phrases($text, $conceptlist);
    // Actually search for concepts!
}
Пример #14
0
/** 
 *  sends an email to the teachers of the course where the given feedback is placed.
 *  @param object $cm the coursemodule-record
 *  @param $feedback
 *  @param $course
 *  @param $userid
 *  @return void
 */
function feedback_send_email($cm, $feedback, $course, $userid)
{
    global $CFG;
    if ($feedback->email_notification == 0) {
        // No need to do anything
        return;
    }
    $user = get_record('user', 'id', $userid);
    if (groupmode($course, $cm) == SEPARATEGROUPS) {
        // Separate groups are being used
        $groups = get_records_sql_menu("SELECT g.name, g.id\n                                          FROM {$CFG->prefix}groups g,\n                                                 {$CFG->prefix}groups_members m\n                                          WHERE g.courseid = '{$course->id}'\n                                             AND g.id = m.groupid\n                                             AND m.userid = '{$userid}'\n                                             ORDER BY name ASC");
        $groups = array_values($groups);
        $teachers = feedback_get_receivemail_users($cm->id, $groups);
    } else {
        $teachers = feedback_get_receivemail_users($cm->id);
    }
    if ($teachers) {
        $strfeedbacks = get_string('modulenameplural', 'feedback');
        $strfeedback = get_string('modulename', 'feedback');
        $strcompleted = get_string('completed', 'feedback');
        $printusername = $feedback->anonymous == FEEDBACK_ANONYMOUS_NO ? fullname($user) : get_string('anonymous_user', 'feedback');
        foreach ($teachers as $teacher) {
            unset($info);
            $info->username = $printusername;
            $info->feedback = format_string($feedback->name, true);
            $info->url = $CFG->wwwroot . '/mod/feedback/show_entries.php?id=' . $cm->id . '&userid=' . $userid . '&do_show=showentries';
            $postsubject = $strcompleted . ': ' . $info->username . ' -> ' . $feedback->name;
            $posttext = feedback_send_email_text($info, $course);
            $posthtml = $teacher->mailformat == 1 ? feedback_send_email_html($info, $course, $cm) : '';
            if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
                @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml);
            } else {
                @email_to_user($teacher, $teacher, $postsubject, $posttext, $posthtml);
            }
        }
    }
}
Пример #15
0
function quiz_report_grade_bands($bandwidth, $bands, $quizid, $useridlist = '')
{
    global $CFG;
    $sql = "SELECT\n        FLOOR(qg.grade/{$bandwidth}) AS band,\n        COUNT(1) AS num\n    FROM\n        {$CFG->prefix}quiz_grades qg, \n        {$CFG->prefix}quiz q\n    WHERE qg.quiz = q.id AND qg.quiz = {$quizid} \n            " . ($useridlist ? "AND qg.userid IN ({$useridlist}) " : '') . "\n    GROUP BY FLOOR(qg.grade/{$bandwidth})\n    ORDER BY band";
    if (!($data = get_records_sql_menu($sql))) {
        $data = array();
    }
    //need to create array elements with values 0 at indexes where there is no element
    $data = $data + array_fill(0, $bands + 1, 0);
    ksort($data);
    //place the maximum (prefect grade) into the last band i.e. make last
    //band for example 9 <= g <=10 (where 10 is the perfect grade) rather than
    //just 9 <= g <10.
    $data[$bands - 1] += $data[$bands];
    unset($data[$bands]);
    return $data;
}
Пример #16
0
        }
        $post->id = $existing->id;
        $post->subject = $existing->subject;
        $post->summary = $existing->summary;
        $post->publishstate = $existing->publishstate;
        $post->format = $existing->format;
        $post->action = $action;
        $strformheading = get_string('updateentrywithid', 'blog');
        if ($ptags = get_records_sql_menu("SELECT t.id, t.text FROM\n                                     {$CFG->prefix}tags t,\n                                     {$CFG->prefix}blog_tag_instance bti\n                                     WHERE t.id = bti.tagid\n                                     AND t.type = 'personal'\n                                     AND bti.entryid = {$post->id}")) {
            $post->ptags = implode(', ', $ptags);
        } else {
            //$idsql = " AND bti.entryid = 0";
            //was used but seems redundant.
            $post->ptags = '';
        }
        if ($otags = get_records_sql_menu("SELECT t.id, t.text FROM\n                                     {$CFG->prefix}tags t,\n                                     {$CFG->prefix}blog_tag_instance bti\n                                     WHERE t.id = bti.tagid\n                                     AND t.type = 'official'\n                                     AND bti.entryid = {$post->id}")) {
            $post->otags = array_keys($otags);
        }
        break;
    default:
        error('Unknown action!');
}
// done here in order to allow deleting of posts with wrong user id above
if (!($user = get_record('user', 'id', $userid))) {
    error('Incorrect user id');
}
print_header("{$SITE->shortname}: {$strblogs}", $SITE->fullname, '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $userid . '">' . fullname($user) . '</a> ->
                <a href="' . $CFG->wwwroot . '/blog/index.php?userid=' . $userid . '">' . $strblogs . '</a> -> ' . $strformheading, '', '', true);
$blogeditform->set_data($post);
$blogeditform->display();
print_footer();
Пример #17
0
function lesson_grades($lessonid)
{
    /// Must return an array of grades for a given instance of this module,
    /// indexed by user.  It also returns a maximum allowed grade.
    global $CFG;
    if (!($lesson = get_record("lesson", "id", $lessonid))) {
        return NULL;
    }
    if ($lesson->retake) {
        if ($lesson->usemaxgrade) {
            $grades = get_records_sql_menu("SELECT userid,MAX(grade) FROM {$CFG->prefix}lesson_grades WHERE\n            lessonid = {$lessonid} GROUP BY userid");
        } else {
            $grades = get_records_sql_menu("SELECT userid,AVG(grade) FROM {$CFG->prefix}lesson_grades WHERE\n            lessonid = {$lessonid} GROUP BY userid");
        }
    } else {
        // Retakes is turned Off; only count first attempt
        $firstgrades = get_records_sql("SELECT userid, MIN(completed), grade FROM {$CFG->prefix}lesson_grades WHERE lessonid = {$lessonid} GROUP BY userid");
        $grades = array();
        if (!empty($firstgrades)) {
            foreach ($firstgrades as $userid => $info) {
                $grades[$userid] = $info->grade;
            }
        }
    }
    // convert grades from percentages and tidy the numbers
    if (!$lesson->practice) {
        // dont display practice lessons
        if ($grades) {
            foreach ($grades as $userid => $grade) {
                $return->grades[$userid] = number_format($grade * $lesson->grade / 100.0, 1);
            }
        }
        $return->maxgrade = $lesson->grade;
        return $return;
    } else {
        return NULL;
    }
}
Пример #18
0
$buttontext = update_module_button($cm->id, $course->id, $strfeedback);
$navlinks = array();
$navlinks[] = array('name' => $strfeedbacks, 'link' => "index.php?id={$course->id}", 'type' => 'activity');
$navlinks[] = array('name' => format_string($feedback->name), 'link' => "", 'type' => 'activityinstance');
$navigation = build_navigation($navlinks);
print_header_simple(format_string($feedback->name), "", $navigation, "", "", true, $buttontext, navmenu($course, $cm));
include 'tabs.php';
// print_simple_box(get_string('mapcourseinfo', 'feedback'), 'center', '80%');
print_box(get_string('mapcourseinfo', 'feedback'), 'generalbox boxaligncenter boxwidthwide');
// print_simple_box_start('center', '70%');
print_box_start('generalbox boxaligncenter boxwidthwide');
echo '<form method="post">';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" />';
$sql = "select c.id, c.shortname from {$CFG->prefix}course c\n            where\n                c.shortname " . sql_ilike() . " '%{$searchcourse}%'\n            OR c.fullname " . sql_ilike() . " '%{$searchcourse}%'";
if (($courses = get_records_sql_menu($sql)) && !empty($searchcourse)) {
    echo ' ' . get_string('courses') . ': ';
    choose_from_menu($courses, 'coursefilter', $coursefilter, 'choose');
    echo '<input type="submit" value="' . get_string('mapcourse', 'feedback') . '"/>';
    helpbutton('mapcourses', '', 'feedback', true, true);
    echo '<input type="button" value="' . get_string('searchagain') . '" onclick="document.location=\'mapcourse.php?id=' . $id . '\'"/>';
    echo '<input type="hidden" name="searchcourse" value="' . $searchcourse . '"/>';
    echo '<input type="hidden" name="feedbackid" value="' . $feedback->id . '"/>';
    helpbutton('searchcourses', '', 'feedback', true, true);
} else {
    echo '<input type="text" name="searchcourse" value="' . $searchcourse . '"/> <input type="submit" value="' . get_string('searchcourses') . '"/>';
    helpbutton('searchcourses', '', 'feedback', true, true);
}
echo '</form>';
if ($coursemap = feedback_get_courses_from_sitecourse_map($feedback->id)) {
    $table = new flexible_table('coursemaps');
Пример #19
0
 function getCoursesPerSemester($semester = null)
 {
     global $CFG;
     $sem = "";
     if (is_array($semester)) {
         $sem = "AND sec.semestersid IN (" . implode(',', $semester) . ")";
     } else {
         if (is_numeric($semester)) {
             $sem = "AND sec.semestersid = {$semester}";
         }
     }
     $sql = "SELECT sec.semestersid, COUNT(cou.id) as count\n                    FROM {$CFG->prefix}block_courseprefs_sections sec,\n                         {$CFG->prefix}block_courseprefs_courses cou,\n                         {$CFG->prefix}block_courseprefs_teachers t\n                    WHERE sec.coursesid = cou.id\n                      AND t.sectionsid = sec.id\n                      AND t.usersid = {$this->id}\n                      AND t.primary_flag = 1\n                      AND (t.status = 'enroll' OR t.status = 'enrolled')\n                      AND sec.status != 'unwanted'\n                      {$sem}\n                 GROUP BY sec.semestersid";
     $results = get_records_sql_menu($sql);
     return $results;
 }
Пример #20
0
print_js_call('capability_report.cap_filter_init', array(get_string('search')));
echo '</form>';
print_box_end();
// If we have a capability, generate the report.
if ($capability) {
    // Work out the bits needed for the SQL WHERE clauses.
    $sqlroletest = '';
    if (count($cleanedroleids) != count($allroles)) {
        $sqlroletest = 'AND roleid IN (' . implode(',', $cleanedroleids) . ')';
    }
    // Get all the role_capabilities rows for this capability - that is, all
    // role definitions, and all role overrides.
    $rolecaps = get_records_sql("\n            SELECT id, roleid, contextid, permission\n            FROM {role_capabilities}\n            WHERE capability = '{$capability}' {$sqlroletest}");
    // In order to display a nice tree of contexts, we need to get all the
    // ancestors of all the contexts in the query we just did.
    $relevantpaths = get_records_sql_menu("\n            SELECT DISTINCT con.path, 1\n            FROM {context} con JOIN {role_capabilities} rc ON rc.contextid = con.id\n            WHERE capability = '{$capability}' {$sqlroletest}");
    $requiredcontexts = array($systemcontext->id);
    if (!empty($relevantpaths)) {
        foreach ($relevantpaths as $path => $notused) {
            $requiredcontexts = array_merge($requiredcontexts, explode('/', trim($path, '/')));
        }
    }
    $requiredcontexts = array_unique($requiredcontexts);
    // Now load those contexts.
    if (count($requiredcontexts) > 0) {
        $contexts = get_sorted_contexts('ctx.id IN (' . implode(',', $requiredcontexts) . ')');
    }
    if (empty($contexts)) {
        $contexts = array();
    }
    // Prepare some empty arrays to hold the data we are about to compute.
Пример #21
0
function insert_category_and_question_ids($course, $backup_unique_code, $instances = null)
{
    global $CFG;
    // Create missing categories and reasign orphaned questions.
    fix_orphaned_questions($course);
    // First, all categories from this course's context.
    $coursecontext = get_context_instance(CONTEXT_COURSE, $course);
    $status = execute_sql("INSERT INTO {$CFG->prefix}backup_ids\n                                   (backup_code, table_name, old_id, info)\n                               SELECT '{$backup_unique_code}', 'question_categories', qc.id, ''\n                               FROM {$CFG->prefix}question_categories qc\n                               WHERE qc.contextid = {$coursecontext->id}", false);
    // then, all categories from this course's modules' contexts.
    // using 'dummykeyname' in sql because otherwise get_records_sql_menu returns an error
    // if two key names are the same.
    $cmcontexts = get_records_sql_menu("SELECT c.id, c.id AS dummykeyname FROM {$CFG->prefix}modules m,\n                                                        {$CFG->prefix}course_modules cm,\n                                                        {$CFG->prefix}context c\n                               WHERE m.name = 'quiz' AND m.id = cm.module AND cm.id = c.instanceid\n                                    AND c.contextlevel = " . CONTEXT_MODULE . " AND cm.course = {$course}");
    if ($cmcontexts) {
        $status = $status && execute_sql("INSERT INTO {$CFG->prefix}backup_ids\n                                       (backup_code, table_name, old_id, info)\n                                   SELECT '{$backup_unique_code}', 'question_categories', qc.id, ''\n                                   FROM {$CFG->prefix}question_categories qc\n                                   WHERE qc.contextid IN (" . join(array_keys($cmcontexts), ', ') . ")", false);
    }
    //put the ids of the questions from all these categories into the db.
    $status = $status && execute_sql("INSERT INTO {$CFG->prefix}backup_ids\n                                       (backup_code, table_name, old_id, info)\n                                       SELECT '{$backup_unique_code}', 'question', q.id, ''\n                                       FROM {$CFG->prefix}question q, {$CFG->prefix}backup_ids bk\n                                       WHERE q.category = bk.old_id AND bk.table_name = 'question_categories' AND\n                                        bk.backup_code = '{$backup_unique_code}'", false);
    // Then categories from parent contexts used by the quizzes we are backing up.
    //TODO this will need generalising when we have modules other than quiz using shared questions above course level.
    $parentcontexts = get_parent_contexts($coursecontext);
    $from = "{$CFG->prefix}quiz quiz,";
    $where = "AND quiz.course = '{$course}'\n                     AND qqi.quiz = quiz.id";
    if (!empty($instances) && is_array($instances) && count($instances)) {
        $questionselectsqlfrom = '';
        $questionselectsqlwhere = 'AND qqi.quiz IN (' . implode(',', array_keys($instances)) . ')';
    } else {
        $questionselectsqlfrom = "{$CFG->prefix}quiz quiz,";
        $questionselectsqlwhere = "AND quiz.course = '{$course}'\n                         AND qqi.quiz = quiz.id";
    }
    $categories = get_records_sql("\n                SELECT id, parent, 0 AS childrendone\n                FROM {$CFG->prefix}question_categories\n                WHERE contextid IN (" . join($parentcontexts, ', ') . ")\n                  AND id IN (\n                    SELECT DISTINCT question.category\n                    FROM {$CFG->prefix}question question,\n                         {$questionselectsqlfrom}\n                         {$CFG->prefix}quiz_question_instances qqi\n                    WHERE qqi.question = question.id\n                      {$questionselectsqlwhere}\n                )", false);
    if (!$categories) {
        $categories = array();
    } else {
        //put the ids of the used questions from all these categories into the db.
        $status = $status && execute_sql("INSERT INTO {$CFG->prefix}backup_ids\n                                       (backup_code, table_name, old_id, info)\n                                       SELECT DISTINCT {$backup_unique_code}, 'question', q.id, ''\n                                       FROM {$CFG->prefix}question q,\n                                       {$from}\n                                       {$CFG->prefix}question_categories qc,\n                                       {$CFG->prefix}quiz_question_instances qqi\n                                       WHERE (qqi.question = q.id\n                                       OR qqi.question = q.parent)\n                                       AND q.category = qc.id\n                                       AND qc.contextid IN (" . join($parentcontexts, ', ') . ")\n                                       {$where}", false);
        // Add the parent categories, of these categories up to the top of the category tree.
        // not backing up the questions in these categories.
        foreach ($categories as $category) {
            while ($category->parent != 0) {
                if (array_key_exists($category->parent, $categories)) {
                    // Parent category already on the list.
                    break;
                }
                $currentid = $category->id;
                $category = get_record('question_categories', 'id', $category->parent, '', '', '', '', 'id, parent, 0 AS childrendone');
                if ($category) {
                    $categories[$category->id] = $category;
                } else {
                    // Parent not found: this indicates an error, but just fix it.
                    set_field('question_categories', 'parent', 0, 'id', $currentid);
                    break;
                }
            }
        }
        // Now we look for categories from other courses containing random questions
        // in our quizzes that select from the category and its subcategories. That implies
        // those subcategories also need to be backed up. (The categories themselves
        // and their parents will already have been included.)
        $categorieswithrandom = get_records_sql("\n                    SELECT question.category AS id, SUM(" . sql_cast_char2int('questiontext', true) . ") AS numqsusingsubcategories\n                    FROM {$CFG->prefix}quiz_question_instances qqi,\n                         {$from}\n                         {$CFG->prefix}question question\n                    WHERE question.id = qqi.question\n                      AND question.qtype = '" . RANDOM . "'\n                      {$where}\n                    GROUP BY question.category\n                    ");
        $randomselectedquestions = array();
        if ($categorieswithrandom) {
            foreach ($categorieswithrandom as $category) {
                if ($category->numqsusingsubcategories > 0) {
                    $status = $status && quiz_backup_add_sub_categories($categories, $randomselectedquestions, $category->id);
                }
            }
            $returnval = get_records_sql("\n                    SELECT question.id\n                    FROM {$CFG->prefix}question question\n                    WHERE question.category IN  (" . join(array_keys($categorieswithrandom), ', ') . ")");
            if ($returnval) {
                $randomselectedquestions += $returnval;
            }
        }
        // Finally, add all these extra categories to the backup_ids table.
        foreach ($categories as $category) {
            $status = $status && backup_putid($backup_unique_code, 'question_categories', $category->id, 0);
        }
        // Finally, add all these extra categories to the backup_ids table.
        foreach ($randomselectedquestions as $question) {
            $status = $status && backup_putid($backup_unique_code, 'question', $question->id, 0);
        }
    }
    return $status;
}
Пример #22
0
 $db_names_function = $mod->name . '_db_names';
 $updates = array();
 if (file_exists($class_file)) {
     require_once $class_file;
     //if both required functions exist
     if (function_exists($delete_function) and function_exists($db_names_function) and function_exists($get_document_function)) {
         mtrace("Checking {$mod->name} module for updates.");
         $valuesArray = $db_names_function();
         if ($valuesArray) {
             foreach ($valuesArray as $values) {
                 $where = isset($values[5]) ? 'AND (' . $values[5] . ')' : '';
                 $itemtypes = $values[4] != '*' && $values[4] != 'any' ? " AND itemtype = '{$values[4]}' " : '';
                 //TODO: check 'in' syntax with other RDBMS' (add and update.php as well)
                 $table = SEARCH_DATABASE_TABLE;
                 $query = "\n                                SELECT \n                                    docid,\n                                    itemtype\n                                FROM \n                                    {$CFG->prefix}{$table}\n                                WHERE\n                                    doctype = '{$mod->name}'\n                                    {$itemtypes}\n                            ";
                 $docIds = get_records_sql_menu($query);
                 $docIdList = $docIds ? implode("','", array_keys($docIds)) : '';
                 $query = "\n                                SELECT \n                                    id, \n                                    {$values[0]} as docid\n                                FROM \n                                    {$CFG->prefix}{$values[1]} \n                                WHERE \n                                    {$values[3]} > {$indexdate} AND \n                                    id IN ('{$docIdList}')\n                                    {$where}\n                            ";
                 $records = get_records_sql($query);
                 if (is_array($records)) {
                     foreach ($records as $record) {
                         $updates[] = $delete_function($record->docid, $docIds[$record->docid]);
                     }
                 }
             }
             foreach ($updates as $update) {
                 ++$update_count;
                 //delete old document
                 $doc = $index->find("+docid:{$update->id} +doctype:{$mod->name} +itemtype:{$update->itemtype}");
                 //get the record, should only be one
                 foreach ($doc as $thisdoc) {
Пример #23
0
/**
 * Returns an array of names of quizzes that use this question
 *
 * @param object $questionid
 * @return array of strings
 */
function quiz_question_list_instances($questionid)
{
    global $CFG;
    // TODO: we should also consider other questions that are used by
    // random questions in this quiz, but that is very hard.
    $sql = "SELECT q.id, q.name\n            FROM {$CFG->prefix}quiz q\n            INNER JOIN\n                 {$CFG->prefix}quiz_question_instances qqi\n            ON q.id = qqi.quiz\n            WHERE qqi.question = '{$questionid}'";
    if ($instances = get_records_sql_menu($sql)) {
        return $instances;
    }
    return array();
}
Пример #24
0
/**
 * authorize_print_orders
 *
 */
function authorize_print_orders($courseid, $userid)
{
    global $CFG, $USER, $SITE;
    global $strs, $authstrs;
    require_once $CFG->libdir . '/tablelib.php';
    $perpage = 10;
    $status = optional_param('status', AN_STATUS_NONE, PARAM_INT);
    $searchtype = optional_param('searchtype', 'id', PARAM_ALPHA);
    $idortransid = optional_param('idortransid', '0', PARAM_INT);
    $showonlymy = optional_param('showonlymy', 0, PARAM_BOOL);
    $canmanagepayments = has_capability('enrol/authorize:managepayments', get_context_instance(CONTEXT_COURSE, $courseid));
    if ($showonlymy || !$canmanagepayments) {
        $userid = $USER->id;
    }
    $baseurl = $CFG->wwwroot . "/enrol/authorize/index.php?user={$userid}";
    $statusmenu = array(AN_STATUS_NONE => $strs->all, AN_STATUS_AUTH | AN_STATUS_UNDERREVIEW | AN_STATUS_APPROVEDREVIEW => $authstrs->allpendingorders, AN_STATUS_AUTH => $authstrs->authorizedpendingcapture, AN_STATUS_AUTHCAPTURE => $authstrs->authcaptured, AN_STATUS_CREDIT => $authstrs->refunded, AN_STATUS_VOID => $authstrs->cancelled, AN_STATUS_EXPIRE => $authstrs->expired, AN_STATUS_UNDERREVIEW => $authstrs->underreview, AN_STATUS_APPROVEDREVIEW => $authstrs->approvedreview, AN_STATUS_REVIEWFAILED => $authstrs->reviewfailed, AN_STATUS_TEST => $authstrs->tested);
    $sql = "SELECT c.id, c.fullname FROM {$CFG->prefix}course c INNER JOIN {$CFG->prefix}enrol_authorize e ON c.id = e.courseid ";
    if ($userid > 0) {
        $sql .= "WHERE (e.userid='{$userid}') ";
    }
    $sql .= "ORDER BY c.sortorder, c.fullname";
    if ($popupcrs = get_records_sql_menu($sql)) {
        $popupcrs = array($SITE->id => $SITE->fullname) + $popupcrs;
        echo "<table border='0' width='100%' cellspacing='0' cellpadding='3' class='generaltable generalbox'>";
        echo "<tr>";
        echo "<td width='5%' valign='top'>{$strs->status}: </td><td width='10%'>";
        popup_form($baseurl . '&amp;course=' . $courseid . '&amp;status=', $statusmenu, 'statusmenu', $status, '', '', '', false);
        if ($canmanagepayments) {
            echo "<br />\n";
            print_checkbox('showonlymy', '1', $userid == $USER->id, get_string('mypaymentsonly', 'enrol_authorize'), '', "var locationtogo = '{$CFG->wwwroot}/enrol/authorize/index.php?status={$status}&amp;course={$courseid}';\n                                  locationtogo += '&amp;user='******'{$USER->id}' : '0');\n                                  top.location.href=locationtogo;");
        }
        echo "</td>\n";
        echo "<td width='5%' valign='top'>{$strs->course}: </td><td width='10%' valign='top'>";
        popup_form($baseurl . '&amp;status=' . $status . '&amp;course=', $popupcrs, 'coursesmenu', $courseid, '', '', '', false);
        echo "</td>\n";
        if (has_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_USER, $USER->id))) {
            echo "<form method='get' action='uploadcsv.php'>";
            echo "<td rowspan='2' align='right' valign='middle' width='50%'><div><input type='submit' value='" . get_string('uploadcsv', 'enrol_authorize') . "' /></div></td>";
            echo "</form>";
        } else {
            echo "<td rowspan=2 width='100%'>&nbsp;</td>";
        }
        echo "</tr>\n";
        echo "<tr><td>{$strs->search}: </td>";
        $searchmenu = array('id' => $authstrs->orderid, 'transid' => $authstrs->transid);
        echo "<form method='POST' action='index.php' autocomplete='off'>";
        echo "<td colspan='3'>";
        choose_from_menu($searchmenu, 'searchtype', $searchtype, '');
        echo " = <fieldset class=\"invisiblefieldset\"><input type='text' size='14' name='idortransid' value='' /> ";
        echo "<input type='submit' value='{$strs->search}' /></fieldset></td>";
        echo "</form>";
        echo "</tr>";
        echo "</table>";
    }
    $table = new flexible_table('enrol-authorize');
    $table->set_attribute('width', '100%');
    $table->set_attribute('cellspacing', '0');
    $table->set_attribute('cellpadding', '3');
    $table->set_attribute('id', 'orders');
    $table->set_attribute('class', 'generaltable generalbox');
    $table->define_columns(array('id', 'timecreated', 'userid', 'status', ''));
    $table->define_headers(array($authstrs->orderid, $strs->time, $authstrs->nameoncard, $strs->status, $strs->action));
    $table->define_baseurl($baseurl . "&amp;status={$status}&amp;course={$courseid}");
    $table->sortable(true, 'id', SORT_DESC);
    $table->pageable(true);
    $table->setup();
    $select = "SELECT e.id, e.paymentmethod, e.transid, e.courseid, e.userid, e.status, e.ccname, e.timecreated, e.settletime ";
    $from = "FROM {$CFG->prefix}enrol_authorize e ";
    $where = "WHERE (1=1) ";
    if ($status > AN_STATUS_NONE) {
        switch ($status) {
            case AN_STATUS_AUTH | AN_STATUS_UNDERREVIEW | AN_STATUS_APPROVEDREVIEW:
                $where .= 'AND (e.status IN(' . AN_STATUS_AUTH . ',' . AN_STATUS_UNDERREVIEW . ',' . AN_STATUS_APPROVEDREVIEW . ')) ';
                break;
            case AN_STATUS_CREDIT:
                $from .= "INNER JOIN {$CFG->prefix}enrol_authorize_refunds r ON e.id = r.orderid ";
                $where .= "AND (e.status = '" . AN_STATUS_AUTHCAPTURE . "') ";
                break;
            case AN_STATUS_TEST:
                $newordertime = time() - 120;
                // -2 minutes. Order may be still in process.
                $where .= "AND (e.status = '" . AN_STATUS_NONE . "') AND (e.transid = '0') AND (e.timecreated < {$newordertime}) ";
                break;
            default:
                $where .= "AND (e.status = '{$status}') ";
                break;
        }
    } else {
        if (empty($CFG->an_test)) {
            $where .= "AND (e.status != '" . AN_STATUS_NONE . "') ";
        }
    }
    if ($courseid != SITEID) {
        $where .= "AND (e.courseid = '" . $courseid . "') ";
    }
    if (!empty($idortransid)) {
        // Ignore old where.
        if ($searchtype == 'transid') {
            $where = "WHERE (e.transid = {$idortransid}) ";
        } else {
            $where = "WHERE (e.id = {$idortransid}) ";
        }
    }
    // This must be always last where!!!
    if ($userid > 0) {
        $where .= "AND (e.userid = '" . $userid . "') ";
    }
    if ($sort = $table->get_sql_sort()) {
        $sort = ' ORDER BY ' . $sort;
    }
    $totalcount = count_records_sql('SELECT COUNT(*) ' . $from . $where);
    $table->initialbars($totalcount > $perpage);
    $table->pagesize($perpage, $totalcount);
    if ($records = get_records_sql($select . $from . $where . $sort, $table->get_page_start(), $table->get_page_size())) {
        foreach ($records as $record) {
            $actionstatus = authorize_get_status_action($record);
            $color = authorize_get_status_color($actionstatus->status);
            $actions = '';
            if (empty($actionstatus->actions)) {
                $actions .= $strs->none;
            } else {
                foreach ($actionstatus->actions as $value) {
                    $actions .= "&nbsp;&nbsp;<a href='index.php?{$value}=y&amp;sesskey={$USER->sesskey}&amp;order={$record->id}'>{$authstrs->{$value}}</a> ";
                }
            }
            $table->add_data(array("<a href='index.php?order={$record->id}'>{$record->id}</a>", userdate($record->timecreated), $record->ccname, "<font style='color:{$color}'>" . $authstrs->{$actionstatus->status} . "</font>", $actions));
        }
    }
    $table->print_html();
}
Пример #25
0
 /**
  * Check the time with lines processed
  * Log an error if it's not a weekend
  */
 function empty_files($now)
 {
     global $CFG;
     // If we're in a weekend, it doesn't matter
     $weekend = array(6, 7);
     $current_day = date("N", $now);
     if (in_array($current_day, $weekend)) {
         return false;
     }
     $sql = "SELECT name, value \n                FROM {$CFG->prefix}block_courseprefs_config\n                WHERE name LIKE '%_lines'";
     $lines = get_records_sql_menu($sql);
     return array_sum(array_values($lines)) == 0;
 }
Пример #26
0
function hotpot_get_grades($hotpot, $user_ids = '')
{
    global $CFG;
    $grades = array();
    $weighting = $hotpot->grade / 100;
    $precision = hotpot_get_precision($hotpot);
    // set the SQL string to determine the $grade
    $grade = "";
    switch ($hotpot->grademethod) {
        case HOTPOT_GRADEMETHOD_HIGHEST:
            $grade = "ROUND(MAX(score) * {$weighting}, {$precision}) AS grade";
            break;
        case HOTPOT_GRADEMETHOD_AVERAGE:
            // the 'AVG' function skips abandoned quizzes, so use SUM(score)/COUNT(id)
            $grade = "ROUND(SUM(score)/COUNT(id) * {$weighting}, {$precision}) AS grade";
            break;
        case HOTPOT_GRADEMETHOD_FIRST:
            $grade = "ROUND(score * {$weighting}, {$precision})";
            $grade = sql_concat('timestart', "'_'", $grade);
            $grade = "MIN({$grade}) AS grade";
            break;
        case HOTPOT_GRADEMETHOD_LAST:
            $grade = "ROUND(score * {$weighting}, {$precision})";
            $grade = sql_concat('timestart', "'_'", $grade);
            $grade = "MAX({$grade}) AS grade";
            break;
    }
    if ($grade) {
        $userid_condition = empty($user_ids) ? '' : "AND userid IN ({$user_ids}) ";
        $grades = get_records_sql_menu("\n            SELECT userid, {$grade}\n            FROM {$CFG->prefix}hotpot_attempts\n            WHERE timefinish>0 AND hotpot='{$hotpot->id}' {$userid_condition}\n            GROUP BY userid\n        ");
        if ($grades) {
            if ($hotpot->grademethod == HOTPOT_GRADEMETHOD_FIRST || $hotpot->grademethod == HOTPOT_GRADEMETHOD_LAST) {
                // remove left hand characters in $grade (up to and including the underscore)
                foreach ($grades as $userid => $grade) {
                    $grades[$userid] = substr($grades[$userid], strpos($grades[$userid], '_') + 1);
                }
            }
        }
    }
    return $grades;
}
Пример #27
0
 $db_names_function = $mod->name . '_db_names';
 $updates = array();
 if (file_exists($class_file)) {
     require_once $class_file;
     //if both required functions exist
     if (function_exists($delete_function) and function_exists($db_names_function) and function_exists($get_document_function)) {
         mtrace("Checking {$mod->name} module for updates.");
         $valuesArray = $db_names_function();
         if ($valuesArray) {
             foreach ($valuesArray as $values) {
                 $where = !empty($values[5]) ? 'AND (' . $values[5] . ')' : '';
                 $itemtypes = $values[4] != '*' && $values[4] != 'any' ? " AND itemtype = '{$values[4]}' " : '';
                 //TODO: check 'in' syntax with other RDBMS' (add and update.php as well)
                 $table = SEARCH_DATABASE_TABLE;
                 $query = "\n                                SELECT \n                                    docid,\n                                    itemtype\n                                FROM \n                                    {$CFG->prefix}{$table}\n                                WHERE\n                                    doctype = '{$values[1]}'\n                                    {$itemtypes}\n                            ";
                 $docIds = get_records_sql_menu($query, array($mod->name));
                 $docIdList = $docIds ? implode("','", array_keys($docIds)) : '';
                 $query = "\n                                SELECT \n                                    id, \n                                    {$values[0]} as docid\n                                FROM \n                                    {$CFG->prefix}{$values[1]} \n                                WHERE \n                                    {$values[3]} > {$indexdate} AND \n                                    id IN ('{$docIdList}')\n                                    {$where}\n                            ";
                 $records = get_records_sql($query);
                 if (is_array($records)) {
                     foreach ($records as $record) {
                         $updates[] = $delete_function($record->docid, $docIds[$record->docid]);
                     }
                 }
             }
             foreach ($updates as $update) {
                 ++$update_count;
                 //delete old document
                 $doc = $index->find("+docid:{$update->id} +doctype:{$mod->name} +itemtype:{$update->itemtype}");
                 //get the record, should only be one
                 foreach ($doc as $thisdoc) {
Пример #28
0
/**
 * Get a list of userids from a list of usernames
 *
 * @param $usernames array list of usernames
 *
 * @returns array list of userids
 */
function username_to_id($usernames)
{
    if (!empty($usernames)) {
        $ids = get_records_sql_menu('
            SELECT username, id FROM {usr}
            WHERE deleted = 0
            AND LOWER(username) IN (' . join(',', array_fill(0, count($usernames), '?')) . ')', array_map('strtolower', $usernames));
    }
    return empty($ids) ? array() : $ids;
}
Пример #29
0
/**
 * Returns a menu of all available scales from the site as well as the given course
 *
 * @uses $CFG
 * @param int $courseid The id of the course as found in the 'course' table.
 * @return object
 */
function get_scales_menu($courseid = 0)
{
    global $CFG;
    $sql = "SELECT id, name FROM {$CFG->prefix}scale\n             WHERE courseid = '0' or courseid = '{$courseid}'\n          ORDER BY courseid ASC, name ASC";
    if ($scales = get_records_sql_menu($sql)) {
        return $scales;
    }
    make_default_scale();
    return get_records_sql_menu($sql);
}
Пример #30
0
function certificate_get_possible_linked_activities(&$course, $certid)
{
    global $CFG;
    $lacts[0] = '-- none --';
    if (record_exists('modules', 'name', 'quiz')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'quiz a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'quiz\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Quiz: ' . $name;
            }
        }
    }
    if (record_exists('modules', 'name', 'assignment')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'assignment a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'assignment\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Assignment: ' . $name;
            }
        }
    }
    if (record_exists('modules', 'name', 'questionnaire')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'questionnaire a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'questionnaire\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Questionnaire: ' . $name;
            }
        }
    }
    if (record_exists('modules', 'name', 'lesson')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'lesson a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'lesson\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Lesson: ' . $name;
            }
        }
    }
    if (record_exists('modules', 'name', 'feedback')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'feedback a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'feedback\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Feedback: ' . $name;
            }
        }
    }
    if (record_exists('modules', 'name', 'survey')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'survey a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'survey\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Survey: ' . $name;
            }
        }
    }
    $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'scorm a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'scorm\' AND cm.module = m.id AND a.course = ' . $course->id;
    if ($mods = get_records_sql_menu($sql)) {
        foreach ($mods as $key => $name) {
            $lacts[$key] = 'Scorm: ' . $name;
        }
    }
    if (record_exists('modules', 'name', 'facetoface')) {
        $sql = 'SELECT DISTINCT cm.id,a.name ' . 'FROM ' . $CFG->prefix . 'course_modules cm,' . $CFG->prefix . 'facetoface a,' . $CFG->prefix . 'modules m ' . 'WHERE cm.course = ' . $course->id . ' AND cm.instance = a.id AND ' . 'm.name = \'facetoface\' AND cm.module = m.id AND a.course = ' . $course->id;
        if ($mods = get_records_sql_menu($sql)) {
            foreach ($mods as $key => $name) {
                $lacts[$key] = 'Face-to-face: ' . $name;
            }
        }
    }
    return $lacts;
}