function execute($data, $user, $courseid)
 {
     $data->value = addslashes($data->value);
     $ilike = sql_ilike();
     switch ($data->operator) {
         case 'LIKE % %':
             $sql = "{$data->field} {$ilike} '%{$data->value}%'";
             break;
         default:
             $sql = "{$data->field} {$data->operator} '{$data->value}'";
     }
     $courses = get_records_select('course', $sql);
     if ($courses) {
         return array_keys($courses);
     }
     return array();
 }
Example #2
0
 /**
  * Returns the condition to be used with SQL where
  * @param array $data filter settings
  * @return string the filtering condition or null if the filter is disabled
  */
 function get_sql_filter($data)
 {
     $operator = $data['operator'];
     $value = addslashes($data['value']);
     $field = $this->_field;
     if ($operator != 5 and $value === '') {
         return '';
     }
     $ilike = sql_ilike();
     switch ($operator) {
         case 0:
             // contains
             $res = "{$ilike} '%{$value}%'";
             break;
         case 1:
             // does not contain
             $res = "NOT {$ilike} '%{$value}%'";
             break;
         case 2:
             // equal to
             $res = "{$ilike} '{$value}'";
             break;
         case 3:
             // starts with
             $res = "{$ilike} '{$value}%'";
             break;
         case 4:
             // ends with
             $res = "{$ilike} '%{$value}'";
             break;
         case 5:
             // empty
             $res = "=''";
             break;
         default:
             return '';
     }
     return $field . ' ' . $res;
 }
 function execute($data, $user, $courseid)
 {
     $data->value = addslashes($data->value);
     $ilike = sql_ilike();
     if (strpos($data->field, 'profile_') === 0) {
         if ($fieldid = get_field('user_info_field', 'id', 'shortname', str_replace('profile_', '', $data->field))) {
             switch ($data->operator) {
                 case 'LIKE % %':
                     $sql = "fieldid = {$fieldid} AND data {$ilike} '%{$data->value}%'";
                     break;
                 default:
                     $sql = "fieldid = {$fieldid} AND data {$data->operator} '{$data->value}'";
             }
             if ($infodata = get_records_select('user_info_data', $sql)) {
                 $finalusersid = array();
                 foreach ($infodata as $d) {
                     $finalusersid[] = $d->userid;
                 }
                 return $finalusersid;
             }
         }
     } else {
         switch ($data->operator) {
             case 'LIKE % %':
                 $sql = "{$data->field} {$ilike} '%{$data->value}%'";
                 break;
             default:
                 $sql = "{$data->field} {$data->operator} '{$data->value}'";
         }
         $users = get_records_select('user', $sql);
         if ($users) {
             return array_keys($users);
         }
     }
     return array();
 }
Example #4
0
/**
 * ELIS(TM): Enterprise Learning Intelligence Suite
 * Copyright (C) 2008-2012 Remote Learner.net Inc http://www.remote-learner.net
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    elis
 * @subpackage php_reports
 * @author     Remote-Learner.net Inc
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2008-2012 Remote Learner.net Inc http://www.remote-learner.net
 *
 */
