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;
        }
    }
}
function game_bottomtext_onupdate()
{
    global $CFG;
    $update = $_POST['update'];
    $sesskey = $_POST['sesskey'];
    $top = $_POST['top'];
    $field = $top ? 'toptext' : 'bottomtext';
    $gameid = get_field_select("course_modules", "instance", "id={$update}");
    $game->id = $gameid;
    $game->{$field} = $_POST[$field];
    if (!update_record('game', $game)) {
        error("game_bottomtext_onupdate: Can't update game id={$game->id}");
    }
    redirect("{$CFG->wwwroot}/course/mod.php?update={$update}&sesskey={$sesskey}&sr=1");
}
 function process_form()
 {
     $tag = optional_param('tag', '', PARAM_TEXT);
     $delete = optional_param('delete', 0, PARAM_INT);
     if (!empty($tag)) {
         $record = new object();
         $record->gallery = $this->gallery->id;
         $record->image = $this->image;
         $record->metatype = 'tag';
         $record->description = strtolower($tag);
         insert_record('lightboxgallery_image_meta', $record);
     } else {
         if ($delete) {
             $select = "metatype = 'tag' AND id = {$delete} AND gallery = {$this->gallery->id} AND image = '{$this->image}'";
             if ($id = get_field_select('lightboxgallery_image_meta', 'id', $select)) {
                 delete_records('lightboxgallery_image_meta', 'id', $id);
             }
         }
     }
 }
function game_sudoku_check_last($id, $game, $attempt, $sudoku, $finishattempt)
{
    global $CFG;
    $correct = get_field_select('game_queries', 'COUNT(*) AS c', "attemptid={$attempt->id} AND score > 0.9");
    $all = get_field_select('game_queries', 'COUNT(*) AS c', "attemptid={$attempt->id}");
    if ($all) {
        $grade = $correct / $all;
    } else {
        $grade = 0;
    }
    game_updateattempts($game, $attempt, $grade, $finishattempt);
    redirect("{$CFG->wwwroot}/mod/game/attempt.php?id={$id}", '', 0);
}
/**
 * Display History tab content with page versions
 */
function wiki_info_content(&$WS)
{
    global $CFG, $COURSE, $USER;
    //generate a list with all versions
    $vers = wiki_get_all_page_versions($CFG->prefix, $WS->page, $WS->dfwiki->id, $WS->groupmember->groupid, $WS->member->id);
    if ($vers) {
        $countver = count($vers);
        if ($countver > 1) {
            echo '<script type="text/javascript" src="wiki/hist.js"></script>';
            echo '<form id="historyform" method="post" ' . 'action="view.php?id=' . $WS->linkid . '&amp;page=' . urlencode('diff/' . $WS->page) . "&amp;gid={$WS->groupmember->groupid}&amp;uid={$WS->member->id}" . '">';
            echo '<input type="submit" name="' . get_string('compareversions', 'wiki') . '" value="' . get_string('compareversions', 'wiki') . '"/>';
            echo '<br/><br/>';
        }
        //print table with the page versions
        $prop = null;
        $prop->id = 'historytable';
        $prop->width = "100%";
        $prop->border = "1";
        $prop->padding = "5";
        $prop->spacing = "1";
        $prop->class = "generaltable boxalignleft";
        $prop->header = "true";
        $prop->valignth = "top";
        $prop->classth = 'header c0 nwikileftnow';
        wiki_table_start($prop);
        if ($countver > 1) {
            echo '';
            $prop = null;
            $prop->header = "true";
            $prop->valign = "top";
            $prop->class = "nwikileftnow header c1";
            wiki_change_column($prop);
        }
        echo get_string('version');
        $prop = null;
        $prop->header = "true";
        $prop->valign = "top";
        $prop->class = "nwikileftnow header c1";
        wiki_change_column($prop);
        echo get_string('user');
        $prop = null;
        $prop->header = "true";
        $prop->valign = "top";
        $prop->class = "nwikileftnow header c2";
        wiki_change_column($prop);
        echo get_string('lastmodified');
        if (wiki_grade_got_permission($WS)) {
            $prop = null;
            $prop->header = "true";
            $prop->valign = "top";
            $prop->class = "nwikileftnow header c3";
            wiki_change_column($prop);
            echo get_string('eval_editions_quality', 'wiki');
        }
        $prop = null;
        $prop->header = "true";
        //print content
        $i = 0;
        foreach ($vers as $ver) {
            if ($ver->highlight) {
                $class = "textcenter nwikihighlight";
            } else {
                $class = "textcenter nwikibargroundblanco";
            }
            if (isset($prop->header)) {
                $prop->class = $class;
                wiki_change_row($prop);
            } else {
                $prop = null;
                $prop->class = $class;
                wiki_change_row($prop);
            }
            // input types for history diff
            if ($countver > 1) {
                $style = 'style="visibility:hidden" ';
                $checked = 'checked="checked"';
                if ($i == 0) {
                    echo '<input type="radio" value="' . $ver->version . '" name="oldid" ' . $style . ' />';
                    echo '<input type="radio" value="' . $ver->version . '" name="diff" ' . $checked . ' />';
                } elseif ($i == 1) {
                    echo '<input type="radio" value="' . $ver->version . '" name="oldid" ' . $checked . ' />';
                    echo '<input type="radio" value="' . $ver->version . '" name="diff" ' . $style . ' />';
                } else {
                    echo '<input type="radio" value="' . $ver->version . '" name="oldid" />';
                    echo '<input type="radio" value="' . $ver->version . '" name="diff" ' . $style . ' />';
                }
                $prop = null;
                $prop->class = $class;
                wiki_change_column($prop);
            }
            if ($ver->version == $WS->pagedata->version) {
                echo $ver->version;
            } else {
                $prop = null;
                $prop->href = "javascript:document.forms['formu" . $i . "'].submit()";
                $out = wiki_a($ver->version, $prop, true);
                $prop = null;
                $prop->name = "dfcontent";
                $prop->value = "11";
                $out .= wiki_input_hidden($prop, true);
                $out2 = wiki_div($out, '', true);
                $prop = null;
                $prop->id = "formu{$i}";
                $prop->action = "view.php?id={$WS->linkid}&amp;page=" . urlencode("oldversion/{$ver->pagename}") . "&amp;ver={$ver->version}&amp;gid={$WS->groupmember->groupid}&amp;uid={$WS->member->id}";
                $prop->method = "post";
                wiki_form($out2, $prop);
            }
            $prop = null;
            $prop->class = $class;
            wiki_change_column($prop);
            $author = wiki_get_user_info($ver->author);
            echo $author;
            $prop = null;
            $prop->class = $class;
            wiki_change_column($prop);
            $modified = strftime('%A, %d %B %Y %H:%M', $ver->lastmodified);
            echo $modified;
            if (wiki_grade_got_permission($WS)) {
                $prop = null;
                $prop->class = $class;
                wiki_change_column($prop);
                $scale = array(1 => "+", 2 => "=", 3 => "-");
                $gradevalue = get_field_select('wiki_evaluation_edition', 'valoration', 'wiki_pageid=' . $ver->id);
                if ($gradevalue) {
                    echo wiki_grade_translate($gradevalue, $scale);
                } else {
                    echo get_string('eval_notset', 'wiki');
                }
            }
            $i++;
        }
        wiki_table_end();
        if ($countver > 1) {
            echo '<br/>';
            echo '<input type="submit" name="' . get_string('compareversions', 'wiki') . '" value="' . get_string('compareversions', 'wiki') . '"/>';
        }
        echo '</form>';
    } else {
        print_string('noversion', 'wiki');
    }
}
Beispiel #6
0
 function get_field_select($table, $return, $select)
 {
     global $CFG;
     $CFG->prefix = $this->prefix;
     $records = get_field_select($table, $return, $select);
     $CFG->prefix = $this->newmoodleprefix;
     return $records;
 }
