Exemple #1
0
 /**
 * Notify users about enrolments that are going to expire soon!
 * This function is run by admin/cron.php
 * @return void
 */
 function cron()
 {
     global $CFG, $USER, $SITE;
     if (!isset($CFG->lastexpirynotify)) {
         set_config('lastexpirynotify', 0);
     }
     // notify once a day only - TODO: add some tz handling here, maybe use timestamps
     if ($CFG->lastexpirynotify == date('Ymd')) {
         return;
     }
     if ($rs = get_recordset_select('course', 'enrolperiod > 0 AND expirynotify > 0 AND expirythreshold > 0')) {
         $cronuser = clone $USER;
         $admin = get_admin();
         while ($course = rs_fetch_next_record($rs)) {
             $a = new object();
             $a->coursename = $course->shortname . '/' . $course->fullname;
             // must be processed by format_string later
             $a->threshold = $course->expirythreshold / 86400;
             $a->extendurl = $CFG->wwwroot . '/user/index.php?id=' . $course->id;
             $a->current = array();
             $a->past = array();
             $expiry = time() + $course->expirythreshold;
             $cname = $course->fullname;
             /// Get all the manual role assignments for this course that have expired.
             if (!($context = get_context_instance(CONTEXT_COURSE, $course->id))) {
                 continue;
             }
             if ($oldenrolments = get_records_sql("\n                      SELECT u.*, ra.timeend\n                        FROM {$CFG->prefix}user u\n                             JOIN {$CFG->prefix}role_assignments ra ON (ra.userid = u.id)\n                        WHERE ra.contextid = {$context->id}\n                              AND ra.timeend > 0 AND ra.timeend <= {$expiry}\n                              AND ra.enrol = 'manual'")) {
                 // inform user who can assign roles or admin
                 if ($teachers = get_users_by_capability($context, 'moodle/role:assign', '', '', '', '', '', '', false)) {
                     $teachers = sort_by_roleassignment_authority($teachers, $context);
                     $teacher = reset($teachers);
                 } else {
                     $teachers = array($admin);
                     $teacher = $admin;
                 }
                 $a->teacherstr = fullname($teacher, true);
                 foreach ($oldenrolments as $user) {
                     /// Email all users about to expire
                     $a->studentstr = fullname($user, true);
                     if ($user->timeend < $expiry - 86400) {
                         $a->past[] = fullname($user) . " <{$user->email}>";
                     } else {
                         $a->current[] = fullname($user) . " <{$user->email}>";
                         if ($course->notifystudents) {
                             // Send this guy notice
                             // setup global $COURSE properly - needed for languages
                             $USER = $user;
                             course_setup($course);
                             $a->coursename = format_string($cname);
                             $a->course = $a->coursename;
                             $strexpirynotifystudentsemail = get_string('expirynotifystudentsemail', '', $a);
                             $strexpirynotify = get_string('expirynotify');
                             email_to_user($user, $teacher, format_string($SITE->fullname) . ' ' . $strexpirynotify, $strexpirynotifystudentsemail);
                         }
                     }
                 }
                 $a->current = implode("\n", $a->current);
                 $a->past = implode("\n", $a->past);
                 if ($a->current || $a->past) {
                     foreach ($teachers as $teacher) {
                         // setup global $COURSE properly - needed for languages
                         $USER = $teacher;
                         course_setup($course);
                         $a->coursename = format_string($cname);
                         $strexpirynotifyemail = get_string('expirynotifyemail', '', $a);
                         $strexpirynotify = get_string('expirynotify');
                         email_to_user($teacher, $admin, $a->coursename . ' ' . $strexpirynotify, $strexpirynotifyemail);
                     }
                 }
             }
         }
         $USER = $cronuser;
         course_setup($SITE);
         // More environment
     }
     set_config('lastexpirynotify', date('Ymd'));
 }