function xmldb_block_php_report_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2011040600) {
        /// Define table php_report_schedule to be created
        $table = new XMLDBTable('php_report_schedule');
        /// Adding fields to table php_report_schedule
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('report', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('config', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table php_report_schedule
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table php_report_schedule
        $table->addIndexInfo('report_idx', XMLDB_INDEX_NOTUNIQUE, array('report'));
        /// Launch create table for php_report_schedule
        $result = $result && create_table($table);
        /// Define field userid to be added to php_report_schedule
        $table = new XMLDBTable('php_report_schedule');
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch add field userid
        $result = $result && add_field($table, $field);
        /// Define index userid_idx (not unique) to be added to php_report_schedule
        $table = new XMLDBTable('php_report_schedule');
        $index = new XMLDBIndex('userid_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        /// Launch add index userid_idx
        $result = $result && add_index($table, $index);
    }
    if ($result && $oldversion < 2011042900) {
        $query = "name " . sql_ilike() . " 'php_report%'";
        $result = $result && delete_records_select('user_preferences', $query);
    }
    return $result;
}
Example #5
0
File: lib.php Project: r007/PMoodle
function message_search($searchterms, $fromme = true, $tome = true, $courseid = 'none', $userid = 0)
{
    /// Returns a list of posts found using an array of search terms
    /// eg   word  +word -word
    ///
    global $CFG, $USER;
    /// If no userid sent then assume current user
    if ($userid == 0) {
        $userid = $USER->id;
    }
    /// Some differences in SQL syntax
    $LIKE = sql_ilike();
    $NOTLIKE = 'NOT ' . $LIKE;
    if ($CFG->dbfamily == "postgres") {
        $REGEXP = "~*";
        $NOTREGEXP = "!~*";
    } else {
        $REGEXP = "REGEXP";
        $NOTREGEXP = "NOT REGEXP";
    }
    $messagesearch = "";
    foreach ($searchterms as $searchterm) {
        if (strlen($searchterm) < 2) {
            continue;
        }
        /// Under Oracle and MSSQL, trim the + and - operators and perform
        /// simpler LIKE search
        if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
            $searchterm = trim($searchterm, '+-');
        }
        if ($messagesearch) {
            $messagesearch .= " AND ";
        }
        if (substr($searchterm, 0, 1) == "+") {
            $searchterm = substr($searchterm, 1);
            $messagesearch .= " m.message {$REGEXP} '(^|[^a-zA-Z0-9]){$searchterm}([^a-zA-Z0-9]|\$)' ";
        } else {
            if (substr($searchterm, 0, 1) == "-") {
                $searchterm = substr($searchterm, 1);
                $messagesearch .= " m.message {$NOTREGEXP} '(^|[^a-zA-Z0-9]){$searchterm}([^a-zA-Z0-9]|\$)' ";
            } else {
                $messagesearch .= " m.message {$LIKE} '%{$searchterm}%' ";
            }
        }
    }
    if ($messagesearch == '') {
        // if only 1 letter words searched
        return false;
    }
    $messagesearch = "({$messagesearch}) ";
    /// There are several possibilities
    /// 1. courseid = SITEID : The admin is searching messages by all users
    /// 2. courseid = ??     : A teacher is searching messages by users in
    ///                        one of their courses - currently disabled
    /// 3. courseid = none   : User is searching their own messages;
    ///    a.  Messages from user
    ///    b.  Messages to user
    ///    c.  Messages to and from user
    if ($courseid == SITEID) {
        /// admin is searching all messages
        $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated\n                                     FROM {$CFG->prefix}message_read m\n                                     WHERE {$messagesearch}");
        $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated\n                                     FROM {$CFG->prefix}message m\n                                     WHERE {$messagesearch}");
        if ($m_read === false) {
            $m_read = array();
        }
        if ($m_unread === false) {
            $m_unread = array();
        }
    } elseif ($courseid !== 'none') {
        /// This has not been implemented due to security concerns
    } else {
        if ($fromme and $tome) {
            $messagesearch .= "AND (m.useridfrom='{$userid}' OR m.useridto='{$userid}') ";
        } elseif ($fromme) {
            $messagesearch .= "AND m.useridfrom='{$userid}' ";
        } elseif ($tome) {
            $messagesearch .= "AND m.useridto='{$userid}' ";
        }
        $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated\n                                     FROM {$CFG->prefix}message_read m\n                                     WHERE {$messagesearch}");
        $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated\n                                     FROM {$CFG->prefix}message m\n                                     WHERE {$messagesearch}");
        if ($m_read === false) {
            $m_read = array();
        }
        if ($m_unread === false) {
            $m_unread = array();
        }
    }
    /// The keys may be duplicated in $m_read and $m_unread so we can't
    /// do a simple concatenation
    $message = array();
    foreach ($m_read as $m) {
        $messages[] = $m;
    }
    foreach ($m_unread as $m) {
        $messages[] = $m;
    }
    return empty($messages) ? false : $messages;
}
Example #6
0
/**
 * Returns array of userinfo of all students in this course
 * or on this site if courseid is id of site
 *
 * @uses $CFG
 * @uses SITEID
 * @param int $courseid The course in question.
 * @param string $sort ?
 * @param string $dir ?
 * @param int $page ?
 * @param int $recordsperpage ?
 * @param string $firstinitial ?
 * @param string $lastinitial ?
 * @param ? $group ?
 * @param string $search ?
 * @param string $fields A comma separated list of fields to be returned from the chosen table.
 * @param string $exceptions ?
 * @return object
 * @todo Finish documenting this function
 */
function get_course_students($courseid, $sort = 'ul.timeaccess', $dir = '', $page = '', $recordsperpage = '', $firstinitial = '', $lastinitial = '', $group = NULL, $search = '', $fields = '', $exceptions = '')
{
    global $CFG;
    if ($courseid == SITEID and $CFG->allusersaresitestudents) {
        // return users with confirmed, undeleted accounts who are not site teachers
        // the following is a mess because of different conventions in the different user functions
        $sort = str_replace('s.timeaccess', 'lastaccess', $sort);
        // site users can't be sorted by timeaccess
        $sort = str_replace('timeaccess', 'lastaccess', $sort);
        // site users can't be sorted by timeaccess
        $sort = str_replace('u.', '', $sort);
        // the get_user function doesn't use the u. prefix to fields
        $fields = str_replace('u.', '', $fields);
        if ($sort) {
            $sort = $sort . ' ' . $dir;
        }
        // Now we have to make sure site teachers are excluded
        if ($teachers = get_course_teachers(SITEID)) {
            foreach ($teachers as $teacher) {
                $exceptions .= ',' . $teacher->userid;
            }
            $exceptions = ltrim($exceptions, ',');
        }
        return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial, $page, $recordsperpage, $fields ? $fields : '*');
    }
    $LIKE = sql_ilike();
    $fullname = sql_fullname('u.firstname', 'u.lastname');
    $groupmembers = '';
    // make sure it works on the site course
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    $select = "c.contextlevel=" . CONTEXT_COURSE . " AND ";
    // Must be on a course
    if ($courseid != SITEID) {
        // If not site, require specific course
        $select .= "c.instanceid={$courseid} AND ";
    }
    $select .= "rc.capability='moodle/legacy:student' AND rc.permission=" . CAP_ALLOW . " AND ";
    $select .= ' u.deleted = \'0\' ';
    if (!$fields) {
        $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, ' . 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, ' . 'u.country, u.picture, u.idnumber, u.department, u.institution, ' . 'u.emailstop, u.lang, u.timezone, ul.timeaccess as lastaccess';
    }
    if ($search) {
        $search = ' AND (' . $fullname . ' ' . $LIKE . '\'%' . $search . '%\' OR email ' . $LIKE . '\'%' . $search . '%\') ';
    }
    if ($firstinitial) {
        $select .= ' AND u.firstname ' . $LIKE . '\'' . $firstinitial . '%\' ';
    }
    if ($lastinitial) {
        $select .= ' AND u.lastname ' . $LIKE . '\'' . $lastinitial . '%\' ';
    }
    if ($group === 0) {
        /// Need something here to get all students not in a group
        return array();
    } else {
        if ($group !== NULL) {
            $groupmembers = "INNER JOIN {$CFG->prefix}groups_members gm on u.id=gm.userid";
            $select .= ' AND gm.groupid = \'' . $group . '\'';
        }
    }
    if (!empty($exceptions)) {
        $select .= ' AND u.id NOT IN (' . $exceptions . ')';
    }
    if ($sort) {
        $sort = ' ORDER BY ' . $sort . ' ';
    }
    $students = get_records_sql("SELECT {$fields}\n                                FROM {$CFG->prefix}user u INNER JOIN\n                                     {$CFG->prefix}role_assignments ra on u.id=ra.userid INNER JOIN\n                                     {$CFG->prefix}role_capabilities rc ON ra.roleid=rc.roleid INNER JOIN\n                                     {$CFG->prefix}context c ON c.id=ra.contextid LEFT OUTER JOIN\n                                     {$CFG->prefix}user_lastaccess ul on ul.userid=ra.userid\n                                     {$groupmembers}\n                                WHERE {$select} {$search} {$sort} {$dir}", $page, $recordsperpage);
    return $students;
}
Example #7
0
 /**
  * Render the view of the module or feature.
  * This MUST be overridden to provide functionality.
  */
 function render()
 {
     global $CFG, $USER;
     // Were any of the delete parameters specified in HTTP (e.g. from a form)?
     if (!empty($this->deleteuserobjects) || !empty($this->deletesloodleentry) || !empty($this->userconfirmed)) {
         // Convert them to session parameters
         if (!empty($this->deleteuserobjects)) {
             $_SESSION['deleteuserobjects'] = $this->deleteuserobjects;
         }
         if (!empty($this->deletesloodleentry)) {
             $_SESSION['deletesloodleentry'] = $this->deletesloodleentry;
         }
         if (!empty($this->userconfirmed)) {
             $_SESSION['userconfirmed'] = $this->userconfirmed;
         }
         // Construct our full URL, with GET parameters
         $url = sloodle_get_web_path();
         $url .= "?_type=user&id={$this->moodleuserid}";
         if (!empty($this->courseid)) {
             $url .= "&course={$this->courseid}";
         }
         if (!empty($this->searchstr)) {
             $url .= "&search={$this->searchstr}";
         }
         if (!empty($this->start)) {
             $url .= "&start={$this->start}";
         }
         // Reload this page without those parameters
         redirect($url);
         exit;
     }
     // Extract data from our session parameters
     if (isset($_SESSION['deleteuserobjects'])) {
         $this->deleteuserobjects = $_SESSION['deleteuserobjects'];
         unset($_SESSION['deleteuserobjects']);
     }
     if (isset($_SESSION['deletesloodleentry'])) {
         $this->deletesloodleentry = $_SESSION['deletesloodleentry'];
         unset($_SESSION['deletesloodleentry']);
     }
     if (isset($_SESSION['userconfirmed'])) {
         $this->userconfirmed = $_SESSION['userconfirmed'];
         unset($_SESSION['userconfirmed']);
     }
     // Check the mode: all, search, pending, or single
     $allentries = false;
     $searchentries = false;
     if (strcasecmp($this->moodleuserid, 'all') == 0) {
         $allentries = true;
         $this->moodleuserid = -1;
     } else {
         if (strcasecmp($this->moodleuserid, 'search') == 0) {
             $searchentries = true;
             $this->moodleuserid = -1;
         } else {
             // Make sure the Moodle user ID is an integer
             $this->moodleuserid = (int) $this->moodleuserid;
             if ($this->moodleuserid <= 0) {
                 error(ucwords(get_string('unknownuser', 'sloodle')));
             }
         }
     }
     // Get the URL and names of the course
     $courseurl = $CFG->wwwroot . '/course/view.php?_type=user&amp;id=' . $this->courseid;
     $courseshortname = $this->course->shortname;
     $coursefullname = $this->course->fullname;
     // This value will indicate if we are currently confirming a deletion
     $confirmingdeletion = false;
     // These are localization strings used by the deletion confirmation form
     $form_yes = get_string('Yes', 'sloodle');
     $form_no = get_string('No', 'sloodle');
     // Are we deleting a Sloodle entry?
     $deletemsg = '';
     if ($this->deletesloodleentry != NULL) {
         // Determine if the user is allowed to delete this entry
         $allowdelete = $this->canedit;
         // Just go with the editing ability for now... will maybe change this later. -PRB
         // Has the deletion been confirmed?
         if ($this->userconfirmed == $form_yes) {
             if (record_exists('sloodle_users', 'id', $this->deletesloodleentry)) {
                 // Is the user allowed to delete this?
                 if ($allowdelete) {
                     // Make sure it's a valid ID
                     if (is_int($this->deletesloodleentry) && $this->deletesloodleentry > 0) {
                         // Attempt to delete the entry
                         $deleteresult = delete_records('sloodle_users', 'id', $this->deletesloodleentry);
                         if ($deleteresult === FALSE) {
                             $deletemsg = get_string('deletionfailed', 'sloodle') . ': ' . get_string('databasequeryfailed', 'sloodle');
                         } else {
                             $deletemsg = get_string('deletionsuccessful', 'sloodle');
                         }
                     } else {
                         $deletemsg = get_string('deletionfailed', 'sloodle') . ': ' . get_string('invalidid', 'sloodle');
                     }
                 } else {
                     $deletemsg = get_string('deletionfailed', 'sloodle') . ': ' . get_string('insufficientpermission', 'sloodle');
                 }
             }
         } else {
             if (is_null($this->userconfirmed)) {
                 // User needs to confirm deletion
                 $confirmingdeletion = true;
                 $form_url = SLOODLE_WWWROOT . "/view.php";
                 $deletemsg .= '<h3>' . get_string('delete', 'sloodle') . ' ' . get_string('ID', 'sloodle') . ': ' . $this->deletesloodleentry . '<br/>' . get_string('confirmdelete', 'sloodle') . '</h3>';
                 $deletemsg .= '<form action="' . $form_url . '" method="get">';
                 $deletemsg .= '<input type="hidden" name="_type" value="user" />';
                 if ($allentries) {
                     $deletemsg .= '<input type="hidden" name="id" value="all" />';
                 } else {
                     if ($searchentries) {
                         $deletemsg .= '<input type="hidden" name="id" value="search" /><input type="hidden" name="search" value="' . $this->searchstr . '" />';
                     } else {
                         $deletemsg .= '<input type="hidden" name="id" value="' . $this->moodleuserid . '" />';
                     }
                 }
                 if (!is_null($this->courseid)) {
                     $deletemsg .= '<input type="hidden" name="course" value="' . $this->courseid . '" />';
                 }
                 $deletemsg .= '<input type="hidden" name="delete" value="' . $this->deletesloodleentry . '" />';
                 $deletemsg .= '<input type="hidden" name="start" value="' . $this->start . '" />';
                 $deletemsg .= '<input style="color:green;" type="submit" value="' . $form_yes . '" name="confirm" />&nbsp;&nbsp;';
                 $deletemsg .= '<input style="color:red;" type="submit" value="' . $form_no . '" name="confirm" />';
                 $deletemsg .= '</form><br/>';
             } else {
                 $deletemsg = get_string('deletecancelled', 'sloodle');
             }
         }
     }
     // Are we getting all entries, searching, or just viewing one?
     if ($allentries) {
         // All entries
         $moodleuserdata = null;
         // Fetch a list of all Sloodle user entries
         $sloodleentries = get_records('sloodle_users');
     } else {
         if ($searchentries && !empty($this->searchstr)) {
             // Search entries
             $moodleuserdata = null;
             $LIKE = sql_ilike();
             $fullsloodleentries = get_records_select('sloodle_users', "avname {$LIKE} '%{$this->searchstr}%' OR uuid {$LIKE} '%{$this->searchstr}%'", 'avname');
             if (!$fullsloodleentries) {
                 $fullsloodleentries = array();
             }
             $sloodleentries = array();
             // Eliminate entries belonging to avatars who are not in the current course
             foreach ($fullsloodleentries as $fse) {
                 // Does the Moodle user have permission?
                 if (has_capability('moodle/course:view', $this->course_context, $fse->userid)) {
                     // Copy it to our filtered list
                     $sloodleentries[] = $fse;
                 }
             }
         } else {
             // Attempt to fetch the Moodle user data
             $moodleuserdata = get_record('user', 'id', $this->moodleuserid);
             // Fetch a list of all Sloodle user entries associated with this Moodle account
             $sloodleentries = get_records('sloodle_users', 'userid', $this->moodleuserid);
         }
     }
     // Post-process the query results
     if ($sloodleentries === FALSE) {
         $sloodleentries = array();
     }
     $numsloodleentries = count($sloodleentries);
     // Get the localization strings
     $strsloodle = get_string('modulename', 'sloodle');
     $strsloodles = get_string('modulenameplural', 'sloodle');
     $strunknown = get_string('unknown', 'sloodle');
     // Construct the breadcrumb links
     $navigation = "";
     if ($this->courseid != 1) {
         $navigation .= "<a href=\"{$courseurl}\">{$courseshortname}</a> -> ";
     }
     $navigation .= "<a href=\"" . SLOODLE_WWWROOT . "/view.php?_type=users&amp;course={$this->courseid}\">" . get_string('sloodleuserprofiles', 'sloodle') . '</a> -> ';
     if ($this->moodleuserid > 0) {
         if ($moodleuserdata) {
             $navigation .= $moodleuserdata->firstname . ' ' . $moodleuserdata->lastname;
         } else {
             $navigation .= get_string('unknownuser', 'sloodle');
         }
     } else {
         if ($searchentries) {
             $navigation .= get_string('avatarsearch', 'sloodle');
         } else {
             $navigation .= get_string('allentries', 'sloodle');
         }
     }
     // Display the header
     print_header(get_string('sloodleuserprofile', 'sloodle'), get_string('sloodleuserprofile', 'sloodle'), $navigation, "", "", true);
     echo '<div style="text-align:center;padding-left:8px;padding-right:8px;">';
     // Display the deletion message if we have one
     if (!empty($deletemsg)) {
         echo '<div style="text-align:center; padding:3px; border:solid 1px #aaaaaa; background-color:#dfdfdf; font-weight:bold; color:#dd0000;">';
         echo $deletemsg;
         echo '</div>';
     }
     echo '<br/>';
     // Are we dealing with an actual Moodle account?
     if ($this->moodleuserid > 0) {
         echo '<p>';
         // Yes - do we have an account?
         if ($moodleuserdata) {
             // Yes - display the name and other general info
             echo '<span style="font-size:18pt; font-weight:bold;">' . $moodleuserdata->firstname . ' ' . $moodleuserdata->lastname . '</span>';
             echo " <span style=\"font-size:10pt; color:#444444; font-style:italic;\">(<a href=\"{$CFG->wwwroot}/user/view.php?id={$this->moodleuserid}&amp;course={$this->courseid}\">" . get_string('moodleuserprofile', 'sloodle') . "</a>)</span><br/>";
         } else {
             echo get_string('moodleusernotfound', 'sloodle') . '<br/>';
         }
         echo "<br/><br/>\n";
         // Check for issues such as no entries, or multiple entries
         if ($numsloodleentries == 0) {
             echo '<span style="color:red; font-weight:bold;">';
             print_string('noentries', 'sloodle');
             echo '</span>';
             // If it is the profile owner who is viewing this, then offer a link to the loginzone entry page
             if ($this->moodleuserid == $USER->id) {
                 echo "<br/><br/><p style=\"padding:8px; border:solid 1px #555555;\"><a href=\"{$CFG->wwwroot}/mod/sloodle/classroom/loginzone.php?id={$this->courseid}\">";
                 print_string('getnewloginzoneallocation', 'sloodle');
                 echo '</a></p>';
             }
         } else {
             if ($numsloodleentries > 1) {
                 echo '<span style="color:red; font-weight:bold; border:solid 2px #990000; padding:4px; background-color:white;">';
                 print_string('multipleentries', 'sloodle');
                 helpbutton('multiple_entries', get_string('help:multipleentries', 'sloodle'), 'sloodle', true, false);
                 echo '</span>';
             }
         }
         echo '</p>';
     } else {
         if ($searchentries) {
             // Searching for users
             echo '<span style="font-size:18pt; font-weight:bold; ">' . get_string('avatarsearch', 'sloodle') . ": \"{$this->searchstr}\"</span><br/><br/>";
             // Check to see if there are no entries
             if ($numsloodleentries == 0) {
                 echo '<span style="color:red; font-weight:bold;">';
                 print_string('noentries', 'sloodle');
                 echo '</span>';
             }
         } else {
             // Assume we're listing all entries - explain what this means
             echo '<span style="font-size:18pt; font-weight:bold; ">' . get_string('allentries', 'sloodle') . '</span><br/>';
             echo '<center><p style="width:550px; text-align:left;">' . get_string('allentries:info', 'sloodle') . '</p></center>';
             // Check to see if there are no entries
             if ($numsloodleentries == 0) {
                 echo '<span style="color:red; font-weight:bold;">';
                 print_string('noentries', 'sloodle');
                 echo '</span>';
             }
         }
     }
     // Construct and display a table of Sloodle entries
     if ($numsloodleentries > 0) {
         $sloodletable = new stdClass();
         $sloodletable->head = array(get_string('avatarname', 'sloodle'), get_string('avataruuid', 'sloodle'), get_string('lastactive', 'sloodle'), '');
         $sloodletable->align = array('left', 'left', 'left', 'left');
         $sloodletable->size = array('28%', '42%', '20%', '10%');
         $deletestr = get_string('delete', 'sloodle');
         // We want to build a list of Sloodle user objects too
         $userobjects = array();
         // Create a dummy Sloodle Session
         $sloodle = new SloodleSession(false);
         // Check if our start is past the end of our results
         if ($this->start >= count($sloodleentries)) {
             $this->start = 0;
         }
         // Go through each Sloodle entry for this user
         $resultnum = 0;
         $resultsdisplayed = 0;
         $maxperpage = 20;
         foreach ($sloodleentries as $su) {
             // Only display this result if it is after our starting result number
             if ($resultnum >= $this->start) {
                 // Add this user's Sloodle objects (if we're not in 'all' or search modes)
                 if (!$allentries && !$searchentries) {
                     if ($sloodle->user->load_avatar($su->uuid, '')) {
                         $userobjects += $sloodle->user->get_user_objects();
                     }
                 }
                 // Is this entry being deleted (i.e. is the user being asked to confirm its deletion)?
                 $deletingcurrent = $confirmingdeletion == true && $su->id == $this->deletesloodleentry;
                 // Reset the line's content
                 $line = array();
                 // Fetch the avatar name and UUID
                 $curavname = '-';
                 $curuuid = '-';
                 if (!empty($su->avname)) {
                     $curavname = $su->avname;
                 }
                 if (!empty($su->uuid)) {
                     $curuuid = $su->uuid;
                 }
                 // If we are in all or searching mode, add a link to the Sloodle user profile
                 if ($allentries || $searchentries) {
                     //$curavname .= " <span style=\"font-size:10pt; color:#444444; font-style:italic;\">(<a href=\"{$CFG->wwwroot}/mod/sloodle/view.php?_type=user&amp;id={$su->userid}&amp;course={$this->courseid}\">".get_string('sloodleuserprofile','sloodle')."</a>)</span>";
                     $curavname = "<a href=\"{$CFG->wwwroot}/mod/sloodle/view.php?_type=user&amp;id={$su->userid}&amp;course={$this->courseid}\">{$curavname}</a>";
                 }
                 // Add a red cross beside the avatar name if it is being deleted
                 if ($deletingcurrent) {
                     $curavname = '<span style="color:red; font-weight:bold;">X</span> ' . $curavname;
                 }
                 // Add them to the table
                 $line[] = $curavname;
                 $line[] = $curuuid;
                 // Do we know when the avatar was last active
                 if (!empty($su->lastactive)) {
                     // Calculate the time difference
                     $difference = time() - (int) $su->lastactive;
                     if ($difference < 0) {
                         $difference = 0;
                     }
                     // Add it to the table
                     $line[] = sloodle_describe_approx_time($difference, true);
                 } else {
                     $line[] = '(' . $strunknown . ')';
                 }
                 // Display the "delete" action
                 if ($this->canedit || $su->userid == $USER->id) {
                     if ($allentries) {
                         $deleteurl = $CFG->wwwroot . "/mod/sloodle/view.php?_type=user&amp;id=all&amp;course={$this->courseid}&amp;delete={$su->id}&amp;start={$this->start}";
                     } else {
                         if ($searchentries) {
                             $deleteurl = $CFG->wwwroot . "/mod/sloodle/view.php?_type=user&amp;id=search&amp;course={$this->courseid}&amp;search={$this->searchstr}&amp;delete={$su->id}&amp;start={$this->start}";
                         } else {
                             $deleteurl = $CFG->wwwroot . "/mod/sloodle/view.php?_type=user&amp;id={$this->moodleuserid}&amp;course={$this->courseid}&amp;delete={$su->id}&amp;start={$this->start}";
                         }
                     }
                     $deletecaption = get_string('clicktodeleteentry', 'sloodle');
                     $line[] = "<a href=\"{$deleteurl}\" title=\"{$deletecaption}\">{$deletestr}</a>";
                 } else {
                     $line[] = '<span style="color:#777777;" title="' . get_string('nodeletepermission', 'sloodle') . '">' . get_string('delete', 'sloodle') . '</span>';
                 }
                 // Add the line to the table
                 $sloodletable->data[] = $line;
                 $resultsdisplayed++;
             }
             // Have we displayed the maximum number of results for this page?
             $resultnum++;
             if ($resultsdisplayed >= $maxperpage) {
                 break;
             }
         }
         // Construct our basic URL to this page
         $basicurl = SLOODLE_WWWROOT . "/view.php?_type=user&amp;course={$this->courseid}";
         if ($searchentries) {
             $basicurl .= "&amp;id=search&amp;search={$this->searchstr}";
         } else {
             if ($allentries) {
                 $basicurl .= "&amp;id=all";
             } else {
                 $basicurl .= "&amp;id={$this->moodleuserid}";
             }
         }
         // Construct the next/previous links
         $previousstart = max(0, $this->start - $maxperpage);
         $nextstart = $this->start + $maxperpage;
         $prevlink = null;
         $nextlink = null;
         if ($previousstart != $this->start) {
             $prevlink = "<a href=\"{$basicurl}&amp;start={$previousstart}\" style=\"color:#0000ff;\">&lt;&lt;</a>&nbsp;&nbsp;";
         }
         if ($nextstart < count($sloodleentries)) {
             $nextlink = "<a href=\"{$basicurl}&amp;start={$nextstart}\" style=\"color:#0000ff;\">&gt;&gt;</a>";
         }
         // Display the next/previous links, if we have at least one
         if (!empty($prevlink) || !empty($nextlink)) {
             echo '<p style="text-align:center; font-size:14pt;">';
             if (!empty($prevlink)) {
                 echo $prevlink;
             } else {
                 echo '<span style="color:#777777;">&lt;&lt;</span>&nbsp;&nbsp;';
             }
             if (!empty($nextlink)) {
                 echo $nextlink;
             } else {
                 echo '<span style="color:#777777;">&gt;&gt;</span>&nbsp;&nbsp;';
             }
             echo '</p>';
         }
         // Display the table
         print_table($sloodletable);
         // Now display the section of user-authorized objects
         if (!$allentries && !$searchentries) {
             echo '<br><h3>' . get_string('userobjects', 'sloodle');
             helpbutton('user_objects', get_string('userobjects', 'sloodle'), 'sloodle', true, false, '', false);
             echo "</h3>\n";
             // Have we been asked to delete the user objects?
             if ($this->deleteuserobjects == 'true') {
                 // Yes - display a confirmation form
                 echo '<h4 style="color:red; font-weight:bold;">' . get_string('confirmdeleteuserobjects', 'sloodle') . '</h4>';
                 echo '<table style="border-style:none; margin-left:auto; margin-right:auto;"><tr><td>';
                 echo '<form action="view_user.php" method="GET">';
                 echo '<input type="hidden" name="_type" value="user" />';
                 echo '<input type="hidden" name="id" value="' . $this->moodleuserid . '" >';
                 if (!empty($courseid)) {
                     echo '<input type="hidden" name="course" value="' . $this->courseid . '" >';
                 }
                 echo '<input type="hidden" name="deleteuserobjects" value="confirm" >';
                 echo '<input type="hidden" name="start" value="' . $this->start . '" />';
                 echo '<input type="submit" value="' . get_string('yes') . '" title="' . get_string('deleteuserobjects:help', 'sloodle') . '" >';
                 echo '</form>';
                 echo '</td><td>';
                 echo '<form action="view_user.php" method="GET">';
                 echo '<input type="hidden" name="id" value="' . $this->moodleuserid . '" >';
                 if (!empty($this->courseid)) {
                     echo '<input type="hidden" name="course" value="' . $this->courseid . '" >';
                 }
                 echo '<input type="hidden" name="start" value="' . $this->start . '" />';
                 echo '<input type="submit" value="' . get_string('no') . '" >';
                 echo '</form>';
                 echo '</td></tr></table><br>';
             } else {
                 if ($this->deleteuserobjects == 'confirm') {
                     // Delete each one
                     $numdeleted = 0;
                     foreach ($userobjects as $obj) {
                         delete_records('sloodle_user_object', 'id', $obj->id);
                         $numdeleted++;
                     }
                     $userobjects = array();
                     echo get_string('numdeleted', 'sloodle') . ': ' . $numdeleted . '<br><br>';
                 }
             }
             // Do we have any objects to display?
             if (count($userobjects) > 0) {
                 // Yes - prepare the table
                 $sloodletable = new stdClass();
                 $sloodletable->head = array(get_string('ID', 'sloodle'), get_string('avataruuid', 'sloodle'), get_string('uuid', 'sloodle'), get_string('name', 'sloodle'), get_string('isauthorized', 'sloodle'), get_string('lastused', 'sloodle'));
                 $sloodletable->align = array('center', 'left', 'left', 'left', 'center', 'left');
                 //$sloodletable->size = array('5%', '5%', '27%', '35%', '20%', '8%');
                 // Store the current timestamp for consistency
                 $curtime = time();
                 // Go through each object
                 foreach ($userobjects as $obj) {
                     $line = array();
                     $line[] = $obj->id;
                     $line[] = $obj->avuuid;
                     $line[] = $obj->objuuid;
                     $line[] = $obj->objname;
                     if ($obj->authorized) {
                         $line[] = ucwords(get_string('yes'));
                     } else {
                         $line[] = ucwords(get_string('no'));
                     }
                     $lastused = (int) $obj->timeupdated;
                     if ($lastused > 0) {
                         $line[] = sloodle_describe_approx_time($curtime - $lastused, true);
                     } else {
                         $line[] = '(' . get_string('unknown', 'sloodle') . ')';
                     }
                     $sloodletable->data[] = $line;
                 }
                 // Display the table
                 print_table($sloodletable);
                 // Display a button to delete all the Sloodle objects
                 if (empty($deleteuserobjects)) {
                     echo '<br><form action="user.php" method="GET">';
                     echo '<input type="hidden" name="_type" value="user" />';
                     echo '<input type="hidden" name="id" value="' . $this->moodleuserid . '" >';
                     if (!empty($this->courseid)) {
                         echo '<input type="hidden" name="course" value="' . $this->courseid . '" >';
                     }
                     echo '<input type="hidden" name="deleteuserobjects" value="true" >';
                     echo '<input type="hidden" name="start" value="' . $this->start . '" />';
                     echo '<input type="submit" value="' . get_string('deleteuserobjects', 'sloodle') . '" title="' . get_string('deleteuserobjects:help', 'sloodle') . '" >';
                     echo '</form><br>';
                 }
             } else {
                 // No user objects
                 echo '<span style="color:red; font-weight:bold;">';
                 print_string('noentries', 'sloodle');
                 echo '</span>';
             }
         }
     }
     echo '</div>';
 }