function game_hiddenpicture_check_questions($id, $game, &$attempt, &$hiddenpicture, $finishattempt)
{
    global $QTYPES, $CFG;
    $responses = data_submitted();
    $offsetquestions = game_sudoku_compute_offsetquestions($game->sourcemodule, $attempt, $numbers, $correctquestions);
    $questionlist = game_sudoku_getquestionlist($offsetquestions);
    $questions = game_sudoku_getquestions($questionlist);
    $actions = question_extract_responses($questions, $responses, QUESTION_EVENTSUBMIT);
    $correct = $wrong = 0;
    foreach ($questions as $question) {
        if (!array_key_exists($question->id, $actions)) {
            //no answered
            continue;
        }
        unset($state);
        unset($cmoptions);
        $question->maxgrade = 100;
        $state->responses = $actions[$question->id]->responses;
        $state->event = QUESTION_EVENTGRADE;
        $cmoptions = array();
        $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
        unset($query);
        $select = "attemptid={$attempt->id}";
        $select .= " AND questionid={$question->id}";
        if (($query->id = get_field_select('game_queries', 'id', $select)) == 0) {
            die("problem game_hiddenpicture_check_questions (select={$select})");
            continue;
        }
        $answertext = $state->responses[''];
        if ($answertext != '') {
            $grade = $state->raw_grade;
            if ($grade < 50) {
                //wrong answer
                game_update_queries($game, $attempt, $query, $grade / 100, $answertext);
                $wrong++;
            } else {
                //correct answer
                game_update_queries($game, $attempt, $query, 1, $answertext);
                $correct++;
            }
        }
    }
    $hiddenpicture->correct += $correct;
    $hiddenpicture->wrong += $wrong;
    if (!update_record('game_hiddenpicture', $hiddenpicture)) {
        error('game_hiddenpicture_check_questions: error updating in game_hiddenpicture');
    }
    $attempt->score = game_hidden_picture_computescore($game, $hiddenpicture);
    if (!update_record('game_attempts', $attempt)) {
        error('game_hiddenpicture_check_questions: error updating in game_attempt');
    }
    game_sudoku_check_last($id, $game, $attempt, $hiddenpicture, $finishattempt);
}
Beispiel #8
0
function chat_update_chat_times($chatid = 0)
{
    /// Updates chat records so that the next chat time is correct
    $timenow = time();
    if ($chatid) {
        if (!($chats[] = get_record_select("chat", "id = '{$chatid}' AND chattime <= '{$timenow}' AND schedule > '0'"))) {
            return;
        }
    } else {
        if (!($chats = get_records_select("chat", "chattime <= '{$timenow}' AND schedule > '0'"))) {
            return;
        }
    }
    foreach ($chats as $chat) {
        unset($chat->name);
        unset($chat->intro);
        switch ($chat->schedule) {
            case 1:
                // Single event - turn off schedule and disable
                $chat->chattime = 0;
                $chat->schedule = 0;
                break;
            case 2:
                // Repeat daily
                while ($chat->chattime <= $timenow) {
                    $chat->chattime += 24 * 3600;
                }
                break;
            case 3:
                // Repeat weekly
                while ($chat->chattime <= $timenow) {
                    $chat->chattime += 7 * 24 * 3600;
                }
                break;
        }
        update_record("chat", $chat);
        $event = NULL;
        // Update calendar too
        $cond = "modulename='chat' AND instance = {$chat->id} \n                 AND timestart != {$chat->chattime}";
        if ($event->id = get_field_select('event', 'id', $cond)) {
            $event->timestart = $chat->chattime;
            update_event($event);
        }
    }
}
Beispiel #9
0
 /**
  * In addition to perform parent::insert(), calls force_regrading() method too.
  * @param string $source from where was the object inserted (mod/forum, manual, etc.)
  * @return int PK ID if successful, false otherwise
  */
 function insert($source = null)
 {
     global $CFG;
     if (empty($this->courseid)) {
         error('Can not insert grade item without course id!');
     }
     // load scale if needed
     $this->load_scale();
     // add parent category if needed
     if (empty($this->categoryid) and !$this->is_course_item() and !$this->is_category_item()) {
         $course_category = grade_category::fetch_course_category($this->courseid);
         $this->categoryid = $course_category->id;
     }
     // always place the new items at the end, move them after insert if needed
     $last_sortorder = get_field_select('grade_items', 'MAX(sortorder)', "courseid = {$this->courseid}");
     if (!empty($last_sortorder)) {
         $this->sortorder = $last_sortorder + 1;
     } else {
         $this->sortorder = 1;
     }
     // add proper item numbers to manual items
     if ($this->itemtype == 'manual') {
         if (empty($this->itemnumber)) {
             $this->itemnumber = 0;
         }
     }
     // make sure there is not 0 in outcomeid
     if (empty($this->outcomeid)) {
         $this->outcomeid = null;
     }
     $this->timecreated = $this->timemodified = time();
     if (parent::insert($source)) {
         // force regrading of items if needed
         $this->force_regrading();
         return $this->id;
     } else {
         debugging("Could not insert this grade_item in the database!");
         return false;
     }
 }
