function game_cryptex_check($id, $game, $attempt, $cryptexrec, $q, $answer)
{
    if ($attempt === false) {
        game_cryptex_continue($id, $game, $attempt, $cryptexrec);
        return;
    }
    $crossm = get_record_select('game_cross', "id={$attempt->id}");
    $query = get_record_select('game_queries', "id={$q}");
    $answer1 = trim(game_upper($query->answertext));
    $answer2 = trim(game_upper($answer));
    $textlib = textlib_get_instance();
    $len1 = $textlib->strlen($answer1);
    $len2 = $textlib->strlen($answer2);
    $equal = $len1 == $len2;
    if ($equal) {
        for ($i = 0; $i < $len1; $i++) {
            if ($textlib->substr($answer1, $i, 1) != $textlib->substr($answer2, $i, 1)) {
                $equal = true;
                break;
            }
        }
    }
    if ($equal == false) {
        game_update_queries($game, $attempt, $query, 0, $answer2);
        game_cryptex_play($id, $game, $attempt, $cryptexrec, $crossm, true);
        return;
    }
    game_update_queries($game, $attempt, $query, 1, $answer2);
    game_cryptex_play($id, $game, $attempt, $cryptexrec, $crossm, true);
}
Esempio n. 2
0
 /**
  * Optional method. If exists, allows this class to decide the title for
  * all blockinstances of this type
  */
 public static function get_instance_title(BlockInstance $bi)
 {
     $configdata = $bi->get('configdata');
     if (!empty($configdata['collection'])) {
         require_once 'collection.php';
         $data = get_record_select('collection', 'id = ?', array($configdata['collection']));
         $collection = new Collection($configdata['collection'], (array) $data);
         $title = $collection->get('name');
         return $title;
     }
     return '';
 }
function wikibook_page_content($pagename)
{
    global $WS;
    $select = "dfwiki = {$WS->dfwiki->id} AND pagename = '{$pagename}' " . "AND groupid = {$WS->groupmember->groupid}";
    if ($WS->dfwiki->studentmode != '0' || $WS->cm->groupmode == '0') {
        $select .= " AND ownerid = {$WS->member->id}";
    }
    if ($version = get_field_select('wiki_pages', 'MAX(version)', $select)) {
        if ($record = get_record_select('wiki_pages', $select . " AND version = {$version}")) {
            return $record->content;
        }
    }
}
/**
* checks an user has local identity and comes from a known host
* @param string $username the user's login
* @param string $remotehostroot the host he comes from
* @return a failure report if unchecked, null elsewhere.
*
*/
function tracker_rpc_check($username, $remotehostroot, &$localuser)
{
    // get local identity for user
    if (!($remotehost = get_record('mnet_host', 'wwwroot', $remotehostroot))) {
        $response->status = RPC_FAILURE;
        $response->error = "Calling host is not registered. Check MNET configuration";
        return json_encode($response);
    }
    if (!($localuser = get_record_select('user', "username = '******' AND mnethostid = {$remotehost->id} AND deleted = 0"))) {
        $response->status = RPC_FAILURE_USER;
        $response->error = "Calling user has no local account. Register remote user first";
        return json_encode($response);
    }
    return null;
}
function ondeleteattempt($cm, $return, $attemptid, $update, $sesskey)
{
    global $CFG;
    $attempt = get_record_select('game_attempts', 'id=' . $attemptid);
    $game = get_record_select('game', 'id=' . $attempt->gameid);
    switch ($game->gamekind) {
        case 'bookquiz':
            delete_records('game_bookquiz_chapters', 'attemptid', $attemptid);
            break;
    }
    delete_records('game_queries', 'attemptid', $attemptid);
    delete_records('game_attempts', 'id', $attemptid);
    $url = $CFG->wwwroot . "/course/mod.php?update={$update}";
    $url .= "&return=true";
    $url .= "&sesskey={$sesskey}";
    redirect($url);
}
Esempio n. 6
0
/**
 * Returns a form to mark a view as unobjectionable,
 * if the user is allowed to do that.
 *
 * @returns array Form elements.
 */
function notrude_form()
{
    global $USER, $view, $artefact;
    $owner = $view->get('owner');
    if (!($owner && ($USER->get('admin') || $USER->is_admin_for_user($owner)) || $view->get('group') && $USER->get('admin') || $view->get('group') && group_user_access($view->get('group'), $USER->get('id')) == 'admin')) {
        return;
    }
    if ($artefact) {
        $params = array('artefact', $artefact->get('id'));
    } else {
        $params = array('view', $view->get('id'));
    }
    $isrude = get_record_select('objectionable', 'objecttype = ? AND objectid = ? AND resolvedby IS NULL LIMIT 1', $params);
    if (!$isrude) {
        return;
    }
    return array('name' => 'notrude_form', 'class' => 'form-inline', 'method' => 'post', 'elements' => array('objection' => array('type' => 'hidden', 'value' => $isrude->id), 'text' => array('type' => 'html', 'class' => 'pbm', 'value' => get_string('viewobjectionableunmark', 'view')), 'submit' => array('type' => 'button', 'usebuttontag' => true, 'class' => 'btn-default', 'value' => '<span class="icon icon-lg icon-times text-danger prs"></span> ' . get_string('notobjectionable'))));
}
/**
 * Returns a form to mark a view as unobjectionable,
 * if the user is allowed to do that.
 *
 * @returns array Form elements.
 */