Example #8
0
File: lib.php Project: r007/PMoodle
/**
 * Returns a list of posts found using an array of search terms.
 * @param $searchterms - array of search terms, e.g. word +word -word
 * @param $courseid - if 0, we search through the whole site
 * @param $page
 * @param $recordsperpage=50
 * @param &$totalcount
 * @param $extrasql
 * @return array of posts found
 */
function forum_search_posts($searchterms, $courseid = 0, $limitfrom = 0, $limitnum = 50, &$totalcount, $extrasql = '')
{
    global $CFG, $USER;
    require_once $CFG->libdir . '/searchlib.php';
    $forums = forum_get_readable_forums($USER->id, $courseid);
    if (count($forums) == 0) {
        $totalcount = 0;
        return false;
    }
    $now = round(time(), -2);
    // db friendly
    $fullaccess = array();
    $where = array();
    foreach ($forums as $forumid => $forum) {
        $select = array();
        if (!$forum->viewhiddentimedposts) {
            $select[] = "(d.userid = {$USER->id} OR (d.timestart < {$now} AND (d.timeend = 0 OR d.timeend > {$now})))";
        }
        if ($forum->type == 'qanda') {
            if (!empty($forum->onlydiscussions)) {
                $discussionsids = implode(',', $forum->onlydiscussions);
                $select[] = "(d.id IN ({$discussionsids}) OR p.parent = 0)";
            } else {
                $select[] = "p.parent = 0";
            }
        }
        if (!empty($forum->onlygroups)) {
            $groupids = implode(',', $forum->onlygroups);
            $select[] = "d.groupid IN ({$groupids})";
        }
        if ($select) {
            $selects = implode(" AND ", $select);
            $where[] = "(d.forum = {$forumid} AND {$selects})";
        } else {
            $fullaccess[] = $forumid;
        }
    }
    if ($fullaccess) {
        $fullids = implode(',', $fullaccess);
        $where[] = "(d.forum IN ({$fullids}))";
    }
    $selectdiscussion = "(" . implode(" OR ", $where) . ")";
    // Some differences SQL
    $LIKE = sql_ilike();
    $NOTLIKE = 'NOT ' . $LIKE;
    if ($CFG->dbfamily == 'postgres') {
        $REGEXP = '~*';
        $NOTREGEXP = '!~*';
    } else {
        $REGEXP = 'REGEXP';
        $NOTREGEXP = 'NOT REGEXP';
    }
    $messagesearch = '';
    $searchstring = '';
    // Need to concat these back together for parser to work.
    foreach ($searchterms as $searchterm) {
        if ($searchstring != '') {
            $searchstring .= ' ';
        }
        $searchstring .= $searchterm;
    }
    // We need to allow quoted strings for the search. The quotes *should* be stripped
    // by the parser, but this should be examined carefully for security implications.
    $searchstring = str_replace("\\\"", "\"", $searchstring);
    $parser = new search_parser();
    $lexer = new search_lexer($parser);
    if ($lexer->parse($searchstring)) {
        $parsearray = $parser->get_parsed_array();
        // Experimental feature under 1.8! MDL-8830
        // Use alternative text searches if defined
        // This feature only works under mysql until properly implemented for other DBs
        // Requires manual creation of text index for forum_posts before enabling it:
        // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
        // Experimental feature under 1.8! MDL-8830
        if (!empty($CFG->forum_usetextsearches)) {
            $messagesearch = search_generate_text_SQL($parsearray, 'p.message', 'p.subject', 'p.userid', 'u.id', 'u.firstname', 'u.lastname', 'p.modified', 'd.forum');
        } else {
            $messagesearch = search_generate_SQL($parsearray, 'p.message', 'p.subject', 'p.userid', 'u.id', 'u.firstname', 'u.lastname', 'p.modified', 'd.forum');
        }
    }
    $fromsql = "{$CFG->prefix}forum_posts p,\n                  {$CFG->prefix}forum_discussions d,\n                  {$CFG->prefix}user u";
    $selectsql = " {$messagesearch}\n               AND p.discussion = d.id\n               AND p.userid = u.id\n               AND {$selectdiscussion}\n                   {$extrasql}";
    $countsql = "SELECT COUNT(*)\n                   FROM {$fromsql}\n                  WHERE {$selectsql}";
    $searchsql = "SELECT p.*,\n                         d.forum,\n                         u.firstname,\n                         u.lastname,\n                         u.email,\n                         u.picture,\n                         u.imagealt\n                    FROM {$fromsql}\n                   WHERE {$selectsql}\n                ORDER BY p.modified DESC";
    $totalcount = count_records_sql($countsql);
    return get_records_sql($searchsql, $limitfrom, $limitnum);
}
Example #9
0
/**
 * who has this capability in this context
 * does not handling user level resolving!!!
 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
 * @param $context - object
 * @param $capability - string capability
 * @param $fields - fields to be pulled
 * @param $sort - the sort order
 * @param $limitfrom - number of records to skip (offset)
 * @param $limitnum - number of records to fetch
 * @param $groups - single group or array of groups - group(s) user is in
 * @param $exceptions - list of users to exclude
 */
