function validation($data, $files)
 {
     global $CFG, $db, $USER;
     $errors = parent::validation($data, $files);
     $sql = stripslashes($data['querysql']);
     // Simple test to avoid evil stuff in the SQL.
     if (report_customsql_contains_bad_word($sql)) {
         $errors['querysql'] = get_string('notallowedwords', 'report_customsql', implode(', ', report_customsql_bad_words_list()));
         // Do not allow any semicolons.
     } else {
         if (strpos($sql, ';') !== false) {
             $errors['querysql'] = get_string('nosemicolon', 'report_customsql');
             // Make sure prefix is prefix_, not explicit.
         } else {
             if ($CFG->prefix != '' && preg_match('/\\b' . $CFG->prefix . '\\w+/i', $sql)) {
                 $errors['querysql'] = get_string('noexplicitprefix', 'report_customsql', $CFG->prefix);
                 // Now try running the SQL, and ensure it runs without errors.
             } else {
                 $report = new stdClass();
                 $report->querysql = $sql;
                 $report->runable = $data['runable'];
                 $sql = report_customsql_prepare_sql($report, time());
                 $rs = report_customsql_execute_query($sql, 2);
                 if (!$rs) {
                     $errors['querysql'] = get_string('queryfailed', 'report_customsql', $db->ErrorMsg());
                 } else {
                     if (!empty($data['singlerow'])) {
                         if (rs_EOF($rs)) {
                             $errors['querysql'] = get_string('norowsreturned', 'report_customsql');
                         } else {
                             rs_fetch_next_record($rs);
                             if (!rs_EOF($rs)) {
                                 $errors['querysql'] = get_string('morethanonerowreturned', 'report_customsql');
                             }
                         }
                     }
                 }
                 if ($rs) {
                     rs_close($rs);
                 }
             }
         }
     }
     return $errors;
 }
示例#2
0
 function validation($data, $files)
 {
     global $DB, $CFG, $db, $USER;
     $errors = parent::validation($data, $files);
     $sql = $data['querysql'];
     $sql = trim($sql);
     // Simple test to avoid evil stuff in the SQL.
     if (preg_match('/\\b(ALTER|CREATE|DELETE|DROP|GRANT|INSERT|INTO|TRUNCATE|UPDATE|SET|VACUUM|REINDEX|DISCARD|LOCK)\\b/i', $sql)) {
         $errors['querysql'] = get_string('notallowedwords', 'block_configurable_reports');
         // Do not allow any semicolons.
     } else {
         if (strpos($sql, ';') !== false) {
             $errors['querysql'] = get_string('nosemicolon', 'report_customsql');
             // Make sure prefix is prefix_, not explicit.
         } else {
             if ($CFG->prefix != '' && preg_match('/\\b' . $CFG->prefix . '\\w+/i', $sql)) {
                 $errors['querysql'] = get_string('noexplicitprefix', 'block_configurable_reports');
                 // Now try running the SQL, and ensure it runs without errors.
             } else {
                 $sql = $this->_customdata['reportclass']->prepare_sql($sql);
                 $rs = $this->_customdata['reportclass']->execute_query($sql, 2);
                 if (!$rs) {
                     $errors['querysql'] = get_string('queryfailed', 'block_configurable_reports', $db->ErrorMsg());
                 } else {
                     if (!empty($data['singlerow'])) {
                         if (rs_EOF($rs)) {
                             $errors['querysql'] = get_string('norowsreturned', 'block_configurable_reports');
                         }
                     }
                 }
                 if ($rs) {
                     $rs->close();
                 }
             }
         }
     }
     return $errors;
 }