Beispiel #10
0
/**
 * Process a chunk of the task
 *
 * @param array $state the task state
 */
function user_activity_task_process(&$state)
{
    global $CFG;
    $sessiontimeout = $state['sessiontimeout'];
    $sessiontail = $state['sessiontail'];
    $starttime = $state['starttime'];
    // find the record ID corresponding to our start time
    $startrec = get_field_select('log', 'MIN(id)', "time >= {$starttime}");
    $startrec = empty($startrec) ? 0 : $startrec;
    // find the last record that's close to our chunk size, without
    // splitting a second between runs
    $endtime = get_field_select('log', 'MIN(time)', 'id >= ' . ($startrec + USERACT_RECORD_CHUNK));
    if (!$endtime) {
        $endtime = time();
    }
    // Get the logs between the last time we ran, and the current time.  Sort
    // by userid (so all records for a given user are together), and then by
    // time (so that we process a user's logs sequentially).
    $recstarttime = max(0, $starttime - $state['sessiontimeout']);
    $rs = get_recordset_select('log', "time >= {$recstarttime} AND time < {$endtime} AND userid != 0", 'userid, time');
    if ($CFG->debug >= DEBUG_ALL) {
        mtrace("* processing records from time:{$starttime} to time:{$endtime}");
    }
    $curuser = -1;
    $session_start = 0;
    $last_course = -1;
    $module_session_start = 0;
    $last_module = -1;
    $last_time = 0;
    if ($rs) {
        while ($rec = rs_fetch_next_record($rs)) {
            if ($rec->userid != $curuser) {
                // end of user's record
                if ($curuser > 0 && $session_start > 0) {
                    // flush current session data
                    if ($last_time > $endtime - $sessiontimeout) {
                        /* Last record is within the session timeout of our end
                         * time for this run.  Just use our last logged time as
                         * the session end time, and the rest will be picked up
                         * by the next run of the sessionizer. */
                        $session_end = $last_time;
                    } else {
                        /* Last record is not within the session timeout of our
                         * end time for this run, so do our normal session
                         * ending. */
                        $session_end = $last_time + $sessiontail;
                    }
                    user_activity_add_session($curuser, $last_course, $session_start, $session_end);
                    if ($last_module > 0) {
                        user_module_activity_add_session($curuser, $last_course, $last_module, $module_session_start, $session_end);
                    }
                }
                $curuser = $rec->userid;
                $session_start = 0;
                $last_course = -1;
                $module_session_start = 0;
                $last_module = -1;
                $last_time = 0;
            }
            if ($rec->time < $starttime) {
                // Find the last log for the user before our start time, that's
                // within the session timeout, and start the session with that
                // record.
                $session_start = $rec->time;
                $last_time = $rec->time;
                $last_course = $rec->course;
                $module_session_start = $rec->time;
                $last_module = $rec->cmid;
            } elseif ($rec->time > $last_time + $sessiontimeout) {
                if ($last_course >= 0) {
                    // session timed out -- add record
                    if (defined('ETLUA_EXTRA_DEBUG') && $CFG->debug >= DEBUG_DEVELOPER) {
                        mtrace('** session timed out');
                    }
                    $session_end = $last_time + $sessiontail;
                    user_activity_add_session($curuser, $last_course, $session_start, $session_end);
                    if ($last_module > 0) {
                        user_module_activity_add_session($curuser, $last_course, $last_module, $module_session_start, $session_end);
                    }
                }
                // start a new session with the current record
                $session_start = $rec->time;
                $last_course = $rec->course;
                $module_session_start = $rec->time;
                $last_module = $rec->cmid;
            } elseif ($rec->action === 'logout') {
                // user logged out -- add record
                if (defined('ETLUA_EXTRA_DEBUG') && $CFG->debug >= DEBUG_DEVELOPER) {
                    mtrace('** user logged out');
                }
                $session_end = $rec->time;
                user_activity_add_session($curuser, $last_course, $session_start, $session_end);
                if ($last_module > 0) {
                    user_module_activity_add_session($curuser, $last_course, $last_module, $module_session_start, $session_end);
                }
                // clear session info
                $session_start = 0;
                $module_session_start = 0;
            } elseif ($rec->course != $last_course) {
                // user switched to a different course -- start new session record
                if ($last_course >= 0) {
                    if (defined('ETLUA_EXTRA_DEBUG') && $CFG->debug >= DEBUG_DEVELOPER) {
                        mtrace('** user switched courses');
                    }
                    $session_end = $rec->time;
                    user_activity_add_session($curuser, $last_course, $session_start, $session_end);
                    if ($last_module > 0) {
                        user_module_activity_add_session($curuser, $last_course, $last_module, $module_session_start, $session_end);
                    }
                }
                $session_start = $rec->time;
                $last_course = $rec->course;
                $module_session_start = $rec->time;
                $last_module = $rec->cmid;
            } elseif ($rec->cmid != $last_module) {
                // user switched to a different module -- start new module session
                if ($last_module > 0) {
                    if (defined('ETLUA_EXTRA_DEBUG') && $CFG->debug >= DEBUG_DEVELOPER) {
                        mtrace('** user switched modules');
                    }
                    $session_end = $rec->time;
                    user_module_activity_add_session($curuser, $last_course, $last_module, $module_session_start, $session_end);
                }
                $module_session_start = $rec->time;
                $last_module = $rec->cmid;
            }
            $last_time = $rec->time;
        }
    }
    if ($curuser > 0 && $session_start > 0) {
        // flush session data
        if ($last_time > $endtime - $sessiontimeout) {
            $session_end = $last_time;
        } else {
            $session_end = $last_time + $sessiontail;
        }
        user_activity_add_session($curuser, $last_course, $session_start, $session_end);
    }
    $state['starttime'] = $endtime;
    $endrec = get_field_select('log', 'MAX(id)', "time < {$endtime}");
    // possibly skip the last time when calculating the total number of
    // records, since we are purposely skipping anything less than $endtime
    $lasttime = get_field_select('log', 'MAX(time)', 'TRUE');
    $totalrec = get_field_select('log', 'MAX(id)', "time < {$lasttime}");
    $totalrec = max($totalrec, $endrec);
    return array($endrec ? $endrec - $state['startrec'] : 0, $totalrec ? $totalrec - $state['startrec'] : 0);
}
Beispiel #11
0
 function test_get_field_select()
 {
     $this->assertEqual(get_field_select($this->table, 'numberfield', 'id = 1'), 101);
 }