function internalmail_get_users_by_capability($context, $capability, $fields = '', $sort = 'u.firstname', $limitfrom = '', $limitnum = '', $groups = '', $exceptions = '', $doanything = true, $search = '', $firstinitial = '', $lastinitial = '')
{
    global $CFG, $USER, $COURSE;
    /// Sorting out groups
    if ($groups !== '') {
        $groupjoin = 'INNER JOIN ' . $CFG->prefix . 'groups_members gm ON gm.userid = ra.userid';
        if (is_array($groups)) {
            $groupsql = 'AND gm.groupid IN (' . implode(',', $groups) . ')';
        } else {
            if ($groups == 0) {
                if (!has_capability('block/email_list:viewallgroups', $context) && $COURSE->groupmode == 1) {
                    $groupids = groups_get_groups_for_user($USER->id, $COURSE->id);
                    $groupsql = 'AND gm.groupid IN (' . implode(',', $groupids) . ')';
                } else {
                    $groupsql = '';
                }
            } else {
                $groupsql = 'AND gm.groupid = ' . $groups;
            }
        }
    } else {
        $groupjoin = '';
        $groupsql = '';
    }
    /// Sorting out exceptions
    $exceptionsql = $exceptions ? "AND u.id NOT IN ({$exceptions})" : '';
    /// Set up default fields
    if (empty($fields)) {
        $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
    }
    /// Set up default sort
    if (empty($sort)) {
        $sortby = 'ul.timeaccess';
    }
    $sortby = $sort ? " ORDER BY {$sort} " : '';
    /// If context is a course, then construct sql for ul
    if ($context->contextlevel == CONTEXT_COURSE) {
        $courseid = $context->instanceid;
        $coursesql = "AND (ul.courseid = {$courseid} OR ul.courseid IS NULL)";
    } else {
        $coursesql = '';
    }
    $LIKE = sql_ilike();
    $fullname = sql_fullname();
    $search_sql = '';
    if (!empty($search)) {
        $search = trim($search);
        $search_sql .= " AND ({$fullname} {$LIKE} '%{$search}%' OR email {$LIKE} '%{$search}%' OR username {$LIKE} '%{$search}%' OR idnumber {$LIKE} '%{$search}%') ";
    }
    if ($firstinitial) {
        $search_sql .= ' AND firstname ' . $LIKE . ' \'' . $firstinitial . '%\'';
    }
    if ($lastinitial) {
        $search_sql .= ' AND lastname ' . $LIKE . ' \'' . $lastinitial . '%\'';
    }
    /// Sorting out roles with this capability set
    if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
        if (!$doanything) {
            if (!($sitecontext = get_context_instance(CONTEXT_SYSTEM))) {
                return false;
                // Something is seriously wrong
            }
            $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
        }
        $validroleids = array();
        foreach ($possibleroles as $possiblerole) {
            if (!$doanything) {
                if (isset($doanythingroles[$possiblerole->id])) {
                    // We don't want these included
                    continue;
                }
            }
            if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) {
                // resolved list
                if (isset($caps[$capability]) && $caps[$capability] > 0) {
                    // resolved capability > 0
                    $validroleids[] = $possiblerole->id;
                }
            }
        }
        if (empty($validroleids)) {
            return false;
        }
        $roleids = '(' . implode(',', $validroleids) . ')';
    } else {
        return false;
        // No need to continue, since no roles have this capability set
    }
    /// Construct the main SQL
    $select = " SELECT {$fields}";
    $from = " FROM {$CFG->prefix}user u\r\n                INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id\r\n                INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid\r\n                LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id\r\n                {$groupjoin}";
    $where = " WHERE ra.contextid " . get_related_contexts_string($context) . "\r\n                  AND u.deleted = 0\r\n                  AND ra.roleid in {$roleids}\r\n                      {$exceptionsql}\r\n                      {$coursesql}\r\n                      {$groupsql}\r\n                      {$search_sql}";
    return get_records_sql($select . $from . $where . $sortby, $limitfrom, $limitnum);
}
Example #10
0
$strfeedback = get_string("modulename", "feedback");
$buttontext = update_module_button($cm->id, $course->id, $strfeedback);
$navlinks = array();
$navlinks[] = array('name' => $strfeedbacks, 'link' => "index.php?id={$course->id}", 'type' => 'activity');
$navlinks[] = array('name' => format_string($feedback->name), 'link' => "", 'type' => 'activityinstance');
$navigation = build_navigation($navlinks);
print_header_simple(format_string($feedback->name), "", $navigation, "", "", true, $buttontext, navmenu($course, $cm));
include 'tabs.php';
// print_simple_box(get_string('mapcourseinfo', 'feedback'), 'center', '80%');
print_box(get_string('mapcourseinfo', 'feedback'), 'generalbox boxaligncenter boxwidthwide');
// print_simple_box_start('center', '70%');
print_box_start('generalbox boxaligncenter boxwidthwide');
echo '<form method="post">';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" />';
$sql = "select c.id, c.shortname from {$CFG->prefix}course c\n            where\n                c.shortname " . sql_ilike() . " '%{$searchcourse}%'\n            OR c.fullname " . sql_ilike() . " '%{$searchcourse}%'";
if (($courses = get_records_sql_menu($sql)) && !empty($searchcourse)) {
    echo ' ' . get_string('courses') . ': ';
    choose_from_menu($courses, 'coursefilter', $coursefilter, 'choose');
    echo '<input type="submit" value="' . get_string('mapcourse', 'feedback') . '"/>';
    helpbutton('mapcourses', '', 'feedback', true, true);
    echo '<input type="button" value="' . get_string('searchagain') . '" onclick="document.location=\'mapcourse.php?id=' . $id . '\'"/>';
    echo '<input type="hidden" name="searchcourse" value="' . $searchcourse . '"/>';
    echo '<input type="hidden" name="feedbackid" value="' . $feedback->id . '"/>';
    helpbutton('searchcourses', '', 'feedback', true, true);
} else {
    echo '<input type="text" name="searchcourse" value="' . $searchcourse . '"/> <input type="submit" value="' . get_string('searchcourses') . '"/>';
    helpbutton('searchcourses', '', 'feedback', true, true);
}
echo '</form>';
if ($coursemap = feedback_get_courses_from_sitecourse_map($feedback->id)) {
Example #11
0
 /**
  * Returns an array of cluster ids that are children of the supplied cluster and
  * the current user has access to enrol users into
  *
  * @param   int        $clusterid  The cluster whose children we care about
  * @return  int array              The array of accessible cluster ids
  */
 public static function get_allowed_clusters($clusterid)
 {
     global $USER, $CURMAN;
     $context = cm_context_set::for_user_with_capability('cluster', 'block/curr_admin:cluster:enrol_cluster_user', $USER->id);
     $allowed_clusters = array();
     //get the clusters and check the context against them
     $cluster_context_level = context_level_base::get_custom_context_level('cluster', 'block_curr_admin');
     $cluster_context_instance = get_context_instance($cluster_context_level, $clusterid);
     $path = sql_concat('ctxt.path', "'/%'");
     $like = sql_ilike();
     //query to get sub-cluster contexts
     $cluster_permissions_sql = "SELECT clst.* FROM\n                                    {$CURMAN->db->prefix_table(CLSTTABLE)} clst\n                                    JOIN {$CURMAN->db->prefix_table('context')} ctxt\n                                    ON clst.id = ctxt.instanceid\n                                    AND ctxt.contextlevel = {$cluster_context_level}\n                                    AND '{$cluster_context_instance->path}' {$like} {$path}";
     if ($records = get_records_sql($cluster_permissions_sql)) {
         //filter the records based on what contexts have the cluster:enrol_cluster_user capability
         $allowed_clusters = $context->get_allowed_instances($records, 'cluster', 'id');
     }
     return $allowed_clusters;
 }
function forum_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2003042402) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name')");
    }
    if ($oldversion < 2003082500) {
        table_column("forum", "", "assesstimestart", "integer", "10", "unsigned", "0", "", "assessed");
        table_column("forum", "", "assesstimefinish", "integer", "10", "unsigned", "0", "", "assesstimestart");
    }
    if ($oldversion < 2003082502) {
        execute_sql("UPDATE {$CFG->prefix}forum SET scale = (- scale)");
    }
    if ($oldversion < 2003100600) {
        table_column("forum", "", "maxbytes", "integer", "10", "unsigned", "0", "", "scale");
    }
    if ($oldversion < 2004010100) {
        table_column("forum", "", "assesspublic", "integer", "4", "unsigned", "0", "", "assessed");
    }
    if ($oldversion < 2004011404) {
        table_column("forum_discussions", "", "userid", "integer", "10", "unsigned", "0", "", "firstpost");
        if ($discussions = get_records_sql("SELECT d.id, p.userid\n                                            FROM {$CFG->prefix}forum_discussions as d, \n                                                 {$CFG->prefix}forum_posts as p\n                                           WHERE d.firstpost = p.id")) {
            foreach ($discussions as $discussion) {
                update_record("forum_discussions", $discussion);
            }
        }
    }
    if ($oldversion < 2004012200) {
        table_column("forum_discussions", "", "groupid", "integer", "10", "unsigned", "0", "", "userid");
    }
    if ($oldversion < 2004020600) {
        table_column("forum_discussions", "", "usermodified", "integer", "10", "unsigned", "0", "", "timemodified");
    }
    if ($oldversion < 2004050300) {
        table_column("forum", "", "rsstype", "integer", "2", "unsigned", "0", "", "forcesubscribe");
        table_column("forum", "", "rssarticles", "integer", "2", "unsigned", "0", "", "rsstype");
        set_config("forum_enablerssfeeds", 0);
    }
    if ($oldversion < 2004060100) {
        modify_database('', "CREATE TABLE prefix_forum_queue (\n                           id SERIAL PRIMARY KEY,\n                           userid integer default 0 NOT NULL,\n                           discussionid integer default 0 NOT NULL,\n                           postid integer default 0 NOT NULL\n                           );");
    }
    if ($oldversion < 2004070700) {
        // This may be redoing it from STABLE but that's OK
        table_column("forum_discussions", "groupid", "groupid", "integer", "10", "", "0", "");
    }
    if ($oldversion < 2004111700) {
        execute_sql(" DROP INDEX {$CFG->prefix}forum_posts_parent_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_posts_discussion_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_posts_userid_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_discussions_forum_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_discussions_userid_idx;", false);
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_posts_parent_idx ON {$CFG->prefix}forum_posts (parent) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_posts_discussion_idx ON {$CFG->prefix}forum_posts (discussion) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_posts_userid_idx ON {$CFG->prefix}forum_posts (userid) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_discussions_forum_idx ON {$CFG->prefix}forum_discussions (forum) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_discussions_userid_idx ON {$CFG->prefix}forum_discussions (userid) ");
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}forum_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_queue_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_queue_discussion_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_queue_postid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_ratings_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_ratings_post_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_subscriptions_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_subscriptions_forum_idx;", false);
        modify_database('', 'CREATE INDEX prefix_forum_course_idx ON prefix_forum (course);');
        modify_database('', 'CREATE INDEX prefix_forum_queue_userid_idx ON prefix_forum_queue (userid);');
        modify_database('', 'CREATE INDEX prefix_forum_queue_discussion_idx ON prefix_forum_queue (discussionid);');
        modify_database('', 'CREATE INDEX prefix_forum_queue_postid_idx ON prefix_forum_queue (postid);');
        modify_database('', 'CREATE INDEX prefix_forum_ratings_userid_idx ON prefix_forum_ratings (userid);');
        modify_database('', 'CREATE INDEX prefix_forum_ratings_post_idx ON prefix_forum_ratings (post);');
        modify_database('', 'CREATE INDEX prefix_forum_subscriptions_userid_idx ON prefix_forum_subscriptions (userid);');
        modify_database('', 'CREATE INDEX prefix_forum_subscriptions_forum_idx ON prefix_forum_subscriptions (forum);');
    }
    if ($oldversion < 2005011500) {
        modify_database('', 'CREATE TABLE prefix_forum_read (
                          id SERIAL PRIMARY KEY,
                          userid integer default 0 NOT NULL,
                          forumid integer default 0 NOT NULL,
                          discussionid integer default 0 NOT NULL,
                          postid integer default 0 NOT NULL,
                          firstread integer default 0 NOT NULL,
                          lastread integer default 0 NOT NULL
                        );');
        modify_database('', 'CREATE INDEX prefix_forum_user_forum_idx ON prefix_forum_read (userid, forumid);');
        modify_database('', 'CREATE INDEX prefix_forum_user_discussion_idx ON prefix_forum_read (userid, discussionid);');
        modify_database('', 'CREATE INDEX prefix_forum_user_post_idx ON prefix_forum_read (userid, postid);');
        set_config('upgrade', 'forumread');
        // The upgrade of this table will be done later by admin/upgradeforumread.php
    }
    if ($oldversion < 2005032900) {
        modify_database('', 'CREATE INDEX prefix_forum_posts_created_idx ON prefix_forum_posts (created);');
        modify_database('', 'CREATE INDEX prefix_forum_posts_mailed_idx ON prefix_forum_posts (mailed);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}forum_discussions, {$CFG->prefix}forum_posts ";
        $sql .= "where {$CFG->prefix}forum_posts.discussion = {$CFG->prefix}forum_discussions.id ";
        $sql .= "and {$CFG->prefix}forum_posts.id = ";
        $wtm->update('forum_posts', 'message', 'format', $sql);
    }
    if ($oldversion < 2005042300) {
        // Add tracking prefs table
        modify_database('', 'CREATE TABLE prefix_forum_track_prefs (
                          id SERIAL PRIMARY KEY, 
                          userid integer default 0 NOT NULL,
                          forumid integer default 0 NOT NULL
                        );');
    }
    if ($oldversion < 2005042600) {
        table_column('forum', '', 'trackingtype', 'integer', '2', 'unsigned', '1', '', 'forcesubscribe');
        modify_database('', 'CREATE INDEX prefix_forum_track_user_forum_idx ON prefix_forum_track_prefs (userid, forumid);');
    }
    if ($oldversion < 2005042601) {
        // Mass cleanup of bad postgres upgrade scripts
        modify_database('', 'ALTER TABLE prefix_forum ALTER trackingtype SET NOT NULL');
    }
    if ($oldversion < 2005111100) {
        table_column('forum_discussions', '', 'timestart', 'integer');
        table_column('forum_discussions', '', 'timeend', 'integer');
    }
    if ($oldversion < 2006011600) {
        notify('forum_type does not exists, you can ignore and this will properly removed');
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type");
        execute_sql("ALTER TABLE {$CFG->prefix}forum ADD CONSTRAINT {$CFG->prefix}forum_type CHECK (type IN ('single','news','general','social','eachuser','teacher','qanda')) ");
    }
    if ($oldversion < 2006011601) {
        table_column('forum', '', 'warnafter');
        table_column('forum', '', 'blockafter');
        table_column('forum', '', 'blockperiod');
    }
    if ($oldversion < 2006011700) {
        table_column('forum_posts', '', 'mailnow', 'integer');
    }
    if ($oldversion < 2006011701) {
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type_check");
    }
    if ($oldversion < 2006011702) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'firstname||\\' \\'||lastname')");
    }
    if ($oldversion < 2006081800) {
        // Upgrades for new roles and capabilities support.
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        $forummod = get_record('modules', 'name', 'forum');
        if ($forums = get_records('forum')) {
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notify('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notify('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
                notify('Default guest role was not found. Roles and permissions ' . 'for teacher forums will have to be manually set after ' . 'this upgrade.');
            }
            foreach ($forums as $forum) {
                if (!forum_convert_to_roles($forum, $forummod->id, $teacherroles, $studentroles, $guestroles)) {
                    notify('Forum with id ' . $forum->id . ' was not upgraded');
                }
            }
            // We need to rebuild all the course caches to refresh the state of
            // the forum modules.
            rebuild_course_cache();
        }
        // End if.
        // Drop column forum.open.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN open;');
        // Drop column forum.assesspublic.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN assesspublic;');
    }
    if ($oldversion < 2006082700) {
        $sql = "UPDATE {$CFG->prefix}forum_posts SET message = REPLACE(message, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('forum_posts', "message {$likecond}")) {
                break;
            }
            execute_sql($sql);
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Example #13
0
function glossary_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2004022200) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004050900) {
        table_column("glossary", "", "rsstype", "integer", "2", "unsigned", "0", "", "entbypage");
        table_column("glossary", "", "rssarticles", "integer", "2", "unsigned", "0", "", "rsstype");
        set_config("glossary_enablerssfeeds", 0);
    }
    if ($oldversion < 2004051400) {
        print_simple_box("This update might take several seconds.<p>The more glossaries, entries and aliases you have created, the more it will take so please be patient.", "center", "50%", '', "20", "noticebox");
        if ($entries = get_records("glossary_entries", '', '', '', 'id,concept')) {
            foreach ($entries as $entry) {
                set_field("glossary_entries", "concept", addslashes(trim($entry->concept)), "id", $entry->id);
            }
        }
        if ($aliases = get_records("glossary_alias")) {
            foreach ($aliases as $alias) {
                set_field("glossary_alias", "alias", addslashes(trim($alias->alias)), "id", $alias->id);
            }
        }
    }
    if ($oldversion < 2004072300) {
        table_column("glossary_alias", "alias", "alias", "VARCHAR", "255", "", "", "NOT NULL");
    }
    if ($oldversion < 2004072400) {
        //Create new table glossary_formats to store format info
        execute_sql("CREATE TABLE {$CFG->prefix}glossary_formats (\n                       id SERIAL8 PRIMARY KEY,\n                       name VARCHAR(50) NOT NULL,\n                       popupformatname VARCHAR(50) NOT NULL, \n                       visible int2  NOT NULL default '1',\n                       showgroup int2  NOT NULL default '1',\n                       defaultmode VARCHAR(50) NOT NULL default '',\n                       defaulthook VARCHAR(50) NOT NULL default '',\n                       sortkey VARCHAR(50) NOT NULL default '',\n                       sortorder VARCHAR(50) NOT NULL default ''\n                   ) ");
        //Define current 0-6 format names
        $formatnames = array('dictionary', 'continuous', 'fullwithauthor', 'encyclopedia', 'faq', 'fullwithoutauthor', 'entrylist');
        //Fill the new table from the old one (only 'valid', 0-6, formats)
        if ($formats = get_records('glossary_displayformats')) {
            foreach ($formats as $format) {
                //Format names
                if ($format->fid >= 0 && $format->fid <= 6) {
                    $format->name = $formatnames[$format->fid];
                }
                //Format popupformatname
                $format->popupformatname = 'dictionary';
                //Default format
                if ($format->relatedview >= 0 && $format->relatedview <= 6) {
                    $format->popupformatname = $formatnames[$format->relatedview];
                }
                //Insert the new record
                //Only if $format->name is set (ie. formats 0-6)
                if ($format->name) {
                    insert_record('glossary_formats', $format);
                }
            }
        }
        //Drop the old formats table
        execute_sql("DROP TABLE {$CFG->prefix}glossary_displayformats");
        //Modify the glossary->displayformat field
        table_column('glossary', 'displayformat', 'displayformat', 'VARCHAR', '50', '', 'dictionary', 'NOT NULL');
        //Update glossary->displayformat field
        if ($glossaries = get_records('glossary')) {
            foreach ($glossaries as $glossary) {
                $displayformat = 'dictionary';
                //Default format
                if ($glossary->displayformat >= 0 && $glossary->displayformat <= 6) {
                    $displayformat = $formatnames[$glossary->displayformat];
                }
                set_field('glossary', 'displayformat', $displayformat, 'id', $glossary->id);
            }
        }
    }
    if ($oldversion < 2004080800) {
        table_column("glossary", "", "editalways", "integer", "2", "unsigned", "0", "", "entbypage");
    }
    //Activate editalways in old secondary glossaries (old behaviour)
    if ($oldversion < 2004080900) {
        set_field('glossary', 'editalways', '1', 'mainglossary', '0');
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}glossary_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_alias_entryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_categories_glossaryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_comments_entryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_comments_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_glossaryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_concept_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_categories_category_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_categories_entryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_ratings_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_ratings_entryid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_glossary_course_idx ON prefix_glossary (course);');
        modify_database('', 'CREATE INDEX prefix_glossary_alias_entryid_idx ON prefix_glossary_alias (entryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_categories_glossaryid_idx ON prefix_glossary_categories (glossaryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_comments_entryid_idx ON prefix_glossary_comments (entryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_comments_userid_idx ON prefix_glossary_comments (userid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_glossaryid_idx ON prefix_glossary_entries (glossaryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_userid_idx ON prefix_glossary_entries (userid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_concept_idx ON prefix_glossary_entries (concept);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_categories_category_idx ON prefix_glossary_entries_categories (categoryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_categories_entryid_idx ON prefix_glossary_entries_categories (entryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_ratings_userid_idx ON prefix_glossary_ratings (userid);');
        modify_database('', 'CREATE INDEX prefix_glossary_ratings_entryid_idx ON prefix_glossary_ratings (entryid);');
    }
    //Delete orphaned categories (bug 2140)
    if ($oldversion < 2005011100) {
        $categories = get_records('glossary_categories', '', '', '', 'id, glossaryid');
        if ($categories) {
            foreach ($categories as $category) {
                $glossary = get_record('glossary', 'id', "{$category->glossaryid}");
                if (!$glossary) {
                    delete_records('glossary_categories', 'id', "{$category->id}");
                }
            }
        }
    }
    //Allowprintview flag
    if ($oldversion < 2005011200) {
        table_column('glossary', '', 'allowprintview', 'integer', '2', 'unsigned', '1', '', 'allowcomments');
        $glossaries = get_records('glossary', '', '', '', 'id, name');
        if ($glossaries) {
            foreach ($glossaries as $glossary) {
                set_field('glossary', 'allowprintview', '1', 'id', "{$glossary->id}");
            }
        }
    }
    if ($oldversion < 2005031001) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('glossary', 'view entry', 'glossary_entries', 'concept');");
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        // update glossary_entries->definition
        $sql = "select course from {$CFG->prefix}glossary,{$CFG->prefix}glossary_entries ";
        $sql .= "where {$CFG->prefix}glossary.id = {$CFG->prefix}glossary_entries.glossaryid ";
        $sql .= "and {$CFG->prefix}glossary_entries.id = ";
        $wtm->update('glossary_entries', 'definition', 'format');
        // update glossary_comments->text
        $sql = "select course from {$CFG->prefix}glossary,{$CFG->prefix}glossary_entries,{$CFG->prefix}glossary_comments ";
        $sql .= "where {$CFG->prefix}glossary.id = {$CFG->prefix}glossary_entries.glossaryid ";
        $sql .= "and {$CFG->prefix}glossary_entries.id = {$CFG->prefix}glossary_comments.entryid ";
        $sql .= "and {$CFG->prefix}glossary_comments.id = ";
        $wtm->update('glossary_comments', 'text', 'format', $sql);
    }
    if ($oldversion < 2005041901) {
        // Mass cleanup of bad postgres upgrade scripts
        table_column('glossary', 'allowprintview', 'allowprintview', 'smallint', '4', 'unsigned', '1');
    }
    if ($oldversion < 2006082600) {
        $sql1 = "UPDATE {$CFG->prefix}glossary_entries SET definition = REPLACE(definition, '" . TRUSTTEXT . "', '');";
        $sql2 = "UPDATE {$CFG->prefix}glossary_comments SET comment = REPLACE(comment, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('glossary_entries', "definition {$likecond}")) {
                break;
            }
            execute_sql($sql1);
        }
        while (true) {
            if (!count_records_select('glossary_comments', "comment {$likecond}")) {
                break;
            }
            execute_sql($sql2);
        }
    }
    if ($oldversion < 2006090400) {
        table_column('glossary_comments', 'comment', 'entrycomment', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Example #14
0
File: lib.php Project: rrusso/EARS
 function print_form()
 {
     global $THEME, $CFG;
     // get the search string, if it exists
     $searchtext = optional_param('searchtext', '', PARAM_RAW);
     $previoussearch = optional_param('previoussearch', 0, PARAM_BOOL);
     $showall = optional_param('showall', 0, PARAM_BOOL);
     $strshowall = get_string('showall');
     $strsearchresults = get_string('searchresults');
     $previoussearch = $searchtext != '' or $previoussearch ? 1 : 0;
     // Showing all means that we need to clear out the search string
     if ($showall) {
         $searchtext = '';
         $previoussearch = 0;
     }
     $searchtext = trim($searchtext);
     if ($searchtext !== '') {
         $LIKE = sql_ilike();
         $selectsql = " AND (CONCAT(u.firstname, ' ', u.lastname) \n                           {$LIKE} '%{$searchtext}%' OR email {$LIKE} '%{$searchtext}%') ";
     } else {
         $selectsql = '';
         $previoussearch = 0;
     }
     define('MAX_USERS_PER_PAGE', 5000);
     define('MAX_USERS_TO_LIST_PER_ROLE', 20);
     //Find all the users that are assigned this role
     $sql = $this->get_sql();
     $sub_sql = $this->get_context_user_sql();
     $everyone = $this->get_everyone_sql();
     $excsql = $this->get_exclusive_sql($sub_sql);
     // These are the people who are assigned
     $contextusers = get_records_sql($sql . $sub_sql);
     if (!$contextusers) {
         $contextusers = array();
     }
     // These are people who can be potentially assigned
     $availableusers = get_recordset_sql($sql . $everyone . $selectsql . $excsql);
     $usercount = $availableusers->_numOfRows;
     $strsearch = get_string('search');
     print_box_start();
     include 'assign.html';
     print_box_end();
 }
/**
 * Calculates a new label for a copy of an existing PHP report schedule
 * based on the existing schedule's name
 *
 * @param   string  $parent_label  The label from the original schedule instance
 *
 * @return  string                 The label for the new schedule instance
 */
function block_php_report_get_copy_label($parent_label)
{
    //first guess at to our copy number
    $i = 1;
    $done = false;
    while (!$done) {
        //get the proposed label
        $a = new stdClass();
        $a->label = $parent_label;
        $a->index = $i;
        $label = get_string('task_copy_label', 'block_php_report', $a);
        //look for records containing the proposed namy anywhere in their config data
        //(may include false-positives but very unlikely)
        if ($records = get_recordset_select('php_report_schedule', 'config ' . sql_ilike() . " '%{$label}%'")) {
            //track whether an exact match was found
            $found = false;
            //go through all possible matches
            while ($record = rs_fetch_next_record($records)) {
                //perform an exact comparison
                $config = unserialize($record->config);
                if ($config['label'] == $label) {
                    //exact match
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                //all cases were false, positive, so accept
                $done = true;
            } else {
                //exact match, so increment and try again
                $i++;
            }
        } else {
            //no config contained the proposed label, so accept
            $done = true;
        }
    }
    return $label;
}
Example #16
0
        $searchselect = ' ';
    }
} else {
    if ($search) {
        $what = ' DISTINCT r.id, r.approved, r.userid, u.firstname, u.lastname ';
        $count = ' COUNT(DISTINCT c.recordid) ';
        $tables = $CFG->prefix . 'data_content c,' . $CFG->prefix . 'data_records r, ' . $CFG->prefix . 'user u ';
        $where = 'WHERE c.recordid = r.id
                     AND r.userid = u.id
                     AND r.dataid = ' . $data->id;
        $sortorder = ' ORDER BY r.id ASC ';
        // If requiredentries is not reached, only show current user's entries
        if (!$requiredentries_allowed) {
            $where .= ' AND u.id = ' . $USER->id;
        }
        $searchselect = ' AND (c.content ' . sql_ilike() . " '%{$search}%') ";
        //Be case-insensitive
    } else {
        $what = ' DISTINCT r.id, r.approved, r.timecreated, r.userid, u.firstname, u.lastname ';
        $count = ' COUNT(r.id) ';
        $tables = $CFG->prefix . 'data_records r, ' . $CFG->prefix . 'user u ';
        $where = 'WHERE r.dataid = ' . $data->id . ' AND r.userid = u.id ';
        $sortorder = ' ORDER BY r.timecreated ' . $order . ' ';
        $searchselect = ' ';
        // If requiredentries is not reached, only show current user's entries
        if (!$requiredentries_allowed) {
            $where .= ' AND u.id = ' . $USER->id;
        }
    }
}
/// To actually fetch the records
Example #17
0
function data_fieldname_exists($name, $dataid, $fieldid = 0)
{
    global $CFG;
    $LIKE = sql_ilike();
    if ($fieldid) {
        return record_exists_sql("SELECT * from {$CFG->prefix}data_fields df\n                                  WHERE df.name {$LIKE} '{$name}' AND df.dataid = {$dataid}\n                                    AND ((df.id < {$fieldid}) OR (df.id > {$fieldid}))");
    } else {
        return record_exists_sql("SELECT * from {$CFG->prefix}data_fields df\n                                  WHERE df.name {$LIKE} '{$name}' AND df.dataid = {$dataid}");
    }
}
 /**
  * Returns the condition to be used with SQL where
  * @param array $data filter settings
  * @return string the filtering condition or null if the filter is disabled
  */
 function get_sql_filter($data)
 {
     global $CFG;
     $value = addslashes($data['value']);
     $roleid = $data['roleid'];
     $categoryid = $data['categoryid'];
     if (empty($value) and empty($roleid) and empty($categoryid)) {
         return '';
     }
     $timenow = round(time(), 100);
     // rounding - enable sql caching
     $where = "b.contextlevel=50 AND a.timestart<{$timenow} AND (a.timeend=0 OR a.timeend>{$timenow})";
     if ($roleid) {
         $where .= " AND a.roleid={$roleid}";
     }
     if ($categoryid) {
         $where .= " AND c.category={$categoryid}";
     }
     if ($value) {
         $where .= " AND c.shortname " . sql_ilike() . " '{$value}'";
     }
     return "id IN (SELECT userid\n                         FROM {$CFG->prefix}role_assignments a\n                   INNER JOIN {$CFG->prefix}context b ON a.contextid=b.id\n                   INNER JOIN {$CFG->prefix}course c ON b.instanceid=c.id\n                        WHERE {$where})";
 }
Example #19
0
function search_generate_SQL($parsetree, $datafield, $metafield, $mainidfield, $useridfield, $userfirstnamefield, $userlastnamefield, $timefield, $instancefield)
{
    global $CFG;
    $LIKE = sql_ilike();
    $NOTLIKE = 'NOT ' . $LIKE;
    if ($CFG->dbfamily == "postgres") {
        $REGEXP = "~*";
        $NOTREGEXP = "!~*";
    } else {
        $REGEXP = "REGEXP";
        $NOTREGEXP = "NOT REGEXP";
    }
    $ntokens = count($parsetree);
    if ($ntokens == 0) {
        return "";
    }
    $SQLString = '';
    for ($i = 0; $i < $ntokens; $i++) {
        if ($i > 0) {
            // We have more than one clause, need to tack on AND
            $SQLString .= ' AND ';
        }
        $type = $parsetree[$i]->getType();
        $value = $parsetree[$i]->getValue();
        /// Under Oracle and MSSQL, transform TOKEN searches into STRING searches and trim +- chars
        if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
            $value = trim($value, '+-');
            if ($type == TOKEN_EXACT) {
                $type = TOKEN_STRING;
            }
        }
        switch ($type) {
            case TOKEN_STRING:
                $SQLString .= "(({$datafield} {$LIKE} '%{$value}%') OR ({$metafield} {$LIKE} '%{$value}%') )";
                break;
            case TOKEN_EXACT:
                $SQLString .= "(({$datafield} {$REGEXP} '[[:<:]]" . $value . "[[:>:]]') OR ({$metafield} {$REGEXP} '[[:<:]]" . $value . "[[:>:]]'))";
                break;
            case TOKEN_META:
                if ($metafield != '') {
                    $SQLString .= "({$metafield} {$LIKE} '%{$value}%')";
                }
                break;
            case TOKEN_USER:
                $SQLString .= "(({$mainidfield} = {$useridfield}) AND (({$userfirstnamefield} {$LIKE} '%{$value}%') OR ({$userlastnamefield} {$LIKE} '%{$value}%')))";
                break;
            case TOKEN_USERID:
                $SQLString .= "({$useridfield} = {$value})";
                break;
            case TOKEN_INSTANCE:
                $SQLString .= "({$instancefield} = {$value})";
                break;
            case TOKEN_DATETO:
                $SQLString .= "({$timefield} <= {$value})";
                break;
            case TOKEN_DATEFROM:
                $SQLString .= "({$timefield} >= {$value})";
                break;
            case TOKEN_NEGATE:
                $SQLString .= "(NOT (({$datafield}  {$LIKE} '%{$value}%') OR ({$metafield}  {$LIKE} '%{$value}%')))";
                break;
            default:
                return '';
        }
    }
    return $SQLString;
}
Example #20
0
/**
 * Returns a list of posts found using an array of search terms.
 * @param $searchterms - array of search terms, e.g. word +word -word
 * @param $courseid - if 0, we search through the whole site
 * @param $page
 * @param $recordsperpage=50
 * @param &$totalcount
 * @param $extrasql
 * @return array of posts found
 */