function backup_user_info($bf, $preferences)
{
    global $CFG;
    require_once $CFG->dirroot . '/tag/lib.php';
    $status = true;
    // Use a recordset to for the memory handling on to
    // the DB and run faster
    // Note the outer join with mnet_host: It shouldn't be neccesary
    // but there are some sites having mnet_host records missing
    // and that causes backup to fail (no users). Being a bit more
    // flexible here (outer joing) we bypass the problem and doesn't
    // cause more troubles. Eloy - MDL-16879
    $users = get_recordset_sql("SELECT b.old_id, b.table_name, b.info,\n                                           u.*, m.wwwroot\n                                    FROM   {$CFG->prefix}backup_ids b\n                                      JOIN {$CFG->prefix}user       u ON b.old_id=u.id\n                                      LEFT JOIN {$CFG->prefix}mnet_host  m ON u.mnethostid=m.id\n                                    WHERE b.backup_code = '{$preferences->backup_unique_code}' AND\n                                          b.table_name = 'user'");
    //If we have users to backup
    if ($users && !rs_EOF($users)) {
        //Begin Users tag
        fwrite($bf, start_tag("USERS", 2, true));
        $counter = 0;
        //With every user
        while ($user = rs_fetch_next_record($users)) {
            //Begin User tag
            fwrite($bf, start_tag("USER", 3, true));
            //Output all user data
            fwrite($bf, full_tag("ID", 4, false, $user->id));
            fwrite($bf, full_tag("AUTH", 4, false, $user->auth));
            fwrite($bf, full_tag("CONFIRMED", 4, false, $user->confirmed));
            fwrite($bf, full_tag("POLICYAGREED", 4, false, $user->policyagreed));
            fwrite($bf, full_tag("DELETED", 4, false, $user->deleted));
            fwrite($bf, full_tag("USERNAME", 4, false, $user->username));
            // Prevent user passwords in backup files unless
            // $CFG->includeuserpasswordsinbackup is defined. MDL-20838
            if (!empty($CFG->includeuserpasswordsinbackup)) {
                fwrite($bf, full_tag("PASSWORD", 4, false, $user->password));
            }
            fwrite($bf, full_tag("IDNUMBER", 4, false, $user->idnumber));
            fwrite($bf, full_tag("FIRSTNAME", 4, false, $user->firstname));
            fwrite($bf, full_tag("LASTNAME", 4, false, $user->lastname));
            fwrite($bf, full_tag("EMAIL", 4, false, $user->email));
            fwrite($bf, full_tag("EMAILSTOP", 4, false, $user->emailstop));
            fwrite($bf, full_tag("ICQ", 4, false, $user->icq));
            fwrite($bf, full_tag("SKYPE", 4, false, $user->skype));
            fwrite($bf, full_tag("YAHOO", 4, false, $user->yahoo));
            fwrite($bf, full_tag("AIM", 4, false, $user->aim));
            fwrite($bf, full_tag("MSN", 4, false, $user->msn));
            fwrite($bf, full_tag("PHONE1", 4, false, $user->phone1));
            fwrite($bf, full_tag("PHONE2", 4, false, $user->phone2));
            fwrite($bf, full_tag("INSTITUTION", 4, false, $user->institution));
            fwrite($bf, full_tag("DEPARTMENT", 4, false, $user->department));
            fwrite($bf, full_tag("ADDRESS", 4, false, $user->address));
            fwrite($bf, full_tag("CITY", 4, false, $user->city));
            fwrite($bf, full_tag("COUNTRY", 4, false, $user->country));
            fwrite($bf, full_tag("LANG", 4, false, $user->lang));
            fwrite($bf, full_tag("THEME", 4, false, $user->theme));
            fwrite($bf, full_tag("TIMEZONE", 4, false, $user->timezone));
            fwrite($bf, full_tag("FIRSTACCESS", 4, false, $user->firstaccess));
            fwrite($bf, full_tag("LASTACCESS", 4, false, $user->lastaccess));
            fwrite($bf, full_tag("LASTLOGIN", 4, false, $user->lastlogin));
            fwrite($bf, full_tag("CURRENTLOGIN", 4, false, $user->currentlogin));
            fwrite($bf, full_tag("LASTIP", 4, false, $user->lastip));
            fwrite($bf, full_tag("PICTURE", 4, false, $user->picture));
            fwrite($bf, full_tag("URL", 4, false, $user->url));
            fwrite($bf, full_tag("DESCRIPTION", 4, false, $user->description));
            fwrite($bf, full_tag("MAILFORMAT", 4, false, $user->mailformat));
            fwrite($bf, full_tag("MAILDIGEST", 4, false, $user->maildigest));
            fwrite($bf, full_tag("MAILDISPLAY", 4, false, $user->maildisplay));
            fwrite($bf, full_tag("HTMLEDITOR", 4, false, $user->htmleditor));
            fwrite($bf, full_tag("AJAX", 4, false, $user->ajax));
            fwrite($bf, full_tag("AUTOSUBSCRIBE", 4, false, $user->autosubscribe));
            fwrite($bf, full_tag("TRACKFORUMS", 4, false, $user->trackforums));
            if ($user->mnethostid != $CFG->mnet_localhost_id && !empty($user->wwwroot)) {
                fwrite($bf, full_tag("MNETHOSTURL", 4, false, $user->wwwroot));
            }
            fwrite($bf, full_tag("TIMEMODIFIED", 4, false, $user->timemodified));
            /// write assign/override code for context_userid
            $user->isneeded = strpos($user->info, "needed");
            fwrite($bf, start_tag("ROLES", 4, true));
            if ($user->info != "needed" && $user->info != "") {
                //PRINT ROLE INFO
                $roles = explode(",", $user->info);
                foreach ($roles as $role) {
                    if ($role != "" && $role != "needed") {
                        fwrite($bf, start_tag("ROLE", 5, true));
                        //Print Role info
                        fwrite($bf, full_tag("TYPE", 6, false, $role));
                        //Print ROLE end
                        fwrite($bf, end_tag("ROLE", 5, true));
                    }
                }
            }
            //Needed
            if ($user->isneeded !== false) {
                //Print ROLE start
                fwrite($bf, start_tag("ROLE", 5, true));
                //Print Role info
                fwrite($bf, full_tag("TYPE", 6, false, "needed"));
                //Print ROLE end
                fwrite($bf, end_tag("ROLE", 5, true));
            }
            //End ROLES tag
            fwrite($bf, end_tag("ROLES", 4, true));
            //Check if we have custom profile fields to backup
            if ($cpfields = get_records_sql("SELECT uif.shortname, uif.datatype, uidata.data\n                                                 FROM {$CFG->prefix}user_info_field uif,\n                                                      {$CFG->prefix}user_info_data uidata\n                                                 WHERE uif.id = uidata.fieldid\n                                                   AND uidata.userid = {$user->id}")) {
                //Start USER_CUSTOM_PROFILE_FIELDS tag
                fwrite($bf, start_tag("USER_CUSTOM_PROFILE_FIELDS", 4, true));
                //Write custom profile fields
                foreach ($cpfields as $cpfield) {
                    fwrite($bf, start_tag("USER_CUSTOM_PROFILE_FIELD", 5, true));
                    fwrite($bf, full_tag("FIELD_NAME", 6, false, $cpfield->shortname));
                    fwrite($bf, full_tag("FIELD_TYPE", 6, false, $cpfield->datatype));
                    fwrite($bf, full_tag("FIELD_DATA", 6, false, $cpfield->data));
                    fwrite($bf, end_tag("USER_CUSTOM_PROFILE_FIELD", 5, true));
                }
                //End USER_CUSTOM_PROFILE_FIELDS tag
                fwrite($bf, end_tag("USER_CUSTOM_PROFILE_FIELDS", 4, true));
            }
            //Check if we have user tags to backup
            if (!empty($CFG->usetags)) {
                if ($tags = tag_get_tags('user', $user->id)) {
                    //This return them ordered by default
                    //Start USER_TAGS tag
                    fwrite($bf, start_tag("USER_TAGS", 4, true));
                    //Write user tags fields
                    foreach ($tags as $tag) {
                        fwrite($bf, start_tag("USER_TAG", 5, true));
                        fwrite($bf, full_tag("NAME", 6, false, $tag->name));
                        fwrite($bf, full_tag("RAWNAME", 6, false, $tag->rawname));
                        fwrite($bf, end_tag("USER_TAG", 5, true));
                    }
                    //End USER_TAGS tag
                    fwrite($bf, end_tag("USER_TAGS", 4, true));
                }
            }
            //Check if we have user_preferences to backup
            if ($preferences_data = get_records("user_preferences", "userid", $user->old_id)) {
                //Start USER_PREFERENCES tag
                fwrite($bf, start_tag("USER_PREFERENCES", 4, true));
                //Write each user_preference
                foreach ($preferences_data as $user_preference) {
                    fwrite($bf, start_tag("USER_PREFERENCE", 5, true));
                    fwrite($bf, full_tag("NAME", 6, false, $user_preference->name));
                    fwrite($bf, full_tag("VALUE", 6, false, $user_preference->value));
                    fwrite($bf, end_tag("USER_PREFERENCE", 5, true));
                }
                //End USER_PREFERENCES tag
                fwrite($bf, end_tag("USER_PREFERENCES", 4, true));
            }
            $context = get_context_instance(CONTEXT_USER, $user->old_id);
            write_role_overrides_xml($bf, $context, 4);
            /// write role_assign code here
            write_role_assignments_xml($bf, $preferences, $context, 4);
            //End User tag
            fwrite($bf, end_tag("USER", 3, true));
            //Do some output
            $counter++;
            if ($counter % 10 == 0) {
                echo ".";
                if ($counter % 200 == 0) {
                    echo "<br />";
                }
                backup_flush(300);
            }
        }
        //End Users tag
        fwrite($bf, end_tag("USERS", 2, true));
    } else {
        // There aren't any users.
        $status = true;
    }
    if ($users) {
        rs_close($users);
    }
    return $status;
}
示例#4
0
/**
 * Get an array of data from one or more fields from a database
 * use to get a column, or a series of distinct values
 *
 * @uses $CFG
 * @uses $db
 * @param string $sql The SQL string you wish to be executed.
 * @return mixed|false Returns the value return from the SQL statment or false if an error occured.
 * @todo Finish documenting this function
 */