function notrude_form()
{
    global $USER, $view, $artefact;
    $owner = $view->get('owner');
    if (!($owner && ($USER->get('admin') || $USER->is_admin_for_user($owner)) || $view->get('group') && $USER->get('admin'))) {
        return;
    }
    if ($artefact) {
        $params = array('artefact', $artefact->get('id'));
    } else {
        $params = array('view', $view->get('id'));
    }
    $isrude = get_record_select('objectionable', 'objecttype = ? AND objectid = ? AND resolvedby IS NULL LIMIT 1', $params);
    if (!$isrude) {
        return;
    }
    return array('name' => 'notrude_form', 'method' => 'post', 'elements' => array('objection' => array('type' => 'hidden', 'value' => $isrude->id), 'text' => array('type' => 'html', 'value' => get_string('viewobjectionableunmark', 'view')), 'submit' => array('type' => 'submit', 'value' => get_string('notobjectionable'))));
}
Esempio n. 8
0
function print_classhour_delete_form($courseid, $sesskey, $timetableid, $validhour, $i, $group, $weekend)
{
    $selectclause = "starthour='" . $validhour->starthour . "' AND endhour='" . $validhour->endhour . "' AND weekday='" . $i . "' AND groupid = " . $group->id . "";
    $c = get_record_select('timetable_hourtable', $selectclause);
    // or die(mysql_error());
    $classroom = get_record('timetable_classroom', 'id', $c->classroomid);
    global $USER;
    echo '<form action = "../controller/ttcontroller.php?viewrequired=editinghourtable" method = "POST">';
    echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" >';
    echo '<input type="hidden" name="courseid" value="' . $courseid . '" >';
    echo '<input type="hidden" name="timetableid" value="' . $timetableid . '" >';
    echo '<input type="hidden" name="groupid" value="' . $group->id . '" >';
    echo '<input type="hidden" name="actionparam" value="action" >';
    echo '<input type="hidden" name="actiontype" value="edithourtable" >';
    echo '<input type="hidden" name="actionedithourtable" value="delete" >';
    echo '<input type="hidden" name="starthour" value="' . $validhour->starthour . '" >';
    echo '<input type="hidden" name="endhour" value="' . $validhour->endhour . '" >';
    echo '<input type="hidden" name="weekday" value="' . $i . '" >';
    echo '<input type="hidden" name="classroomid" value="' . $c->classroomid . '" >';
    echo '<FONT';
    if ($classroom->capacity < $group->studentsnumber || $weekend) {
        $title = '';
        if ($weekend) {
            $title = $title . get_string('classhouraddedinweekendday', 'block_timetable');
        }
        if ($classroom->capacity < $group->studentsnumber) {
            if ($title != '') {
                $title = $title . ' and ';
            }
            $title = $title . get_string('expectedstudentsnumberlessthancapacity', 'block_timetable');
        }
        echo ' COLOR="BLUE" title="' . $title . '">';
    } else {
        echo '>';
    }
    echo '<font size="-2">' . $classroom->name . '</font><BR>';
    echo '</FONT>';
    echo '<input type="image" name="boton" src="../icons/action_stop.gif" width="16" height="16" title="' . get_string('deleteclassroom', 'block_timetable') . '" >';
    echo '</form>';
}
Esempio n. 9
0
/**
 * Generate public/private keys and store in the config table
 *
 * Use the distinguished name provided to create a CSR, and then sign that CSR
 * with the same credentials. Store the keypair you create in the config table.
 * If a distinguished name is not provided, create one using the fullname of
 * 'the course with ID 1' as your organization name, and your hostname (as
 * detailed in $CFG->wwwroot).
 *
 * @param   array  $dn  The distinguished name of the server
 * @return  string      The signature over that text
 */