function forum_search_posts($searchterms, $courseid = 0, $limitfrom = 0, $limitnum = 50, &$totalcount, $extrasql = '')
{
    global $CFG, $USER;
    require_once $CFG->libdir . '/searchlib.php';
    $forums = forum_get_readable_forums($USER->id, $courseid);
    if (count($forums) == 0) {
        return false;
    }
    for ($i = 0; $i < count($forums); $i++) {
        if ($i == 0) {
            $selectdiscussion = " ((d.forum = {$forums[$i]->id}";
        } else {
            $selectdiscussion .= " OR (d.forum = {$forums[$i]->id}";
        }
        if (!empty($CFG->forum_enabletimedposts) && !$forums[$i]->viewhiddentimedposts) {
            $now = time();
            $selectdiscussion .= " AND ( d.userid = {$USER->id}\n                                   OR ((d.timestart = 0 OR d.timestart <= {$now})\n                                   AND (d.timeend = 0 OR d.timeend > {$now})) )";
        }
        if ($forums[$i]->type == 'qanda' && isset($forums[$i]->onlydiscussions)) {
            // This is a qanda forum.
            if (is_array($forums[$i]->onlydiscussions)) {
                // Show question posts as well as posts from discussions in
                // which the user has posted a reply.
                $onlydiscussions = implode(' OR d.id = ', $forums[$i]->onlydiscussions);
                $selectdiscussion .= " AND ((d.id = {$onlydiscussions}) OR p.parent = 0)";
            } else {
                // Show only the question posts.
                $selectdiscussion .= ' AND (p.parent = 0)';
            }
        }
        if (!$forums[$i]->accessallgroups) {
            if (!empty($forums[$i]->accessgroup)) {
                $groups = rtrim(implode(",", $forums[$i]->accessgroup), ",");
                $selectdiscussion .= " AND (d.groupid in ({$groups})";
                $selectdiscussion .= ' OR d.groupid = -1)';
                // -1 means open for all groups.
            } else {
                // User isn't in any group. Only search discussions that are
                // open to all groups.
                $selectdiscussion .= ' AND d.groupid = -1';
            }
        }
        $selectdiscussion .= ")\n";
    }
    $selectdiscussion .= ")";
    // Some differences SQL
    $LIKE = sql_ilike();
    $NOTLIKE = 'NOT ' . $LIKE;
    if ($CFG->dbfamily == 'postgres') {
        $REGEXP = '~*';
        $NOTREGEXP = '!~*';
    } else {
        $REGEXP = 'REGEXP';
        $NOTREGEXP = 'NOT REGEXP';
    }
    $messagesearch = '';
    $searchstring = '';
    // Need to concat these back together for parser to work.
    foreach ($searchterms as $searchterm) {
        if ($searchstring != '') {
            $searchstring .= ' ';
        }
        $searchstring .= $searchterm;
    }
    // We need to allow quoted strings for the search. The quotes *should* be stripped
    // by the parser, but this should be examined carefully for security implications.
    $searchstring = str_replace("\\\"", "\"", $searchstring);
    $parser = new search_parser();
    $lexer = new search_lexer($parser);
    if ($lexer->parse($searchstring)) {
        $parsearray = $parser->get_parsed_array();
        // Experimental feature under 1.8! MDL-8830
        // Use alternative text searches if defined
        // This feature only works under mysql until properly implemented for other DBs
        // Requires manual creation of text index for forum_posts before enabling it:
        // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
        // Experimental feature under 1.8! MDL-8830
        if (!empty($CFG->forum_usetextsearches)) {
            $messagesearch = search_generate_text_SQL($parsearray, 'p.message', 'p.subject', 'p.userid', 'u.id', 'u.firstname', 'u.lastname', 'p.modified', 'd.forum');
        } else {
            $messagesearch = search_generate_SQL($parsearray, 'p.message', 'p.subject', 'p.userid', 'u.id', 'u.firstname', 'u.lastname', 'p.modified', 'd.forum');
        }
    }
    $fromsql = "{$CFG->prefix}forum_posts p,\n                  {$CFG->prefix}forum_discussions d,\n                  {$CFG->prefix}user u";
    $selectsql = " {$messagesearch}\n               AND p.discussion = d.id\n               AND p.userid = u.id\n               AND {$selectdiscussion}\n                   {$extrasql}";
    $countsql = "SELECT COUNT(*)\n                   FROM {$fromsql}\n                  WHERE {$selectsql}";
    $searchsql = "SELECT p.*,\n                         d.forum,\n                         u.firstname,\n                         u.lastname,\n                         u.email,\n                         u.picture,\n                         u.imagealt\n                    FROM {$fromsql}\n                   WHERE {$selectsql}\n                ORDER BY p.modified DESC";
    $totalcount = count_records_sql($countsql);
    return get_records_sql($searchsql, $limitfrom, $limitnum);
}
Example #21
0
/**
 * Gets the users for a course who are not in a specified group
 * @param int $groupid The id of the group
 * @param string searchtext similar to searchtext in role assign, search
 * @return array An array of the userids of the non-group members,  or false if
 * an error occurred.
 * This function was changed to get_users_by_capability style
 * mostly because of the searchtext requirement
 */