Exemple #2
0
        if ($pass != $CFG->cronremotepassword) {
            // wrong password.
            print_error('cronerrorpassword', 'admin');
            exit;
        }
    }
}
/// emulate normal session
$SESSION = new object();
$USER = get_admin();
/// Temporarily, to provide environment for this script
/// ignore admins timezone, language and locale - use site deafult instead!
$USER->timezone = $CFG->timezone;
$USER->lang = '';
$USER->theme = '';
course_setup(SITEID);
/// send mime type and encoding
if (check_browser_version('MSIE')) {
    //ugly IE hack to work around downloading instead of viewing
    @header('Content-Type: text/html; charset=utf-8');
    echo "<xmp>";
    //<pre> is not good enough for us here
} else {
    //send proper plaintext header
    @header('Content-Type: text/plain; charset=utf-8');
}
/// no more headers and buffers
while (@ob_end_flush()) {
}
/// increase memory limit (PHP 5.2 does different calculation, we need more memory now)
@raise_memory_limit('128M');
Exemple #3
0
// user id
$mode = optional_param('mode', "todaylogs", PARAM_ALPHA);
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', 100, PARAM_INT);
if (!($course = get_record("course", "id", $id))) {
    error("Course id is incorrect.");
}
if (!($user = get_record("user", "id", $user))) {
    error("User ID is incorrect");
}
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$personalcontext = get_context_instance(CONTEXT_USER, $user->id);
require_login();
if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !has_capability('moodle/course:view', $coursecontext)) {
    // do not require parents to be enrolled in courses ;-)
    course_setup($course);
} else {
    require_login($course);
}
if ($user->deleted) {
    print_header();
    print_heading(get_string('userdeleted'));
    print_footer();
    die;
}
// prepare list of allowed modes
$myreports = ($course->showreports and $USER->id == $user->id);
$anyreport = has_capability('moodle/user:viewuseractivitiesreport', $personalcontext);
$modes = array();
if ($myreports or $anyreport or has_capability('coursereport/outline:view', $coursecontext)) {
    $modes[] = 'outline';
<?php

// $Id: chatinput.php,v 1.11.4.3 2008/10/08 06:41:55 dongsheng Exp $
$nomoodlecookie = true;
// Session not needed!
require '../../../config.php';
require '../lib.php';
$chat_sid = required_param('chat_sid', PARAM_ALPHANUM);
if (!($chatuser = get_record('chat_users', 'sid', $chat_sid))) {
    error('Not logged in!');
}
//Get the user theme
$USER = get_record('user', 'id', $chatuser->userid);
//Setup course, lang and theme
course_setup($chatuser->course);
ob_start();
?>
<script type="text/javascript">
scroll_active = true;
function empty_field_and_submit() {
    var cf   = document.getElementById('sendform');
    var inpf = document.getElementById('inputform');
    cf.chat_msgidnr.value = parseInt(cf.chat_msgidnr.value) + 1;
    cf.chat_message.value = inpf.chat_message.value;
    inpf.chat_message.value='';
    cf.submit();
    inpf.chat_message.focus();
    return false;
}
function setfocus() {
    document.getElementsByName("chat_message")[0].focus(); 
Exemple #5
0
/**
 * Function to be run periodically according to the moodle cron
 *
 * Finds all assignment notifications that have yet to be mailed out, and mails them
 */
function assignment_cron()
{
    global $CFG, $USER;
    /// first execute all crons in plugins
    if ($plugins = get_list_of_plugins('mod/assignment/type')) {
        foreach ($plugins as $plugin) {
            require_once "{$CFG->dirroot}/mod/assignment/type/{$plugin}/assignment.class.php";
            $assignmentclass = "assignment_{$plugin}";
            $ass = new $assignmentclass();
            $ass->cron();
        }
    }
    /// Notices older than 1 day 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 - 24 * 3600;
    /// One day earlier
    if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
        $CFG->enablerecordcache = true;
        // We want all the caching we can get
        $realuser = clone $USER;
        foreach ($submissions as $key => $submission) {
            if (!set_field("assignment_submissions", "mailed", "1", "id", "{$submission->id}")) {
                echo "Could not update the mailed field for id {$submission->id}.  Not mailed.\n";
                unset($submissions[$key]);
            }
        }
        $timenow = time();
        foreach ($submissions as $submission) {
            echo "Processing assignment submission {$submission->id}\n";
            if (!($user = get_record("user", "id", "{$submission->userid}"))) {
                echo "Could not find user {$post->userid}\n";
                continue;
            }
            if (!($course = get_record("course", "id", "{$submission->course}"))) {
                echo "Could not find course {$submission->course}\n";
                continue;
            }
            /// Override the language and timezone of the "current" user, so that
            /// mail is customised for the receiver.
            $USER = $user;
            course_setup($course);
            if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
                echo fullname($user) . " not an active participant in " . format_string($course->shortname) . "\n";
                continue;
            }
            if (!($teacher = get_record("user", "id", "{$submission->teacher}"))) {
                echo "Could not find teacher {$submission->teacher}\n";
                continue;
            }
            if (!($mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id))) {
                echo "Could not find course module for assignment id {$submission->assignment}\n";
                continue;
            }
            if (!$mod->visible) {
                /// Hold mail notification for hidden assignments until later
                continue;
            }
            $strassignments = get_string("modulenameplural", "assignment");
            $strassignment = get_string("modulename", "assignment");
            $assignmentinfo = new object();
            $assignmentinfo->teacher = fullname($teacher);
            $assignmentinfo->assignment = format_string($submission->name, true);
            $assignmentinfo->url = "{$CFG->wwwroot}/mod/assignment/view.php?id={$mod->id}";
            $postsubject = "{$course->shortname}: {$strassignments}: " . format_string($submission->name, true);
            $posttext = "{$course->shortname} -> {$strassignments} -> " . format_string($submission->name, true) . "\n";
            $posttext .= "---------------------------------------------------------------------\n";
            $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo) . "\n";
            $posttext .= "---------------------------------------------------------------------\n";
            if ($user->mailformat == 1) {
                // HTML
                $posthtml = "<p><font face=\"sans-serif\">" . "<a href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">{$course->shortname}</a> ->" . "<a href=\"{$CFG->wwwroot}/mod/assignment/index.php?id={$course->id}\">{$strassignments}</a> ->" . "<a href=\"{$CFG->wwwroot}/mod/assignment/view.php?id={$mod->id}\">" . format_string($submission->name, true) . "</a></font></p>";
                $posthtml .= "<hr /><font face=\"sans-serif\">";
                $posthtml .= "<p>" . get_string("assignmentmailhtml", "assignment", $assignmentinfo) . "</p>";
                $posthtml .= "</font><hr />";
            } else {
                $posthtml = "";
            }
            if (!email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
                echo "Error: assignment cron: Could not send out mail for id {$submission->id} to user {$user->id} ({$user->email})\n";
            }
        }
        $USER = $realuser;
        course_setup(SITEID);
        // reset cron user language, theme and timezone settings
    }
    return true;
}
Exemple #6
0
/**
 * This function checks that the current user is logged in and has the
 * required privileges
 *
 * This function checks that the current user is logged in, and optionally
 * whether they are allowed to be in a particular course and view a particular
 * course module.
 * If they are not logged in, then it redirects them to the site login unless
 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
 * case they are automatically logged in as guests.
 * If $courseid is given and the user is not enrolled in that course then the
 * user is redirected to the course enrolment page.
 * If $cm is given and the coursemodule is hidden and the user is not a teacher
 * in the course then the user is redirected to the course home page.
 *
 * @uses $CFG
 * @uses $SESSION
 * @uses $USER
 * @uses $FULLME
 * @uses SITEID
 * @uses $COURSE
 * @param mixed $courseorid id of the course or course object
 * @param bool $autologinguest
 * @param object $cm course module object
 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
 *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
 *             in order to keep redirects working properly. MDL-14495
 */