function mnet_generate_keypair($dn = null, $days = 28)
{
    global $CFG, $USER;
    // check if lifetime has been overriden
    if (!empty($CFG->mnetkeylifetime)) {
        $days = $CFG->mnetkeylifetime;
    }
    $host = strtolower($CFG->wwwroot);
    $host = ereg_replace("^http(s)?://", '', $host);
    $break = strpos($host . '/', '/');
    $host = substr($host, 0, $break);
    if ($result = get_record_select('course', " id ='" . SITEID . "' ")) {
        $organization = $result->fullname;
    } else {
        $organization = 'None';
    }
    $keypair = array();
    $country = 'NZ';
    $province = 'Wellington';
    $locality = 'Wellington';
    $email = $CFG->noreplyaddress;
    if (!empty($USER->country)) {
        $country = $USER->country;
    }
    if (!empty($USER->city)) {
        $province = $USER->city;
        $locality = $USER->city;
    }
    if (!empty($USER->email)) {
        $email = $USER->email;
    }
    if (is_null($dn)) {
        $dn = array("countryName" => $country, "stateOrProvinceName" => $province, "localityName" => $locality, "organizationName" => $organization, "organizationalUnitName" => 'Moodle', "commonName" => $CFG->wwwroot, "emailAddress" => $email);
    }
    $dnlimits = array('countryName' => 2, 'stateOrProvinceName' => 128, 'localityName' => 128, 'organizationName' => 64, 'organizationalUnitName' => 64, 'commonName' => 64, 'emailAddress' => 128);
    foreach ($dnlimits as $key => $length) {
        $dn[$key] = substr($dn[$key], 0, $length);
    }
    // ensure we remove trailing slashes
    $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
    if (!empty($CFG->opensslcnf)) {
        //allow specification of openssl.cnf especially for Windows installs
        $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf));
        $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf));
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf));
    } else {
        $new_key = openssl_pkey_new();
        $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits', 2048));
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
    }
    unset($csr_rsc);
    // Free up the resource
    // We export our self-signed certificate to a string.
    openssl_x509_export($selfSignedCert, $keypair['certificate']);
    openssl_x509_free($selfSignedCert);
    // Export your public/private key pair as a PEM encoded string. You
    // can protect it with an optional passphrase if you wish.
    if (!empty($CFG->opensslcnf)) {
        //allow specification of openssl.cnf especially for Windows installs
        $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf));
    } else {
        $export = openssl_pkey_export($new_key, $keypair['keypair_PEM']);
    }
    openssl_pkey_free($new_key);
    unset($new_key);
    // Free up the resource
    return $keypair;
}
Esempio n. 10
0
 /**
  * will update a local user record from an external source.
  * is a lighter version of the one in moodlelib -- won't do
  * expensive ops such as enrolment
  *
  * If you don't pass $updatekeys, there is a performance hit and
  * values removed from DB won't be removed from moodle.
  *
  * @param string $username username (with system magic quotes)
  */
 function update_user_record($username, $updatekeys = false)
 {
     global $CFG;
     //just in case check text case
     $username = trim(moodle_strtolower($username));
     // get the current user record
     $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
     if (empty($user)) {
         // trouble
         error_log("Cannot update non-existent user: {$username}");
         print_error('auth_dbusernotexist', 'auth', $username);
         die;
     }
     // Ensure userid is not overwritten
     $userid = $user->id;
     if ($newinfo = $this->get_userinfo($username)) {
         $newinfo = truncate_userinfo($newinfo);
         if (empty($updatekeys)) {
             // all keys? this does not support removing values
             $updatekeys = array_keys($newinfo);
         }
         foreach ($updatekeys as $key) {
             if (isset($newinfo[$key])) {
                 $value = $newinfo[$key];
             } else {
                 $value = '';
             }
             if (!empty($this->config->{'field_updatelocal_' . $key})) {
                 if ($user->{$key} != $value) {
                     // only update if it's changed
                     set_field('user', $key, addslashes($value), 'id', $userid);
                 }
             }
         }
     }
     return get_record_select('user', "id = {$userid} AND deleted = 0");
 }