/**
* submits an issue in the current tracker
* @uses $CFG
* @param int $trackerid the current tracker
*/
function tracker_submitanissue(&$tracker)
{
    global $CFG;
    $issue->datereported = required_param('datereported', PARAM_INT);
    $issue->summary = required_param('summary', PARAM_TEXT);
    $issue->description = addslashes(required_param('description', PARAM_CLEANHTML));
    $issue->format = addslashes(required_param('format', PARAM_CLEANHTML));
    $issue->assignedto = 0;
    $issue->bywhomid = 0;
    $issue->trackerid = $tracker->id;
    $issue->status = POSTED;
    $issue->reportedby = required_param('reportedby', PARAM_INT);
    // fetch max actual priority
    $maxpriority = get_field_select('tracker_issue', 'MAX(resolutionpriority)', " trackerid = {$tracker->id} GROUP BY trackerid ");
    $issue->resolutionpriority = $maxpriority + 1;
    $issue->id = insert_record('tracker_issue', $issue, true);
    if ($issue->id) {
        tracker_recordelements($issue);
        // if not CCed, the assignee should be
        tracker_register_cc($tracker, $issue, $issue->reportedby);
        return $issue;
    } else {
        error("Could not submit issue");
    }
}
/**
 * Saves a new version of the given named page within a subwiki. Can create
 * a new page or just add a new version to an existing one. In case of
 * failure, ends up calling error() rather than returning something.
 * @param object $course Course object
 * @param object $cm Course-module object
 * @param object $ouwiki OU wiki object
 * @param object $subwiki Subwiki object
 * @param string $pagename Name of page (NO SLASHES)
 * @param string $content XHTML Content (NO SLASHES)
 * @param int $changestart For section changes. Start position of change. (-1 if not section change)
 * @param int $changesize Size of changed section.
 * @param int $changeprevsize Previous size of changed section
 * @param bool $nouser If true, creates as system
 */