function get_fieldset_sql($sql)
{
    global $db, $CFG;
    if (defined('MDL_PERFDB')) {
        global $PERF;
        $PERF->dbqueries++;
    }
    $rs = $db->Execute($sql);
    if (!$rs) {
        debugging($db->ErrorMsg() . '<br /><br />' . s($sql));
        if (!empty($CFG->dblogerror)) {
            $debug = array_shift(debug_backtrace());
            error_log("SQL " . $db->ErrorMsg() . " in {$debug['file']} on line {$debug['line']}. STATEMENT:  {$sql}");
        }
        return false;
    }
    if (!rs_EOF($rs)) {
        $keys = array_keys($rs->fields);
        $key0 = $keys[0];
        $results = array();
        while (!$rs->EOF) {
            array_push($results, $rs->fields[$key0]);
            $rs->MoveNext();
        }
        /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
        /// to '' (empty string) for Oracle. It's the only way to work with
        /// all those NOT NULL DEFAULT '' fields until we definetively delete them
        if ($CFG->dbfamily == 'oracle') {
            array_walk($results, 'onespace2empty');
        }
        /// End of DIRTY HACK
        rs_close($rs);
        return $results;
    } else {
        rs_close($rs);
        return false;
    }
}
示例#5
0
    function validation_low_security($data, $files) {
        global $DB, $CFG, $db, $USER;

        $errors = parent::validation($data, $files);

        $sql = $data['querysql'];
        $sql = trim($sql);


        if (empty($this->_customdata['report']->runstatistics) OR $this->_customdata['report']->runstatistics == 0) {
            // Simple test to avoid evil stuff in the SQL.
            //if (preg_match('/\b(ALTER|CREATE|DELETE|DROP|GRANT|INSERT|INTO|TRUNCATE|UPDATE|SET|VACUUM|REINDEX|DISCARD|LOCK)\b/i', $sql)) {
            // Allow cron SQL queries to run CREATE|INSERT|INTO queries.
            if (preg_match('/\b(ALTER|DELETE|DROP|GRANT|TRUNCATE|UPDATE|SET|VACUUM|REINDEX|DISCARD|LOCK)\b/i', $sql)) {
                $errors['querysql'] = get_string('notallowedwords', 'block_cobalt_reports');
            }

            // Now try running the SQL, and ensure it runs without errors.
        } else {

            $sql = $this->_customdata['reportclass']->prepare_sql($sql);
            $rs = $this->_customdata['reportclass']->execute_query($sql, 2);
            if (!$rs) {
                $errors['querysql'] = get_string('queryfailed', 'block_cobalt_reports', $db->ErrorMsg());
            } else if (!empty($data['singlerow'])) {
                if (rs_EOF($rs)) {
                    $errors['querysql'] = get_string('norowsreturned', 'block_cobalt_reports');
                }
            }

            if ($rs) {
                $rs->close();
            }
        }

        return $errors;
    }
示例#6
0
文件: lib.php 项目: r007/PMoodle
/**
 * Function to be run periodically according to the moodle cron
 * Finds all posts that have yet to be mailed out, and mails them
 * out to all subscribers
 * @return void
 */