function groups_get_users_not_in_group($courseid, $groupid, $searchtext = '')
{
    global $CFG;
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    if ($searchtext !== '') {
        // Search for a subset of remaining users
        $LIKE = sql_ilike();
        $FULLNAME = sql_fullname();
        $wheresearch = " AND u.id IN (SELECT id FROM {$CFG->prefix}user WHERE {$FULLNAME} {$LIKE} '%{$searchtext}%' OR email {$LIKE} '%{$searchtext}%' )";
    } else {
        $wheresearch = '';
    }
    $capability = 'moodle/course:view';
    $doanything = false;
    // find all possible "student" roles
    if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
        if (!$doanything) {
            if (!($sitecontext = get_context_instance(CONTEXT_SYSTEM))) {
                return false;
                // Something is seriously wrong
            }
            $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
        }
        $validroleids = array();
        foreach ($possibleroles as $possiblerole) {
            if (!$doanything) {
                if (isset($doanythingroles[$possiblerole->id])) {
                    // We don't want these included
                    continue;
                }
            }
            if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) {
                // resolved list
                if (isset($caps[$capability]) && $caps[$capability] > 0) {
                    // resolved capability > 0
                    $validroleids[] = $possiblerole->id;
                }
            }
        }
        if (empty($validroleids)) {
            return false;
        }
        $roleids = '(' . implode(',', $validroleids) . ')';
    } else {
        return false;
        // No need to continue, since no roles have this capability set
    }
    /// Construct the main SQL
    $select = " SELECT u.id, u.firstname, u.lastname";
    $from = " FROM {$CFG->prefix}user u\n                INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id\n                INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid";
    $where = " WHERE ra.contextid " . get_related_contexts_string($context) . "\n                  AND u.deleted = 0\n                  AND ra.roleid in {$roleids}\n                  AND u.id NOT IN (SELECT userid\n                                   FROM {$CFG->prefix}groups_members\n                                   WHERE groupid = {$groupid})\n                  {$wheresearch}";
    $groupby = " GROUP BY u.id, u.firstname, u.lastname ";
    return get_records_sql($select . $from . $where . $groupby);
}
Example #22
0
/**
 * This function returns an object of all users whithin current course who match
 * the search query.
 *  *Modified version of datalib.php's search_user() function
 *
 * @param object $course Current Course object
 * @param string $query Search query
 * @param boolean $dispadmins Flag to return course admins or not
 * @param boolean $displayunconfirmed Flag to specify to return unconfirmed users
 * @return object result set of all matching users
 * @todo Add option to remove active user from results
 */