function require_login($courseorid = 0, $autologinguest = true, $cm = null, $setwantsurltome = true)
{
    global $CFG, $SESSION, $USER, $COURSE, $FULLME;
    /// setup global $COURSE, themes, language and locale
    course_setup($courseorid);
    /// If the user is not even logged in yet then make sure they are
    if (!isloggedin()) {
        //NOTE: $USER->site check was obsoleted by session test cookie,
        //      $USER->confirmed test is in login/index.php
        if ($setwantsurltome) {
            $SESSION->wantsurl = $FULLME;
        }
        if (!empty($_SERVER['HTTP_REFERER'])) {
            $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
        }
        if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest)) {
            $loginguest = '?loginguest=true';
        } else {
            $loginguest = '';
        }
        if (empty($CFG->loginhttps) or $loginguest) {
            //do not require https for guest logins
            redirect($CFG->wwwroot . '/login/index.php' . $loginguest);
        } else {
            $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
            redirect($wwwroot . '/login/index.php');
        }
        exit;
    }
    /// loginas as redirection if needed
    if ($COURSE->id != SITEID and !empty($USER->realuser)) {
        if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
            if ($USER->loginascontext->instanceid != $COURSE->id) {
                print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid);
            }
        }
    }
    /// check whether the user should be changing password (but only if it is REALLY them)
    if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
        $userauth = get_auth_plugin($USER->auth);
        if ($userauth->can_change_password()) {
            $SESSION->wantsurl = $FULLME;
            if ($changeurl = $userauth->change_password_url()) {
                //use plugin custom url
                redirect($changeurl);
            } else {
                //use moodle internal method
                if (empty($CFG->loginhttps)) {
                    redirect($CFG->wwwroot . '/login/change_password.php');
                } else {
                    $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
                    redirect($wwwroot . '/login/change_password.php');
                }
            }
        } else {
            print_error('nopasswordchangeforced', 'auth');
        }
    }
    /// Check that the user account is properly set up
    if (user_not_fully_set_up($USER)) {
        $SESSION->wantsurl = $FULLME;
        redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&amp;course=' . SITEID);
    }
    /// Make sure current IP matches the one for this session (if required)
    if (!empty($CFG->tracksessionip)) {
        if ($USER->sessionIP != md5(getremoteaddr())) {
            print_error('sessionipnomatch', 'error');
        }
    }
    /// Make sure the USER has a sesskey set up.  Used for checking script parameters.
    sesskey();
    // Check that the user has agreed to a site policy if there is one
    if (!empty($CFG->sitepolicy)) {
        if (!$USER->policyagreed) {
            $SESSION->wantsurl = $FULLME;
            redirect($CFG->wwwroot . '/user/policy.php');
        }
    }
    // Fetch the system context, we are going to use it a lot.
    $sysctx = get_context_instance(CONTEXT_SYSTEM);
    /// If the site is currently under maintenance, then print a message
    if (!has_capability('moodle/site:config', $sysctx)) {
        if (file_exists($CFG->dataroot . '/' . SITEID . '/maintenance.html')) {
            print_maintenance_message();
            exit;
        }
    }
    /// groupmembersonly access control
    if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
        if (isguestuser() or !groups_has_membership($cm)) {
            print_error('groupmembersonlyerror', 'group', $CFG->wwwroot . '/course/view.php?id=' . $cm->course);
        }
    }
    // Fetch the course context, and prefetch its child contexts
    if (!isset($COURSE->context)) {
        if (!($COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id))) {
            print_error('nocontext');
        }
    }
    if (!empty($cm) && !isset($cm->context)) {
        if (!($cm->context = get_context_instance(CONTEXT_MODULE, $cm->id))) {
            print_error('nocontext');
        }
    }
    if ($COURSE->id == SITEID) {
        /// Eliminate hidden site activities straight away
        if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
            redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
        }
        user_accesstime_log($COURSE->id);
        /// Access granted, update lastaccess times
        return;
    } else {
        /// Check if the user can be in a particular course
        if (empty($USER->access['rsw'][$COURSE->context->path])) {
            //
            // MDL-13900 - If the course or the parent category are hidden
            // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
            //
            if (!($COURSE->visible && course_parent_visible($COURSE)) && !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
                print_header_simple();
                notice(get_string('coursehidden'), $CFG->wwwroot . '/');
            }
        }
        /// Non-guests who don't currently have access, check if they can be allowed in as a guest
        if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
            if ($COURSE->guest == 1) {
                // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
                $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
            }
        }
        /// If the user is a guest then treat them according to the course policy about guests
        if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
            if (has_capability('moodle/site:doanything', $sysctx)) {
                // administrators must be able to access any course - even if somebody gives them guest access
                user_accesstime_log($COURSE->id);
                /// Access granted, update lastaccess times
                return;
            }
            switch ($COURSE->guest) {
                /// Check course policy about guest access
                case 1:
                    /// Guests always allowed
                    if (!has_capability('moodle/course:view', $COURSE->context)) {
                        // Prohibited by capability
                        print_header_simple();
                        notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "{$CFG->wwwroot}/login/index.php");
                    }
                    if (!empty($cm) and !$cm->visible) {
                        // Not allowed to see module, send to course page
                        redirect($CFG->wwwroot . '/course/view.php?id=' . $cm->course, get_string('activityiscurrentlyhidden'));
                    }
                    user_accesstime_log($COURSE->id);
                    /// Access granted, update lastaccess times
                    return;
                    // User is allowed to see this course
                    break;
                case 2:
                    /// Guests allowed with key
                    if (!empty($USER->enrolkey[$COURSE->id])) {
                        // Set by enrol/manual/enrol.php
                        user_accesstime_log($COURSE->id);
                        /// Access granted, update lastaccess times
                        return true;
                    }
                    //  otherwise drop through to logic below (--> enrol.php)
                    break;
                default:
                    /// Guests not allowed
                    $strloggedinasguest = get_string('loggedinasguest');
                    print_header_simple('', '', build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
                    if (empty($USER->access['rsw'][$COURSE->context->path])) {
                        // Normal guest
                        notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "{$CFG->wwwroot}/login/index.php");
                    } else {
                        notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
                        echo '<div class="notifyproblem">' . switchroles_form($COURSE->id) . '</div>';
                        print_footer($COURSE);
                        exit;
                    }
                    break;
            }
            /// For non-guests, check if they have course view access
        } else {
            if (has_capability('moodle/course:view', $COURSE->context)) {
                if (!empty($USER->realuser)) {
                    // Make sure the REAL person can also access this course
                    if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
                        print_header_simple();
                        notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/');
                    }
                }
                /// Make sure they can read this activity too, if specified
                if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
                    redirect($CFG->wwwroot . '/course/view.php?id=' . $cm->course, get_string('activityiscurrentlyhidden'));
                }
                user_accesstime_log($COURSE->id);
                /// Access granted, update lastaccess times
                return;
                // User is allowed to see this course
            }
        }
        /// Currently not enrolled in the course, so see if they want to enrol
        $SESSION->wantsurl = $FULLME;
        redirect($CFG->wwwroot . '/course/enrol.php?id=' . $COURSE->id);
        die;
    }
}
Exemple #7
0
            }
        }
    }
}
if (!isset($coursecontext)) {
    // Has not yet been set by post.php.
    $coursecontext = get_context_instance(CONTEXT_COURSE, $forum->course);
}
if (!($cm = get_coursemodule_from_instance('forum', $forum->id, $course->id))) {
    // For the logs
    error('Could not get the course module for the forum instance.');
}
$modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
// setup course variable to force form language
// fix for MDL-6926
course_setup($course->id);
require_once 'post_form.php';
$mform_post = new mod_forum_post_form('post.php', array('course' => $course, 'coursecontext' => $coursecontext, 'modcontext' => $modcontext, 'forum' => $forum, 'post' => $post));
if ($fromform = $mform_post->get_data()) {
    require_login($course, false, $cm);
    if (empty($SESSION->fromurl)) {
        $errordestination = "{$CFG->wwwroot}/mod/forum/view.php?f={$forum->id}";
    } else {
        $errordestination = $SESSION->fromurl;
    }
    // TODO add attachment processing
    //$fromform->attachment = isset($_FILES['attachment']) ? $_FILES['attachment'] : NULL;
    trusttext_after_edit($fromform->message, $modcontext);
    if ($fromform->edit) {
        // Updating a post
        $fromform->id = $fromform->edit;
Exemple #8
0
/**
 * 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;
}
Exemple #9
0
        if (file_exists($CFG->dataroot . '/lang/' . $lang . '_utf8') or file_exists($CFG->dirroot . '/lang/' . $lang . '_utf8')) {
            $SESSION->lang = $lang . '_utf8';
        }
    }
}
setup_lang_from_browser();
unset($lang);
if (empty($CFG->lang)) {
    if (empty($SESSION->lang)) {
        $CFG->lang = 'en_utf8';
    } else {
        $CFG->lang = $SESSION->lang;
    }
}
// set default locale and themes - might be changed again later from require_login()
course_setup();
if (!empty($CFG->opentogoogle)) {
    if (empty($USER->id)) {
        // Ignore anyone logged in
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false) {
                $USER = guest_user();
            } else {
                if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false) {
                    // Google
                    $USER = guest_user();
                } else {
                    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false) {
                        // Yahoo
                        $USER = guest_user();
                    } else {
Exemple #10
0
/**
 * Function to be run periodically according to the moodle cron
 * Mails new conversations out to participants, checks for any new
 * participants, and cleans up expired/closed conversations
 * @return   bool   true when complete
 */
function dialogue_cron()
{
    global $CFG, $USER;
    $context_cache = array();
    // delete any closed conversations which have expired
    dialogue_delete_expired_conversations();
    // Finds all dialogue entries that have yet to be mailed out, and mails them
    $sql = "SELECT e.* FROM {$CFG->prefix}dialogue_entries e " . "INNER JOIN {$CFG->prefix}dialogue d ON e.dialogueid = d.id " . "WHERE e.timecreated + d.edittime * 60 < " . time() . " AND e.mailed = 0 ";
    if ($entries = get_records_sql($sql)) {
        foreach ($entries as $entry) {
            echo "Processing dialogue entry {$entry->id}\n";
            if (!($userfrom = get_record('user', 'id', $entry->userid))) {
                mtrace("Could not find user {$entry->userid}\n");
                continue;
            }
            // get conversation record
            if (!($conversation = get_record('dialogue_conversations', 'id', $entry->conversationid))) {
                mtrace("Could not find conversation {$entry->conversationid}\n");
            }
            if ($userfrom->id == $conversation->userid) {
                if (!($userto = get_record('user', 'id', $conversation->recipientid))) {
                    mtrace("Could not find use {$conversation->recipientid}\n");
                }
            } else {
                if (!($userto = get_record('user', 'id', $conversation->userid))) {
                    mtrace("Could not find use {$conversation->userid}\n");
                }
            }
            $USER->lang = $userto->lang;
            if (!($dialogue = get_record('dialogue', 'id', $conversation->dialogueid))) {
                echo "Could not find dialogue id {$conversation->dialogueid}\n";
                continue;
            }
            if (!($course = get_record('course', 'id', $dialogue->course))) {
                echo "Could not find course {$dialogue->course}\n";
                continue;
            }
            if (!($cm = get_coursemodule_from_instance('dialogue', $dialogue->id, $course->id))) {
                echo "Course Module ID was incorrect\n";
            }
            if (empty($context_cache[$course->id])) {
                $context_cache[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
            }
            if (!has_capability('mod/dialogue:participate', $context_cache[$course->id], $userfrom->id) && !has_capability('mod/dialogue:manage', $context_cache[$course->id], $userfrom->id)) {
                set_field('dialogue_entries', 'mailed', '1', 'id', $entry->id);
                continue;
                // Not an active participant
            }
            if (!has_capability('mod/dialogue:participate', $context_cache[$course->id], $userto->id) && !has_capability('mod/dialogue:manage', $context_cache[$course->id], $userto->id)) {
                set_field('dialogue_entries', 'mailed', '1', 'id', $entry->id);
                continue;
                // Not an active participant
            }
            $strdialogues = get_string('modulenameplural', 'dialogue');
            $strdialogue = get_string('modulename', 'dialogue');
            $dialogueinfo = new object();
            $dialogueinfo->userfrom = fullname($userfrom);
            $dialogueinfo->dialogue = format_string($dialogue->name);
            $dialogueinfo->url = "{$CFG->wwwroot}/mod/dialogue/view.php?id={$cm->id}";
            $postsubject = "{$course->shortname}: {$strdialogues}: {$dialogueinfo->dialogue}: " . get_string('newentry', 'dialogue');
            $posttext = "{$course->shortname} -> {$strdialogues} -> {$dialogueinfo->dialogue}\n";
            $posttext .= "---------------------------------------------------------------------\n";
            $posttext .= get_string('dialoguemail', 'dialogue', $dialogueinfo) . " \n";
            $posttext .= "---------------------------------------------------------------------\n";
            if ($userto->mailformat == 1) {
                // HTML
                $posthtml = "<p><font face=\"sans-serif\">" . "<a href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">{$course->shortname}</a> ->" . "<a href=\"{$CFG->wwwroot}/mod/dialogue/index.php?id={$course->id}\">dialogues</a> ->" . "<a href=\"{$CFG->wwwroot}/mod/dialogue/view.php?id={$cm->id}\">" . $dialogueinfo->dialogue . "</a></font></p>";
                $posthtml .= "<hr /><font face=\"sans-serif\">";
                $posthtml .= '<p>' . get_string('dialoguemailhtml', 'dialogue', $dialogueinfo) . '</p>';
                $posthtml .= "</font><hr />";
            } else {
                $posthtml = '';
            }
            if (!email_to_user($userto, $userfrom, $postsubject, $posttext, $posthtml)) {
                mtrace("Error: dialogue cron: Could not send out mail for id {$entry->id} to user {$userto->id} ({$userto->email})\n");
            }
            if (!set_field('dialogue_entries', 'mailed', '1', 'id', $entry->id)) {
                mtrace("Could not update the mailed field for id {$entry->id}\n");
            }
        }
    }
    /// Find conversations sent to all participants and check for new participants
    $rs = get_recordset_select('dialogue_conversations', 'grouping != 0 AND grouping IS NOT NULL', 'dialogueid, grouping');
    $dialogueid = 0;
    $grouping = 0;
    $groupid = null;
    $inconversation = array();
    $newusers = array();
    while ($conversation = rs_fetch_next_record($rs)) {
        if ($dialogueid != $conversation->dialogueid || $groupid != $conversation->groupid || $grouping != $conversation->grouping) {
            if ($dialogueid == 0 || $groupid === null) {
                $dialogueid = $conversation->dialogueid;
                $groupid = $conversation->groupid;
            }
            $cm = get_coursemodule_from_instance('dialogue', $dialogueid);
            $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            $users = (array) get_users_by_capability($context, 'mod/dialogue:participate', 'u.id, u.firstname, u.lastname', null, null, null, empty($groupid) ? null : $groupid, null, null, null, false);
            $managers = (array) get_users_by_capability($context, 'mod/dialogue:manage', 'u.id, u.firstname, u.lastname', null, null, null, null, null, null, null, false);
            $dialogueid = $conversation->dialogueid;
            $groupid = $conversation->groupid;
        }
        if ($grouping != $conversation->grouping) {
            if ($grouping) {
                if ($userdiff = array_diff_key($users, $inconversation, $managers)) {
                    foreach ($userdiff as $userid => $value) {
                        $newusers[$userid . ',' . $grouping] = array('userid' => $userid, 'courseid' => $cm->course, 'grouping' => $grouping);
                    }
                }
            }
            $inconversation = array();
            $grouping = $conversation->grouping;
        }
        $inconversation[$conversation->recipientid] = true;
    }
    if (!empty($dialogueid)) {
        // Finish of any remaing users
        $cm = get_coursemodule_from_instance('dialogue', $dialogueid);
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
        $users = (array) get_users_by_capability($context, 'mod/dialogue:participate', 'u.id, u.firstname, u.lastname', null, null, null, empty($groupid) ? null : $groupid, null, null, null, false);
        $managers = (array) get_users_by_capability($context, 'mod/dialogue:manage', 'u.id, u.firstname, u.lastname', null, null, null, null, null, null, null, false);
        if ($userdiff = array_diff_key($users, $inconversation, $managers)) {
            foreach ($userdiff as $userid => $value) {
                $newusers[$userid . ',' . $grouping] = array('userid' => $userid, 'courseid' => $cm->course, 'grouping' => $grouping);
            }
        }
    }
    rs_close($rs);
    if (!empty($newusers)) {
        foreach ($newusers as $key => $newuser) {
            begin_sql();
            course_setup($newuser['courseid']);
            if ($conversations = get_records('dialogue_conversations', 'grouping', $newuser['grouping'], 'id', '*', 0, 1)) {
                $conversation = array_pop($conversations);
                // we only need one to get the common field values
                if ($entry = get_records('dialogue_entries', 'conversationid', $conversation->id, 'id', '*', 0, 1)) {
                    unset($conversation->id);
                    $conversation->recipientid = $newuser['userid'];
                    $conversation->lastrecipientid = $newuser['userid'];
                    $conversation->timemodified = time();
                    $conversation->seenon = false;
                    $conversation->closed = 0;
                    $conversation = addslashes_object($conversation);
                    if (!($conversationid = insert_record('dialogue_conversations', $conversation))) {
                        rollback_sql();
                        continue;
                    }
                    $entry = array_pop($entry);
                    $srcentry = clone $entry;
                    unset($entry->id);
                    $entry->conversationid = $conversationid;
                    $entry->timecreated = $conversation->timemodified;
                    $entry->recipientid = $conversation->recipientid;
                    $entry->mailed = false;
                    $entry = addslashes_object($entry);
                    if (!($entry->id = insert_record('dialogue_entries', $entry))) {
                        rollback_sql();
                        continue;
                    }
                    $read = new stdClass();
                    $lastread = time();
                    $read->conversationid = $conversationid;
                    $read->entryid = $entry->id;
                    $read->userid = $conversation->userid;
                    $read->firstread = $lastread;
                    $read->lastread = $lastread;
                    insert_record('dialogue_read', $read);
                    if ($entry->attachment) {
                        $srcdir = dialogue_file_area($srcentry);
                        $dstdir = dialogue_file_area($entry);
                        copy($srcdir . '/' . $entry->attachment, $dstdir . '/' . $entry->attachment);
                    }
                } else {
                    mtrace('Failed to find entry for conversation: ' . $conversation->id);
                }
            } else {
                mtrace('Failed to find conversation: ' . $conversation->id);
            }
            commit_sql();
        }
    }
    return true;
}
Exemple #11
0
 function message_broadcast($message, $sender)
 {
     if (empty($this->conn_sets)) {
         return true;
     }
     $now = time();
     // First of all, mark this chatroom as having had activity now
     $this->chatrooms[$message->chatid]['lastactivity'] = $now;
     foreach ($this->sets_info as $sessionid => $info) {
         // We need to get handles from users that are in the same chatroom, same group
         if ($info['chatid'] == $message->chatid && ($info['groupid'] == $message->groupid || $message->groupid == 0)) {
             // Simply give them the message
             course_setup($info['course'], $info['user']);
             $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
             $this->trace('Delivering message "' . $output->text . '" to ' . $this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
             if ($output->beep) {
                 $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="' . $this->_beepsoundsrc . '" autostart="true" hidden="true" />');
             }
             if ($info['quirks'] & QUIRK_CHUNK_UPDATE) {
                 $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
                 $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
                 $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
             }
             if (!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
                 $this->disconnect_session($sessionid);
             }
             //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
         }
     }
 }
Exemple #12
0
<?php

// $Id: en.php,v 1.4.10.2 2010/01/14 10:20:29 mudrd8mz Exp $
include "../../../../config.php";
$lastmodified = filemtime("en.php");
$lifetime = 1800;
// Commenting this out since it's creating problems
// where solution seem to be hard to find...
// http://moodle.org/mod/forum/discuss.php?d=34376
//if ( function_exists('ob_gzhandler') ) {
//    ob_start("ob_gzhandler");
//}
// use course language
$courseid = optional_param('id', 1, PARAM_INT);
course_setup($courseid);
header("Content-type: application/x-javascript; charset: utf-8");
// Correct MIME type
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastmodified) . " GMT");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + $lifetime) . " GMT");
// See Bug #2387
header("Cache-control: max_age = -1");
header("Pragma: no-cache");
?>
// I18N constants