function forum_cron()
{
    global $CFG, $USER;
    $cronuser = clone $USER;
    $site = get_site();
    // all users that are subscribed to any post that needs sending
    $users = array();
    // status arrays
    $mailcount = array();
    $errorcount = array();
    // caches
    $discussions = array();
    $forums = array();
    $courses = array();
    $coursemodules = array();
    $subscribedusers = array();
    // Posts older than 2 days will not be mailed.  This is to avoid the problem where
    // cron has not been running for a long time, and then suddenly people are flooded
    // with mail from the past few weeks or months
    $timenow = time();
    $endtime = $timenow - $CFG->maxeditingtime;
    $starttime = $endtime - 48 * 3600;
    // Two days earlier
    if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
        // Mark them all now as being mailed.  It's unlikely but possible there
        // might be an error later so that a post is NOT actually mailed out,
        // but since mail isn't crucial, we can accept this risk.  Doing it now
        // prevents the risk of duplicated mails, which is a worse problem.
        if (!forum_mark_old_posts_as_mailed($endtime)) {
            mtrace('Errors occurred while trying to mark some posts as being mailed.');
            return false;
            // Don't continue trying to mail them, in case we are in a cron loop
        }
        // checking post validity, and adding users to loop through later
        foreach ($posts as $pid => $post) {
            $discussionid = $post->discussion;
            if (!isset($discussions[$discussionid])) {
                if ($discussion = get_record('forum_discussions', 'id', $post->discussion)) {
                    $discussions[$discussionid] = $discussion;
                } else {
                    mtrace('Could not find discussion ' . $discussionid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            $forumid = $discussions[$discussionid]->forum;
            if (!isset($forums[$forumid])) {
                if ($forum = get_record('forum', 'id', $forumid)) {
                    $forums[$forumid] = $forum;
                } else {
                    mtrace('Could not find forum ' . $forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            $courseid = $forums[$forumid]->course;
            if (!isset($courses[$courseid])) {
                if ($course = get_record('course', 'id', $courseid)) {
                    $courses[$courseid] = $course;
                } else {
                    mtrace('Could not find course ' . $courseid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            if (!isset($coursemodules[$forumid])) {
                if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
                    $coursemodules[$forumid] = $cm;
                } else {
                    mtrace('Could not course module for forum ' . $forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            // caching subscribed users of each forum
            if (!isset($subscribedusers[$forumid])) {
                if ($subusers = forum_subscribed_users($courses[$courseid], $forums[$forumid], 0, false)) {
                    foreach ($subusers as $postuser) {
                        // do not try to mail users with stopped email
                        if ($postuser->emailstop) {
                            if (!empty($CFG->forum_logblocked)) {
                                add_to_log(SITEID, 'forum', 'mail blocked', '', '', 0, $postuser->id);
                            }
                            continue;
                        }
                        // this user is subscribed to this forum
                        $subscribedusers[$forumid][$postuser->id] = $postuser->id;
                        // this user is a user we have to process later
                        $users[$postuser->id] = $postuser;
                    }
                    unset($subusers);
                    // release memory
                }
            }
            $mailcount[$pid] = 0;
            $errorcount[$pid] = 0;
        }
    }
    if ($users && $posts) {
        $urlinfo = parse_url($CFG->wwwroot);
        $hostname = $urlinfo['host'];
        foreach ($users as $userto) {
            @set_time_limit(120);
            // terminate if processing of any account takes longer than 2 minutes
            // set this so that the capabilities are cached, and environment matches receiving user
            $USER = $userto;
            mtrace('Processing user ' . $userto->id);
            // init caches
            $userto->viewfullnames = array();
            $userto->canpost = array();
            $userto->markposts = array();
            $userto->enrolledin = array();
            // reset the caches
            foreach ($coursemodules as $forumid => $unused) {
                $coursemodules[$forumid]->cache = new object();
                $coursemodules[$forumid]->cache->caps = array();
                unset($coursemodules[$forumid]->uservisible);
            }
            foreach ($posts as $pid => $post) {
                // Set up the environment for the post, discussion, forum, course
                $discussion = $discussions[$post->discussion];
                $forum = $forums[$discussion->forum];
                $course = $courses[$forum->course];
                $cm =& $coursemodules[$forum->id];
                // Do some checks  to see if we can bail out now
                if (!isset($subscribedusers[$forum->id][$userto->id])) {
                    continue;
                    // user does not subscribe to this forum
                }
                // Verify user is enrollend in course - if not do not send any email
                if (!isset($userto->enrolledin[$course->id])) {
                    $userto->enrolledin[$course->id] = has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $course->id));
                }
                if (!$userto->enrolledin[$course->id]) {
                    // oops - this user should not receive anything from this course
                    continue;
                }
                // Get info about the sending user
                if (array_key_exists($post->userid, $users)) {
                    // we might know him/her already
                    $userfrom = $users[$post->userid];
                } else {
                    if ($userfrom = get_record('user', 'id', $post->userid)) {
                        $users[$userfrom->id] = $userfrom;
                        // fetch only once, we can add it to user list, it will be skipped anyway
                    } else {
                        mtrace('Could not find user ' . $post->userid);
                        continue;
                    }
                }
                // setup global $COURSE properly - needed for roles and languages
                course_setup($course);
                // More environment
                // Fill caches
                if (!isset($userto->viewfullnames[$forum->id])) {
                    $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                    $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                if (!isset($userto->canpost[$discussion->id])) {
                    $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                    $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                }
                if (!isset($userfrom->groups[$forum->id])) {
                    if (!isset($userfrom->groups)) {
                        $userfrom->groups = array();
                        $users[$userfrom->id]->groups = array();
                    }
                    $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                    $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                }
                // Make sure groups allow this user to see this email
                if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
                    // Groups are being used
                    if (!groups_group_exists($discussion->groupid)) {
                        // Can't find group
                        continue;
                        // Be safe and don't send it to anyone
                    }
                    if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
                        // do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
                        continue;
                    }
                }
                // Make sure we're allowed to see it...
                if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
                    mtrace('user ' . $userto->id . ' can not see ' . $post->id);
                    continue;
                }
                // OK so we need to send the email.
                // Does the user want this post in a digest?  If so postpone it for now.
                if ($userto->maildigest > 0) {
                    // This user wants the mails to be in digest form
                    $queue = new object();
                    $queue->userid = $userto->id;
                    $queue->discussionid = $discussion->id;
                    $queue->postid = $post->id;
                    $queue->timemodified = $post->created;
                    if (!insert_record('forum_queue', $queue)) {
                        mtrace("Error: mod/forum/cron.php: Could not queue for digest mail for id {$post->id} to user {$userto->id} ({$userto->email}) .. not trying again.");
                    }
                    continue;
                }
                // Prepare to actually send the post now, and build up the content
                $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
                $userfrom->customheaders = array('Precedence: Bulk', 'List-Id: "' . $cleanforumname . '" <moodleforum' . $forum->id . '@' . $hostname . '>', 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id, 'Message-ID: <moodlepost' . $post->id . '@' . $hostname . '>', 'In-Reply-To: <moodlepost' . $post->parent . '@' . $hostname . '>', 'References: <moodlepost' . $post->parent . '@' . $hostname . '>', 'X-Course-Id: ' . $course->id, 'X-Course-Name: ' . format_string($course->fullname, true));
                $postsubject = "{$course->shortname}: " . format_string($post->subject, true);
                $posttext = forum_make_mail_text($course, $forum, $discussion, $post, $userfrom, $userto);
                $posthtml = forum_make_mail_html($course, $forum, $discussion, $post, $userfrom, $userto);
                // Send the post now!
                mtrace('Sending ', '');
                if (!($mailresult = email_to_user($userto, $userfrom, $postsubject, $posttext, $posthtml, '', '', $CFG->forum_replytouser))) {
                    mtrace("Error: mod/forum/cron.php: Could not send out mail for id {$post->id} to user {$userto->id}" . " ({$userto->email}) .. not trying again.");
                    add_to_log($course->id, 'forum', 'mail error', "discuss.php?d={$discussion->id}#p{$post->id}", substr(format_string($post->subject, true), 0, 30), $cm->id, $userto->id);
                    $errorcount[$post->id]++;
                } else {
                    if ($mailresult === 'emailstop') {
                        // should not be reached anymore - see check above
                    } else {
                        $mailcount[$post->id]++;
                        // Mark post as read if forum_usermarksread is set off
                        if (!$CFG->forum_usermarksread) {
                            $userto->markposts[$post->id] = $post->id;
                        }
                    }
                }
                mtrace('post ' . $post->id . ': ' . $post->subject);
            }
            // mark processed posts as read
            forum_tp_mark_posts_read($userto, $userto->markposts);
        }
    }
    if ($posts) {
        foreach ($posts as $post) {
            mtrace($mailcount[$post->id] . " users were sent post {$post->id}, '{$post->subject}'");
            if ($errorcount[$post->id]) {
                set_field("forum_posts", "mailed", "2", "id", "{$post->id}");
            }
        }
    }
    // release some memory
    unset($subscribedusers);
    unset($mailcount);
    unset($errorcount);
    $USER = clone $cronuser;
    course_setup(SITEID);
    $sitetimezone = $CFG->timezone;
    // Now see if there are any digest mails waiting to be sent, and if we should send them
    mtrace('Starting digest processing...');
    @set_time_limit(300);
    // terminate if not able to fetch all digests in 5 minutes
    if (!isset($CFG->digestmailtimelast)) {
        // To catch the first time
        set_config('digestmailtimelast', 0);
    }
    $timenow = time();
    $digesttime = usergetmidnight($timenow, $sitetimezone) + $CFG->digestmailtime * 3600;
    // Delete any really old ones (normally there shouldn't be any)
    $weekago = $timenow - 7 * 24 * 3600;
    delete_records_select('forum_queue', "timemodified < {$weekago}");
    mtrace('Cleaned old digest records');
    if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
        mtrace('Sending forum digests: ' . userdate($timenow, '', $sitetimezone));
        $digestposts_rs = get_recordset_select('forum_queue', "timemodified < {$digesttime}");
        if (!rs_EOF($digestposts_rs)) {
            // We have work to do
            $usermailcount = 0;
            //caches - reuse the those filled before too
            $discussionposts = array();
            $userdiscussions = array();
            while ($digestpost = rs_fetch_next_record($digestposts_rs)) {
                if (!isset($users[$digestpost->userid])) {
                    if ($user = get_record('user', 'id', $digestpost->userid)) {
                        $users[$digestpost->userid] = $user;
                    } else {
                        continue;
                    }
                }
                $postuser = $users[$digestpost->userid];
                if ($postuser->emailstop) {
                    if (!empty($CFG->forum_logblocked)) {
                        add_to_log(SITEID, 'forum', 'mail blocked', '', '', 0, $postuser->id);
                    }
                    continue;
                }
                if (!isset($posts[$digestpost->postid])) {
                    if ($post = get_record('forum_posts', 'id', $digestpost->postid)) {
                        $posts[$digestpost->postid] = $post;
                    } else {
                        continue;
                    }
                }
                $discussionid = $digestpost->discussionid;
                if (!isset($discussions[$discussionid])) {
                    if ($discussion = get_record('forum_discussions', 'id', $discussionid)) {
                        $discussions[$discussionid] = $discussion;
                    } else {
                        continue;
                    }
                }
                $forumid = $discussions[$discussionid]->forum;
                if (!isset($forums[$forumid])) {
                    if ($forum = get_record('forum', 'id', $forumid)) {
                        $forums[$forumid] = $forum;
                    } else {
                        continue;
                    }
                }
                $courseid = $forums[$forumid]->course;
                if (!isset($courses[$courseid])) {
                    if ($course = get_record('course', 'id', $courseid)) {
                        $courses[$courseid] = $course;
                    } else {
                        continue;
                    }
                }
                if (!isset($coursemodules[$forumid])) {
                    if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
                        $coursemodules[$forumid] = $cm;
                    } else {
                        continue;
                    }
                }
                $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
                $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
            }
            rs_close($digestposts_rs);
            /// Finished iteration, let's close the resultset
            // Data collected, start sending out emails to each user
            foreach ($userdiscussions as $userid => $thesediscussions) {
                @set_time_limit(120);
                // terminate if processing of any account takes longer than 2 minutes
                $USER = $cronuser;
                course_setup(SITEID);
                // reset cron user language, theme and timezone settings
                mtrace(get_string('processingdigest', 'forum', $userid), '... ');
                // First of all delete all the queue entries for this user
                delete_records_select('forum_queue', "userid = {$userid} AND timemodified < {$digesttime}");
                $userto = $users[$userid];
                // Override the language and timezone of the "current" user, so that
                // mail is customised for the receiver.
                $USER = $userto;
                course_setup(SITEID);
                // init caches
                $userto->viewfullnames = array();
                $userto->canpost = array();
                $userto->markposts = array();
                $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
                $headerdata = new object();
                $headerdata->sitename = format_string($site->fullname, true);
                $headerdata->userprefs = $CFG->wwwroot . '/user/edit.php?id=' . $userid . '&amp;course=' . $site->id;
                $posttext = get_string('digestmailheader', 'forum', $headerdata) . "\n\n";
                $headerdata->userprefs = '<a target="_blank" href="' . $headerdata->userprefs . '">' . get_string('digestmailprefs', 'forum') . '</a>';
                $posthtml = "<head>";
                foreach ($CFG->stylesheets as $stylesheet) {
                    $posthtml .= '<link rel="stylesheet" type="text/css" href="' . $stylesheet . '" />' . "\n";
                }
                $posthtml .= "</head>\n<body id=\"email\">\n";
                $posthtml .= '<p>' . get_string('digestmailheader', 'forum', $headerdata) . '</p><br /><hr size="1" noshade="noshade" />';
                foreach ($thesediscussions as $discussionid) {
                    @set_time_limit(120);
                    // to be reset for each post
                    $discussion = $discussions[$discussionid];
                    $forum = $forums[$discussion->forum];
                    $course = $courses[$forum->course];
                    $cm = $coursemodules[$forum->id];
                    //override language
                    course_setup($course);
                    // Fill caches
                    if (!isset($userto->viewfullnames[$forum->id])) {
                        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                        $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                    }
                    if (!isset($userto->canpost[$discussion->id])) {
                        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                        $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                    }
                    $strforums = get_string('forums', 'forum');
                    $canunsubscribe = !forum_is_forcesubscribed($forum);
                    $canreply = $userto->canpost[$discussion->id];
                    $posttext .= "\n \n";
                    $posttext .= '=====================================================================';
                    $posttext .= "\n \n";
                    $posttext .= "{$course->shortname} -> {$strforums} -> " . format_string($forum->name, true);
                    if ($discussion->name != $forum->name) {
                        $posttext .= " -> " . format_string($discussion->name, true);
                    }
                    $posttext .= "\n";
                    $posthtml .= "<p><font face=\"sans-serif\">" . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">{$course->shortname}</a> -> " . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/forum/index.php?id={$course->id}\">{$strforums}</a> -> " . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/forum/view.php?f={$forum->id}\">" . format_string($forum->name, true) . "</a>";
                    if ($discussion->name == $forum->name) {
                        $posthtml .= "</font></p>";
                    } else {
                        $posthtml .= " -> <a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/forum/discuss.php?d={$discussion->id}\">" . format_string($discussion->name, true) . "</a></font></p>";
                    }
                    $posthtml .= '<p>';
                    $postsarray = $discussionposts[$discussionid];
                    sort($postsarray);
                    foreach ($postsarray as $postid) {
                        $post = $posts[$postid];
                        if (array_key_exists($post->userid, $users)) {
                            // we might know him/her already
                            $userfrom = $users[$post->userid];
                        } else {
                            if ($userfrom = get_record('user', 'id', $post->userid)) {
                                $users[$userfrom->id] = $userfrom;
                                // fetch only once, we can add it to user list, it will be skipped anyway
                            } else {
                                mtrace('Could not find user ' . $post->userid);
                                continue;
                            }
                        }
                        if (!isset($userfrom->groups[$forum->id])) {
                            if (!isset($userfrom->groups)) {
                                $userfrom->groups = array();
                                $users[$userfrom->id]->groups = array();
                            }
                            $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                            $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                        }
                        $userfrom->customheaders = array("Precedence: Bulk");
                        if ($userto->maildigest == 2) {
                            // Subjects only
                            $by = new object();
                            $by->name = fullname($userfrom);
                            $by->date = userdate($post->modified);
                            $posttext .= "\n" . format_string($post->subject, true) . ' ' . get_string("bynameondate", "forum", $by);
                            $posttext .= "\n---------------------------------------------------------------------";
                            $by->name = "<a target=\"_blank\" href=\"{$CFG->wwwroot}/user/view.php?id={$userfrom->id}&amp;course={$course->id}\">{$by->name}</a>";
                            $posthtml .= '<div><a target="_blank" href="' . $CFG->wwwroot . '/mod/forum/discuss.php?d=' . $discussion->id . '#p' . $post->id . '">' . format_string($post->subject, true) . '</a> ' . get_string("bynameondate", "forum", $by) . '</div>';
                        } else {
                            // The full treatment
                            $posttext .= forum_make_mail_text($course, $forum, $discussion, $post, $userfrom, $userto, true);
                            $posthtml .= forum_make_mail_post($course, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
                            // Create an array of postid's for this user to mark as read.
                            if (!$CFG->forum_usermarksread) {
                                $userto->markposts[$post->id] = $post->id;
                            }
                        }
                    }
                    if ($canunsubscribe) {
                        $posthtml .= "\n<div align=\"right\"><font size=\"1\"><a href=\"{$CFG->wwwroot}/mod/forum/subscribe.php?id={$forum->id}\">" . get_string("unsubscribe", "forum") . "</a></font></div>";
                    } else {
                        $posthtml .= "\n<div align=\"right\"><font size=\"1\">" . get_string("everyoneissubscribed", "forum") . "</font></div>";
                    }
                    $posthtml .= '<hr size="1" noshade="noshade" /></p>';
                }
                $posthtml .= '</body>';
                if ($userto->mailformat != 1) {
                    // This user DOESN'T want to receive HTML
                    $posthtml = '';
                }
                if (!($mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, '', '', $CFG->forum_replytouser))) {
                    mtrace("ERROR!");
                    echo "Error: mod/forum/cron.php: Could not send out digest mail to user {$userto->id} ({$userto->email})... not trying again.\n";
                    add_to_log($course->id, 'forum', 'mail digest error', '', '', $cm->id, $userto->id);
                } else {
                    if ($mailresult === 'emailstop') {
                        // should not happen anymore - see check above
                    } else {
                        mtrace("success.");
                        $usermailcount++;
                        // Mark post as read if forum_usermarksread is set off
                        forum_tp_mark_posts_read($userto, $userto->markposts);
                    }
                }
            }
        }
        /// We have finishied all digest emails, update $CFG->digestmailtimelast
        set_config('digestmailtimelast', $timenow);
    }
    $USER = $cronuser;
    course_setup(SITEID);
    // reset cron user language, theme and timezone settings
    if (!empty($usermailcount)) {
        mtrace(get_string('digestsentusers', 'forum', $usermailcount));
    }
    if (!empty($CFG->forum_lastreadclean)) {
        $timenow = time();
        if ($CFG->forum_lastreadclean + 24 * 3600 < $timenow) {
            set_config('forum_lastreadclean', $timenow);
            mtrace('Removing old forum read tracking info...');
            forum_tp_clean_read_records();
        }
    } else {
        set_config('forum_lastreadclean', time());
    }
    return true;
}
示例#7
0
文件: datalib.php 项目: r007/PMoodle
/**
 * Ensure all courses have a valid course category
 * useful if a category has been removed manually
 **/
function fix_coursecategory_orphans()
{
    global $CFG;
    // Note: the handling of sortorder here is arguably
    // open to race conditions. Hard to fix here, unlikely
    // to hit anyone in production.
    $sql = "SELECT c.id, c.category, c.shortname\n            FROM {$CFG->prefix}course c\n            LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id\n            WHERE cc.id IS NULL AND c.id != " . SITEID;
    $rs = get_recordset_sql($sql);
    if (!rs_EOF($rs)) {
        // we have some orphans
        // the "default" category is the lowest numbered...
        $default = get_field_sql("SELECT MIN(id)\n                                    FROM {$CFG->prefix}course_categories");
        $sortorder = get_field_sql("SELECT MAX(sortorder)\n                                    FROM {$CFG->prefix}course\n                                    WHERE category={$default}");
        begin_sql();
        $tx = true;
        while ($tx && ($course = rs_fetch_next_record($rs))) {
            $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
            $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
        }
        if ($tx) {
            commit_sql();
        } else {
            rollback_sql();
        }
    }
    rs_close($rs);
}
示例#8
0
/**
 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
 * or key means do not change existing.
 *
 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
 *
 * Manual, course or category items can not be updated by this function.
 * @public
 * @param string $source source of the grade such as 'mod/assignment'
 * @param int $courseid id of course
 * @param string $itemtype type of grade item - mod, block
 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
 * @param int $iteminstance instance it of graded subject
 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
 */
function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades = NULL, $itemdetails = NULL)
{
    global $USER, $CFG;
    // only following grade_item properties can be changed in this function
    $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
    // list of 10,5 numeric fields
    $floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
    // grade item identification
    $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
    if (is_null($courseid) or is_null($itemtype)) {
        debugging('Missing courseid or itemtype');
        return GRADE_UPDATE_FAILED;
    }
    if (!($grade_items = grade_item::fetch_all($params))) {
        // create a new one
        $grade_item = false;
    } else {
        if (count($grade_items) == 1) {
            $grade_item = reset($grade_items);
            unset($grade_items);
            //release memory
        } else {
            debugging('Found more than one grade item');
            return GRADE_UPDATE_MULTIPLE;
        }
    }
    if (!empty($itemdetails['deleted'])) {
        if ($grade_item) {
            if ($grade_item->delete($source)) {
                return GRADE_UPDATE_OK;
            } else {
                return GRADE_UPDATE_FAILED;
            }
        }
        return GRADE_UPDATE_OK;
    }
    /// Create or update the grade_item if needed
    if (!$grade_item) {
        if ($itemdetails) {
            $itemdetails = (array) $itemdetails;
            // grademin and grademax ignored when scale specified
            if (array_key_exists('scaleid', $itemdetails)) {
                if ($itemdetails['scaleid']) {
                    unset($itemdetails['grademin']);
                    unset($itemdetails['grademax']);
                }
            }
            foreach ($itemdetails as $k => $v) {
                if (!in_array($k, $allowed)) {
                    // ignore it
                    continue;
                }
                if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
                    // no grade item needed!
                    return GRADE_UPDATE_OK;
                }
                $params[$k] = $v;
            }
        }
        $grade_item = new grade_item($params);
        $grade_item->insert();
    } else {
        if ($grade_item->is_locked()) {
            // no notice() here, test returned value instead!
            return GRADE_UPDATE_ITEM_LOCKED;
        }
        if ($itemdetails) {
            $itemdetails = (array) $itemdetails;
            $update = false;
            foreach ($itemdetails as $k => $v) {
                if (!in_array($k, $allowed)) {
                    // ignore it
                    continue;
                }
                if (in_array($k, $floats)) {
                    if (grade_floats_different($grade_item->{$k}, $v)) {
                        $grade_item->{$k} = $v;
                        $update = true;
                    }
                } else {
                    if ($grade_item->{$k} != $v) {
                        $grade_item->{$k} = $v;
                        $update = true;
                    }
                }
            }
            if ($update) {
                $grade_item->update();
            }
        }
    }
    /// reset grades if requested
    if (!empty($itemdetails['reset'])) {
        $grade_item->delete_all_grades('reset');
        return GRADE_UPDATE_OK;
    }
    /// Some extra checks
    // do we use grading?
    if ($grade_item->gradetype == GRADE_TYPE_NONE) {
        return GRADE_UPDATE_OK;
    }
    // no grade submitted
    if (empty($grades)) {
        return GRADE_UPDATE_OK;
    }
    /// Finally start processing of grades
    if (is_object($grades)) {
        $grades = array($grades->userid => $grades);
    } else {
        if (array_key_exists('userid', $grades)) {
            $grades = array($grades['userid'] => $grades);
        }
    }
    /// normalize and verify grade array
    foreach ($grades as $k => $g) {
        if (!is_array($g)) {
            $g = (array) $g;
            $grades[$k] = $g;
        }
        if (empty($g['userid']) or $k != $g['userid']) {
            debugging('Incorrect grade array index, must be user id! Grade ignored.');
            unset($grades[$k]);
        }
    }
    if (empty($grades)) {
        return GRADE_UPDATE_FAILED;
    }
    $count = count($grades);
    if ($count == 1) {
        reset($grades);
        $uid = key($grades);
        $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = {$grade_item->id} AND userid = {$uid}";
    } else {
        if ($count < 200) {
            $uids = implode(',', array_keys($grades));
            $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = {$grade_item->id} AND userid IN ({$uids})";
        } else {
            $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = {$grade_item->id}";
        }
    }
    $rs = get_recordset_sql($sql);
    $failed = false;
    while (count($grades) > 0) {
        $grade_grade = null;
        $grade = null;
        while ($rs and !rs_EOF($rs)) {
            if (!($gd = rs_fetch_next_record($rs))) {
                break;
            }
            $userid = $gd->userid;
            if (!isset($grades[$userid])) {
                // this grade not requested, continue
                continue;
            }
            // existing grade requested
            $grade = $grades[$userid];
            $grade_grade = new grade_grade($gd, false);
            unset($grades[$userid]);
            break;
        }
        if (is_null($grade_grade)) {
            if (count($grades) == 0) {
                // no more grades to process
                break;
            }
            $grade = reset($grades);
            $userid = $grade['userid'];
            $grade_grade = new grade_grade(array('itemid' => $grade_item->id, 'userid' => $userid), false);
            $grade_grade->load_optional_fields();
            // add feedback and info too
            unset($grades[$userid]);
        }
        $rawgrade = false;
        $feedback = false;
        $feedbackformat = FORMAT_MOODLE;
        $usermodified = $USER->id;
        $datesubmitted = null;
        $dategraded = null;
        if (array_key_exists('rawgrade', $grade)) {
            $rawgrade = $grade['rawgrade'];
        }
        if (array_key_exists('feedback', $grade)) {
            $feedback = $grade['feedback'];
        }
        if (array_key_exists('feedbackformat', $grade)) {
            $feedbackformat = $grade['feedbackformat'];
        }
        if (array_key_exists('usermodified', $grade)) {
            $usermodified = $grade['usermodified'];
        }
        if (array_key_exists('datesubmitted', $grade)) {
            $datesubmitted = $grade['datesubmitted'];
        }
        if (array_key_exists('dategraded', $grade)) {
            $dategraded = $grade['dategraded'];
        }
        // update or insert the grade
        if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified, $dategraded, $datesubmitted, $grade_grade)) {
            $failed = true;
        }
    }
    if ($rs) {
        rs_close($rs);
    }
    if (!$failed) {
        return GRADE_UPDATE_OK;
    } else {
        return GRADE_UPDATE_FAILED;
    }
}
示例#9
0
/**
 * Drops a table from the database pointed to by the database connection.
 * This undoes the create performed by load_test_table().
 *
 * This function should not be used in real code. Only for testing and debugging.
 *
 * @param string $tablename the name of the table to populate. E.g. 'mdl_unittest_user'.
 * @param object $db an AdoDB database connection.
 * @param bool $cascade If true, also drop tables that depend on this one, e.g. through
 *      foreign key constraints.
 */