function email_search_course_users($course, $query = '', $dispadmins = false, $dispunconfirmed = true)
{
    global $CFG, $USER;
    $LIKE = sql_ilike();
    $order = 'ORDER BY firstname, lastname, id';
    $select = 'u.deleted = \'0\'';
    if (!$dispunconfirmed) {
        $select .= ' AND u.confirmed = \'1\'';
    }
    if (!$course or $course->id == SITEID) {
        $results = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email\n                      FROM {$CFG->prefix}user u\n                      WHERE {$select}\n                          AND (u.firstname {$LIKE} '{$query}%' OR u.lastname {$LIKE} '{$query}%')\n                          AND u.username != 'guest'\n                          {$order}");
    } else {
        if ($course->id == SITEID) {
            $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
        } else {
            $context = get_context_instance(CONTEXT_COURSE, $course->id);
        }
        $contextlists = get_related_contexts_string($context);
        // Returns only group(s) members for users without the viewallgroups capability
        $groupmembers = '';
        // Separate groups
        $groupmode = groups_get_course_groupmode($course);
        if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
            // Returns all groups current user is assigned to in course
            if ($groups = groups_get_all_groups($course->id, $USER->id)) {
                $groupmembers = array();
                foreach ($groups as $group) {
                    $groupmembers += groups_get_members($group->id, 'u.id');
                }
                if (!empty($groupmembers)) {
                    $groupmembers = 'AND u.id IN (' . implode(',', array_keys($groupmembers)) . ')';
                } else {
                    // Nobody in their groups :(
                    return false;
                }
            } else {
                // They have no group :(
                return false;
            }
        }
        // Hides course admin roles (eg: admin && course creator) if requested (default)
        if (!$dispadmins) {
            $avoidroles = array();
            if ($roles = get_roles_used_in_context($context, true)) {
                $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
                $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $context);
                if (!$CFG->email_add_admins) {
                    $adminsroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW, $context);
                }
                foreach ($roles as $role) {
                    if (!isset($canviewroles[$role->id])) {
                        // Avoid this role (eg course creator)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }
                    if (isset($doanythingroles[$role->id])) {
                        // Avoid this role (ie admin)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }
                    if (!$CFG->email_add_admins) {
                        if (isset($adminsroles[$role->id])) {
                            // Avoid this role (ie admin)
                            $avoidroles[] = $role->id;
                            unset($roles[$role->id]);
                            continue;
                        }
                    }
                }
            }
            // exclude users with roles we are avoiding
            if ($avoidroles) {
                $adminroles = 'AND ra.roleid NOT IN (';
                $adminroles .= implode(',', $avoidroles);
                $adminroles .= ')';
            } else {
                $adminroles = '';
            }
        } else {
            $adminroles = '';
        }
        $results = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email\n                      FROM {$CFG->prefix}user u,\n                           {$CFG->prefix}role_assignments ra\n                      WHERE {$select} AND ra.contextid {$contextlists} AND ra.userid = u.id\n                          AND (u.firstname {$LIKE} '{$query}%' OR u.lastname {$LIKE} '{$query}%')\n                          AND (u.username != 'guest')\n                          {$adminroles} {$groupmembers} {$order}");
    }
    return $results;
}
Example #23
0
 /// setup group and approve restrictions
 if (!$approvecap && $data->approval) {
     if (isloggedin()) {
         $approveselect = ' AND (r.approved=1 OR r.userid=' . $USER->id . ') ';
     } else {
         $approveselect = ' AND r.approved=1 ';
     }
 } else {
     $approveselect = ' ';
 }
 if ($currentgroup) {
     $groupselect = " AND (r.groupid = '{$currentgroup}' OR r.groupid = 0)";
 } else {
     $groupselect = ' ';
 }
 $ilike = sql_ilike();
 //Be case-insensitive
 /// Find the field we are sorting on
 if ($sort <= 0 or !($sortfield = data_get_field_from_id($sort, $data))) {
     switch ($sort) {
         case DATA_LASTNAME:
             $ordering = "u.lastname {$order}, u.firstname {$order}";
             break;
         case DATA_FIRSTNAME:
             $ordering = "u.firstname {$order}, u.lastname {$order}";
             break;
         case DATA_APPROVED:
             $ordering = "r.approved {$order}, r.timecreated {$order}";
             break;
         case DATA_TIMEMODIFIED:
             $ordering = "r.timemodified {$order}";
Example #24
0
 /**
  * Returns the condition to be used with SQL where
  * @param array $data filter settings
  * @return string the filtering condition or null if the filter is disabled
  */
 function get_sql_filter($data)
 {
     $operator = $data['operator'];
     $value = addslashes($data['value']);
     $field = $this->_field;
     $combine_op = ' OR ';
     if ($operator != 5 and $value === '') {
         return '';
     }
     $ilike = sql_ilike();
     switch ($operator) {
         case 0:
             // contains
             $res = "{$ilike} '%{$value}%'";
             break;
         case 1:
             // does not contain
             $res = "NOT {$ilike} '%{$value}%'";
             $combine_op = ' AND ';
             break;
         case 2:
             // equal to
             $res = "{$ilike} '{$value}'";
             break;
         case 3:
             // starts with
             $res = "{$ilike} '{$value}%'";
             break;
         case 4:
             // ends with
             $res = "{$ilike} '%{$value}'";
             break;
         case 5:
             // empty
             $res = "=''";
             break;
         default:
             return '';
     }
     $conditions = array();
     foreach ($this->_fields as $field) {
         $conditions[] = $field . ' ' . $res;
     }
     return '(' . implode($combine_op, $conditions) . ')';
 }
Example #25
0
 function get_sql_where()
 {
     if (!isset($this->columns['fullname'])) {
         return '';
     }
     $LIKE = sql_ilike();
     if (!empty($this->sess->i_first) && !empty($this->sess->i_last)) {
         return 'firstname ' . $LIKE . ' \'' . $this->sess->i_first . '%\' AND lastname ' . $LIKE . ' \'' . $this->sess->i_last . '%\'';
     } else {
         if (!empty($this->sess->i_first)) {
             return 'firstname ' . $LIKE . ' \'' . $this->sess->i_first . '%\'';
         } else {
             if (!empty($this->sess->i_last)) {
                 return 'lastname ' . $LIKE . ' \'' . $this->sess->i_last . '%\'';
             }
         }
     }
     return '';
 }
Example #26
0
/**
 * shortdesc (optional)
 *
 * longdesc
 *
 * @uses $CFG
 * @param string $sort ?
 * @param string $dir ?
 * @param int $categoryid ?
 * @param int $categoryid ?
 * @param string $search ?
 * @param string $firstinitial ?
 * @param string $lastinitial ?
 * @returnobject {@link $USER} records
 * @todo Finish documenting this function
 */
function get_users_listing($sort = 'lastaccess', $dir = 'ASC', $page = 0, $recordsperpage = 0, $search = '', $firstinitial = '', $lastinitial = '', $extraselect = '')
{
    global $CFG;
    $LIKE = sql_ilike();
    $fullname = sql_fullname();
    $select = "deleted <> '1'";
    if (!empty($search)) {
        $search = trim($search);
        $select .= " AND ({$fullname} {$LIKE} '%{$search}%' OR email {$LIKE} '%{$search}%' OR username='******') ";
    }
    if ($firstinitial) {
        $select .= ' AND firstname ' . $LIKE . ' \'' . $firstinitial . '%\' ';
    }
    if ($lastinitial) {
        $select .= ' AND lastname ' . $LIKE . ' \'' . $lastinitial . '%\' ';
    }
    if ($extraselect) {
        $select .= " AND {$extraselect} ";
    }
    if ($sort) {
        $sort = ' ORDER BY ' . $sort . ' ' . $dir;
    }
    /// warning: will return UNCONFIRMED USERS
    return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid\n                              FROM {$CFG->prefix}user\n                             WHERE {$select} {$sort}", $page, $recordsperpage);
}
Example #27
0
if ($context->contextlevel == CONTEXT_SYSTEM) {
    print_box(get_string('globalroleswarning', 'role'));
}
if ($roleid) {
    /// prints a form to swap roles
    /// Get all existing participants in this context.
    // Why is this not done with get_users???
    if (!($contextusers = get_role_users($roleid, $context, false, 'u.id, u.firstname, u.lastname, u.email, ra.hidden'))) {
        $contextusers = array();
    }
    $select = "username <> 'guest' AND deleted = 0 AND confirmed = 1";
    $usercount = count_records_select('user', $select) - count($contextusers);
    $searchtext = trim($searchtext);
    if ($searchtext !== '') {
        // Search for a subset of remaining users
        $LIKE = sql_ilike();
        $FULLNAME = sql_fullname();
        $selectsql = " AND ({$FULLNAME} {$LIKE} '%{$searchtext}%' OR email {$LIKE} '%{$searchtext}%') ";
        $select .= $selectsql;
    } else {
        $selectsql = "";
    }
    if ($context->contextlevel > CONTEXT_COURSE && !is_inside_frontpage($context)) {
        // mod or block (or group?)
        /************************************************************************
         *                                                                      *
         * context level is above or equal course context level                 *
         * in this case we pull out all users matching search criteria (if any) *
         *                                                                      *
         * MDL-11324                                                            *
         * a mini get_users_by_capability() call here, this is done instead of  *
 /**
  * Dummy can_do method for viewing a curriculum report (needed for the
  * cluster tree parameter for reports)
  */
 function can_do_viewreport()
 {
     global $CFG, $CURMAN;
     $id = $this->required_param('id', PARAM_INT);
     //needed for execution mode constants
     require_once $CFG->dirroot . '/blocks/php_report/php_report_base.php';
     //check if we're scheduling or viewing
     $execution_mode = $this->optional_param('execution_mode', php_report::EXECUTION_MODE_SCHEDULED, PARAM_INT);
     //check the correct capability
     $capability = $execution_mode == php_report::EXECUTION_MODE_SCHEDULED ? 'block/php_report:schedule' : 'block/php_report:view';
     if ($this->_has_capability($capability)) {
         return true;
     }
     /*
      * Start of cluster hierarchy extension
      */
     $viewable_clusters = cluster::get_viewable_clusters($capability);
     $cluster_context_level = context_level_base::get_custom_context_level('cluster', 'block_curr_admin');
     $like = sql_ilike();
     $parent_path = sql_concat('parent_context.path', "'/%'");
     //if the user has no additional access through parent clusters, then they can't view this cluster
     if (empty($viewable_clusters)) {
         return false;
     }
     $cluster_filter = implode(',', $viewable_clusters);
     //determine if this cluster is the parent of some accessible child cluster
     $sql = "SELECT parent_context.instanceid\n                FROM {$CURMAN->db->prefix_table('context')} parent_context\n                JOIN {$CURMAN->db->prefix_table('context')} child_context\n                  ON child_context.path {$like} {$parent_path}\n                  AND parent_context.contextlevel = {$cluster_context_level}\n                  AND child_context.contextlevel = {$cluster_context_level}\n                  AND child_context.instanceid IN ({$cluster_filter})\n                  AND parent_context.instanceid = {$id}";
     return record_exists_sql($sql);
     /*
      * End of cluster hierarchy extension
      */
 }
function ewiki_database_moodle($action, &$args, $sw1, $sw2)
{
    global $wiki, $wiki_entry, $CFG;
    #-- result array
    $r = array();
    switch ($action) {
        /*  Returns database entry as array for the page whose name was given
                with the "id" key in the $args array, usually fetches the latest
                version of a page, unless a specific "version" was requested in
                the $args array.
            */
        # Ugly, but we need to choose which wiki we are about to change/read
        case "GET":
            $id = "'" . anydb_escape_string($args["id"]) . "'";
            $version = 0 + @$args["version"] and $version = "AND (version={$version})" or $version = "";
            # $result = mysql_query("SELECT * FROM " . EWIKI_DB_TABLE_NAME
            #   . " WHERE (pagename=$id) $version  ORDER BY version DESC  LIMIT 1"
            #);
            #if ($result && ($r = mysql_fetch_array($result, MYSQL_ASSOC))) {
            #   $r["id"] = $r["pagename"];
            #   unset($r["pagename"]);
            #}
            #if (strlen($r["meta"])) {
            #   $r["meta"] = @unserialize($r["meta"]);
            #}
            $select = "(pagename={$id}) AND wiki=" . $wiki_entry->id . "  {$version} ";
            $sort = "version DESC";
            if ($result_arr = get_records_select(EWIKI_DB_TABLE_NAME, $select, $sort, "*", 0, 1)) {
                //Iterate to get the first (and unique!)
                foreach ($result_arr as $obj) {
                    $result_obj = $obj;
                }
            }
            if ($result_obj) {
                //Convert to array
                $r = get_object_vars($result_obj);
                $r["id"] = $r["pagename"];
                unset($r["pagename"]);
                $r["meta"] = @unserialize($r["meta"]);
            }
            break;
            /*  Increases the hit counter for the page name given in $args array
                    with "id" index key.
                */
        /*  Increases the hit counter for the page name given in $args array
                with "id" index key.
            */
        case "HIT":
            #mysql_query("UPDATE " . EWIKI_DB_TABLE_NAME . " SET hits=(hits+1) WHERE pagename='" . anydb_escape_string($args["id"]) . "'");
            # set_field does not work because of the "hits+1" construct
            #print "DO ".anydb__escape_string($args["id"]); exit;
            execute_sql("UPDATE " . $CFG->prefix . EWIKI_DB_TABLE_NAME . " SET hits=(hits+1) WHERE pagename='" . anydb_escape_string($args["id"]) . "' and wiki=" . $wiki_entry->id, 0);
            break;
            /*  Stores the $data array into the database, while not overwriting
                    existing entries (using WRITE); returns 0 on failure and 1 if
                    saved correctly.
                */
        /*  Stores the $data array into the database, while not overwriting
                existing entries (using WRITE); returns 0 on failure and 1 if
                saved correctly.
            */
        case "OVERWRITE":
            $COMMAND = "REPLACE";
            break;
        case "WRITE":
            $COMMAND = "WRITE";
            $args["pagename"] = $args["id"];
            unset($args["id"]);
            if (is_array($args["meta"])) {
                $args["meta"] = serialize($args["meta"]);
            }
            #$sql1 = $sql2 = "";
            #foreach ($args as $index => $value) {
            #   if (is_int($index)) {
            #      continue;
            #   }
            #   $a = ($sql1 ? ', ' : '');
            #   $sql1 .= $a . $index;
            #   $sql2 .= $a . "'" . anydb_escape_string($value) . "'";
            #}
            #strlen(@$COMMAND) || ($COMMAND = "INSERT");
            foreach ($args as $index => $value) {
                if (is_int($index)) {
                    continue;
                }
                $args[$index] = anydb_escape_string($value);
            }
            $args["wiki"] = $wiki_entry->id;
            # Check if Record exists
            if ($COMMAND == "REPLACE") {
                if (count_records(EWIKI_DB_TABLE_NAME, "wiki", $wiki_entry->id, "pagename", $args["pagename"], "version", $args["version"])) {
                    delete_record(EWIKI_DB_TABLE_NAME, "wiki", $wiki_entry->id, "pagename", $args["pagename"], "version", $args["version"]);
                }
            }
            # Write
            $result = insert_record(EWIKI_DB_TABLE_NAME, (object) $args, false);
            #$result = mysql_query("$COMMAND INTO " . EWIKI_DB_TABLE_NAME .
            #   " (" . $sql1 . ") VALUES (" . $sql2 . ")"
            #);
            #return($result && mysql_affected_rows() ?1:0);
            return $result;
            break;
            /*  Checks for existence of the WikiPages whose names are given in
                    the $args array. Returns an array with the specified WikiPageNames
                    associated with values of "0" or "1" (stating if the page exists
                    in the database). For images/binary db entries returns the "meta"
                    field instead of an "1".
                */
        /*  Checks for existence of the WikiPages whose names are given in
                the $args array. Returns an array with the specified WikiPageNames
                associated with values of "0" or "1" (stating if the page exists
                in the database). For images/binary db entries returns the "meta"
                field instead of an "1".
            */
        case "FIND":
            $select = "";
            foreach (array_values($args) as $id) {
                if (strlen($id)) {
                    $r[$id] = 0;
                    $select .= ($select ? " OR " : "") . "(pagename='" . anydb_escape_string($id) . "')";
                }
            }
            if ($select) {
                $select = "(" . $select . ") AND wiki=" . $wiki_entry->id;
                $result = get_records_select(EWIKI_DB_TABLE_NAME, $select);
                #$sql = "SELECT pagename AS id, meta FROM " .
                #   EWIKI_DB_TABLE_NAME . " WHERE $sql "
                #);
                #while ($result && ($row = mysql_fetch_row($result))) {
                #   $r[$row[0]] = strpos($row[1], 's:5:"image"') ? $row[1] : 1;
                while (list($key, $val) = @each($result)) {
                    $r[$val->pagename] = strpos($val->meta, 's:5:"image"') ? $val->meta : 1;
                }
            }
            break;
            /* Counts the number of Versions
             */
        /* Counts the number of Versions
         */
        case "COUNTVERSIONS":
            $sql = "SELECT pagename AS id, count(*) as versioncount" . " FROM " . $CFG->prefix . EWIKI_DB_TABLE_NAME . " WHERE wiki = " . $wiki_entry->id . " GROUP BY pagename";
            #print "$sql";
            $result = get_records_sql($sql);
            while (list($key, $val) = each($result)) {
                $r[$key] = $val->versioncount;
            }
            break;
            /*  Returns an array of the lastest versions of __all__ pages,
                    where each entry is made up of the fields from the database
                    requested with the $args array, e.g.
                    array("flags","meta","lastmodified");
                */
        /*  Returns an array of the lastest versions of __all__ pages,
                where each entry is made up of the fields from the database
                requested with the $args array, e.g.
                array("flags","meta","lastmodified");
            */
        case "GETALL":
            switch ($CFG->dbfamily) {
                case 'postgres':
                    // All but the latest version eliminated by DISTINCT
                    // ON (pagename)
                    $sql = "SELECT DISTINCT ON (pagename) pagename AS id, " . implode(", ", $args) . " FROM " . $CFG->prefix . EWIKI_DB_TABLE_NAME . " WHERE wiki = " . $wiki_entry->id . " ORDER BY pagename, version DESC";
                    break;
                case 'mysql':
                    // All but the latest version eliminated by
                    // mysql-specific GROUP BY-semantics
                    $sql = "SELECT pagename AS id, " . implode(", ", $args) . " FROM " . $CFG->prefix . EWIKI_DB_TABLE_NAME . " WHERE wiki = " . $wiki_entry->id . " GROUP BY id, version DESC ";
                default:
                    // All but the latest version are here eliminated in
                    // get_records_sql, since it will return an array
                    // with only one result per id-field value. Note,
                    // that for this to work the query needs to order the
                    // records ascending by version, so later versions
                    // will overwrite previous ones in
                    // recordset_to_array. This is not pretty.
                    $sql = "SELECT pagename AS id, " . implode(", ", $args) . " FROM " . $CFG->prefix . EWIKI_DB_TABLE_NAME . " WHERE wiki = " . $wiki_entry->id . " ORDER BY version";
            }
            $result = get_records_sql($sql);
            $r = new ewiki_dbquery_result($args);
            if ($result) {
                foreach ($result as $val) {
                    $r->add(get_object_vars($val));
                }
            }
            break;
            /*  Returns array of database entries (also arrays), where the one
                    specified column matches the specified content string, for example
                    $args = array("content" => "text...piece")
                    is not guaranteed to only search/return the latest version of a page
                */
        /*  Returns array of database entries (also arrays), where the one
                specified column matches the specified content string, for example
                $args = array("content" => "text...piece")
                is not guaranteed to only search/return the latest version of a page
            */
        case "SEARCH":
            $field = implode("", array_keys($args));
            $content = strtolower(implode("", $args));
            if ($field == "id") {
                $field = "pagename";
            }
            $sql = "SELECT pagename AS id, version, flags" . (EWIKI_DBQUERY_BUFFER && $field != "pagename" ? ", {$field}" : "") . " FROM " . $CFG->prefix . EWIKI_DB_TABLE_NAME . " WHERE {$field} " . sql_ilike() . " '%" . anydb_escape_string($content) . "%'  and wiki=" . $wiki_entry->id . " ORDER BY id, version ASC";
            $result = get_records_sql($sql);
            $r = new ewiki_dbquery_result(array("id", "version", $field));
            $drop = "";
            #while ($result && ($row = mysql_fetch_array($result, MYSQL_ASSOC))) {
            #   $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"];
            #   if ($i != $drop) {
            #      $drop = $i;
            #      $r->add($row);
            #   }
            #}
            while (list($key, $val) = @each($result)) {
                $row = get_object_vars($val);
                $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"];
                if ($i != $drop) {
                    $drop = $i;
                    $r->add($row);
                }
            }
            break;
        case "DELETE":
            $id = anydb_escape_string($args["id"]);
            $version = $args["version"];
            #mysql_query("DELETE FROM " . EWIKI_DB_TABLE_NAME ."
            #   WHERE pagename='$id' AND version=$version");
            # print "DELETING wiki:".$wiki_entry->id."Pagename: $id Version: $version <br />\n";
            delete_records(EWIKI_DB_TABLE_NAME, "wiki", $wiki_entry->id, "pagename", $id, "version", $version);
            break;
        case "INIT":
            #mysql_query("CREATE TABLE " . EWIKI_DB_TABLE_NAME ."
            #   (pagename VARCHAR(160) NOT NULL,
            #   version INTEGER UNSIGNED NOT NULL DEFAULT 0,
            #   flags INTEGER UNSIGNED DEFAULT 0,
            #   content MEDIUMTEXT,
            #   author VARCHAR(100) DEFAULT 'ewiki',
            #   created INTEGER UNSIGNED DEFAULT ".time().",
            #   lastmodified INTEGER UNSIGNED DEFAULT 0,
            #   refs MEDIUMTEXT,
            #   meta MEDIUMTEXT,
            #   hits INTEGER UNSIGNED DEFAULT 0,
            #   PRIMARY KEY id (pagename, version) )
            #   ");
            #echo mysql_error();
            break;
        default:
    }
    return $r;
}
Example #30
-1
function forum_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    if ($oldversion < 2002073008) {
        execute_sql("DELETE FROM modules WHERE name = 'discuss' ");
        execute_sql("ALTER TABLE `discuss` RENAME `forum_discussions` ");
        execute_sql("ALTER TABLE `discuss_posts` RENAME `forum_posts` ");
        execute_sql("ALTER TABLE `discuss_ratings` RENAME `forum_ratings` ");
        execute_sql("ALTER TABLE `forum` CHANGE `intro` `intro` TEXT NOT NULL ");
        execute_sql("ALTER TABLE `forum` ADD `forcesubscribe` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `assessed`");
        execute_sql("ALTER TABLE `forum` CHANGE `type` `type` ENUM( 'single', 'news', 'social', 'general', \n                             'eachuser', 'teacher' ) DEFAULT 'general' NOT NULL ");
        execute_sql("ALTER TABLE `forum_posts` CHANGE `discuss` `discussion` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add', 'forum', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name') ");
        execute_sql("DELETE FROM log_display WHERE module = 'discuss' ");
        execute_sql("UPDATE log SET action = 'view discussion' WHERE module = 'discuss' AND action = 'view' ");
        execute_sql("UPDATE log SET action = 'add discussion' WHERE module = 'discuss' AND action = 'add' ");
        execute_sql("UPDATE log SET module = 'forum' WHERE module = 'discuss' ");
        notify("Renamed all the old discuss tables (now part of forum) and created new forum_types");
    }
    if ($oldversion < 2002080100) {
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'update', 'forum', 'name') ");
    }
    if ($oldversion < 2002082900) {
        execute_sql(" ALTER TABLE `forum_posts` ADD `attachment` VARCHAR(100) NOT NULL AFTER `message` ");
    }
    if ($oldversion < 2002091000) {
        if (!execute_sql(" ALTER TABLE `forum_posts` ADD `attachment` VARCHAR(100) NOT NULL AFTER `message` ")) {
            echo "<p>Don't worry about this error - your server already had this upgrade applied";
        }
    }
    if ($oldversion < 2002100300) {
        execute_sql(" ALTER TABLE `forum` CHANGE `open` `open` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL ");
        execute_sql(" UPDATE `forum` SET `open` = 2 WHERE `open` = 1 ");
        execute_sql(" UPDATE `forum` SET `open` = 1 WHERE `open` = 0 ");
    }
    if ($oldversion < 2002101001) {
        execute_sql(" ALTER TABLE `forum_posts` ADD `format` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `message` ");
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `forum_posts` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `forum_ratings` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `forum_subscriptions` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2003042402) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name')");
    }
    if ($oldversion < 2003081403) {
        table_column("forum", "assessed", "assessed", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003082500) {
        table_column("forum", "", "assesstimestart", "integer", "10", "unsigned", "0", "", "assessed");
        table_column("forum", "", "assesstimefinish", "integer", "10", "unsigned", "0", "", "assesstimestart");
    }
    if ($oldversion < 2003082502) {
        table_column("forum", "scale", "scale", "integer", "10", "", "0");
        execute_sql("UPDATE {$CFG->prefix}forum SET scale = (- scale)");
    }
    if ($oldversion < 2003100600) {
        table_column("forum", "", "maxbytes", "integer", "10", "unsigned", "0", "", "scale");
    }
    if ($oldversion < 2004010100) {
        table_column("forum", "", "assesspublic", "integer", "4", "unsigned", "0", "", "assessed");
    }
    if ($oldversion < 2004011404) {
        table_column("forum_discussions", "", "userid", "integer", "10", "unsigned", "0", "", "firstpost");
        if ($discussions = get_records_sql("SELECT d.id, p.userid\n                                            FROM {$CFG->prefix}forum_discussions as d, \n                                                 {$CFG->prefix}forum_posts as p\n                                           WHERE d.firstpost = p.id")) {
            foreach ($discussions as $discussion) {
                update_record("forum_discussions", $discussion);
            }
        }
    }
    if ($oldversion < 2004012200) {
        table_column("forum_discussions", "", "groupid", "integer", "10", "unsigned", "0", "", "userid");
    }
    if ($oldversion < 2004013000) {
        table_column("forum_posts", "mailed", "mailed", "tinyint", "2");
    }
    if ($oldversion < 2004020600) {
        table_column("forum_discussions", "", "usermodified", "integer", "10", "unsigned", "0", "", "timemodified");
    }
    if ($oldversion < 2004050300) {
        table_column("forum", "", "rsstype", "tinyint", "2", "unsigned", "0", "", "forcesubscribe");
        table_column("forum", "", "rssarticles", "tinyint", "2", "unsigned", "0", "", "rsstype");
        set_config("forum_enablerssfeeds", 0);
    }
    if ($oldversion < 2004060100) {
        modify_database('', "CREATE TABLE `prefix_forum_queue` (\n                                `id` int(11) unsigned NOT NULL auto_increment,\n                                `userid` int(11) unsigned default 0 NOT NULL,\n                                `discussionid` int(11) unsigned default 0 NOT NULL,\n                                `postid` int(11) unsigned default 0 NOT NULL,\n                                PRIMARY KEY  (`id`),\n                                KEY `user` (userid),\n                                KEY `post` (postid)\n                              ) TYPE=MyISAM COMMENT='For keeping track of posts that will be mailed in digest form';");
    }
    if ($oldversion < 2004070700) {
        // This may be redoing it from STABLE but that's OK
        table_column("forum_discussions", "groupid", "groupid", "integer", "10", "", "0", "");
    }
    if ($oldversion < 2004111700) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_parent_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_discussion_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_userid_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` DROP INDEX {$CFG->prefix}forum_discussions_forum_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` DROP INDEX {$CFG->prefix}forum_discussions_userid_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_parent_idx (parent) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_discussion_idx (discussion) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_userid_idx (userid) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` ADD INDEX {$CFG->prefix}forum_discussions_forum_idx (forum) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` ADD INDEX {$CFG->prefix}forum_discussions_userid_idx (userid) ");
    }
    if ($oldversion < 2004111700) {
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_ratings DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_ratings DROP INDEX post;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_subscriptions DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_subscriptions DROP INDEX forum;", false);
        modify_database('', 'ALTER TABLE prefix_forum ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_forum_ratings ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_forum_ratings ADD INDEX post (post);');
        modify_database('', 'ALTER TABLE prefix_forum_subscriptions ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_forum_subscriptions ADD INDEX forum (forum);');
    }
    if ($oldversion < 2005011500) {
        modify_database('', 'CREATE TABLE prefix_forum_read (
                  `id` int(10) unsigned NOT NULL auto_increment, 
                  `userid` int(10) NOT NULL default \'0\',
                  `forumid` int(10) NOT NULL default \'0\',
                  `discussionid` int(10) NOT NULL default \'0\',
                  `postid` int(10) NOT NULL default \'0\',
                  `firstread` int(10) NOT NULL default \'0\',
                  `lastread` int(10) NOT NULL default \'0\',
                  PRIMARY KEY  (`id`),
                  KEY `prefix_forum_user_forum_idx` (`userid`,`forumid`),
                  KEY `prefix_forum_user_discussion_idx` (`userid`,`discussionid`),
                  KEY `prefix_forum_user_post_idx` (`userid`,`postid`)
                  ) COMMENT=\'Tracks each users read posts\';');
        set_config('upgrade', 'forumread');
        // The upgrade of this table will be done later by admin/upgradeforumread.php
    }
    if ($oldversion < 2005032900) {
        modify_database('', 'ALTER TABLE prefix_forum_posts ADD INDEX prefix_form_posts_created_idx (created);');
        modify_database('', 'ALTER TABLE prefix_forum_posts ADD INDEX prefix_form_posts_mailed_idx (mailed);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}forum_discussions, {$CFG->prefix}forum_posts ";
        $sql .= "where {$CFG->prefix}forum_posts.discussion = {$CFG->prefix}forum_discussions.id ";
        $sql .= "and {$CFG->prefix}forum_posts.id = ";
        $wtm->update('forum_posts', 'message', 'format', $sql);
    }
    if ($oldversion < 2005042300) {
        // Add tracking prefs table
        modify_database('', 'CREATE TABLE prefix_forum_track_prefs (
                  `id` int(10) unsigned NOT NULL auto_increment, 
                  `userid` int(10) NOT NULL default \'0\',
                  `forumid` int(10) NOT NULL default \'0\',
                  PRIMARY KEY  (`id`),
                  KEY `user_forum_idx` (`userid`,`forumid`)
                  ) COMMENT=\'Tracks each users untracked forums.\';');
    }
    if ($oldversion < 2005042500) {
        table_column('forum', '', 'trackingtype', 'tinyint', '2', 'unsigned', '1', '', 'forcesubscribe');
    }
    if ($oldversion < 2005111100) {
        table_column('forum_discussions', '', 'timestart', 'integer');
        table_column('forum_discussions', '', 'timeend', 'integer');
    }
    if ($oldversion < 2006011600) {
        execute_sql("alter table " . $CFG->prefix . "forum change column type type enum('single','news','general','social','eachuser','teacher','qanda') not null default 'general'");
    }
    if ($oldversion < 2006011601) {
        table_column('forum', '', 'warnafter');
        table_column('forum', '', 'blockafter');
        table_column('forum', '', 'blockperiod');
    }
    if ($oldversion < 2006011700) {
        table_column('forum_posts', '', 'mailnow', 'integer');
    }
    if ($oldversion < 2006011702) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'CONCAT(firstname,\\' \\',lastname)')");
    }
    if ($oldversion < 2006081800) {
        // Upgrades for new roles and capabilities support.
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        $forummod = get_record('modules', 'name', 'forum');
        if ($forums = get_records('forum')) {
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notify('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notify('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
                notify('Default guest role was not found. Roles and permissions ' . 'for teacher forums will have to be manually set after ' . 'this upgrade.');
            }
            foreach ($forums as $forum) {
                if (!forum_convert_to_roles($forum, $forummod->id, $teacherroles, $studentroles, $guestroles)) {
                    notify('Forum with id ' . $forum->id . ' was not upgraded');
                }
            }
            // We need to rebuild all the course caches to refresh the state of
            // the forum modules.
            include_once "{$CFG->dirroot}/course/lib.php";
            rebuild_course_cache();
        }
        // End if.
        // Drop column forum.open.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN open;');
        // Drop column forum.assesspublic.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN assesspublic;');
    }
    if ($oldversion < 2006082700) {
        $sql = "UPDATE {$CFG->prefix}forum_posts SET message = REPLACE(message, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('forum_posts', "message {$likecond}")) {
                break;
            }
            execute_sql($sql);
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}