Esempio n. 11
0
<?php 
            print_box_end();
            print_footer('empty');
            exit;
        }
    }
}
if (!empty($quiz->delay1) or !empty($quiz->delay2)) {
    //quiz enforced time delay
    if ($attempts = quiz_get_user_attempts($quiz->id, $USER->id)) {
        $numattempts = count($attempts);
    } else {
        $numattempts = 0;
    }
    $timenow = time();
    $lastattempt_obj = get_record_select('quiz_attempts', "quiz = {$quiz->id} AND attempt = {$numattempts} AND userid = {$USER->id}", 'timefinish, timestart');
    if ($lastattempt_obj) {
        $lastattempt = $lastattempt_obj->timefinish;
        if ($quiz->timelimit > 0) {
            $lastattempt = min($lastattempt, $lastattempt_obj->timestart + $quiz->timelimit * 60);
        }
    }
    if ($numattempts == 1 && !empty($quiz->delay1)) {
        if ($timenow - $quiz->delay1 < $lastattempt) {
            print_error('timedelay', 'quiz', 'view.php?q=' . $quiz->id);
        }
    } else {
        if ($numattempts > 1 && !empty($quiz->delay2)) {
            if ($timenow - $quiz->delay2 < $lastattempt) {
                print_error('timedelay', 'quiz', 'view.php?q=' . $quiz->id);
            }
Esempio n. 12
0
/**
 * has there been a request between these two users?
 *
 * @param int $userid1
 * @param int $userid2
 */
function get_friend_request($userid1, $userid2)
{
    return get_record_select('usr_friend_request', '("owner" = ? AND requester = ?) OR (requester = ? AND "owner" = ?)', array($userid1, $userid2, $userid1, $userid2));
}
Esempio n. 13
0
function restore_create_events($restore, $xml_file)
{
    global $CFG, $db;
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        $status = false;
    }
    //Get info from xml
    if ($status) {
        //events will contain the old_id of every event
        //in backup_ids->info will be the real info (serialized)
        $events = restore_read_xml_events($restore, $xml_file);
    }
    //Get admin->id for later use
    $admin = get_admin();
    $adminid = $admin->id;
    //Now, if we have anything in events, we have to restore that
    //events
    if ($events) {
        if ($events !== true) {
            //Iterate over each event
            foreach ($events as $event) {
                //Get record from backup_ids
                $data = backup_getid($restore->backup_unique_code, "event", $event->id);
                //Init variables
                $create_event = false;
                if ($data) {
                    //Now get completed xmlized object
                    $info = $data->info;
                    //traverse_xmlize($info);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //if necessary, write to restorelog and adjust date/time fields
                    if ($restore->course_startdateoffset) {
                        restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
                    }
                    //Now build the EVENT record structure
                    $eve->name = backup_todb($info['EVENT']['#']['NAME']['0']['#']);
                    $eve->description = backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
                    $eve->format = backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
                    $eve->courseid = $restore->course_id;
                    $eve->groupid = backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
                    $eve->userid = backup_todb($info['EVENT']['#']['USERID']['0']['#']);
                    $eve->repeatid = backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
                    $eve->modulename = "";
                    if (!empty($info['EVENT']['#']['MODULENAME'])) {
                        $eve->modulename = backup_todb($info['EVENT']['#']['MODULENAME']['0']['#']);
                    }
                    $eve->instance = 0;
                    $eve->eventtype = backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
                    $eve->timestart = backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
                    $eve->timeduration = backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
                    $eve->visible = backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
                    $eve->timemodified = backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
                    //Now search if that event exists (by name, description, timestart fields) in
                    //restore->course_id course
                    //Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides.
                    $compare_description_clause = sql_compare_text('description') . "=" . sql_compare_text("'" . $eve->description . "'");
                    $eve_db = get_record_select("event", "courseid={$eve->courseid} AND name='{$eve->name}' AND {$compare_description_clause} AND timestart={$eve->timestart}");
                    //If it doesn't exist, create
                    if (!$eve_db) {
                        $create_event = true;
                    }
                    //If we must create the event
                    if ($create_event) {
                        //We must recode the userid
                        $user = backup_getid($restore->backup_unique_code, "user", $eve->userid);
                        if ($user) {
                            $eve->userid = $user->new_id;
                        } else {
                            //Assign it to admin
                            $eve->userid = $adminid;
                        }
                        //We have to recode the groupid field
                        $group = backup_getid($restore->backup_unique_code, "groups", $eve->groupid);
                        if ($group) {
                            $eve->groupid = $group->new_id;
                        } else {
                            //Assign it to group 0
                            $eve->groupid = 0;
                        }
                        //The structure is equal to the db, so insert the event
                        $newid = insert_record("event", $eve);
                        //We must recode the repeatid if the event has it
                        //The repeatid now refers to the id of the original event. (see Bug#5956)
                        if ($newid && !empty($eve->repeatid)) {
                            $repeat_rec = backup_getid($restore->backup_unique_code, "event_repeatid", $eve->repeatid);
                            if ($repeat_rec) {
                                //Exists, so use it...
                                $eve->repeatid = $repeat_rec->new_id;
                            } else {
                                //Doesn't exists, calculate the next and save it
                                $oldrepeatid = $eve->repeatid;
                                $eve->repeatid = $newid;
                                backup_putid($restore->backup_unique_code, "event_repeatid", $oldrepeatid, $eve->repeatid);
                            }
                            $eve->id = $newid;
                            // update the record to contain the correct repeatid
                            update_record('event', $eve);
                        }
                    } else {
                        //get current event id
                        $newid = $eve_db->id;
                    }
                    if ($newid) {
                        //We have the newid, update backup_ids
                        backup_putid($restore->backup_unique_code, "event", $event->id, $newid);
                    }
                }
            }
        }
    } else {
        $status = false;
    }
    return $status;
}
Esempio n. 14
0
/** 
 *  deletes a completed given by completedid.
 *  all related data such values or tracking data also will be deleted
 *  @param int $completedid
 *  @return boolean
 */
function feedback_delete_completed($completedid)
{
    if (!($completed = get_record('feedback_completed', 'id', $completedid))) {
        return false;
    }
    //first we delete all related values
    @delete_records('feedback_value', 'completed', $completed->id);
    //now we delete all tracking data
    if ($tracking = get_record_select('feedback_tracking', " completed = " . $completed->id . " AND feedback = " . $completed->feedback . " ")) {
        @delete_records('feedback_tracking', 'completed', $completed->id);
    }
    //last we delete the completed-record
    return delete_records('feedback_completed', 'id', $completed->id);
}
Esempio n. 15
0
function moodle_process_email($modargs, $body)
{
    // the first char should be an unencoded letter. We'll take this as an action
    switch ($modargs[0]) {
        case 'B':
            // bounce
            list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
            if ($user = get_record_select("user", "id={$userid}", "id,email")) {
                // check the half md5 of their email
                $md5check = substr(md5($user->email), 0, 16);
                if ($md5check == substr($modargs, -16)) {
                    set_bounce_count($user);
                }
                // else maybe they've already changed it?
            }
            break;
            // maybe more later?
    }
}
Esempio n. 16
0
 /**
  * Retrieve the invisible key for this view, if there is one. (A view can only have one
  * invisible key, because it can only be submitted to one place at a time.)
  * @param int $viewid
  * @return mixed Returns a boolean FALSE if there is no invisible token, a data object if there is one
  */
 public static function get_invisible_token($viewid)
 {
     return get_record_select('view_access', 'view = ? AND token IS NOT NULL AND visible = 0', array($viewid), 'view, visible, token, ctime');
 }
Esempio n. 17
0
function activity_locate_typerecord($activitytype, $plugintype = null, $pluginname = null)
{
    if (is_object($activitytype)) {
        return $activitytype;
    }
    if (is_numeric($activitytype)) {
        $at = get_record('activity_type', 'id', $activitytype);
    } else {
        if (empty($plugintype) && empty($pluginname)) {
            $at = get_record_select('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array($activitytype));
        } else {
            $at = get_record('activity_type', 'name', $activitytype, 'plugintype', $plugintype, 'pluginname', $pluginname);
        }
    }
    if (empty($at)) {
        throw new SystemException("Invalid activity type {$activitytype}");
    }
    return $at;
}
Esempio n. 18
0
function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value)
{
    $id = null;
    if ($track = get_record_select('scorm_scoes_track', "userid='{$userid}' AND scormid='{$scormid}' AND scoid='{$scoid}' AND attempt='{$attempt}' AND element='{$element}'")) {
        $track->value = $value;
        $track->timemodified = time();
        $id = update_record('scorm_scoes_track', $track);
    } else {
        $track->userid = $userid;
        $track->scormid = $scormid;
        $track->scoid = $scoid;
        $track->attempt = $attempt;
        $track->element = $element;
        $track->value = addslashes($value);
        $track->timemodified = time();
        $id = insert_record('scorm_scoes_track', $track);
    }
    // MDL-9552, update the gradebook everything raw score is sent
    if (strstr($element, '.score.raw')) {
        $scorm = get_record('scorm', 'id', $scormid);
        include_once 'lib.php';
        scorm_update_grades($scorm, $userid);
    }
    return $id;
}
Esempio n. 19
0
 function importprocess($filename, $lesson, $pageid)
 {
     /// Processes a given file.  There's probably little need to change this
     $timenow = time();
     if (!($lines = $this->readdata($filename))) {
         notify("File could not be read, or was empty");
         return false;
     }
     if (!($questions = $this->readquestions($lines))) {
         // Extract all the questions
         notify("There are no questions in this file!");
         return false;
     }
     notify(get_string('importcount', 'lesson', sizeof($questions)));
     $count = 0;
     foreach ($questions as $question) {
         // Process and store each question
         switch ($question->qtype) {
             // the good ones
             case SHORTANSWER:
             case NUMERICAL:
             case TRUEFALSE:
             case MULTICHOICE:
             case MATCH:
                 $count++;
                 echo "<hr><p><b>{$count}</b>. " . stripslashes($question->questiontext) . "</p>";
                 $newpage = new stdClass();
                 $newpage->lessonid = $lesson->id;
                 $newpage->qtype = $this->qtypeconvert[$question->qtype];
                 switch ($question->qtype) {
                     case SHORTANSWER:
                         if (isset($question->usecase)) {
                             $newpage->qoption = $question->usecase;
                         }
                         break;
                     case MULTICHOICE:
                         if (isset($question->single)) {
                             $newpage->qoption = !$question->single;
                         }
                         break;
                 }
                 $newpage->timecreated = $timenow;
                 if ($question->name != $question->questiontext) {
                     $newpage->title = $question->name;
                 } else {
                     $newpage->title = "Page {$count}";
                 }
                 $newpage->contents = $question->questiontext;
                 // set up page links
                 if ($pageid) {
                     // the new page follows on from this page
                     if (!($page = get_record("lesson_pages", "id", $pageid))) {
                         error("Format: Page {$pageid} not found");
                     }
                     $newpage->prevpageid = $pageid;
                     $newpage->nextpageid = $page->nextpageid;
                     // insert the page and reset $pageid
                     if (!($newpageid = insert_record("lesson_pages", $newpage))) {
                         error("Format: Could not insert new page!");
                     }
                     // update the linked list
                     if (!set_field("lesson_pages", "nextpageid", $newpageid, "id", $pageid)) {
                         error("Format: unable to update link");
                     }
                 } else {
                     // new page is the first page
                     // get the existing (first) page (if any)
                     if (!($page = get_record_select("lesson_pages", "lessonid = {$lesson->id} AND prevpageid = 0"))) {
                         // there are no existing pages
                         $newpage->prevpageid = 0;
                         // this is a first page
                         $newpage->nextpageid = 0;
                         // this is the only page
                         $newpageid = insert_record("lesson_pages", $newpage);
                         if (!$newpageid) {
                             error("Insert page: new first page not inserted");
                         }
                     } else {
                         // there are existing pages put this at the start
                         $newpage->prevpageid = 0;
                         // this is a first page
                         $newpage->nextpageid = $page->id;
                         $newpageid = insert_record("lesson_pages", $newpage);
                         if (!$newpageid) {
                             error("Insert page: first page not inserted");
                         }
                         // update the linked list
                         if (!set_field("lesson_pages", "prevpageid", $newpageid, "id", $page->id)) {
                             error("Insert page: unable to update link");
                         }
                     }
                 }
                 // reset $pageid and put the page ID in $question, used in save_question_option()
                 $pageid = $newpageid;
                 $question->id = $newpageid;
                 $this->questionids[] = $question->id;
                 // Now to save all the answers and type-specific options
                 $question->lessonid = $lesson->id;
                 // needed for foreign key
                 $question->qtype = $this->qtypeconvert[$question->qtype];
                 $result = lesson_save_question_options($question);
                 if (!empty($result->error)) {
                     notify($result->error);
                     return false;
                 }
                 if (!empty($result->notice)) {
                     notify($result->notice);
                     return true;
                 }
                 break;
                 // the Bad ones
             // the Bad ones
             default:
                 notify(get_string('unsupportedqtype', 'lesson', $question->qtype));
         }
     }
     return true;
 }
Esempio n. 20
0
function delete_feedback_completed($completedid)
{
    if (!($completed = get_record('feedback_completed', 'id', $completedid))) {
        return false;
    }
    //erst alle verknuepften Values loeschen
    @delete_records('feedback_value', 'completed', $completed->id);
    //tracking eintraege dekrementieren bzw. loeschen
    if ($tracking = get_record_select('feedback_tracking', " completed = " . $completed->id . " AND feedback = " . $completed->feedback . " ")) {
        @delete_records('feedback_tracking', 'completed', $completed->id);
    }
    //den completed-datensatz loeschen
    return delete_records('feedback_completed', 'id', $completed->id);
}
Esempio n. 21
0
 *
 */
define('INTERNAL', 1);
define('INSTITUTIONALADMIN', 1);
require dirname(dirname(dirname(__FILE__))) . '/init.php';
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'admin');
define('SECTION_PAGE', 'actionregistration');
require_once 'pieforms/pieform.php';
require_once 'institution.php';
$id = param_integer('r');
$action = param_alpha('action');
if (!is_logged_in()) {
    throw new AccessDeniedException();
}
if (!($registration = get_record_select('usr_registration', '"id" = ? AND pending = 1', array($id)))) {
    die_info(get_string('registrationnosuchid', 'auth.internal'));
}
if (!($inst = get_record('institution', 'name', $registration->institution))) {
    die_info(get_string('nosuchinstitution', 'admin'));
}
if ($action == 'approve') {
    $message = get_string('approveregistrationmessage', 'admin', $inst->displayname);
    $submitbtn = get_string('approve', 'admin');
    define('TITLE', get_string('approveregistrationfor2', 'admin', $registration->firstname, $registration->lastname, $registration->email));
    if ($registration->institution != 'mahara') {
        $elements['institutionstaff'] = array('type' => 'switchbox', 'title' => get_string('institutionstaff', 'admin'), 'description' => get_string('makeuserinstitutionstaff', 'admin'), 'defaultvalue' => 0);
    }
} else {
    $message = get_string('denyregistrationmessage', 'admin');
    $submitbtn = get_string('deny', 'admin');
/**
 * Return a small object with summary information about what a 
 * user has done with a given particular instance of this module
 * Used for user activity reports.
 * $return->time = the time they did it
 * $return->info = a short text description
 **/
function game_user_outline($course, $user, $mod, $game)
{
    if ($grade = get_record_select('game_grades', "userid={$user->id} AND gameid = {$game->id}", 'id,score,timemodified')) {
        $result = new stdClass();
        if ((double) $grade->score) {
            $result->info = get_string('grade') . ':&nbsp;' . round($grade->score * $game->grade, $game->decimalpoints) . ' ' . get_string('percent', 'game') . ':&nbsp;' . round(100 * $grade->score, $game->decimalpoints) . ' %';
        }
        $result->time = $grade->timemodified;
        return $result;
    }
    return NULL;
}
Esempio n. 23
0
     break;
 case 'putperformance':
     if ($status == 'Running') {
         echo "error=0\r\nerror_text=Successful\r\n";
     } else {
         if ($status == 'Terminated') {
             echo "error=1\r\nerror_text=Terminated\r\n";
         } else {
             echo "error=1\r\nerror_text=Not Initialized\r\n";
         }
     }
     break;
 case 'exitau':
     if ($status == 'Running') {
         if (isset($SESSION->scorm_session_time) && $SESSION->scorm_session_time != '') {
             if ($track = get_record_select('scorm_scoes_track', "userid='{$USER->id}' AND scormid='{$scorm->id}' AND scoid='{$sco->id}' AND element='cmi.core.total_time'")) {
                 // Add session_time to total_time
                 $value = scorm_add_time($track->value, $SESSION->scorm_session_time);
                 $track->value = $value;
                 $track->timemodified = time();
                 update_record('scorm_scoes_track', $track);
                 $id = $track->id;
             } else {
                 $track = new object();
                 $track->userid = $USER->id;
                 $track->scormid = $scorm->id;
                 $track->scoid = $sco->id;
                 $track->element = 'cmi.core.total_time';
                 $track->value = $SESSION->scorm_session_time;
                 $track->timemodified = time();
                 $id = insert_record('scorm_scoes_track', $track);
 /**
  * Load the submission object for a particular user
  *
  * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
  * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
  * @param bool $teachermodified student submission set if false
  * @return object The submission
  */
 function get_submission($userid = 0, $createnew = false)
 {
     global $USER;
     if (empty($userid)) {
         $userid = $USER->id;
     }
     //$submission = get_record('problemstatement_submissions', 'problemstatement', $this->problemstatement->id, 'userid', $userid);
     $submission = get_record_select('problemstatement_submissions', "problemstatement={$this->problemstatement->id} and userid={$userid} order by timecreated desc");
     if ($submission || !$createnew) {
         return $submission;
     }
     $newsubmission = $this->prepare_new_submission($userid);
     if (!insert_record("problemstatement_submissions", $newsubmission)) {
         error("Could not insert a new empty submission");
     }
     return get_record('problemstatement_submissions', 'problemstatement', $this->problemstatement->id, 'userid', $userid);
 }
Esempio n. 25
0
/**
 * Abstracted version of get_records_select() to work with Moodle 1.8 through 2.0
 *
 * @param string $table The Database Table
 * @param string $select the select SQL query
 * @param string $fields the columns to return
 * @return array An array of data objects
 */
function turnitintool_get_record_select($table, $select, $params = array(), $fields = '*')
{
    global $DB;
    if (is_callable(array($DB, 'get_record_select'))) {
        $return = $DB->get_record_select($table, $select, $params, $fields);
    } else {
        $return = get_record_select($table, $select, $fields);
    }
    return $return;
}
 $feedbackitems = get_records('feedback_item', 'feedback', $feedback->id, 'position');
 $feedbackcompleted = get_record('feedback_completed', 'id', $formdata->completedid);
 if (is_array($feedbackitems)) {
     if ($feedbackcompleted) {
         echo '<p align="center">' . UserDate($feedbackcompleted->timemodified) . '<br />(' . get_string('anonymous', 'feedback') . ')</p>';
     } else {
         echo '<p align="center">' . get_string('not_completed_yet', 'feedback') . '</p>';
     }
     print_simple_box_start("center", '50%');
     echo '<form>';
     echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" />';
     echo '<table>';
     $itemnr = 0;
     foreach ($feedbackitems as $feedbackitem) {
         //value holen
         $value = get_record_select('feedback_value', 'completed =' . $feedbackcompleted->id . ' AND item=' . $feedbackitem->id);
         echo '<tr>';
         if ($feedbackitem->hasvalue == 1) {
             $itemnr++;
             echo '<td valign="top">' . $itemnr . '.)&nbsp;</td>';
         } else {
             echo '<td>&nbsp;</td>';
         }
         if (isset($value->value)) {
             print_feedback_item($feedbackitem, $value->value, true);
         }
         echo '</tr>';
     }
     echo '<tr><td colspan="2" align="center">';
     echo '</td></tr>';
     echo '</table>';
Esempio n. 27
0
function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value)
{
    $id = null;
    if ($track = get_record_select('scorm_scoes_track', "userid='{$userid}' AND scormid='{$scormid}' AND scoid='{$scoid}' AND attempt='{$attempt}' AND element='{$element}'")) {
        $track->value = addslashes_js($value);
        $track->timemodified = time();
        $id = update_record('scorm_scoes_track', $track);
    } else {
        $track->userid = $userid;
        $track->scormid = $scormid;
        $track->scoid = $scoid;
        $track->attempt = $attempt;
        $track->element = $element;
        $track->value = addslashes_js($value);
        $track->timemodified = time();
        $id = insert_record('scorm_scoes_track', $track);
    }
    if (strstr($element, '.score.raw') || ($element == 'cmi.core.lesson_status' || $element == 'cmi.completion_status') && ($track->value == 'completed' || $track->value == 'passed')) {
        $scorm = get_record('scorm', 'id', $scormid);
        $grademethod = $scorm->grademethod % 10;
        include_once 'lib.php';
        scorm_update_grades($scorm, $userid);
    }
    return $id;
}
Esempio n. 28
0
File: lib.php Progetto: kienv/mahara
/**
 * Given an artefact plugin name, this function will test if
 * it's installable or not.  If not, InstallationException will be thrown.
 */
function artefact_check_plugin_sanity($pluginname)
{
    $classname = generate_class_name('artefact', $pluginname);
    safe_require('artefact', $pluginname);
    if (!is_callable(array($classname, 'get_artefact_types'))) {
        throw new InstallationException(get_string('artefactpluginmethodmissing', 'error', $classname, 'get_artefact_types'));
    }
    if (!is_callable(array($classname, 'get_block_types'))) {
        throw new InstallationException(get_string('artefactpluginmethodmissing', 'error', $classname, 'get_block_types'));
    }
    $types = call_static_method($classname, 'get_artefact_types');
    foreach ($types as $type) {
        $typeclassname = generate_artefact_class_name($type);
        if (get_config('installed')) {
            if ($taken = get_record_select('artefact_installed_type', 'name = ? AND plugin != ?', array($type, $pluginname))) {
                // Check the other plugin's code in case the duplicate type is being removed from it at the same time
                $otherclass = generate_class_name('artefact', $taken->plugin);
                safe_require('artefact', $taken->plugin);
                if (in_array($type, call_static_method($otherclass, 'get_artefact_types'))) {
                    throw new InstallationException(get_string('artefacttypenametaken', 'error', $type, $taken->plugin));
                }
            }
        }
        if (!class_exists($typeclassname)) {
            throw new InstallationException(get_string('classmissing', 'error', $typeclassname, $type, $plugin));
        }
    }
    $types = call_static_method($classname, 'get_block_types');
    foreach ($types as $type) {
        $pluginclassname = generate_class_name('blocktype', $type);
        if (get_config('installed')) {
            if (table_exists(new XMLDBTable('blocktype_installed')) && ($taken = get_record_select('blocktype_installed', 'name = ? AND artefactplugin != ? ', array($type, $pluginname)))) {
                throw new InstallationException(get_string('blocktypenametaken', 'error', $type, !empty($taken->artefactplugin) ? $taken->artefactplugin : get_string('system')));
            }
        }
        // go look for the lib file to include
        try {
            safe_require('blocktype', $pluginname . '/' . $type);
        } catch (Exception $_e) {
            throw new InstallationException(get_string('blocktypelibmissing', 'error', $type, $pluginname));
        }
        if (!class_exists($pluginclassname)) {
            throw new InstallationException(get_string('classmissing', 'error', $pluginclassname, $type, $pluginname));
        }
    }
}
Esempio n. 29
0
function file_displayobject($object_id, $object_type)
{
    global $page_owner, $CFG;
    $owner_username = user_info('username', $page_owner);
    $return = "";
    if ($object_type == "file::file") {
        if ($file = get_record_select('files', "ident={$object_id}")) {
            if (run("users:access_level_check", $file->access) == true || $file->owner == $_SESSION['userid']) {
                $username = $owner_username;
                $ident = (int) $file->ident;
                $folder->ident = $file->folder;
                $title = get_access_description($file->access);
                $title .= stripslashes($file->title);
                $description = nl2br(stripslashes($file->description));
                $filetitle = urlencode($title);
                $originalname = stripslashes($file->originalname);
                $filemenu = round($file->size / 1048576, 4) . "MB ";
                $icon = $CFG->wwwroot . "_icon/file/" . $file->ident;
                $filepath = $CFG->wwwroot . "{$username}/files/{$folder->ident}/{$ident}/" . urlencode($originalname);
                $mimetype = mimeinfo('type', $file->originalname);
                if ($mimetype == "audio/mpeg" || $mimetype == "audio/mp3") {
                    $filemenu .= " <object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\"\n\t\t\t\t\tcodebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\"\n\t\t\t\t\twidth=\"17\" height=\"17\" >\n\t\t\t\t\t<param name=\"allowScriptAccess\" value=\"sameDomain\" />\n\t\t\t\t\t<param name=\"movie\" value=\"" . $CFG->wwwroot . "mod/file/mp3player/musicplayer.swf?song_url={$filepath}&amp;song_title={$filetitle}\" />\n\t\t\t\t\t<param name=\"quality\" value=\"high\" />\n\t\t\t\t\t<embed src=\"" . $CFG->wwwroot . "mod/file/mp3player/musicplayer.swf?song_url={$filepath}&amp;song_title={$filetitle}\"\n\t\t\t\t\tquality=\"high\" bgcolor=\"#E6E6E6\" name=\"xspf_player\" allowscriptaccess=\"sameDomain\"\n\t\t\t\t\ttype=\"application/x-shockwave-flash\"\n\t\t\t\t\tpluginspage=\"http://www.macromedia.com/go/getflashplayer\"\n\t\t\t\t\talign=\"center\" height=\"17\" width=\"17\" />\n\t\t\t\t\t</object>";
                }
                $keywords = display_output_field(array("", "keywords", "file", "file", $ident, $file->owner));
                if ($keywords) {
                    $keywords = __gettext("Keywords: ") . $keywords;
                }
                $return = <<<END
\t\t\t\t\t<table>
\t\t\t\t\t\t<tr>
\t\t\t\t\t\t\t<td><img src="{$icon}" alt="{$originalname}" /></td>
\t\t\t\t\t\t\t<td>
\t\t\t\t\t\t\t\t<p><b>{$title}</b></p>
\t\t\t\t\t\t\t\t<p>{$description}</p>
\t\t\t\t\t\t\t\t<p>{$originalname}</p>
\t\t\t\t\t\t\t</td>
\t\t\t\t\t\t</tr>
\t\t\t\t\t</table>
END;
            }
        }
    }
    return $return;
}
Esempio n. 30
0
    die_info(get_string('registeredok', 'auth.internal'));
}
// The user has registered with an institution that requires approval,
// tell them to wait.
if (!empty($_SESSION['registeredokawaiting'])) {
    unset($_SESSION['registeredokawaiting']);
    die_info(get_string('registeredokawaitingemail2', 'auth.internal'));
}
if (!empty($_SESSION['registrationcancelled'])) {
    unset($_SESSION['registrationcancelled']);
    die_info(get_string('registrationcancelledok', 'auth.internal'));
}
// Step three of registration - given a key register the user
if (isset($key)) {
    // Begin the registration form buliding
    if (!($registration = get_record_select('usr_registration', '"key" = ? AND pending != 1', array($key)))) {
        die_info(get_string('registrationnosuchkey1', 'auth.internal'));
    }
    if (strtotime($registration->expiry) < time()) {
        die_info(get_string('registrationexpiredkey', 'auth.internal'));
    }
    // In case a new session has started, reset the session language
    // to the one selected during registration
    if (!empty($registration->lang)) {
        $SESSION->set('lang', $registration->lang);
    }
    function create_registered_user($profilefields = array())
    {
        global $registration, $SESSION, $USER;
        require_once get_config('libroot') . 'user.php';
        db_begin();