function ouwiki_save_new_version($course, $cm, $ouwiki, $subwiki, $pagename, $content, $changestart = -1, $changesize = -1, $changeprevsize = -1, $nouser = false)
{
    $tw = new transaction_wrapper();
    // Find page if it exists
    $pageversion = ouwiki_get_current_page($subwiki, $pagename, OUWIKI_GETPAGE_CREATE);
    // Analyse content for HTML headings that don't already have an ID.
    // These are all assigned unique, fairly short IDs.
    // Get number of version [guarantees in-page uniqueness of generated IDs]
    $versionnumber = count_records('ouwiki_versions', 'pageid', $pageversion->pageid);
    // Remove any spaces from annotation tags that were added for editing or by users
    // and remove any duplicate annotation tags
    $pattern = '~<span\\b.id=\\"annotation(.+?)\\">.*?</span>~';
    $replace = '<span id="annotation$1"></span>';
    $content = preg_replace($pattern, $replace, $content);
    unset($pattern, $replace, $used);
    // Get rid of any heading tags that only contain whitespace
    $emptypatterns = array();
    for ($i = 1; $i <= 6; $i++) {
        $emptypatterns[] = '~<h' . $i . '[^>]*>\\s*(<br[^>]*>\\s*)*</h' . $i . '>~';
    }
    $content = preg_replace($emptypatterns, '', $content);
    // List all headings that already have IDs, to check for duplicates
    $matches = array();
    preg_match_all('|<h[1-9] id="ouw_s(.*?)">(.*?)</h[1-9]>|', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    // Organise list by ID
    $byid = array();
    foreach ($matches as $index => $data) {
        $id = $data[1][0];
        if (!array_key_exists($id, $byid)) {
            $byid[$id] = array();
        }
        $byid[$id][] = $index;
    }
    // Handle any duplicates
    $deletebits = array();
    foreach ($byid as $id => $duplicates) {
        if (count($duplicates) > 1) {
            // We have a duplicate. By default, keep the first one
            $keep = $duplicates[0];
            // See if there is a title entry in the database for it
            $knowntitle = get_field('ouwiki_sections', 'title', 'xhtmlid', addslashes($id), 'pageid', $pageversion->pageid);
            if ($knowntitle) {
                foreach ($duplicates as $duplicate) {
                    $title = ouwiki_get_section_title(null, null, $matches[$duplicate][2][0]);
                    if ($title === $knowntitle) {
                        $keep = $duplicate;
                        break;
                    }
                }
            }
            foreach ($duplicates as $duplicate) {
                if ($duplicate !== $keep) {
                    $deletebits[] = (object) array('startbyte' => $matches[$duplicate][1][1] - 10, 'bytes' => strlen($matches[$duplicate][1][0]) + 11);
                }
            }
        }
    }
    // Were there any?
    if (count($deletebits) > 0) {
        // Sort in reverse order of starting position
        usort($deletebits, 'ouwiki_internal_sort_deletions');
        // Delete each bit
        foreach ($deletebits as $deletebit) {
            $content = substr($content, 0, $deletebit->startbyte) . substr($content, $deletebit->startbyte + $deletebit->bytes);
        }
    }
    // Replace existing empty headings with an ID including version count plus another index
    global $ouwiki_count;
    // Nasty but I can't think of a better way!
    $ouwiki_count = 0;
    global $ouwiki_internal_re;
    $ouwiki_internal_re->version = $versionnumber;
    $ouwiki_internal_re->count = 0;
    $sizebefore = strlen($content);
    $content = preg_replace_callback('/<h([1-9])>/', 'ouwiki_internal_re_headings', $content);
    $sizeafter = strlen($content);
    // Replace wiki links to [[Start page]] with the correct (non
    // language-specific) format [[]]
    $regex = str_replace('.*?', preg_quote(get_string('startpage', 'ouwiki')), OUWIKI_LINKS_SQUAREBRACKETS) . 'ui';
    $content = preg_replace($regex, '[[]]', $content);
    // Create version
    $version = new StdClass();
    $version->pageid = $pageversion->pageid;
    $version->xhtml = addslashes($content);
    $version->timecreated = time();
    if (!$nouser) {
        global $USER;
        $version->userid = $USER->id;
    }
    if ($changestart != -1) {
        $version->changestart = $changestart;
        // In tracking the new size, account for any added headings etc
        $version->changesize = $changesize + ($sizeafter - $sizebefore);
        $version->changeprevsize = $changeprevsize;
    }
    if (!($versionid = insert_record('ouwiki_versions', $version))) {
        $tw->rollback();
        ouwiki_dberror();
    }
    // Update latest version
    if (!set_field('ouwiki_pages', 'currentversionid', $versionid, 'id', $pageversion->pageid)) {
        $tw->rollback();
        ouwiki_dberror();
    }
    // Analyse for links
    $wikilinks = array();
    $externallinks = array();
    // Wiki links: ordinary [[links]]
    $matches = array();
    preg_match_all(OUWIKI_LINKS_SQUAREBRACKETS, $content, $matches, PREG_PATTERN_ORDER);
    foreach ($matches[1] as $match) {
        // Convert to page name (this also removes HTML tags etc)
        $wikilinks[] = ouwiki_get_wiki_link_details($match)->page;
    }
    // Note that we used to support CamelCase links but have removed support because:
    // 1. Confusing: students type JavaScript or MySpace and don't expect it to become a link
    // 2. Not accessible: screenreaders cannot cope with run-together words, and
    //    dyslexic students can have difficulty reading them
    // External links
    preg_match_all('/<a [^>]*href=(?:(?:\'(.*?)\')|(?:"(.*?))")/', $content, $matches, PREG_PATTERN_ORDER);
    foreach ($matches[1] as $match) {
        if ($match) {
            $externallinks[] = html_entity_decode($match);
        }
    }
    foreach ($matches[2] as $match) {
        if ($match) {
            $externallinks[] = html_entity_decode($match);
        }
    }
    // Add link records
    $link = new StdClass();
    $link->fromversionid = $versionid;
    foreach ($wikilinks as $targetpage) {
        if (!empty($targetpage)) {
            $pagerecord = get_record_select('ouwiki_pages', "subwikiid='{$subwiki->id}' AND UPPER(title)=UPPER('" . addslashes($targetpage) . "')");
            if ($pagerecord) {
                $pageid = $pagerecord->id;
            } else {
                $pageid = false;
            }
        } else {
            $pageid = get_field_select('ouwiki_pages', 'id', "subwikiid={$subwiki->id} AND title IS NULL");
        }
        if ($pageid) {
            $link->topageid = $pageid;
            $link->tomissingpage = null;
        } else {
            $link->topageid = null;
            $link->tomissingpage = addslashes(strtoupper($targetpage));
        }
        if (!($link->id = insert_record('ouwiki_links', $link))) {
            $tw->rollback();
            ouwiki_dberror();
        }
    }
    $link->topageid = null;
    $link->tomissingpage = null;
    $tl = textlib_get_instance();
    foreach ($externallinks as $url) {
        // Restrict length of URL
        if ($tl->strlen($url) > 255) {
            $url = $tl->substr($url, 0, 255);
        }
        $link->tourl = addslashes($url);
        if (!($link->id = insert_record('ouwiki_links', $link))) {
            $tw->rollback();
            ouwiki_dberror();
        }
    }
    // Inform search, if installed
    if (ouwiki_search_installed()) {
        $doc = new ousearch_document();
        $doc->init_module_instance('ouwiki', $cm);
        if ($subwiki->groupid) {
            $doc->set_group_id($subwiki->groupid);
        }
        $doc->set_string_ref($pageversion->title === '' ? null : $pageversion->title);
        if ($subwiki->userid) {
            $doc->set_user_id($subwiki->userid);
        }
        $title = is_null($pageversion->title) ? '' : $pageversion->title;
        if (!$doc->update($title, $content)) {
            $tw->rollback();
            ouwiki_dberror();
        }
    }
    // Inform completion system, if available
    if (class_exists('ouflags')) {
        if (completion_is_enabled($course, $cm) && ($ouwiki->completionedits || $ouwiki->completionpages)) {
            completion_update_state($course, $cm, COMPLETION_COMPLETE);
        }
    }
    $tw->commit();
}
 /**
  * Increment the hits of a page.
  *
  * @param   int     $wikiid
  * @param   string  $pagename
  * @param   int     $version
  * @param   int     $groupid
  * @param   int     $ownerid
  */
 function increment_page_hits($wikiid, $pagename, $version, $groupid, $ownerid)
 {
     $select = "dfwiki={$wikiid} AND pagename='" . addslashes($pagename) . "' AND version={$version}";
     if (isset($groupid)) {
         $select .= " AND groupid={$groupid}";
     }
     if (isset($ownerid)) {
         $select .= " AND ownerid={$ownerid}";
     }
     // return set_field_select('wiki_pages', 'hits', 'hits+1', $select);
     $hits = get_field_select('wiki_pages', 'hits', $select);
     return set_field_select('wiki_pages', 'hits', $hits + 1, $select);
 }
function game_snakes_check_questions($id, $game, $attempt, $snakes)
{
    global $QTYPES, $CFG;
    $responses = data_submitted();
    if ($responses->queryid != $snakes->queryid) {
        game_snakes_play($id, $game, $attempt, $snakes);
        return;
    }
    $questionlist = get_field('game_queries', 'questionid', 'id', $responses->queryid);
    $questions = game_sudoku_getquestions($questionlist);
    $actions = question_extract_responses($questions, $responses, QUESTION_EVENTSUBMIT);
    $correct = false;
    $query = '';
    foreach ($questions as $question) {
        if (!array_key_exists($question->id, $actions)) {
            //no answered
            continue;
        }
        unset($state);
        unset($cmoptions);
        $question->maxgrade = 100;
        $state->responses = $actions[$question->id]->responses;
        $state->event = QUESTION_EVENTGRADE;
        $state->responses[''] = game_upper($state->responses['']);
        $cmoptions = array();
        $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
        unset($query);
        $select = "attemptid={$attempt->id} ";
        $select .= " AND questionid={$question->id}";
        if (($query->id = get_field_select('game_queries', 'id', $select)) == 0) {
            die("problem game_sudoku_check_questions (select={$select})");
            continue;
        }
        $grade = $state->raw_grade;
        if ($grade < 50) {
            //wrong answer
            game_update_queries($game, $attempt, $query, 0, '');
            continue;
        }
        //correct answer
        $correct = true;
        game_update_queries($game, $attempt, $query, 1, '');
    }
    //set the grade of the whole game
    game_snakes_position($id, $game, $attempt, $snakes, $correct, $query);
}
/**
* get the last considered location in this scheduler
* @param reference $scheduler
* @uses $USER
* @return the last known location for the current user (teacher)
*/
function scheduler_get_last_location(&$scheduler)
{
    global $USER;
    // we could have made an embedded query in Mysql 5.0
    $lastlocation = '';
    $maxtime = get_field_select('scheduler_slots', 'MAX(timemodified)', "schedulerid = {$scheduler->id} AND teacherid = {$USER->id} GROUP BY timemodified");
    if ($maxtime) {
        $maxid = get_field_select('scheduler_slots', 'MAX(timemodified)', "schedulerid = {$scheduler->id} AND timemodified = {$maxtime} AND teacherid = {$USER->id} GROUP BY timemodified");
        $lastlocation = get_field('scheduler_slots', 'appointmentlocation', 'id', $maxid);
    }
    return $lastlocation;
}
Beispiel #17
0
    $element->optionlistview($cm);
    $caption = get_string('addanoption', 'tracker');
    print_heading($caption . helpbutton('options', get_string('description'), 'tracker', true, false, false, true));
    include "{$CFG->dirroot}/mod/tracker/classes/trackercategorytype/editoptionform.html";
    return -1;
}
/********************************** add an element to be used ***************************/
if ($action == 'addelement') {
    $elementid = required_param('elementid', PARAM_INT);
    if (!tracker_iselementused($tracker->id, $elementid)) {
        /// Add element to element used table;
        $used->elementid = $elementid;
        $used->trackerid = $tracker->id;
        $used->canbemodifiedby = $USER->id;
        /// get last sort order
        $sortorder = 0 + get_field_select('tracker_elementused', 'MAX(sortorder)', "trackerid = {$tracker->id} GROUP BY trackerid");
        $used->sortorder = $sortorder + 1;
        if (!insert_record('tracker_elementused', $used)) {
            error("Cannot add element to list of elements to use for this tracker");
        }
    } else {
        //Feedback message that element is already in uses
        error('Element already in use', "view.php?id={$cm->id}&amp;what=manageelements");
    }
}
/****************************** remove an element from usable list **********************/
if ($action == 'removeelement') {
    $usedid = required_param('usedid', PARAM_INT);
    if (!delete_records('tracker_elementused', 'elementid', $usedid, 'trackerid', $tracker->id)) {
        error("Cannot delete element from list of elements to use for this tracker");
    }
function game_recode_questioncategoryid(&$game, $map_question_categories)
{
    $stamp = $map_question_categories[$game->questioncategoryid];
    $game->questioncategoryid = get_field_select('question_categories', 'id', "stamp='{$stamp}'");
}
        }
        // discard empty field names
        $valuevalue = required_param("item_value{$keyid}", PARAM_CLEANHTML);
        $multiple->{$keyvalue} = $valuevalue;
    }
    if (isset($multiple)) {
        $maprecord->brainstormid = $brainstorm->id;
        $maprecord->userid = $USER->id;
        $maprecord->groupid = $currentgroup;
        $maprecord->operatorid = 'map';
        $maprecord->itemsource = $form->itemsource;
        $maprecord->itemdest = $form->itemdest;
        $maprecord->blobvalue = serialize($multiple);
        $maprecord->timemodified = time();
        $select = "\r\n            brainstormid = {$brainstorm->id} AND\r\n            userid = {$USER->id} AND\r\n            itemsource = {$maprecord->itemsource} AND\r\n            itemdest = {$maprecord->itemdest}\r\n        ";
        if ($oldid = get_field_select('brainstorm_operatordata', 'id', $select)) {
            $maprecord->id = $oldid;
            if (!update_record('brainstorm_operatordata', $maprecord)) {
                error("Could not update map record");
            }
        } else {
            if (!insert_record('brainstorm_operatordata', $maprecord)) {
                error("Could not insert map record");
            }
        }
    }
}
if ($action == 'deletemultiple') {
    $form->itemsource = required_param('source', PARAM_INT);
    $form->itemdest = required_param('dest', PARAM_INT);
    $select = "\r\n        brainstormid = {$brainstorm->id} AND\r\n        userid = {$USER->id} AND\r\n        itemsource = {$form->itemsource} AND\r\n        itemdest = {$form->itemdest}\r\n    ";
function xmldb_block_exabis_eportfolio_upgrade($oldversion = 0, $tmp)
{
    global $CFG, $db;
    $result = true;
    //     if (empty($db)) {
    //         return false;
    //     }
    if ($oldversion < 2008090100 && !empty($db)) {
        // old tables
        $tables = array('block_exabeporpers', 'block_exabeporexte', 'block_exabeporcate', 'block_exabeporbooklink', 'block_exabeporcommlink', 'block_exabeporsharlink', 'block_exabeporbookfile', 'block_exabeporcommfile', 'block_exabeporsharfile', 'block_exabepornote', 'block_exabeporcommnote', 'block_exabeporsharnote');
        $tableNames = array();
        // rename tables to old_*
        foreach ($tables as $table) {
            $tableNames[$table] = 'old_' . $oldversion . '_' . $table;
            $xmltable = new XMLDBTable($table);
            rename_table($xmltable, $tableNames[$table]);
        }
        // add new tables
        install_from_xmldb_file(dirname(__FILE__) . '/install.xml');
        // import data from old tables
        $insert_type = 'REPLACE';
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporuser (id, user_id, persinfo_timemodified, description, user_hash)' . ' SELECT u.id, u.userid, u.timemodified, u.description, e.user_hash FROM ' . $CFG->prefix . $tableNames['block_exabeporpers'] . ' AS u LEFT JOIN ' . $CFG->prefix . $tableNames['block_exabeporexte'] . ' AS e ON u.userid = e.user_id');
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporcate (id, pid, userid, name, timemodified, courseid)' . ' SELECT id, pid, userid, name, timemodified, course FROM ' . $CFG->prefix . $tableNames['block_exabeporcate']);
        $file_id_start = 0;
        $note_id_start = get_field_select($tableNames['block_exabepornote'], 'MAX(id)', null) + 100;
        $link_id_start = get_field_select($tableNames['block_exabeporbooklink'], 'MAX(id)', null) + $note_id_start + 100;
        // combine item table
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitem' . ' (id, userid, type, categoryid, name, url, intro, attachment, timemodified, courseid, shareall, externaccess, externcomment)' . ' SELECT id+' . $file_id_start . ', userid, "file", category, name, url, intro, attachment, timemodified, course, shareall, externaccess, externcomment' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporbookfile']);
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitem' . ' (id, userid, type, categoryid, name, url, intro, attachment, timemodified, courseid, shareall, externaccess, externcomment)' . ' SELECT id+' . $note_id_start . ', userid, "note", category, name, url, intro, attachment, timemodified, course, shareall, externaccess, externcomment' . ' FROM ' . $CFG->prefix . $tableNames['block_exabepornote']);
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitem' . ' (id, userid, type, categoryid, name, url, intro, attachment, timemodified, courseid, shareall, externaccess, externcomment)' . ' SELECT id+' . $link_id_start . ', userid, "link", category, name, url, intro, attachment, timemodified, course, shareall, externaccess, externcomment' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporbooklink']);
        // combine comment table
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitemcomm' . ' (id, itemid, userid, entry, timemodified)' . ' SELECT id, bookmarkid+' . $file_id_start . ', userid, entry, timemodified' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporcommfile']);
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitemcomm' . ' (id, itemid, userid, entry, timemodified)' . ' SELECT id, bookmarkid+' . $note_id_start . ', userid, entry, timemodified' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporcommnote']);
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitemcomm' . ' (id, itemid, userid, entry, timemodified)' . ' SELECT id, bookmarkid+' . $link_id_start . ', userid, entry, timemodified' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporcommlink']);
        // combine share table
        $ret = $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitemshar' . ' (id, itemid, userid, original, courseid)' . ' SELECT id, bookid+' . $file_id_start . ', userid, original, course' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporsharfile']);
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitemshar' . ' (id, itemid, userid, original, courseid)' . ' SELECT id, bookid+' . $note_id_start . ', userid, original, course' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporsharnote']);
        $db->Execute($insert_type . ' INTO ' . $CFG->prefix . 'block_exabeporitemshar' . ' (id, itemid, userid, original, courseid)' . ' SELECT id, bookid+' . $link_id_start . ', userid, original, course' . ' FROM ' . $CFG->prefix . $tableNames['block_exabeporsharlink']);
        $result = true;
    }
    if ($result && $oldversion < 2009010104) {
        // Add THEME support (nadavkav)
        //$result = execute_sql("ALTER TABLE `{$CFG->prefix}_block_exabeporview` ADD `theme` TEXT NULL DEFAULT NULL AFTER `description`");
        $table = new XMLDBTable('block_exabeporview');
        /// Adding fields to table block_exabeporview
        //$table->addFieldInfo('theme', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '25', null, null, null, null, null, null, 'description');
        /// Launch update table for block_exabeporview
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010105) {
        // Add THEME support (nadavkav)
        //$result = execute_sql("ALTER TABLE `{$CFG->prefix}_block_exabeporuser` ADD `emailnotification` TEXT NULL DEFAULT NULL AFTER `description`");
        $table = new XMLDBTable('block_exabeporuser');
        /// Adding fields to table block_exabeporview
        //$table->addFieldInfo('theme', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $field = new XMLDBField('emailnotification');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'user_hash');
        /// Launch update table for block_exabeporview
        $result = $result && add_field($table, $field);
    }
    return $result;
}
    $sql .= " ORDER BY {$sort}";
} else {
    $sql .= " ORDER BY resolutionpriority ASC";
}
/// set list length limits
/*
if ($limit > $numrecords){
    $offset = 0;
} else {
    $offset = $limit * ($page - 1);
}
$sql = $sql . ' LIMIT ' . $limit . ',' . $offset;
*/
//
$issues = get_records_sql($sql, $table->get_page_start(), $table->get_page_size());
$maxpriority = get_field_select('tracker_issue', 'MAX(resolutionpriority)', " trackerid = {$tracker->id} GROUP BY trackerid ");
if (!empty($issues)) {
    /// product data for table
    foreach ($issues as $issue) {
        $issuenumber = "<a href=\"view.php?id={$cm->id}&amp;issueid={$issue->id}\">{$tracker->ticketprefix}{$issue->id}</a>";
        $summary = "<a href=\"view.php?id={$cm->id}&amp;view=view&amp;screen=viewanissue&amp;issueid={$issue->id}\">" . format_string($issue->summary) . '</a>';
        $datereported = date('Y/m/d h:i', $issue->datereported);
        $user = get_record('user', 'id', $issue->reportedby);
        $reportedby = fullname($user);
        $user = get_record('user', 'id', $issue->assignedto);
        if (has_capability('mod/tracker:manage', $context)) {
            // managers can assign bugs
            $status = choose_from_menu($STATUSKEYS, "status{$issue->id}", $issue->status, '', "document.forms['manageform'].schanged{$issue->id}.value = 1;", '', true) . "<input type=\"hidden\" name=\"schanged{$issue->id}\" value=\"0\" />";
            $developers = tracker_getdevelopers($context);
            foreach ($developers as $developer) {
                $developersmenu[$developer->id] = fullname($developer);
/**
 * Get the feedback text that should be show to a student who
 * got this grade on this game.
 *
 * @param float $grade a grade on this game.
 * @param integer $gameid the id of the game object.
 * @return string the comment that corresponds to this grade (empty string if there is not one.
 */
function game_feedback_for_grade($grade, $gameid)
{
    return '';
    $feedback = get_field_select('game_feedback', 'feedbacktext', "gameid = {$gameid} AND mingrade <= {$grade} AND {$grade} < maxgrade");
    if (empty($feedback)) {
        $feedback = '';
    }
    return $feedback;
}
Beispiel #23
0
/**
 * Get volatile flags
 *
 * @param string $type
 * @param string $name
 * @param int    $changedsince
 * @return records array
 *
 */
function get_cache_flag($type, $name, $changedsince = NULL)
{
    $type = addslashes($type);
    $name = addslashes($name);
    $sqlwhere = 'flagtype=\'' . $type . '\' AND name=\'' . $name . '\' AND expiry >= ' . time();
    if ($changedsince !== NULL) {
        $changedsince = (int) $changedsince;
        $sqlwhere .= ' AND timemodified > ' . $changedsince;
    }
    return get_field_select('cache_flags', 'value', $sqlwhere);
}
require_once "../../config.php";
require_once "lib.php";
require_once "locallib.php";
require_once "exportjavame.php";
require_once "exporthtml.php";
if (!isteacherinanycourse($USER->id)) {
    error(get_string('only_teachers', 'game'));
}
if (array_key_exists('action', $_POST)) {
    $update = (int) $_POST['update'];
    $gameid = get_field_select("course_modules", "instance", "id={$update}");
    game_OnExport($gameid);
    die;
}
$update = (int) $_GET['update'];
$gameid = get_field_select("course_modules", "instance", "id={$update}");
$_GET['id'] = $update;
require_once "header.php";
echo '<form name="form" method="post" action="export.php">';
$game = get_record_select('game', "id={$gameid}", 'id,name,gamekind');
switch ($_GET['target']) {
    case 'html':
        game_export_html($game, $update);
        break;
    case 'javame':
        game_export_javame($game, $update);
        break;
}
function game_export_javame($game, $update)
{
    $javame = game_getjavame($game->id);
Beispiel #25
0
/**
 * Get the feedback text that should be show to a student who
 * got this grade on this quiz. The feedback is processed ready for diplay.
 *
 * @param float $grade a grade on this quiz.
 * @param integer $quizid the id of the quiz object.
 * @return string the comment that corresponds to this grade (empty string if there is not one.
 */
function quiz_feedback_for_grade($grade, $quizid)
{
    $feedback = get_field_select('quiz_feedback', 'feedbacktext', "quizid = {$quizid} AND mingrade <= {$grade} AND {$grade} < maxgrade");
    if (empty($feedback)) {
        $feedback = '';
    }
    // Clean the text, ready for display.
    $formatoptions = new stdClass();
    $formatoptions->noclean = true;
    $feedback = format_text($feedback, FORMAT_MOODLE, $formatoptions);
    return $feedback;
}
 /**
  * Finds an existing document. The necessary set_ methods must already
  * have been called. If successful, $this->id will be set. 
  * @return True for success, false for failure
  */
 function find()
 {
     if (!empty($this->id)) {
         // Already got it
         return true;
     }
     // Find existing document
     $where = "plugin='" . addslashes($this->plugin) . "'";
     if (isset($this->courseid)) {
         $where .= " AND courseid='{$this->courseid}'";
     } else {
         $where .= " AND courseid IS NULL";
     }
     if (isset($this->coursemoduleid)) {
         $where .= " AND coursemoduleid='{$this->coursemoduleid}'";
     } else {
         $where .= " AND coursemoduleid IS NULL";
     }
     if (isset($this->groupid)) {
         $where .= " AND groupid='{$this->groupid}'";
     } else {
         $where .= " AND groupid IS NULL";
     }
     if (isset($this->userid)) {
         $where .= " AND userid='{$this->userid}'";
     } else {
         $where .= " AND userid IS NULL";
     }
     if (isset($this->stringref)) {
         $where .= " AND stringref='" . addslashes($this->stringref) . "'";
     } else {
         $where .= " AND stringref IS NULL";
     }
     if (isset($this->intref1)) {
         $where .= " AND intref1='{$this->intref1}'";
     } else {
         $where .= " AND intref1 IS NULL";
     }
     if (isset($this->intref2)) {
         $where .= " AND intref2='{$this->intref2}'";
     } else {
         $where .= " AND intref2 IS NULL";
     }
     $this->id = get_field_select('block_ousearch_documents', 'id', $where);
     return $this->id ? true : false;
 }