// LANG: "en", ENCODING: UTF-8 | ISO-8859-1
// Author: Mihai Bazon, <*****@*****.**>

// FOR TRANSLATORS:
//
//   1. PLEASE PUT YOUR CONTACT INFO IN THE ABOVE LINE
/**
 * Checks if a user is allowed to view a blog. If not, will not return (calls
 * an error function and exits).
 *
 * @param object $oublog
 * @param object $context
 * @param object $cm
 * @return bool
 */
function oublog_check_view_permissions($oublog, $context, $cm = null)
{
    global $COURSE;
    $capability = $oublog->global ? 'mod/oublog:viewpersonal' : 'mod/oublog:view';
    switch ($oublog->maxvisibility) {
        case OUBLOG_VISIBILITY_PUBLIC:
            course_setup($oublog->course);
            return;
        case OUBLOG_VISIBILITY_LOGGEDINUSER:
            require_login(SITEID, false);
            course_setup($oublog->course);
            // Check oublog:view cap
            if (!has_capability($capability, $context)) {
                error(get_string('accessdenied', 'oublog'));
            }
            return;
        case OUBLOG_VISIBILITY_COURSEUSER:
            require_course_login($oublog->course, false, $cm);
            // Check oublog:view cap
            if (!has_capability($capability, $context)) {
                error(get_string('accessdenied', 'oublog'));
            }
            return;
        default:
            error('Unkown visibility level');
    }
}
 function email_digest()
 {
     global $CFG, $PERF;
     // Do digest mails if required. Note this is based on server time not
     // user time.
     $nextdigest = get_config('forumng', 'nextdigest');
     if (!$nextdigest) {
         // Run digest at next occurrence of the requested time
         $nextdigest = strtotime($CFG->digestmailtime . ':00');
         if ($nextdigest <= time()) {
             $nextdigest = strtotime('+1 day', $nextdigest);
         }
         set_config('nextdigest', $nextdigest, 'forumng');
     }
     if (time() < $nextdigest) {
         self::debug("DEBUG: Not yet time for digest");
         return;
     }
     // Run digest again next day at specified time (note: best to
     // get time again, as they may have changed it)
     $nextdigest = strtotime($CFG->digestmailtime . ':00');
     if ($nextdigest <= time()) {
         $nextdigest = strtotime('+1 day', $nextdigest);
     }
     set_config('nextdigest', $nextdigest, 'forumng');
     // OK, now build current digest
     mtrace("Beginning forum digest processing...");
     if (!empty($PERF->dbqueries)) {
         $beforequeries = $PERF->dbqueries;
     }
     $before = microtime(true);
     mtrace('Initial query: ', '');
     $list = new forum_digest_list(true);
     mtrace(round(microtime(true) - $before, 1) . 's');
     $userdigests = array();
     $oldcourse = null;
     // Forum loop
     while ($list->next_forum($forum, $cm, $context, $course)) {
         self::debug("DEBUG: Forum " . $forum->get_name() . " on course {$course->shortname} " . "(cmid {$cm->id} contextid {$context->id})");
         if (!$oldcourse || $course->id != $oldcourse->id) {
             // Finish off and clear users
             if ($oldcourse) {
                 self::digest_finish_course($oldcourse, $userdigests);
             }
             // Set up new course details
             course_setup($course);
             $oldcourse = clone $course;
         }
         // Count posts just for logging
         $postcount = 0;
         // Get subscribers to forum
         $subscribers = $forum->get_subscribers();
         self::debug("DEBUG: Subscribers before filter " . count($subscribers), '');
         self::email_filter_subscribers($course, $cm, $forum, $subscribers, true);
         self::debug(", after " . count($subscribers));
         if (count($subscribers) == 0) {
             continue;
         }
         while ($list->next_discussion($discussion)) {
             self::debug("DEBUG: Discussion " . $discussion->get_subject() . ' (' . $discussion->get_id() . ')');
             // Evaluate list of users based on this discussion (which holds
             // group info). Organise list by language, timezone and email
             // type.
             $discussionusers = array();
             foreach ($subscribers as $subscriber) {
                 if (self::subscriber_receives_discussion($forum, $discussion, $subscriber)) {
                     $discussionusers[$subscriber->id] = $subscriber;
                 }
             }
             while ($list->next_post($post, $inreplyto)) {
                 // Loop through all digest users
                 foreach ($discussionusers as $user) {
                     // Add to digest. (This will set up the user's
                     // digest if they don't already have one)
                     self::digest_add_post_for_user($user, $userdigests, $post, $inreplyto, $discussion, $forum, $cm, $course, $context);
                 }
                 $postcount++;
             }
         }
     }
     if ($oldcourse) {
         self::digest_finish_course($oldcourse, $userdigests);
     }
     $queryinfo = '';
     if (!empty($PERF->dbqueries)) {
         $queryinfo = ', ' . ($PERF->dbqueries - $beforequeries) . ' queries';
     }
     $totalpostcount = $list->get_post_count_so_far();
     mtrace("Digest processing ({$totalpostcount} new digest posts) complete, total: " . round(microtime(true) - $before, 1) . 's' . $queryinfo);
 }