function remove_test_table($tablename, $db, $cascade = false)
{
    global $CFG;
    _private_execute_sql('DROP TABLE ' . $tablename . ($cascade ? ' CASCADE' : '') . ';', $db);
    if ($CFG->dbfamily == 'postgres') {
        $rs = $db->Execute("SELECT relname FROM pg_class WHERE relname = '{$tablename}_id_seq' AND relkind = 'S';");
        if ($rs && !rs_EOF($rs)) {
            _private_execute_sql("DROP SEQUENCE {$tablename}_id_seq;", $db);
        }
    }
    if ($CFG->dbfamily == 'oracle') {
        _private_execute_sql("DROP SEQUENCE {$tablename}_id_seq;", $db);
    }
}
示例#10
0
function backup_user_info($bf, $preferences)
{
    global $CFG;
    $status = true;
    // Use a recordset to for the memory handling on to
    // the DB and run faster
    $users = get_recordset_sql("SELECT b.old_id, b.table_name, b.info,\n                                           u.*, m.wwwroot\n                                    FROM   {$CFG->prefix}backup_ids b\n                                      JOIN {$CFG->prefix}user       u ON b.old_id=u.id\n                                      JOIN {$CFG->prefix}mnet_host  m ON u.mnethostid=m.id\n                                    WHERE b.backup_code = '{$preferences->backup_unique_code}' AND\n                                          b.table_name = 'user'");
    //If we have users to backup
    if ($users && !rs_EOF($users)) {
        //Begin Users tag
        fwrite($bf, start_tag("USERS", 2, true));
        $counter = 0;
        //With every user
        while ($user = rs_fetch_next_record($users)) {
            //Begin User tag
            fwrite($bf, start_tag("USER", 3, true));
            //Output all user data
            fwrite($bf, full_tag("ID", 4, false, $user->id));
            fwrite($bf, full_tag("AUTH", 4, false, $user->auth));
            fwrite($bf, full_tag("CONFIRMED", 4, false, $user->confirmed));
            fwrite($bf, full_tag("POLICYAGREED", 4, false, $user->policyagreed));
            fwrite($bf, full_tag("DELETED", 4, false, $user->deleted));
            fwrite($bf, full_tag("USERNAME", 4, false, $user->username));
            fwrite($bf, full_tag("PASSWORD", 4, false, $user->password));
            fwrite($bf, full_tag("IDNUMBER", 4, false, $user->idnumber));
            fwrite($bf, full_tag("FIRSTNAME", 4, false, $user->firstname));
            fwrite($bf, full_tag("LASTNAME", 4, false, $user->lastname));
            fwrite($bf, full_tag("EMAIL", 4, false, $user->email));
            fwrite($bf, full_tag("EMAILSTOP", 4, false, $user->emailstop));
            fwrite($bf, full_tag("ICQ", 4, false, $user->icq));
            fwrite($bf, full_tag("SKYPE", 4, false, $user->skype));
            fwrite($bf, full_tag("YAHOO", 4, false, $user->yahoo));
            fwrite($bf, full_tag("AIM", 4, false, $user->aim));
            fwrite($bf, full_tag("MSN", 4, false, $user->msn));
            fwrite($bf, full_tag("PHONE1", 4, false, $user->phone1));
            fwrite($bf, full_tag("PHONE2", 4, false, $user->phone2));
            fwrite($bf, full_tag("INSTITUTION", 4, false, $user->institution));
            fwrite($bf, full_tag("DEPARTMENT", 4, false, $user->department));
            fwrite($bf, full_tag("ADDRESS", 4, false, $user->address));
            fwrite($bf, full_tag("CITY", 4, false, $user->city));
            fwrite($bf, full_tag("COUNTRY", 4, false, $user->country));
            fwrite($bf, full_tag("LANG", 4, false, $user->lang));
            fwrite($bf, full_tag("THEME", 4, false, $user->theme));
            fwrite($bf, full_tag("TIMEZONE", 4, false, $user->timezone));
            fwrite($bf, full_tag("FIRSTACCESS", 4, false, $user->firstaccess));
            fwrite($bf, full_tag("LASTACCESS", 4, false, $user->lastaccess));
            fwrite($bf, full_tag("LASTLOGIN", 4, false, $user->lastlogin));
            fwrite($bf, full_tag("CURRENTLOGIN", 4, false, $user->currentlogin));
            fwrite($bf, full_tag("LASTIP", 4, false, $user->lastip));
            fwrite($bf, full_tag("SECRET", 4, false, $user->secret));
            fwrite($bf, full_tag("PICTURE", 4, false, $user->picture));
            fwrite($bf, full_tag("URL", 4, false, $user->url));
            fwrite($bf, full_tag("DESCRIPTION", 4, false, $user->description));
            fwrite($bf, full_tag("MAILFORMAT", 4, false, $user->mailformat));
            fwrite($bf, full_tag("MAILDIGEST", 4, false, $user->maildigest));
            fwrite($bf, full_tag("MAILDISPLAY", 4, false, $user->maildisplay));
            fwrite($bf, full_tag("HTMLEDITOR", 4, false, $user->htmleditor));
            fwrite($bf, full_tag("AJAX", 4, false, $user->ajax));
            fwrite($bf, full_tag("AUTOSUBSCRIBE", 4, false, $user->autosubscribe));
            fwrite($bf, full_tag("TRACKFORUMS", 4, false, $user->trackforums));
            if ($user->mnethostid != $CFG->mnet_localhost_id) {
                fwrite($bf, full_tag("MNETHOSTURL", 4, false, $user->wwwroot));
            }
            fwrite($bf, full_tag("TIMEMODIFIED", 4, false, $user->timemodified));
            /// write assign/override code for context_userid
            $user->isneeded = strpos($user->info, "needed");
            //Output every user role (with its associated info)
            /*
            $user->isadmin = strpos($user->info,"admin");
            $user->iscoursecreator = strpos($user->info,"coursecreator");
            $user->isteacher = strpos($user->info,"teacher");
            $user->isstudent = strpos($user->info,"student");
            
            
            if ($user->isadmin!==false or
                $user->iscoursecreator!==false or
                $user->isteacher!==false or
                $user->isstudent!==false or
                $user->isneeded!==false) {
            */
            fwrite($bf, start_tag("ROLES", 4, true));
            if ($user->info != "needed" && $user->info != "") {
                //Begin ROLES tag
                //PRINT ROLE INFO
                //Admins
                $roles = explode(",", $user->info);
                foreach ($roles as $role) {
                    if ($role != "" && $role != "needed") {
                        fwrite($bf, start_tag("ROLE", 5, true));
                        //Print Role info
                        fwrite($bf, full_tag("TYPE", 6, false, $role));
                        //Print ROLE end
                        fwrite($bf, end_tag("ROLE", 5, true));
                    }
                }
            }
            //Needed
            if ($user->isneeded !== false) {
                //Print ROLE start
                fwrite($bf, start_tag("ROLE", 5, true));
                //Print Role info
                fwrite($bf, full_tag("TYPE", 6, false, "needed"));
                //Print ROLE end
                fwrite($bf, end_tag("ROLE", 5, true));
            }
            //End ROLES tag
            fwrite($bf, end_tag("ROLES", 4, true));
            //Check if we have user_preferences to backup
            if ($preferences_data = get_records("user_preferences", "userid", $user->old_id)) {
                //Start USER_PREFERENCES tag
                fwrite($bf, start_tag("USER_PREFERENCES", 4, true));
                //Write each user_preference
                foreach ($preferences_data as $user_preference) {
                    fwrite($bf, start_tag("USER_PREFERENCE", 5, true));
                    fwrite($bf, full_tag("NAME", 6, false, $user_preference->name));
                    fwrite($bf, full_tag("VALUE", 6, false, $user_preference->value));
                    fwrite($bf, end_tag("USER_PREFERENCE", 5, true));
                }
                //End USER_PREFERENCES tag
                fwrite($bf, end_tag("USER_PREFERENCES", 4, true));
            }
            $context = get_context_instance(CONTEXT_USER, $user->old_id);
            write_role_overrides_xml($bf, $context, 4);
            /// write role_assign code here
            write_role_assignments_xml($bf, $context, 4, $preferences);
            //End User tag
            fwrite($bf, end_tag("USER", 3, true));
            //Do some output
            $counter++;
            if ($counter % 10 == 0) {
                echo ".";
                if ($counter % 200 == 0) {
                    echo "<br />";
                }
                backup_flush(300);
            }
        }
        //End Users tag
        fwrite($bf, end_tag("USERS", 2, true));
    } else {
        // There aren't any users.
        $status = true;
    }
    if ($users) {
        rs_close($users);
    }
    return $status;
}
示例#11
0
 public function valid()
 {
     return !empty($this->rs) && !rs_EOF($this->rs);
 }