function game_importsnakes_do($newrec) { if (!insert_record('game_snakes_database', $newrec)) { print_object($newrec); error("Can't insert to table game_snakes_database"); } }
function update_questionbank() { global $USER, $FULLME; $myurl = new moodle_url($FULLME); $myurl->param('first', 'second'); //print_object($myurl->get_query_string()); //notice('die please'); $qid = optional_param('qid', null); $theQuestion = optional_param('question', null); if (empty($theQuestion)) { return; } $question = get_record('memorybank_bank', 'id', $qid); print_object($question); $question->question = optional_param('question', null); $question->answer = optional_param('answer', null); $question->reference = optional_param('reference', null); $question->initialgrade = optional_param('initialgrade', 4); $question->category = optional_param('category', 0); $question->visible = optional_param('visible', 0); $initviewtime = optional_param('initviewtime', 0); $question->initviewtime = make_timestamp($initviewtime['year'], $initviewtime['month'], $initviewtime['day'], $initviewtime['hour'], $initviewtime['minute']); $question->modifiedby = $USER->id; $question->timemodified = time(); print_object($question); update_record('memorybank_bank', $question); }
function game_insert_category_and_question_ids($course, $backup_unique_code, $instances = null) { global $CFG; // Insert categories used by games $sql = "SELECT DISTINCT g.questioncategoryid as id\n FROM {$CFG->prefix}game g\n WHERE g.course={$course}"; if (($recs = get_records_sql($sql)) == false) { return true; } $status = true; $table = 'question_categories'; foreach ($recs as $rec) { if ($rec->id == 0) { continue; } $select = "backup_code='{$backup_unique_code}' AND table_name='{$table}' AND old_id = '{$rec->id}'"; if (($found = get_record_select('backup_ids', $select)) != false) { continue; } unset($newrec); $newrec->backup_code = $backup_unique_code; $newrec->table_name = $table; $newrec->old_id = $rec->id; $newrec->info = ''; if (!insert_record('backup_ids', $newrec)) { print_object($newrec); error("game_insert_category_and_question_ids: Can't insert to backup_ids"); } } return $status; }
function game_importsnakes_do($newrec) { global $DB; if (!$DB->insert_record('game_snakes_database', $newrec)) { print_object($newrec); print_error("Can't insert to table game_snakes_database"); } }
function local_course_notification_cron() { global $DB; $runtime = time(); echo "Running course notification cron at " . date('D M Y h:m:s', $runtime) . "\n"; // Generate automatic reports. // Training reaching lifetime/expired. if ($checkcourses = $DB->get_records_sql('SELECT * from {local_course_notification} where expiryduration!=0')) { // We have some courses which we need to check against. foreach ($checkcourses as $checkcourse) { $course = $DB->get_record('course', array('id' => $checkcourse->courseid)); if (!$course->visible) { // Don not send course notification for inactive course continue; } $expiredtext = ""; $expiringtext = ""; $latetext = ""; echo "Get completion information for course: {$checkcourse->courseid} of company: {$checkcourse->companyid} \n"; $sql = 'SELECT cc.* FROM {course_completions} cc' . ' JOIN {company_users} cu ON cu.userid = cc.userid ' . 'WHERE cc.course=:courseid AND cu.companyid = :companyid'; $company = $DB->get_record('company', array('id' => $checkcourse->companyid, 'suspended' => 0)); if (!$company) { echo "Either Company not exist or suspended"; continue; } if ($coursecompletions = $DB->get_records_sql($sql, array('courseid' => $checkcourse->courseid, 'companyid' => $checkcourse->companyid))) { print_object($coursecompletions); // Get the course information. foreach ($coursecompletions as $completion) { if (!empty($completion->timeenrolled) && empty($completion->timecompleted)) { $user = $DB->get_record('user', array('id' => $completion->userid)); // Send course overdue email to user /* echo "current time:-" . $runtime; echo "<br>Timeenrol:-" . $completion->timeenrolled; echo "<br>expiryduration:-" . $checkcourse->expiryduration; echo "<br>warnexpire:-" . $checkcourse->warnexpire; echo "warncourseoverdue:-" . $checkcourse->warncourseoverdue; */ if ($checkcourse->warncourseoverdue && $completion->timeenrolled + $checkcourse->expiryduration < $runtime && $runtime <= $completion->timeenrolled + $checkcourse->expiryduration + $checkcourse->warncourseoverdue) { echo "<br>Sending course overdue email to {$user->email} \n"; EmailTemplate::send('expire', array('course' => $course, 'user' => $user)); /*$expiredtext .= $user->firstname . ' ' . $user->lastname . ', ' . $user->email . ' - ' . date('D M Y', $completion->timecompleted) . "\n";*/ } else { if ($checkcourse->warnexpire && $completion->timeenrolled + $checkcourse->expiryduration <= $checkcourse->warnexpire + $runtime && $completion->timeenrolled + $checkcourse->expiryduration > $runtime) { echo "<br>Sending expiry warning email to {$user->email} \n"; EmailTemplate::send('expiry_warn_user', array('course' => $course, 'user' => $user)); /*$expiringtext .= $user->firstname . ' ' . $user->lastname . ', ' . $user->email . ' - ' . date('D M Y', $completion->timecompleted) . "\n";*/ } } } } } } } }
/** * REmove previous log.txt, omr_result[*].txt * Enter description here ... * @param record $scan @see table blended_scans * @throws OMRError */ function omrprocess($scan) { global $CFG; global $scansfoldername; mtrace("Entering OMR phase."); $scan->status = JOB_STATE_BUSY; set_field('blended_scans', 'status', $scan->status, 'id', $scan->id); $scan->timestatus = time(); set_field('blended_scans', 'timestatus', $scan->timestatus, 'id', $scan->id); //update_record('blended_scans', $scan); $strresultlink = get_string('resultlink', 'blended'); $rutaorigen = blended_getOMRSourcePath($scan); $rutafieldset = blended_getOMRFieldsetDir($scan); $rutadestino = blended_getOMRTargetPath($scan); $logfile = blended_getOMRInputLogFilePath($scan); mtrace("Processing Scan: {$scan->scan_name}"); mtrace(" located at: {$rutaorigen}"); mtrace(" fieldset at: {$rutafieldset}"); mtrace(" target at: {$rutadestino} \n"); try { /** * Clean previous results in case of a previous error and a relaunch */ blended_delete_log_file($scan); blended_delete_scan_results($scan); /** * Execute the recognition process */ list($status, $output) = blended_execute_omr_recognition($rutaorigen, $rutadestino, $rutafieldset); mtrace("Command executed. Status Code ="); print_r($status); if ($status != 'OK') { $error = new OMRError($status, OMRError::OMRPROCESS_FAILED); throw $error; } else { $statusMsg = "Command executed. Status Code = 0"; print_object($output); register_status($scan->id, $statusMsg, $output, JOB_STATE_FINISHED); //register_scannedjob($rutascandir,$jobid,$scan->course); $scan->status = JOB_STATE_FINISHED; register_scannedjob($scan); } } catch (OMRError $e) { mtrace("Fatal OMR Error: " . $e->getMessage()); register_exception($e, $scan->id); } catch (ResultsError $e) { mtrace("ResultsError: " . $e->getMessage()); register_exception($e, $scan->id); } return; }
/** * * @global type $CFG * @param string $str * @param string $lang * @param string $component * @return string */ function get_string($str, $lang = 'en', $component = 'core') { global $CFG; $string = array(); if (!file_exists($CFG->dirlang . $lang . '/' . $component . '.php')) { print_object('File does not exist'); } else { include $CFG->dirlang . $lang . '/' . $component . '.php'; if (empty($str)) { print_object('String can\'t be empty'); } else { return $string[$str]; } } }
function helpmenow_wiziq_api($method, $params) { global $CFG; $signature = array(); $signature['access_key'] = $CFG->helpmenow_wiziq_access_key; $signature['timestamp'] = time(); $signature['method'] = $method; $signature['signature'] = helpmenow_wiziq_api_signature($signature); $params = array_merge($signature, $params); $ch = curl_init(); curl_setopt_array($ch, array(CURLOPT_POSTFIELDS => http_build_query($params, '', '&'), CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLINFO_HEADER_OUT => true, CURLOPT_URL => HELPMENOW_WIZIQ_API_URL . "?method={$method}")); $response = curl_exec($ch); curl_close($ch); if (debugging()) { print_object($response); } return new SimpleXMLElement($response); }
function getallhiddenrecipients($cid, $bid) { global $sid; $debug = false; if ($cid == 1) { $blockcontext = get_context_instance(CONTEXT_SYSTEM, $sid); } else { $blockcontext = get_context_instance(CONTEXT_BLOCK, $bid); } $hiddenrecipients = get_users_by_capability($blockcontext, 'block/contact_form:hiddenrecipient', 'u.id, u.firstname, u.lastname, u.email, u.mailformat', 'u.lastname ASC', '', '', '', '', false); if ($debug) { echo '****** Written from line ' . __LINE__ . ' of ' . __FILE__ . ' ********<br />'; echo '<hr />'; echo 'hiddencollector (block/contact_form:hiddenrecipients)<br />'; print_object($hiddenrecipients); } return $hiddenrecipients; }
/** * Defines forms elements */ public function definition() { global $mods; print_object($mods); $mform = $this->_form; $mform->addElement('header', 'general', get_string('general', 'form')); $mform->addElement('text', 'name', get_string('jcodename', 'jcode'), array('size' => '64')); if (!empty($CFG->formatstringstriptags)) { $mform->setType('name', PARAM_TEXT); } else { $mform->setType('name', PARAM_CLEAN); } $mform->addRule('name', null, 'required', null, 'client'); $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); $mform->addHelpButton('name', 'jcodename', 'jcode'); $this->add_intro_editor(); $mform->addElement('text', 'parameters', get_string('parameters', 'jcode')); $mform->addRule('parameters', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); $mform->addElement('text', 'correctanswer', get_string('correctanswer', 'jcode'), array('size' => '128')); $ctx = null; if ($this->current && $this->current->coursemodule) { $cm = get_coursemodule_from_instance('jcode', $this->current->id, 0, false, MUST_EXIST); $ctx = context_module::instance($cm->id); } if ($this->current && $this->current->course) { if (!$ctx) { $ctx = context_course::instance($this->current->course); } } if (empty($entry->id)) { $entry = new stdClass(); $entry->id = null; } $name = get_string('resubmit', 'jcode'); $mform->addElement('selectyesno', 'resubmit', $name); $name = get_string('timeavaliable', 'jcode'); $mform->addElement('date_time_selector', 'timeavaliable', $name, array('optional' => true)); $name = get_string('timedue', 'jcode'); $mform->addElement('date_time_selector', 'timedue', $name, array('optional' => true)); $this->standard_grading_coursemodule_elements(); $this->standard_coursemodule_elements(); $this->add_action_buttons(); }
/** * Render login form to start OpenVirtualDekstop * @param opendesktop_loginform The form to render * @return string */ public function render_opendesktop_loginform(opendesktop_loginform $formdata) { global $CFG, $USER; $o = ''; $sessioninfo = $formdata->session->get_config(); $sessval = $formdata->session->sessionstatus($CFG->opendesktop_useprefix . $USER->username); if ($sessioninfo == false) { $o .= $this->output->error_text(get_string('connecterror', 'opendesktop')); } else { $o .= $this->output->box_start('boxaligncenter '); $o .= print_object($formdata->params['sessionmode']); $formattributes = array(); $formattributes['id'] = 'opendesktop_sessionlogin'; $formattributes['class'] = 'opendesktopconnect'; $formattributes['action'] = $formdata->session->sessurl . '/startsession.php'; $formattributes['method'] = 'post'; $formattributes['name'] = 'launchopendesktop'; $o .= html_writer::start_tag('form', $formattributes); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey())); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'client', 'value' => 'browser')); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'quality', 'value' => $formdata->opendesktop->quality)); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'timezone', 'id' => 'timezone', 'value' => '')); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'login', 'value' => $CFG->opendesktop_useprefix . $USER->username)); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'language', 'value' => $formdata->opendesktop->languagesetting)); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'password', 'id' => 'passwd', 'value' => $formdata->session->randpass)); $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'session_mode', 'id' => 'session_mode', 'value' => $formdata->params['sessionmode'])); $o .= html_writer::start_tag('span', array('id' => 'loading_div', 'class' => 'loading_div')); $o .= html_writer::empty_tag('img', array('src' => 'pix/loading.div', 'alt' => 'Loading...', 'title' => 'Loading...', 'height' => '25', 'width' => '25')); $o .= html_writer::end_tag('span'); $o .= html_writer::start_tag('span', array('id' => 'launch_buttons', 'class' => 'launch_buttons')); $o .= html_writer::empty_tag('input', array('type' => 'button', 'class' => 'failed_button', 'id' => 'failed_button', 'value' => 'ERROR')); $o .= html_writer::tag('span', '<a href="http://www.java.com/download/">Click here to install the free Java-Plugin</a></span>', array('class' => 'java_download')); $o .= html_writer::empty_tag('input', array('type' => 'submit', 'id' => 'launch_button', 'class' => 'launch_button', 'value' => get_string('logintoyourdesktop', 'opendesktop'))); $o .= html_writer::end_tag('span'); $o .= html_writer::end_tag('form'); if ($formdata->opendesktop->windowmode == 'frame') { $o .= html_writer::tag('div', '<script type="text/javascript">document.launchopendesktop.submit();</script>'); } $o .= $this->output->box_end(); } return $o; }
function game_bookquiz_check_questions($id, $game, $attempt, $bookquiz, $context) { global $USER, $DB; $scoreattempt = optional_param('scoreattempt', 0, PARAM_INT); $responses = data_submitted(); $questionlist = $responses->questionids; $questions = game_sudoku_getquestions($questionlist); $grades = game_grade_questions($questions); $scorequestion = 0; $scoreattempt = 0; $chapterid = required_param('chapterid', PARAM_INT); $nextchapterid = required_param('nextchapterid', PARAM_INT); foreach ($questions as $question) { if (!array_key_exists($question->id, $grades)) { //no answered continue; } $grade = $grades[$question->id]; if ($grade->grade < 0.5) { continue; } //found one correct answer if (!$DB->get_field('game_bookquiz_chapters', 'id', array('attemptid' => $attempt->id, 'chapterid' => $chapterid))) { $newrec = new stdClass(); $newrec->attemptid = $attempt->id; $newrec->chapterid = $chapterid; if (!$DB->insert_record('game_bookquiz_chapters', $newrec, false)) { print_object($newrec); print_error("Can't insert to table game_bookquiz_chapters"); } } //Have to go to next page. $bookquiz->lastchapterid = $nextchapterid; $scorequestion = 1; break; } $query = new stdClass(); $query->id = 0; $query->attemptid = $attempt->id; $query->gameid = $game->id; $query->userid = $USER->id; $query->sourcemodule = 'question'; $query->questionid = $question->id; $query->glossaryentryid = 0; $query->questiontext = $question->questiontext; $query->timelastattempt = time(); game_update_queries($game, $attempt, $query, $scorequestion, ''); game_updateattempts($game, $attempt, $scoreattempt, 0); game_bookquiz_continue($id, $game, $attempt, $bookquiz, $bookquiz->lastchapterid, $context); }
public function generate_questions($courses, $modules) { global $DB, $CFG; if (!is_null($this->get('questions_per_course')) && count($courses) > 0 && is_array($courses)) { require_once $CFG->libdir . '/questionlib.php'; require_once $CFG->dirroot . '/mod/quiz/editlib.php'; $questions = array(); $questionsmenu = question_type_menu(); $questiontypes = array(); foreach ($questionsmenu as $qtype => $qname) { $questiontypes[] = $qtype; } // Add the questions foreach ($courses as $courseid) { $questions[$courseid] = array(); for ($i = 0; $i < $this->get('questions_per_course'); $i++) { $qtype = $questiontypes[array_rand($questiontypes)]; // Only the following types are supported right now. Hang around for more! $supported_types = array('match', 'essay', 'multianswer', 'multichoice', 'shortanswer', 'numerical', 'truefalse', 'calculated'); $qtype = $supported_types[array_rand($supported_types)]; if ($qtype == 'calculated') { continue; } $classname = "question_{$qtype}_qtype"; if ($qtype == 'multianswer') { $classname = "embedded_cloze_qtype"; } $question = new $classname(); $question->qtype = $qtype; $questions[$courseid][] = $question->generate_test("question{$qtype}-{$i}", $courseid); $this->verbose("Generated a question of type {$qtype} for course id {$courseid}."); } } // Assign questions to quizzes, if such exist if (!empty($modules['quiz']) && !empty($questions) && !is_null($this->get('questions_per_quiz'))) { $quizzes = $modules['quiz']; // Cannot assign more questions per quiz than are available, so determine which is the largest $questions_per_quiz = max(count($questions), $this->get('questions_per_quiz')); foreach ($quizzes as $quiz) { $questions_added = array(); for ($i = 0; $i < $questions_per_quiz; $i++) { // Add a random question to the quiz do { if (empty($quiz->course)) { print_object($quizzes); die; } $random = rand(0, count($questions[$quiz->course])); } while (in_array($random, $questions_added) || !array_key_exists($random, $questions[$quiz->course])); if (!quiz_add_quiz_question($questions[$quiz->course][$random]->id, $quiz)) { // Could not add question to quiz!! report error if (!$this->get('quiet')) { echo "WARNING: Could not add question id {$random} to quiz id {$quiz->id}{$this->eolchar}"; } } else { $this->verbose("Adding question id {$random} to quiz id {$quiz->id}."); $questions_added[] = $random; } } } } return $questions; } return null; }
/** * Private method. Used by printPass/Fail/Skip/Error. */ function _paintPassFail($passorfail, $message, $stacktrace = null, $debuginfo = null) { global $CFG, $OUTPUT; echo $OUTPUT->box_start($passorfail . ' generalbox '); $url = $this->_htmlEntities($this->_stripParameterFromUrl(qualified_me(), 'path')); echo '<b class="', $passorfail, '">', $this->get_string($passorfail), '</b>: '; $breadcrumb = $this->getTestList(); array_shift($breadcrumb); $file = array_shift($breadcrumb); $pathbits = preg_split('/\\/|\\\\/', substr($file, strlen($CFG->dirroot) + 1)); $file = array_pop($pathbits); $folder = ''; foreach ($pathbits as $pathbit) { $folder .= $pathbit . '/'; echo "<a href=\"{$url}path={$folder}\" title=\"{$this->strrunonlyfolder}\">{$pathbit}</a>/"; } echo "<a href=\"{$url}path={$folder}{$file}\" title=\"{$this->strrunonlyfile}\">{$file}</a>"; echo $this->strseparator, implode($this->strseparator, $breadcrumb); echo '<br />', $this->_htmlEntities($message), "\n\n"; if (!empty($debuginfo)) { print_object('Debug info:'); print_object($debuginfo); } if ($stacktrace) { $dotsadded = false; $interestinglines = 0; $filteredstacktrace = array(); foreach ($stacktrace as $frame) { if (empty($frame['file']) || strpos($frame['file'], 'simpletestlib') === false && strpos($frame['file'], 'simpletestcoveragelib') === false && strpos($frame['file'], 'tool/unittest') === false) { $filteredstacktrace[] = $frame; $interestinglines += 1; $dotsadded = false; } else { if (!$dotsadded) { $filteredstacktrace[] = array('line' => '...', 'file' => '...'); $dotsadded = true; } } } if ($interestinglines > 1 || $passorfail == 'exception' && $interestinglines > 0) { echo '<div class="notifytiny">' . format_backtrace($filteredstacktrace) . "</div>\n\n"; } } echo $OUTPUT->box_end(); flush(); }
/** * Callback called when PEAR throws an error * * @param PEAR_Error $error */ function pear_handle_error($error) { echo '<strong>' . $error->GetMessage() . '</strong> ' . $error->getUserInfo(); echo '<br /> <strong>Backtrace </strong>:'; print_object($error->backtrace); }
/** * Processes the grade entry if grades are updated via Moodle only * * @param object $cm The moodle course module object for this instance * @param object $turnitintool The turnitintool object for this activity * @param array $post The POST array supplied from the grade update form * @return string Returns $notice in the event of an error */ function turnitintool_update_form_grades($cm, $turnitintool, $post) { global $CFG; $notice = ''; $total = 0; $owner = turnitintool_get_owner($turnitintool->course); foreach ($post['grade'] as $id => $thisgrade) { if (!($submission = turnitintool_get_record('turnitintool_submissions', 'id', $id))) { turnitintool_print_error('submissiongeterror', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } if ($thisgrade != $submission->submission_grade) { $total++; } } $loaderbar = new turnitintool_loaderbarclass($total + 2); $tii = new turnitintool_commclass(turnitintool_getUID($owner), $owner->firstname, $owner->lastname, $owner->email, 2, $loaderbar); $tii->startSession(); $proc = 0; foreach ($post['grade'] as $id => $thisgrade) { $thisgrade = round($thisgrade); // round the grade to an integer / Turnitin won't accept a null grade via the API if (!($submission = turnitintool_get_record('turnitintool_submissions', 'id', $id))) { turnitintool_print_error('submissiongeterror', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } if (!($part = turnitintool_get_record_select('turnitintool_parts', "id=" . $submission->submission_part . " AND deleted=0"))) { turnitintool_print_error('partgeterror', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } // work out if the grade has changed from what is stored if (empty($thisgrade) or $thisgrade != $submission->submission_grade) { $user = turnitintool_get_moodleuser($submission->userid, NULL, __FILE__, __LINE__); $update = new object(); $update->id = $id; $update->submission_grade = $thisgrade; print_object($update); if ($thisgrade > $part->maxmarks) { $input = new stdClass(); $input->fullname = $user->firstname . ' ' . $user->lastname; $input->part = turnitintool_partnamefromnum($submission->submission_part); $input->maximum = $part->maxmarks; $notice .= get_string('submissiongradetoohigh', 'turnitintool', $input); } else { if (!($result = turnitintool_update_record('turnitintool_submissions', $update))) { $notice = get_string('submissionupdateerror', 'turnitintool'); } } // now push the grade to Turnitin $post = new stdClass(); $post->oid = $submission->submission_objectid; $post->score = $thisgrade; $post->cid = turnitintool_getCID($turnitintool->course); $proc++; $add = new stdClass(); $add->num = $proc; $add->total = $total; $tii->setGradeMark($post, get_string('pushinggrade', 'turnitintool', $add)); if ($tii->getRerror()) { if ($tii->getAPIunavailable()) { turnitintool_print_error('apiunavailable', 'turnitintool', NULL, NULL, __FILE__, __LINE__); } else { turnitintool_print_error($tii->getRmessage() . ' CODE: ' . $tii->getRcode(), NULL, NULL, NULL, __FILE__, __LINE__); } exit; } @(include_once $CFG->dirroot . "/lib/gradelib.php"); if (function_exists('grade_update')) { $grades = turnitintool_buildgrades($turnitintool, $user); $cm = get_coursemodule_from_instance("turnitintool", $turnitintool->id, $turnitintool->course); $params['idnumber'] = $cm->idnumber; grade_update('mod/turnitintool', $turnitintool->course, 'mod', 'turnitintool', $turnitintool->id, 0, $grades, $params); } } } $tii->endSession(); $loaderbar->endloader(); // Update gradebook grades in Moodle 1.9 and above turnitintool_redirect($CFG->wwwroot . "/mod/turnitintool/view.php?id=" . $cm->id . "&do=allsubmissions&update=1"); return $notice; }
/** * Get a single record as an object using an SQL statement * * The SQL statement should normally only return one record. In debug mode * you will get a warning if more record is returned (unless you * set $expectmultiple to true). In non-debug mode, it just returns * the first record. * * @uses $CFG * @uses $db * @param string $sql The SQL string you wish to be executed, should normally only return one record. * @param bool $expectmultiple If the SQL cannot be written to conveniently return just one record, * set this to true to hide the debug message. * @param bool $nolimit sometimes appending ' LIMIT 1' to the SQL causes an error. Set this to true * to stop your SQL being modified. This argument should probably be deprecated. * @return Found record as object. False if not found or error */ function get_record_sql($sql, $expectmultiple = false, $nolimit = false) { global $CFG; /// Default situation $limitfrom = 0; /// Number of records to skip $limitnum = 1; /// Number of records to retrieve /// Only a few uses of the 2nd and 3rd parameter have been found /// I think that we should avoid to use them completely, one /// record is one record, and everything else should return error. /// So the proposal is to change all the uses, (4-5 inside Moodle /// Core), drop them from the definition and delete the next two /// "if" sentences. (eloy, 2006-08-19) if ($nolimit) { $limitfrom = 0; $limitnum = 0; } else { if ($expectmultiple) { $limitfrom = 0; $limitnum = 1; } else { if (debugging('', DEBUG_DEVELOPER)) { // Debugging mode - don't use a limit of 1, but do change the SQL, because sometimes that // causes errors, and in non-debug mode you don't see the error message and it is // impossible to know what's wrong. $limitfrom = 0; $limitnum = 100; } } } if (!($rs = get_recordset_sql($sql, $limitfrom, $limitnum))) { return false; } $recordcount = $rs->RecordCount(); if ($recordcount == 0) { // Found no records return false; } else { if ($recordcount == 1) { // Found one record /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back /// to '' (empty string) for Oracle. It's the only way to work with /// all those NOT NULL DEFAULT '' fields until we definitively delete them if ($CFG->dbfamily == 'oracle') { array_walk($rs->fields, 'onespace2empty'); } /// End of DIRTY HACK return (object) $rs->fields; } else { // Error: found more than one record notify('Error: Turn off debugging to hide this error.'); notify($sql . '(with limits ' . $limitfrom . ', ' . $limitnum . ')'); if ($records = $rs->GetAssoc(true)) { notify('Found more than one record in get_record_sql !'); print_object($records); } else { notify('Very strange error in get_record_sql !'); print_object($rs); } print_continue("{$CFG->wwwroot}/{$CFG->admin}/config.php"); } } }
/** * Invoke method, every class will have its own * returns true/false on completion, setting both * errormsg and output as necessary */ function invoke() { parent::invoke(); $result = true; /// Set own core attributes //$this->does_generate = ACTION_NONE; $this->does_generate = ACTION_GENERATE_HTML; /// These are always here global $CFG, $XMLDB, $db; /// ADD YOUR CODE HERE require_once $CFG->libdir . '/ddllib.php'; /// Where all the tests will be stored $tests = array(); /// The back to edit table button $b = ' <p class="centerpara buttons">'; $b .= '<a href="index.php">[' . $this->str['back'] . ']</a>'; $b .= '</p>'; $o = $b; /// Silenty drop any previous test tables $table = new XMLDBTable('testtable'); if (table_exists($table)) { $status = drop_table($table, true, false); } $table = new XMLDBTable('anothertest'); if (table_exists($table)) { $status = drop_table($table, true, false); } $table = new XMLDBTable('newnameforthetable'); if (table_exists($table)) { $status = drop_table($table, true, false); } /// 1st test. Complete table creation. $table = new XMLDBTable('testtable'); $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null); $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('type', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general'); $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null); $table->addFieldInfo('intro', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null); $table->addFieldInfo('logo', XMLDB_TYPE_BINARY, 'big', null, XMLDB_NOTNULL, null, null, null); $table->addFieldInfo('assessed', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('assesstimestart', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('assesstimefinish', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('scale', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('maxbytes', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('forcesubscribe', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('trackingtype', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1'); $table->addFieldInfo('rsstype', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('rssarticles', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('grade', XMLDB_TYPE_NUMBER, '20,0', XMLDB_UNSIGNED, null, null, null, null, null); $table->addFieldInfo('percent', XMLDB_TYPE_NUMBER, '5,2', null, null, null, null, null, null); $table->addFieldInfo('warnafter', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('blockafter', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('blockperiod', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id')); $table->addKeyInfo('type-name', XMLDB_KEY_UNIQUE, array('type', 'name')); $table->addIndexInfo('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->addIndexInfo('rsstype', XMLDB_INDEX_UNIQUE, array('rsstype')); $table->setComment("This is a test'n drop table. You can drop it safely"); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getCreateTableSQL($CFG->dbtype, $CFG->prefix, true); $test->status = create_table($table, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['create table'] = $test; /// 2nd test. drop table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getDropTableSQL($CFG->dbtype, $CFG->prefix, true); $test->status = drop_table($table, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop table'] = $test; } /// 3rd test. creating another, smaller table if ($test->status) { $table = new XMLDBTable('anothertest'); $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null); $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, 'Moodle'); $table->addFieldInfo('secondname', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null); $table->addFieldInfo('intro', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null); $table->addFieldInfo('avatar', XMLDB_TYPE_BINARY, 'medium', null, null, null, null, null, null); $table->addFieldInfo('grade', XMLDB_TYPE_NUMBER, '20,10', null, null, null, null, null); $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id')); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getCreateTableSQL($CFG->dbtype, $CFG->prefix, true); $test->status = create_table($table, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['create table - 2'] = $test; } /// Insert two records to do the work with real data $rec->course = 1; $rec->name = 'Martin'; $rec->secondname = 'Dougiamas'; $rec->intro = 'The creator of Moodle'; $rec->grade = 10.0001; insert_record('anothertest', $rec); $rec->course = 2; $rec->name = 'Eloy'; $rec->secondname = 'Lafuente'; $rec->intro = 'One poor developer'; $rec->grade = 9.99; insert_record('anothertest', $rec); /// 4th test. Adding one complex enum field if ($test->status) { /// Create a new field with complex specs (enums are good candidates) $field = new XMLDBField('type'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general', 'course'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getAddFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = add_field($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add enum field'] = $test; } /// 5th test. Dropping one complex enum field if ($test->status) { /// Create a new field with complex specs (enums are good candidates) $test = new stdClass(); $test->sql = $table->getDropFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = drop_field($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop enum field'] = $test; } /// 6th test. Adding one complex enum field if ($test->status) { /// Create a new field with complex specs (enums are good candidates) $field = new XMLDBField('type'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general', 'course'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getAddFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = add_field($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add enum field again'] = $test; } /// 7th test. Adding one numeric field if ($test->status) { /// Create a new field (numeric) $field = new XMLDBField('onenumber'); $field->setAttributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0, 'type'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getAddFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = add_field($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add numeric field'] = $test; } /// 8th test. Dropping one complex enum field if ($test->status) { /// Create a new field with complex specs (enums are good candidates) $field = new XMLDBField('type'); $test = new stdClass(); $test->sql = $table->getDropFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = drop_field($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop enum field again'] = $test; } /// 9th test. Change the type of one column from integer to varchar if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('course'); $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, '0'); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_type($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field type (int2char)'] = $test; } /// 10th test. Change the type of one column from varchar to integer if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('course'); $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_type($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field type (char2int)'] = $test; } /// 11th test. Change the type of one column from number to varchar if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, "test'n drop"); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_type($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field type (number2char)'] = $test; } /// 12th test. Change the type of one column from varchar to float if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_FLOAT, '20,10', XMLDB_UNSIGNED, null, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_type($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field type (char2float)'] = $test; } /// 13th test. Change the type of one column from float to char if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'test'); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_type($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field type (float2char)'] = $test; } /// 14th test. Change the type of one column from char to number if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_NUMBER, '20,10', XMLDB_UNSIGNED, null, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_type($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field type (char2number)'] = $test; } /// 15th test. Change the precision of one text field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('intro'); $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_precision($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field precision (text)'] = $test; } /// 16th test. Change the precision of one char field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('secondname'); $field->setAttributes(XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_precision($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field precision (char)'] = $test; } /// 17th test. Change the precision of one numeric field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_NUMBER, '10,2', null, null, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_precision($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field precision (number)'] = $test; } /// 18th test. Change the precision of one integer field to a smaller one if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('course'); $field->setAttributes(XMLDB_TYPE_INTEGER, '5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_precision($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field precision (integer) to smaller one'] = $test; } /// 19th test. Change the sign of one numeric field to unsigned if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_NUMBER, '10,2', XMLDB_UNSIGNED, null, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_unsigned($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field sign (unsigned)'] = $test; } /// 20th test. Change the sign of one numeric field to signed if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('grade'); $field->setAttributes(XMLDB_TYPE_NUMBER, '10,2', null, null, null, null, null, null); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_unsigned($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field sign (signed)'] = $test; } /// 21th test. Change the nullability of one char field to not null if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('name'); $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'Moodle'); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_notnull($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field nullability (not null)'] = $test; } /// 22th test. Change the nullability of one char field to null if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('name'); $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, null, null, null, null, 'Moodle'); $test->sql = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_notnull($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['change field nullability (null)'] = $test; } /// 23th test. Dropping the default of one field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('name'); $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null); $test->sql = $table->getModifyDefaultSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_default($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop field default of NULL field'] = $test; } /// 24th test. Creating the default for one field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('name'); $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, null, null, null, null, 'Moodle'); $test->sql = $table->getModifyDefaultSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_default($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add field default of NULL field'] = $test; } /// 25th test. Creating the default for one field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('secondname'); $field->setAttributes(XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, null, 'Moodle2'); $test->sql = $table->getModifyDefaultSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_default($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add field default of NOT NULL field'] = $test; } /// 26th test. Dropping the default of one NOT NULL field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('secondname'); $field->setAttributes(XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, null, null); $test->sql = $table->getModifyDefaultSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_default($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop field default of NOT NULL field'] = $test; } /// 27th test. Adding one unique index to the table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $index = new XMLDBIndex('secondname'); $index->setAttributes(XMLDB_INDEX_UNIQUE, array('name', 'secondname', 'grade')); $test->sql = $table->getAddIndexSQL($CFG->dbtype, $CFG->prefix, $index, true); $test->status = add_index($table, $index, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add unique index'] = $test; } /// 28th test. Adding one not unique index to the table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $index = new XMLDBIndex('secondname'); $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'name')); $test->sql = $table->getAddIndexSQL($CFG->dbtype, $CFG->prefix, $index, true); $test->status = add_index($table, $index, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add not unique index'] = $test; } /// 29th test. Re-add the same index than previous test. Check find_index_name() works. if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $index = new XMLDBIndex('secondname'); $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name', 'course')); if ($indexfound = find_index_name($table, $index)) { $test->status = true; $test->sql = array(); } else { $test->status = true; $test->error = 'Index not found!'; $test->sql = array(); } $tests['check find_index_name()'] = $test; } /// 30th test. Dropping one index from the table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $index = new XMLDBIndex('name'); $index->setAttributes(XMLDB_INDEX_UNIQUE, array('name', 'grade', 'secondname')); $test->sql = $table->getDropIndexSQL($CFG->dbtype, $CFG->prefix, $index, true); $test->status = drop_index($table, $index, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop index'] = $test; } /// 31th test. Adding one unique key to the table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $key = new XMLDBKey('id-course-grade'); $key->setAttributes(XMLDB_KEY_UNIQUE, array('id', 'course', 'grade')); $test->sql = $table->getAddKeySQL($CFG->dbtype, $CFG->prefix, $key, true); $test->status = add_key($table, $key, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add unique key'] = $test; } /// 32th test. Adding one foreign+unique key to the table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $key = new XMLDBKey('course'); $key->setAttributes(XMLDB_KEY_FOREIGN_UNIQUE, array('course'), 'anothertest', array('id')); $test->sql = $table->getAddKeySQL($CFG->dbtype, $CFG->prefix, $key, true); $test->status = add_key($table, $key, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add foreign+unique key'] = $test; } /// 33th test. Drop one key if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $key = new XMLDBKey('course'); $key->setAttributes(XMLDB_KEY_FOREIGN_UNIQUE, array('course'), 'anothertest', array('id')); $test->sql = $table->getDropKeySQL($CFG->dbtype, $CFG->prefix, $key, true); $test->status = drop_key($table, $key, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop foreign+unique key'] = $test; } /// 34th test. Adding one foreign key to the table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $key = new XMLDBKey('course'); $key->setAttributes(XMLDB_KEY_FOREIGN, array('course'), 'anothertest', array('id')); $test->sql = $table->getAddKeySQL($CFG->dbtype, $CFG->prefix, $key, true); $test->status = add_key($table, $key, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add foreign key'] = $test; } /// 35th test. Drop one foreign key if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $key = new XMLDBKey('course'); $key->setAttributes(XMLDB_KEY_FOREIGN, array('course'), 'anothertest', array('id')); $test->sql = $table->getDropKeySQL($CFG->dbtype, $CFG->prefix, $key, true); $test->status = drop_key($table, $key, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop foreign key'] = $test; } /// 36th test. Adding one complex enum field if ($test->status) { /// Create a new field with complex specs (enums are good candidates) $field = new XMLDBField('type'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general', 'course'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getAddFieldSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = add_field($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add field with enum'] = $test; } /// 37th test. Dropping the enum of one field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('type'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'general', 'course'); $test->sql = $table->getModifyEnumSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_enum($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['delete enumlist from one field'] = $test; } /// 38th test. Creating the enum for one field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('type'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general', 'course'); $test->sql = $table->getModifyEnumSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_enum($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add enumlist to one field'] = $test; } /// 39th test. Renaming one index if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $index = new XMLDBIndex('anyname'); $index->setAttributes(XMLDB_INDEX_UNIQUE, array('name', 'course')); $test->sql = $table->getRenameIndexSQL($CFG->dbtype, $CFG->prefix, $index, 'newnamefortheindex', true); $test->status = rename_index($table, $index, 'newnamefortheindex', false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['rename index (experimental. DO NOT USE IT)'] = $test; } /// 40th test. Renaming one key if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $key = new XMLDBKey('anyname'); $key->setAttributes(XMLDB_KEY_UNIQUE, array('id', 'course', 'grade')); $test->sql = $table->getRenameKeySQL($CFG->dbtype, $CFG->prefix, $key, 'newnameforthekey', true); $test->status = rename_key($table, $key, 'newnameforthekey', false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['rename key (experimental. DO NOT USE IT)'] = $test; } /// 41th test. Renaming one field if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $field = new XMLDBField('type'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general', 'course'); $test->sql = $table->getRenameFieldSQL($CFG->dbtype, $CFG->prefix, $field, 'newnameforthefield', true); $test->status = rename_field($table, $field, 'newnameforthefield', false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['rename field'] = $test; } /// 42th test. Renaming one table if ($test->status) { /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getRenameTableSQL($CFG->dbtype, $CFG->prefix, 'newnameforthetable', true); $test->status = rename_table($table, 'newnameforthetable', false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['rename table'] = $test; } /// 43th test. Add enum to field containing enum if ($test->status) { /// Add enum to field containing enum $table->setName('newnameforthetable'); $field = new XMLDBField('newnameforthefield'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('single', 'news', 'general', 'social', 'eachuser', 'teacher', 'qanda'), 'general', 'course'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getModifyEnumSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_enum($table, $field, false, false); /// Let's see if the constraint exists to alter results if (check_constraint_exists($table, $field)) { $test->sql = array('Nothing executed. Enum already exists. Correct.'); } else { $test->status = false; } if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['add enum to field containing enum'] = $test; } /// 44th test. Drop enum from field containing enum if ($test->status) { /// Drop enum from field containing enum $table->setName('newnameforthetable'); $field = new XMLDBField('newnameforthefield'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'general', 'course'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getModifyEnumSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_enum($table, $field, false, false); if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop enum from field containing enum'] = $test; } /// 45th test. Drop enum from field not containing enum if ($test->status) { /// Drop enum from field not containing enum $table->setName('newnameforthetable'); $field = new XMLDBField('newnameforthefield'); $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'general', 'course'); /// Get SQL code and execute it $test = new stdClass(); $test->sql = $table->getModifyEnumSQL($CFG->dbtype, $CFG->prefix, $field, true); $test->status = change_field_enum($table, $field, false, false); /// Let's see if the constraint exists to alter results if (!check_constraint_exists($table, $field)) { $test->sql = array('Nothing executed. Enum does not exists. Correct.'); } else { $test->status = false; } if (!$test->status) { $test->error = $db->ErrorMsg(); } $tests['drop enum from field not containing enum'] = $test; } /// 46th test. Getting the PK sequence name for one table if ($test->status) { $test = new stdClass(); $test->sql = array(find_sequence_name($table)); $test->status = find_sequence_name($table); if (!$test->status) { if (!($test->error = $db->ErrorMsg())) { //If no db errors, result is ok. Just the driver doesn't support this $test->sql = array('Not needed for this DB. Correct.'); $test->status = true; } } $tests['find sequence name'] = $test; } /// 47th test. Inserting TEXT contents $textlib = textlib_get_instance(); if ($test->status) { $test = new stdClass(); $test->status = false; $test->sql = array(); $basetext = "\\ ''語 • Русский • Deutsch • English • Español • Français • Italiano • Nederlands • Polski • Português • Svenska • العربية • فارسی 한국어 • עברית • ไทย中文 Ελληνικά • Български • Српски • Українська • Bosanski • Català • Česky • Dansk • Eesti • Simple English • Esperanto • Euskara • Galego • Hrvatski • Ido • Bahasa Indonesia • Íslenska • Lëtzebuergesch • Lietuvių • Magyar • Bahasa Melayu اردو • ئۇيغۇرچه • हिन्दी • नेपाल भाषा मराठी • தமிழ் Հայերեն • Беларуская • Чăваш • Ирон æвзаг • Македонски • Сибирской говор • Afrikaans • Aragonés • Arpitan • Asturianu • Kreyòl Ayisyen • Azərbaycan • Bân-lâm-gú • Basa Banyumasan • Brezhoneg • Corsu • Cymraeg • Deitsch • Føroyskt • Frysk • Furlan • Gaeilge • Gàidhlig • Ilokano • Interlingua • Basa Jawa • Kapampangan • Kernewek • Kurdî كوردی • Ladino לאדינו • Latina • Latviešu • Limburgs • Lumbaart • Nedersaksisch • Nouormand • Occitan • O‘zbek • Piemontèis • Plattdüütsch • Ripoarisch • Sámegiella • Scots • Shqip • Sicilianu • Sinugboanon • Srpskohrvatski / Српскохрватски • Basa Sunda • Kiswahili • Tagalog • Tatarça • Walon • Winaray Авар • Башҡорт • Кыргызча Монгол • Қазақша • Тоҷикӣ • Удмурт • Armãneashce • Bamanankan • Eald Englisc • Gaelg • Interlingue • Kaszëbsczi • Kongo • Ligure • Lingála • lojban • Malagasy • Malti • Māori • Nāhuatl • Ekakairũ Naoero • Novial • Pangasinán • Tok Pisin • Romani / रोमानी • Rumantsch • Runa Simi • Sardu • Tetun • Türkmen / تركمن / Туркмен • Vèneto • Volapük • Võro • West-Vlaoms • Wollof • Zazaki • Žemaitėška"; /// Create one big text (1.500.000 chars) $fulltext = ''; for ($i = 0; $i < 1000; $i++) { //1500 * 1000 chars $fulltext .= $basetext; } /// Build the record to insert $rec->intro = addslashes($fulltext); $rec->name = 'texttest'; /// Calculate its length $textlen = $textlib->strlen($fulltext); if ($rec->id = insert_record('newnameforthetable', $rec)) { if ($new = get_record('newnameforthetable', 'id', $rec->id)) { delete_records('newnameforthetable', 'id', $new->id); $newtextlen = $textlib->strlen($new->intro); if ($fulltext === $new->intro) { $test->sql = array($newtextlen . ' cc. (text) sent and received ok'); $test->status = true; } else { $test->error = $db->ErrorMsg(); $test->sql = array($newtextlen . ' cc. (text) transfer failed. Data changed!'); print_object($new); $test->status = false; } } else { $test->error = $db->ErrorMsg(); } } else { $test->error = $db->ErrorMsg(); } $tests['insert record ' . $textlen . ' cc. (text)'] = $test; } /// 48th test. Inserting BINARY contents if ($test->status) { $test = new stdClass(); $test->status = false; /// Build the record to insert $rec->avatar = addslashes($fulltext); $rec->name = 'binarytest'; /// Calculate its length $textlen = strlen($fulltext); if ($rec->id = insert_record('newnameforthetable', $rec)) { if ($new = get_record('newnameforthetable', 'id', $rec->id)) { $newtextlen = strlen($new->avatar); if ($fulltext === $new->avatar) { $test->sql = array($newtextlen . ' bytes (binary) sent and received ok'); $test->status = true; } else { $test->error = $db->ErrorMsg(); $test->sql = array($newtextlen . ' bytes (binary) transfer failed. Data changed!'); $test->status = false; } } else { $test->error = $db->ErrorMsg(); } } else { $test->error = $db->ErrorMsg(); } $tests['insert record ' . $textlen . ' bytes (binary)'] = $test; } /// 49th test. update_record with TEXT and BINARY contents if ($test->status) { $test = new stdClass(); $test->status = false; $test->sql = array(); /// Build the record to insert $rec->intro = addslashes($basetext); $rec->avatar = addslashes($basetext); $rec->name = 'updatelobs'; /// Calculate its length $textlen = $textlib->strlen($basetext); $imglen = strlen($basetext); if (update_record('newnameforthetable', $rec)) { if ($new = get_record('newnameforthetable', 'id', $rec->id)) { $newtextlen = $textlib->strlen($new->intro); $newimglen = strlen($new->avatar); if ($basetext === $new->avatar && $basetext === $new->intro) { $test->sql = array($newtextlen . ' cc. (text) sent and received ok', $newimglen . ' bytes (binary) sent and received ok'); $test->status = true; } else { if ($rec->avatar !== $new->avatar) { $test->error = $db->ErrorMsg(); $test->sql = array($newimglen . ' bytes (binary) transfer failed. Data changed!'); $test->status = false; } else { $test->error = $db->ErrorMsg(); $test->sql = array($newtextlen . ' cc. (text) transfer failed. Data changed!'); $test->status = false; } } } else { $test->error = $db->ErrorMsg(); } } else { $test->error = $db->ErrorMsg(); } $tests['update record ' . $textlen . ' cc. (text) and ' . $imglen . ' bytes (binary)'] = $test; } /// 50th test. set_field with TEXT contents if ($test->status) { $test = new stdClass(); $test->status = false; $test->sql = array(); /// Build the record to insert $rec->intro = addslashes($fulltext); $rec->name = 'updatelobs'; /// Calculate its length $textlen = $textlib->strlen($fulltext); if (set_field('newnameforthetable', 'intro', $rec->intro, 'name', $rec->name)) { if ($new = get_record('newnameforthetable', 'id', $rec->id)) { $newtextlen = $textlib->strlen($new->intro); if ($fulltext === $new->intro) { $test->sql = array($newtextlen . ' cc. (text) sent and received ok'); $test->status = true; } else { $test->error = $db->ErrorMsg(); $test->sql = array($newtextlen . ' cc. (text) transfer failed. Data changed!'); $test->status = false; } } else { $test->error = $db->ErrorMsg(); } } else { $test->error = $db->ErrorMsg(); } $tests['set field ' . $textlen . ' cc. (text)'] = $test; } /// 51th test. set_field with BINARY contents if ($test->status) { $test = new stdClass(); $test->status = false; $test->sql = array(); /// Build the record to insert $rec->avatar = addslashes($fulltext); $rec->name = 'updatelobs'; /// Calculate its length $textlen = strlen($fulltext); if (set_field('newnameforthetable', 'avatar', $rec->avatar, 'name', $rec->name)) { if ($new = get_record('newnameforthetable', 'id', $rec->id)) { $newtextlen = strlen($new->avatar); if ($fulltext === $new->avatar) { $test->sql = array($newtextlen . ' bytes (binary) sent and received ok'); $test->status = true; } else { $test->error = $db->ErrorMsg(); $test->sql = array($newtextlen . ' bytes (binary) transfer failed. Data changed!'); $test->status = false; } } else { $test->error = $db->ErrorMsg(); } } else { $test->error = $db->ErrorMsg(); } $tests['set field ' . $textlen . ' bytes (binary)'] = $test; } /// TODO: Check here values of the inserted records to see that everything ha the correct value /// Iterate over tests, showing information as needed $o .= '<ol>'; foreach ($tests as $key => $test) { $o .= '<li>' . $key . ($test->status ? '<font color="green"> Ok</font>' : ' <font color="red">Error</font>'); if (!$test->status) { $o .= '<br/><font color="red">' . $test->error . '</font>'; } $o .= '<pre>' . implode('<br/>', $test->sql) . '</pre>'; $o .= '</li>'; } $o .= '</ol>'; $this->output = $o; /// Launch postaction if exists (leave this here!) if ($this->getPostAction() && $result) { return $this->launch($this->getPostAction()); } /// Return ok if arrived here return $result; }
/** * Get a single record as an object using the specified SQL statement * * A LIMIT is normally added to only look for 1 record * If debugging is OFF only the first record is returned even if there is * more than one matching record! * * @uses $CFG * @uses $db * @param string $sql The SQL string you wish to be executed. * @param array $values If using placeholder ?s in the $sql, pass values here. * @return Found record as object. False if not found or error */ function get_record_sql($sql, $values = null, $expectmultiple = false, $nolimit = false) { global $db, $CFG; if (isset($CFG->debug) && $CFG->debug > 7 && !$expectmultiple) { // Debugging mode - don't use limit $limit = ''; } else { if ($nolimit) { $limit = ''; } else { $limit = ' LIMIT 1'; // Workaround - limit to one record } } if (defined('ELGG_PERFDB')) { global $PERF; $PERF->dbqueries++; } $rs = false; if (!empty($values) && is_array($values) && count($values) > 0) { $stmt = $db->Prepare($sql . $limit); $rs = $db->Execute($stmt, $values); } else { $rs = $db->Execute($sql . $limit); } if (!$rs) { if (isset($CFG->debug) and $CFG->debug > 7) { // Debugging mode - print checks notify($db->ErrorMsg() . '<br /><br />' . $sql . $limit); } if (!empty($CFG->dblogerror)) { $debug = debug_backtrace(); foreach ($debug as $d) { if (strpos($d['file'], 'datalib') === false) { error_log("SQL " . $db->ErrorMsg() . " in {$d['file']} on line {$d['line']}. STATEMENT: {$sql}{$limit}"); break; } } } return false; } if (!($recordcount = $rs->RecordCount())) { return false; // Found no records } if ($recordcount == 1) { // Found one record return (object) $rs->fields; } else { // Error: found more than one record notify('Error: Turn off debugging to hide this error.'); notify($sql . $limit); if ($records = $rs->GetAssoc(true)) { notify('Found more than one record in get_record_sql !'); print_object($records); } else { notify('Very strange error in get_record_sql !'); print_object($rs); } print_continue("{$CFG->wwwroot}/{$CFG->admin}/config.php"); } }
function game_view_capability_attempt_showinfo($game, $course, $cm, $unfinished, $numattempts) { global $CFG; echo "<br />"; echo "<div class=\"gameattempt\">"; if ($unfinished) { $buttontext = get_string('continueattemptgame', 'game'); } else { // Work out the appropriate button caption. if ($numattempts == 0) { $buttontext = get_string('attemptgamenow', 'game'); } else { $buttontext = get_string('reattemptgame', 'game'); } // Work out if the game is temporarily unavailable because of the delay option. if (!empty($attempts)) { $tempunavailable = ''; $lastattempt = end($attempts); $lastattempttime = $lastattempt->timefinish; if ($numattempts == 1 && $game->delay1 && $timenow <= $lastattempttime + $game->delay1) { $tempunavailable = get_string('temporaryblocked', 'game') . ' <strong>' . userdate($lastattempttime + $game->delay1) . '</strong>'; } else { if ($numattempts > 1 && $game->delay2 && $timenow <= $lastattempttime + $game->delay2) { $tempunavailable = get_string('temporaryblocked', 'game') . ' <strong>' . userdate($lastattempttime + $game->delay2) . '</strong>'; } } print_object($course); // If so, display a message and prevent the start button from appearing. if ($tempunavailable) { print_simple_box($tempunavailable, "center"); print_continue($CFG->wwwroot . '/course/view.php?id=' . $course->id); $buttontext = ''; } } } // Actually print the start button. if ($buttontext) { $buttontext = htmlspecialchars($buttontext, ENT_QUOTES); // Do we need a confirm javascript alert? if ($unfinished) { $strconfirmstartattempt = ''; } else { if ($game->timelimit && $game->attempts) { $strconfirmstartattempt = addslashes(get_string('confirmstartattempttimelimit', 'game', $game->attempts)); } else { if ($game->timelimit) { $strconfirmstartattempt = addslashes(get_string('confirmstarttimelimit', 'game')); } else { if ($game->attempts) { $strconfirmstartattempt = addslashes(get_string('confirmstartattemptlimit', 'game', $game->attempts)); } else { $strconfirmstartattempt = ''; } } } } // Prepare options depending on whether the game should be a popup. if (!empty($game->popup)) { $window = 'gamepopup'; $windowoptions = "left=0, top=0, height='+window.screen.height+', " . "width='+window.screen.width+', channelmode=yes, fullscreen=yes, " . "scrollbars=yes, resizeable=no, directories=no, toolbar=no, " . "titlebar=no, location=no, status=no, menubar=no"; } else { $window = '_self'; $windowoptions = ''; } // Determine the URL to use. $attempturl = "attempt.php?id={$cm->id}"; if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) { $attempturl = sid_process_url($attempturl); } // TODO eliminate this nasty JavaScript that prints the button. ?> <script type="text/javascript"> //<![CDATA[ document.write('<center><input type="button" value="<?php echo $buttontext; ?> " onclick="javascript: <?php if ($strconfirmstartattempt) { echo "if (confirm(\\'" . addslashes_js($strconfirmstartattempt) . "\\'))"; } ?> window.open(\'<?php echo $attempturl; ?> \', \'<?php echo $window; ?> \', \'<?php echo $windowoptions; ?> \'); " /></center>'); //]]> </script> <noscript> <div> <?php print_heading(get_string('noscript', 'game')); ?> </div> </noscript> <?php } echo "</div>\n"; }
} } else { if ($resetuser == 2 && $id && confirm_sesskey()) { $plagiarismfile = $DB->get_record('plagiarism_unplag_files', array('id' => $id), '*', MUST_EXIST); $file = plagiarism_plugin_unplag::unplag_get_score(plagiarism_plugin_unplag::get_settings(), $plagiarismfile, true); // Reset attempts as this was a manual check. $file->attempt = $file->attempt - 1; $DB->update_record('plagiarism_unplag_files', $file); if ($file->statuscode == UNPLAG_STATUSCODE_ACCEPTED) { echo $OUTPUT->notification(get_string('scorenotavailableyet', 'plagiarism_unplag')); } else { if ($file->statuscode == UNPLAG_STATUSCODE_PROCESSED) { echo $OUTPUT->notification(get_string('scoreavailable', 'plagiarism_unplag')); } else { echo $OUTPUT->notification(get_string('unknownwarning', 'plagiarism_unplag')); print_object($file); } } } } if (!empty($delete) && confirm_sesskey()) { $DB->delete_records('plagiarism_unplag_files', array('id' => $id)); echo $OUTPUT->notification(get_string('filedeleted', 'plagiarism_unplag')); } } $heldevents = array(); // Now show files in an error state. $userfields = get_all_user_name_fields(true, 'u'); $sqlallfiles = "SELECT t.*, " . $userfields . ", m.name as moduletype, " . "cm.course as courseid, cm.instance as cminstance FROM " . "{plagiarism_unplag_files} t, {user} u, {modules} m, {course_modules} cm " . "WHERE m.id=cm.module AND cm.id=t.cm AND t.userid=u.id " . "AND t.errorresponse is not null "; $sqlcount = "SELECT COUNT(id) FROM {plagiarism_unplag_files} WHERE statuscode <> 'Analyzed'"; // Now do sorting if specified.
function getLast20Files() { global $DB; $sql = "select * from {files} order by id desc limit 20;"; $records = $DB->get_records_sql($sql); if (!empty($records)) { foreach ($records as $record) { print_object($record); } } }
function print_object($item) { global $options; foreach ($item as $name => $value) { $name = replace_inv($name); switch (gettype($value)) { case "array": write('elem_s', $name); print_array($value); write('elem_e', $name); break; case "object": write('elem_s', $name); print_object($value); write('elem_e', $name); break; case "integer": case "string": write('obj_int_str', $name, $value); break; case "boolean": case "NULL": write('obj_bool_null', $name, $value); break; } } }
/** * Stores a current group in the user's session, if not already present. * * Current group applies to all modules in the current course that share * a grouping (or use no grouping). * * This function allows the user to change group if they want, but it * checks they have permissions to access the new group and calls error() * otherwise. * @param object $cm Course-module object * @param int $groupmode Group mode * @param int $changegroup If specified, user wants to change to this group * @return Group ID */ function groups_m_get_and_set_current($cm, $groupmode, $changegroup = -1) { // Check group mode is turned on if (!$groupmode) { return false; } // Get current group and return it if no change requested $currentgroupid = groups_m_get_current($cm); if ($changegroup < 0) { return $currentgroupid; } // Check 'all groups' access $context = get_context_instance(CONTEXT_COURSE, $cm->course); $allgroups = has_capability('moodle/site:accessallgroups', $context); // 0 is a special case for 'all groups'. if ($changegroup == 0) { if ($groupmode != VISIBLEGROUPS && !$allgroups) { error('You do not have access to view all groups'); } } else { // Normal group specified // Check group is in the course... if (!groups_group_belongs_to_course($changegroup, $cm->course)) { error('Requested group is not in this course.'); } // ...AND in the right grouping if required... if ($cm->groupingid && !groups_belongs_to_grouping($changegroup, $cm->groupingid)) { print_object($cm); print_object(groups_get_group($changegroup)); error('Requested group is not in this grouping.'); } // ...AND user has access to all groups, or it's in visible groups mode, or // user is a member. if (!$allgroups && $groupmode != VISIBLEGROUPS && !groups_is_member($changegroup)) { } } // OK, now remember this group in session global $SESSION; $SESSION->currentgroupinggroup[$cm->course][$cm->groupingid] = $changegroup; return $changegroup; }
if (!empty($CFG->usetags)) { if ($interests = tag_get_tags_csv('user', $user->id)) { print_row(get_string('interests') . ": ", $interests); } } if (!isset($hiddenfields['suspended'])) { if ($user->suspended) { print_row('', get_string('suspended', 'auth')); } } echo "</table></div></div>"; echo $OUTPUT->blocks_for_region('content'); // Print messaging link if allowed if (isloggedin() && has_capability('moodle/site:sendmessage', $context) && !empty($CFG->messaging) && !isguestuser() && !isguestuser($user) && $USER->id != $user->id) { echo '<div class="messagebox">'; echo '<a href="' . $CFG->wwwroot . '/message/index.php?id=' . $user->id . '">' . get_string('messageselectadd') . '</a>'; echo '</div>'; } if ($CFG->debugdisplay && debugging('', DEBUG_DEVELOPER) && $currentuser) { // Show user object echo '<br /><br /><hr />'; echo $OUTPUT->heading('DEBUG MODE: User session variables'); print_object($USER); } echo '</div>'; // userprofile class echo $OUTPUT->footer(); function print_row($left, $right) { echo "\n<tr><th class=\"label c0\">{$left}</th><td class=\"info c1\">{$right}</td></tr>\n"; }
public function get_trdeleted_record($trno) { global $db; $sql = "SELECT *\r\n FROM delete_log\r\n WHERE receipttype = 'tr'\r\n AND receiptno = {$trno}\r\n "; $data = $db->get_records_sql($sql, 'id'); foreach ($data as $d) { print_object(unserialize($d->data)); } }
/** * Will save the given data, that should be from calling the get_data function. Data will be all of the assessments in the course * * Also handles removing elements that should be deleted from the form. * * @param object $data value from calling get_data on this form * */ function save_assessment_list($data) { global $DB; $changed = array('assessmentname', 'type', 'assessmentprof', 'assessmentexamtype', 'assessmentduedate', 'description', 'gdescription', 'assessmentweight', 'was_deleted'); $learningObjectiveTypes = get_learning_objective_types(); foreach ($learningObjectiveTypes as $learningObjectiveType) { $changed[] = 'learning_objective_' . $learningObjectiveType; } $assessment_types = get_assessment_types(); $exam_types = get_exam_types(); $convertedAttributes = array('type' => function ($value) use($assessment_types) { return $assessment_types[$value]; }, 'assessmentexamtype' => function ($value) use($exam_types) { return $exam_types[$value]; }); $assessment_parser = new recurring_element_parser('courseassessment', 'assessment_list', $changed, $convertedAttributes); $tuples = $assessment_parser->getTuplesFromData($data); foreach ($tuples as $tupleKey => $tuple) { // TODO: Should also delete all the relations for each assessment // If the tuple has been deleted, then remove it from the database if ($tuple['was_deleted'] == true) { $assessment_parser->deleteTupleFromDB($tuple); // Finally, remove it from the tuples that will be saved, because otherwise will just be resaved anyway unset($tuples[$tupleKey]); } } $assessment_parser->saveTuplesToDB($tuples); foreach ($tuples as $tuplekey => $tuple) { $learningObjectiveTypes = get_learning_objective_types(); foreach ($learningObjectiveTypes as $learningObjectiveType) { $key = 'learning_objective_' . $learningObjectiveType; if (array_key_exists($key, $tuple) and is_array($tuple[$key])) { foreach ($tuple[$key] as $objectiveId) { $newLink = new stdClass(); $newLink->assessmentid = $tuple['id']; $newLink->objectiveid = $objectiveId; print_object($newLink); $DB->insert_record('assessmentobjectives', $newLink, false); } } } } }
<?php define('CLI_SCRIPT', true); require_once '../../../config.php'; require_once '../lib.php'; global $CFG, $DB; $roleid = $DB->get_field('role', 'id', array('archetype' => 'student')); echo $roleid . "\n"; print_object($CFG);
//$sch = new single_select(new moodle_url('/local/batches/assignusers.php', array('id'=>$id)), 'costid', $centers, $costid, null); //$sch->set_label(get_string('costcenterid', 'local_costcenter') . ':'); //echo $OUTPUT->render($sch); //echo '</div>'; //} // Get the user_selector we will need. $potentialuserselector = new batch_candidate_selector('addselect', array( 'cohortid'=>$cohort->id, 'accesscontext'=>$context)); $existinguserselector = new batch_existing_selector('removeselect', array('cohortid'=>$cohort->id, 'accesscontext'=>$context)); // Process incoming user assignments to the cohort if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) { $userstoassign = $potentialuserselector->get_selected_users(); print_object($userstoassign); if (!empty($userstoassign)) { // foreach ($userstoassign as $adduser) { $batches->assign_existing_userto_batches_from_assignuser_interface($userstoassign,$cohort->id); // cohort_add_member($cohort->id, $adduser->id); // } //$batches->enrol_course(); $potentialuserselector->invalidate_selected_users(); $existinguserselector->invalidate_selected_users(); } }
// Make worker lists. $joblists = array(); $i = 0; foreach ($allhosts as $h) { $joblist[$i][] = $h->id; $i++; if ($i == $options['workers']) { $i = 0; } } if (!empty($options['simulate'])) { mtrace('Simulate mode. Target host list:'); foreach ($allhosts as $host) { mtrace($host->vhostname . ' (' . $host->name . ')'); } print_object($joblist); die; } if (!file_exists($CFG->dirroot . '/local/vmoodle/cli/' . $options['fixture'] . '.php')) { die("This fixture has no CLI script file\n"); } // Start spreading workers, and pass the list of vhost ids. Launch workers in background // Linux only implementation. if ($CFG->ostype == 'WINDOWS') { $phpcmd = 'php.exe'; } else { $phpcmd = '/usr/bin/php'; } $verboseattr = !empty($options['verbose']) ? '--verbose' : ''; $i = 1; foreach ($joblist as $jl) {