/**
     * Action called on reject of a face to face action
     *
     * @param array $eventdata
     * @param object $msg
     */
    function onreject($eventdata, $msg) {
        global $DB;

        // can manipulate the language by setting $SESSION->lang temporarily
        // Load course
        $userid = $eventdata['userid'];
        $session = $eventdata['session'];
        $facetoface = $eventdata['facetoface'];
        if (!$course = $DB->get_record('course', array('id' => $facetoface->course))) {
            print_error('error:coursemisconfigured', 'facetoface');
            return false;
        }
        if (!$cm = get_coursemodule_from_instance('facetoface', $facetoface->id, $course->id)) {
            print_error('error:incorrectcoursemodule', 'facetoface');
            return false;
        }
        $form = new stdClass();
        $form->s = $session->id;
        $form->requests = array($userid => 1);  // 2 = approve, 1 = decline
        error_log(var_export($form, true));
        // Decline requests
        if (facetoface_approve_requests($form)) {
            add_to_log($course->id, 'facetoface', 'approve requests', "view.php?id=$cm->id", $facetoface->id, $cm->id);
        }

        // issue notification that registration has been declined
        return $this->acceptreject_notification($userid, $facetoface, $session, 'status_declined');
    }
Example #2
0
/**
 * Adds a record of an action to the log
 *
 * @param int $course_id
 * @param string $log_action the generic short name for the event
 * @param string $log_url (optional, defaults to ASSMGR_LOG_URL_PREFIX)
 * @param string $log_info Detailed explanation of what has happened
 * @return void
 */
function ilp_add_to_log($course_id, $log_action, $log_url, $log_info)
{
    // prepend the url prefix if the log_url is not empty
    $log_url = empty($log_url) ? '' : ILP_LOG_URL_PREFIX . '/' . $log_url;
    // add to the moodle log
    add_to_log($course_id, ILP_LOG_MODULE, $log_action, $log_url, $log_info);
}
 function display()
 {
     global $CFG;
     $formatoptions = new object();
     $formatoptions->noclean = true;
     /// Are we displaying the course blocks?
     if ($this->resource->options == 'showblocks') {
         parent::display_course_blocks_start();
         echo format_text($this->resource->alltext, FORMAT_HTML, $formatoptions, $this->course->id);
         parent::display_course_blocks_end();
     } else {
         /// Set up generic stuff first, including checking for access
         parent::display();
         /// Set up some shorthand variables
         $cm = $this->cm;
         $course = $this->course;
         $resource = $this->resource;
         $pagetitle = strip_tags($course->shortname . ': ' . format_string($resource->name));
         $inpopup = optional_param('inpopup', '', PARAM_BOOL);
         // fix for MDL-9021, thanks Etienne Roz
         add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id);
         if ($resource->popup) {
             if ($inpopup) {
                 /// Popup only
                 print_header();
                 print_simple_box(format_text($resource->alltext, FORMAT_HTML, $formatoptions, $course->id), "center clearfix", "", "", "20");
                 print_footer($course);
             } else {
                 /// Make a page and a pop-up window
                 $this->navlinks[] = array('name' => format_string($resource->name), 'link' => '', 'type' => 'activityinstance');
                 $this->navigation = build_navigation($this->navlinks);
                 print_header($pagetitle, $course->fullname, $this->navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm));
                 echo "\n<script type=\"text/javascript\">";
                 echo "\n//<![CDATA[\n";
                 echo "openpopup('/mod/resource/view.php?inpopup=true&id={$cm->id}','resource{$resource->id}','{$resource->popup}');\n";
                 echo "\n//]]>\n";
                 echo '</script>';
                 if (trim(strip_tags($resource->summary))) {
                     print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $course->id), "center clearfix");
                 }
                 $link = "<a href=\"{$CFG->wwwroot}/mod/resource/view.php?inpopup=true&amp;id={$cm->id}\" onclick=\"this.target='resource{$resource->id}'; return openpopup('/mod/resource/view.php?inpopup=true&amp;id={$cm->id}', 'resource{$resource->id}','{$resource->popup}');\">" . format_string($resource->name, true) . "</a>";
                 echo '<div class="popupnotice">';
                 print_string('popupresource', 'resource');
                 echo '<br />';
                 print_string('popupresourcelink', 'resource', $link);
                 echo '</div>';
                 print_footer($course);
             }
         } else {
             /// not a popup at all
             $this->navlinks[] = array('name' => format_string($resource->name), 'link' => '', 'type' => 'activityinstance');
             $this->navigation = build_navigation($this->navlinks);
             print_header($pagetitle, $course->fullname, $this->navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm));
             print_simple_box(format_text($resource->alltext, FORMAT_HTML, $formatoptions, $course->id), "center clearfix", "", "", "20");
             $strlastmodified = get_string("lastmodified");
             echo "<div class=\"modified\">{$strlastmodified}: " . userdate($resource->timemodified) . "</div>";
             print_footer($course);
         }
     }
 }
Example #4
0
function _unenrollUserFromCourse($user, $course)
{
    $retVal = true;
    echo "<br> {$username} is now going to be unenrolled from {$course->fullname}.";
    if (unenrollQSUser($user, $course)) {
        echo "<br> unenrollQSUser for {$user->username} and {$course->fullname} was successful.";
        if (enrollUserInCourse($user->username, $user->username, $course->fullname, false)) {
            echo "<br> enrollUserInCourse for {$user->username} and {$course->fullname} and false was successful.";
            if (!($context = get_context_instance(CONTEXT_COURSE, $course->id))) {
                echo "<br> Course context for {$course->fullname} is invalid";
                admin_moodlefailed_email($user, 'unenrollUser', $course);
                $retVal = false;
            }
            echo "<br> Course context id is {$context->id}";
            if (!role_unassign(0, $user->id, 0, $context->id)) {
                echo "An error occurred in role_unassign while trying to unenroll {$username} from vLab via auto-delete.";
                admin_moodlefailed_email($user, 'unenrollUser', $course);
                $retVal = false;
            }
            echo "<br> role_unassign for user id of {$user->id} and context id of {$context->id} was successful.";
            send_unenrollment_notification($course, $user);
            add_to_log($course->id, 'course', 'unenrol', "auto-delete", $course->id);
        } else {
            enrollQSUser($user, $course);
            echo "An error occurred in enrollUserInCourse while trying to unenrll {$username} from vLab via auto-delete.";
            admin_moodlefailed_email($user, 'unenrollUser', $course);
            $retVal = false;
        }
    } else {
        echo "An error occurred in unenrollQSUser while trying to unenroll {$username} from vLab via auto-delete.";
        admin_moodlefailed_email($user, 'unenrollUser', $course);
        $retVal = false;
    }
    return $retVal;
}
 function display()
 {
     global $CFG;
     $formatoptions = new object();
     $formatoptions->noclean = true;
     /// Are we displaying the course blocks?
     if ($this->resource->options == 'showblocks') {
         parent::display_course_blocks_start();
         $entry = get_record('kaltura_entries', 'context', "R_" . "{$this->resource}->id");
         if (trim(strip_tags($this->resource->alltext))) {
             echo $entry->title;
             $player_url = $CFG->wwwroot . '/mod/kaltura/kswfdoc.php?context=' . $this->course->id . '&entry_id=' . $resource->alltext;
             $formatoptions = new object();
             $formatoptions->noclean = true;
             print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $this->course->id), "center");
             if ($resource->alltext) {
                 echo '<input style="margin-top:20px;" type="button" value="View video presentation" onclick="kalturaInitModalBox(\'' . $player_url . '\', {width:780, height:400});">';
             }
             //            echo embed_kaltura($resource->alltext,get_width($entry),get_height($entry),$entry->entry_type);
         }
         parent::display_course_blocks_end();
     } else {
         /// Set up generic stuff first, including checking for access
         parent::display();
         /// Set up some shorthand variables
         $cm = $this->cm;
         $course = $this->course;
         $resource = $this->resource;
         $entry = get_record('kaltura_entries', 'context', "R_" . "{$resource->id}");
         $pagetitle = strip_tags($course->shortname . ': ' . format_string($resource->name));
         $inpopup = optional_param('inpopup', '', PARAM_BOOL);
         add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id);
         $navigation = build_navigation($this->navlinks, $cm);
         print_header($pagetitle, $course->fullname, $navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm));
         if (trim(strip_tags($this->resource->alltext))) {
             echo $entry->title;
         }
         $formatoptions = new object();
         $formatoptions->noclean = true;
         print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $this->course->id), "center");
         if (trim(strip_tags($this->resource->alltext))) {
             $player_url = $CFG->wwwroot . '/mod/kaltura/kswfdoc.php?context=' . $this->course->id . '&entry_id=' . $resource->alltext;
             if ($resource->alltext) {
                 echo '<input type="button" style="margin-top:20px;"  value="View video presentation" onclick="kalturaInitModalBox(\'' . $player_url . '\', {width:780, height:400});">';
             }
             //          echo embed_kaltura($resource->alltext,get_width($entry),get_height($entry),$entry->entry_type);
         }
         /*       print_simple_box(format_text($resource->alltext, $resource->reference, $formatoptions, $course->id),
                         "center", "", "", "20");
         */
         $strlastmodified = get_string("lastmodified");
         echo "<div class=\"modified\">{$strlastmodified}: " . userdate($resource->timemodified) . "</div>";
         print_footer($course);
     }
 }
 function display()
 {
     global $CFG;
     $formatoptions = new object();
     $formatoptions->noclean = true;
     /// Are we displaying the course blocks?
     if ($this->resource->options == 'showblocks') {
         parent::display_course_blocks_start();
         $entry = get_record('kaltura_entries', 'context', "R_" . "{$this->resource}->id");
         if (trim(strip_tags($this->resource->alltext))) {
             echo $entry->title;
             $context = get_context_instance(CONTEXT_COURSE, $this->course->id);
             $formatoptions = new object();
             $formatoptions->noclean = true;
             print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $this->course->id), "center");
             if (has_capability('moodle/course:manageactivities', $context)) {
                 echo embed_kaltura($resource->alltext, get_width($entry), get_height($entry), $entry->entry_type, $entry->design, true);
             } else {
                 echo embed_kaltura($resource->alltext, get_width($entry), get_height($entry), KalturaEntryType::MEDIA_CLIP, $entry->design, true);
             }
         }
         parent::display_course_blocks_end();
     } else {
         /// Set up generic stuff first, including checking for access
         parent::display();
         /// Set up some shorthand variables
         $cm = $this->cm;
         $course = $this->course;
         $resource = $this->resource;
         $entry = get_record('kaltura_entries', 'context', "R_" . "{$resource->id}");
         $pagetitle = strip_tags($course->shortname . ': ' . format_string($resource->name));
         $inpopup = optional_param('inpopup', '', PARAM_BOOL);
         add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id);
         $navigation = build_navigation($this->navlinks, $cm);
         print_header($pagetitle, $course->fullname, $navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm));
         if (trim(strip_tags($this->resource->alltext))) {
             echo $entry->title;
             $context = get_context_instance(CONTEXT_COURSE, $this->course->id);
             $formatoptions = new object();
             $formatoptions->noclean = true;
             print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $this->course->id), "center");
             if (has_capability('moodle/course:manageactivities', $context)) {
                 echo embed_kaltura($resource->alltext, get_width($entry), get_height($entry), $entry->entry_type, $entry->design, true);
             } else {
                 echo embed_kaltura($resource->alltext, get_width($entry), get_height($entry), KalturaEntryType::MEDIA_CLIP, $entry->design, true);
             }
         }
         /*       print_simple_box(format_text($resource->alltext, $resource->reference, $formatoptions, $course->id),
                         "center", "", "", "20");
         */
         $strlastmodified = get_string("lastmodified");
         echo "<div class=\"modified\">{$strlastmodified}: " . userdate($resource->timemodified) . "</div>";
         print_footer($course);
     }
 }
/**
 * oauth_add_to_log is a quick hack to avoid add_to_log debugging
 */
function oauth_add_to_log($courseid, $module, $action, $url = '', $info = '', $cm = 0, $user = 0)
{
    if (function_exists('get_log_manager')) {
        $manager = get_log_manager();
        $manager->legacy_add_to_log($courseid, $module, $action, $url, $info, $cm, $user);
    } else {
        if (function_exists('add_to_log')) {
            add_to_log($courseid, $module, $action, $url, $info, $cm, $user);
        }
    }
}
 /**
  * override smbwebclient debugging function with function that logs to Moodle logs
  * (non-PHPdoc)
  * @see blocks/smb_web_client/smbwebclient#Debug($message, $level)
  */
 function Debug($message, $level = 0)
 {
     if ($level <= $this->debug) {
         foreach (preg_split('/\\n/', $message) as $line) {
             // Fixed deprecated split function by Jon Witts 2010090600
             if (trim($line) != '') {
                 add_to_log(1, 'smb_webclient', 'view', '', substr($line, 0, 252) . '...');
             }
         }
     }
 }
Example #9
0
 /**
  * Check that the user is logged-in and has permission to alter course settings.
  */
 function check_permission()
 {
     // Ensure the user logs in
     require_login($this->course->id);
     if (isguestuser()) {
         error(get_string('noguestaccess', 'sloodle'));
     }
     add_to_log($this->course->id, 'course', 'view sloodle data', '', "{$this->course->id}");
     // Ensure the user is allowed to update information on this course
     $this->course_context = get_context_instance(CONTEXT_COURSE, $this->course->id);
     require_capability('moodle/course:update', $this->course_context);
 }
Example #10
0
 function doListKeywords()
 {
     global $USER;
     $user = get_record('user', 'username', $this->currentUserId);
     if ($user) {
         $keywords = annotation_keywords_db::list_keywords($user->id);
         $logurl = 'keywords.php';
         add_to_log(null, 'annotation', 'list', $logurl);
         return $keywords;
     } else {
         return array();
     }
 }
/**
 * Save the wikitags list 
 *
 * @param Object $WS WikiStorage
 * @param String $taglist Comma-separated tags
 */
function wiki_tags_save_tags($WS, $taglist)
{
    global $COURSE;
    add_to_log($COURSE->id, 'wiki', 'save tags', addslashes("view.php?id={$WS->cm->id}&amp;page={$WS->page}"), $WS->dfwiki->id, $WS->cm->id);
    $page = wiki_page_last_version($WS->page, $WS);
    // delete the tags of the current wiki page version
    /*
     *$tagids = tag_get_tags_ids('wiki', $taglist);
     *foreach ($tagids as $tagid)
     *    tag_delete_instance('wiki', $page->created, $tagid);
     */
    // add the tags to the next wiki page
    tag_set('wiki', $page->created, explode(',', $taglist));
}
Example #12
0
/**
 * Function for either adding to log or triggering an event
 * depending on Moodle version
 * @param int $courseid Moodle course ID
 * @param string $event_name The event we are logging
 * @param string $link A link to the Turnitin activity
 * @param string $desc Description of the logged event
 * @param int $cmid Course module id
 */
function turnitintooltwo_add_to_log($courseid, $event_name, $link, $desc, $cmid, $userid = 0)
{
    global $CFG, $USER;
    if ((property_exists($CFG, 'branch') and $CFG->branch < 27) || !property_exists($CFG, 'branch')) {
        add_to_log($courseid, "turnitintooltwo", $event_name, $link, $desc, $cmid);
    } else {
        $event_name = str_replace(' ', '_', $event_name);
        $event_path = '\\mod_turnitintooltwo\\event\\' . $event_name;
        $data = array('objectid' => $cmid, 'context' => $cmid == 0 ? context_course::instance($courseid) : context_module::instance($cmid), 'other' => array('desc' => $desc));
        if (!empty($userid) && $userid != $USER->id) {
            $data['relateduserid'] = $userid;
        }
        $event = $event_path::create($data);
        $event->trigger();
    }
}
 public function __sendPassword($email)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     $response = new CliniqueServiceResponce();
     if (!empty($email) || !$email) {
         $select = $DB->sql_like('email', ':email', false, true, false, '|') . " AND mnethostid = :mnethostid AND deleted=0 AND suspended=0";
         $params = array('email' => $DB->sql_like_escape($email, '|'), 'mnethostid' => $CFG->mnet_localhost_id);
         $user = $DB->get_record_select('user', $select, $params, '*', IGNORE_MULTIPLE);
         if ($user and ($user->auth === 'nologin' or !is_enabled_auth($user->auth))) {
             // bad luck - user is not able to login, do not let them reset password
             $user = false;
             $response->response(true, 'fp_nologin');
             die;
         }
         if (!empty($user)) {
             if (is_mnet_remote_user($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Forgot password - mnet user trying to access.', 0, $user->id);
                 $response->response(true, 'cp_mnet_user');
                 die;
             }
             if (isguestuser($user)) {
                 add_to_log(-1, 'custom_webservice', 'guest_user', null, 'Forgot password - guest user credential supplied.', 0, $user->id);
                 $response->response(true, 'fp_guest');
                 die;
             }
             // make sure user is allowed to change password
             require_capability('moodle/user:changeownpassword', $systemcontext, $user->id);
             if (!ForgotPassword::__app_reset_password_and_mail($user)) {
                 add_to_log(-1, 'custom_webservice', 'trigger_mail', null, 'Forgot password - email triggering failure.', 0, $user->id);
                 $response->response(true, 'fp_email_failure');
             } else {
                 set_user_preference('auth_forcepasswordchange', true, $user->id);
                 $response->response(true, 'fp_email_success');
             }
         } else {
             $response->response(false, 'fp_no_record');
         }
     } else {
         add_to_log(-1, 'custom_webservice', 'input_parameters', null, 'Forgot password - input parameters missing.', 0, $user->id);
     }
 }
 public function __getPassword($username, $email, $old_password, $new_password)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     $response = new CliniqueServiceResponce();
     if (!empty($username) && !empty($old_password) && !empty($new_password)) {
         $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0));
         if (!empty($user)) {
             if (is_mnet_remote_user($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Change password - mnet user trying to access.', 0, $user->id);
                 $response->response(true, 'cp_mnet_user');
                 die;
             }
             if (isguestuser($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Change password - guest user credential supplied.', 0, $user->id);
                 $response->response(true, 'cp_guest');
                 die;
             }
             // make sure user is allowed to change password
             require_capability('moodle/user:changeownpassword', $systemcontext, $user->id);
             // $generatePasswordResult = generatePassword::app_validate_internal_user_password($user, $old_password);
             if (!ChangePassword::__app_validate_internal_user_password($user, $old_password)) {
                 $response->response(true, 'cp_wrong_oldpwd');
             } else {
                 $userauth = get_auth_plugin($user->auth);
                 if ($userauth->user_update_password($user, $new_password)) {
                     unset_user_preference('auth_forcepasswordchange', $user);
                     unset_user_preference('create_password', $user);
                     $response->response(false, 'cp_success');
                 } else {
                     add_to_log(-1, 'custom_webservice', 'trigger_mail', null, 'Change password - password change updation failure.', 0, $user->id);
                     $response->response(true, 'cp_failure');
                 }
             }
         } else {
             $response->response(false, 'cp_no_mail_record');
         }
     } else {
         add_to_log(-1, 'custom_webservice', 'input_parameters', null, 'Change password - input parameters missing.', 0, $user->id);
     }
 }
 function process_feedback()
 {
     global $USER;
     if (!($feedback = data_submitted())) {
         // No incoming data?
         return false;
     }
     ///For save and next, we need to know the userid to save, and the userid to go
     ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
     ///as the userid to store
     if ((int) $feedback->saveuserid !== -1) {
         $feedback->userid = $feedback->saveuserid;
     }
     if (!empty($feedback->cancel)) {
         // User hit cancel button
         return false;
     }
     $submission = $this->get_submission($feedback->userid, true);
     // Get or make one
     $submission->grade = $feedback->grade;
     $submission->submissioncomment = $feedback->submissioncomment;
     $submission->format = $feedback->format;
     $submission->teacher = $USER->id;
     $submission->mailed = 0;
     // Make sure mail goes out (again, even)
     $submission->timemarked = time();
     unset($submission->data1);
     // Don't need to update this.
     unset($submission->data2);
     // Don't need to update this.
     if (empty($submission->timemodified)) {
         // eg for offline assignments
         $submission->timemodified = time();
     }
     if (!update_record('assignment_submissions', $submission)) {
         return false;
     }
     add_to_log($this->course->id, 'assignment', 'update grades', 'submissions.php?id=' . $this->assignment->id . '&user=' . $feedback->userid, $feedback->userid, $this->cm->id);
     return $submission;
 }
 /**
  * This functions created news folders
  *
  * @param object $folder Fields of new folder
  * @param int $parentfolder Parent folder
  * @return boolean Success/Fail
  * @todo Finish documenting this function
  **/
 function newfolder($folder, $parentfolder)
 {
     // Add actual time
     $folder->timecreated = time();
     // Make sure course field is not null			Thanks Ann.
     if (!isset($folder->course)) {
         $folder->course = 0;
     }
     // Insert record
     if (!($folder->id = insert_record('email_folder', $folder))) {
         return false;
     }
     // Prepare subfolder
     $subfolder = new stdClass();
     $subfolder->folderparentid = $parentfolder;
     $subfolder->folderchildid = $folder->id;
     // Insert record reference
     if (!insert_record('email_subfolder', $subfolder)) {
         return false;
     }
     add_to_log($folder->userid, "email", "add subfolder", "{$folder->name}");
     return true;
 }
Example #17
0
    //first element in array
} elseif (!in_array($mode, $reportlist)) {
    print_error('erroraccessingreport', 'quiz');
}
// if no questions have been set up yet redirect to edit.php
if (!$quiz->questions and has_capability('mod/quiz:manage', $context)) {
    redirect('edit.php?cmid=' . $cm->id);
}
// Upgrade any attempts that have not yet been upgraded to the
// Moodle 1.5 model (they will not yet have the timestamp set)
if ($attempts = $DB->get_records_sql("SELECT a.*" . "  FROM {quiz_attempts} a, {question_states} s" . " WHERE a.quiz = ? AND s.attempt = a.uniqueid AND s.timestamp = 0", array($quiz->id))) {
    foreach ($attempts as $attempt) {
        quiz_upgrade_states($attempt);
    }
}
add_to_log($course->id, "quiz", "report", "report.php?id={$cm->id}", "{$quiz->id}", "{$cm->id}");
/// Open the selected quiz report and display it
if (!is_readable("report/{$mode}/report.php")) {
    print_error('reportnotfound', 'quiz', '', $mode);
}
include "report/default.php";
// Parent class
include "report/{$mode}/report.php";
$reportclassname = "quiz_{$mode}_report";
$report = new $reportclassname();
if (!$report->display($quiz, $cm, $course)) {
    // Run the report!
    print_error("preprocesserror", 'quiz');
}
/// Print footer
print_footer($course);
Example #18
0
/// Some capability checks.
if (empty($cm->visible) and !has_capability('moodle/course:viewhiddenactivities', $context)) {
    notice(get_string("activityiscurrentlyhidden"));
}
if (!has_capability('mod/forum:viewdiscussion', $context)) {
    notice(get_string('noviewdiscussionspermission', 'forum'));
}
/// find out current groups mode
groups_print_activity_menu($cm, 'view.php?id=' . $cm->id);
$currentgroup = groups_get_activity_group($cm);
$groupmode = groups_get_activity_groupmode($cm);
/// Okay, we can show the discussions. Log the forum view.
if ($cm->id) {
    add_to_log($course->id, "forum", "view forum", "view.php?id={$cm->id}", "{$forum->id}", $cm->id);
} else {
    add_to_log($course->id, "forum", "view forum", "view.php?f={$forum->id}", "{$forum->id}");
}
/// Print settings and things across the top
// If it's a simple single discussion forum, we need to print the display
// mode control.
if ($forum->type == 'single') {
    if (!($discussion = get_record("forum_discussions", "forum", $forum->id))) {
        if ($discussions = get_records("forum_discussions", "forum", $forum->id, "timemodified ASC")) {
            $discussion = array_pop($discussions);
        }
    }
    if ($discussion) {
        if ($mode) {
            set_user_preference("forum_displaymode", $mode);
        }
        $displaymode = get_user_preferences("forum_displaymode", $CFG->forum_displaymode);
Example #19
0
                redirect($CFG->wwwroot . '/my/index.php');
            }
        }
    }
} else {
    // if upgrading from 1.6 or below
    if (isadmin() && moodle_needs_upgrading()) {
        redirect($CFG->wwwroot . '/' . $CFG->admin . '/index.php');
    }
}
if (get_moodle_cookie() == '') {
    set_moodle_cookie('nobody');
    // To help search for cookies on login page
}
if (!empty($USER->id)) {
    add_to_log(SITEID, 'course', 'view', 'view.php?id=' . SITEID, SITEID);
}
if (empty($CFG->langmenu)) {
    $langmenu = '';
} else {
    $currlang = current_language();
    $langs = get_list_of_languages();
    $langlabel = get_accesshide(get_string('language'));
    $langmenu = popup_form($CFG->wwwroot . '/index.php?lang=', $langs, 'chooselang', $currlang, '', '', '', true, 'self', $langlabel);
}
$PAGE = page_create_object(PAGE_COURSE_VIEW, SITEID);
$pageblocks = blocks_setup($PAGE);
$editing = $PAGE->user_is_editing();
$preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), BLOCK_L_MAX_WIDTH);
$preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), BLOCK_R_MAX_WIDTH);
print_header($SITE->fullname, $SITE->fullname, 'home', '', '<meta name="description" content="' . strip_tags(format_text($SITE->summary, FORMAT_HTML)) . '" />', true, '', user_login_string($SITE) . $langmenu);
Example #20
0
                if (!role_unassign($roleid, $removeuser, 0, $context->id)) {
                    $errors[] = "Could not remove user with id {$removeuser} from this role!";
                } else {
                    if ($inmeta) {
                        sync_metacourse($courseid);
                        $newroles = get_user_roles($context, $removeuser, false);
                        if (!empty($newroles) and !array_key_exists($roleid, $newroles)) {
                            $erruser = get_record('user', 'id', $removeuser, '', '', '', '', 'id, firstname, lastname');
                            $errors[] = get_string('metaunassignerror', 'role', fullname($erruser));
                            $allow = false;
                        }
                    }
                }
            }
            $rolename = get_field('role', 'name', 'id', $roleid);
            add_to_log($course->id, 'role', 'unassign', 'admin/roles/assign.php?contextid=' . $context->id . '&roleid=' . $roleid, $rolename, '', $USER->id);
        } else {
            if ($showall) {
                $searchtext = '';
                $previoussearch = 0;
            }
        }
    }
}
if ($context->contextlevel == CONTEXT_COURSE and $context->instanceid == SITEID) {
    print_heading_with_help(get_string('frontpageroles', 'admin'), 'assignroles');
} else {
    print_heading_with_help(get_string('assignrolesin', 'role', print_context_name($context)), 'assignroles');
}
if ($context->contextlevel == CONTEXT_SYSTEM) {
    print_box(get_string('globalroleswarning', 'role'));
Example #21
0
            }
            /// For each field in the add form, add it to the data_content.
            foreach ($datarecord as $name => $value) {
                if (!in_array($name, $ignorenames)) {
                    $namearr = explode('_', $name);
                    // Second one is the field id
                    if (empty($field->field) || $namearr[1] != $field->field->id) {
                        // Try to reuse classes
                        $field = data_get_field_from_id($namearr[1], $data);
                    }
                    if ($field) {
                        $field->update_content($recordid, $value, $name);
                    }
                }
            }
            add_to_log($course->id, 'data', 'add', "view.php?d={$data->id}&amp;rid={$recordid}", $data->id, $cm->id);
            if (!empty($datarecord->saveandview)) {
                redirect($CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&rid=' . $recordid);
            }
        }
    }
}
// End of form processing
/// Print the page header
echo $OUTPUT->header();
groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/data/edit.php?d=' . $data->id);
echo $OUTPUT->heading(format_string($data->name));
/// Print the tabs
$currenttab = 'add';
if ($rid) {
    $editentry = true;
Example #22
0
if (isset($SESSION->scorm_scoid)) {
    unset($SESSION->scorm_scoid);
}
$strscorms = get_string("modulenameplural", "scorm");
$strscorm = get_string("modulename", "scorm");
if ($course->id != SITEID) {
    if ($scorms = get_all_instances_in_course('scorm', $course)) {
        // The module SCORM activity with the least id is the course
        $firstscorm = current($scorms);
        if (!($course->format == 'scorm' && $firstscorm->id == $scorm->id)) {
            $navlinks[] = array('name' => $strscorms, 'link' => "index.php?id={$course->id}", 'type' => 'activity');
        }
    }
}
$pagetitle = strip_tags($course->shortname . ': ' . format_string($scorm->name));
add_to_log($course->id, 'scorm', 'pre-view', 'view.php?id=' . $cm->id, "{$scorm->id}");
if (has_capability('mod/scorm:skipview', get_context_instance(CONTEXT_MODULE, $cm->id)) && scorm_simple_play($scorm, $USER)) {
    exit;
}
//
// Print the page header
//
$navlinks = array();
$navlinks[] = array('name' => format_string($scorm->name, true), 'link' => "view.php?id={$cm->id}", 'type' => 'activityinstance');
$navigation = build_navigation($navlinks);
print_header($pagetitle, $course->fullname, $navigation, '', '', true, update_module_button($cm->id, $course->id, $strscorm), navmenu($course, $cm));
if (has_capability('mod/scorm:viewreport', $context)) {
    $trackedusers = scorm_get_count_users($scorm->id, $cm->groupingid);
    if ($trackedusers > 0) {
        echo "<div class=\"reportlink\"><a {$CFG->frametarget} href=\"report.php?id={$cm->id}\"> " . get_string('viewalluserreports', 'scorm', $trackedusers) . '</a></div>';
    } else {
Example #23
0
/**
 * Function that deletes a role and cleanups up after it
 *
 * @param int $roleid id of role to delete
 * @return bool always true
 */
function delete_role($roleid)
{
    global $DB;
    // first unssign all users
    role_unassign_all(array('roleid' => $roleid));
    // cleanup all references to this role, ignore errors
    $DB->delete_records('role_capabilities', array('roleid' => $roleid));
    $DB->delete_records('role_allow_assign', array('roleid' => $roleid));
    $DB->delete_records('role_allow_assign', array('allowassign' => $roleid));
    $DB->delete_records('role_allow_override', array('roleid' => $roleid));
    $DB->delete_records('role_allow_override', array('allowoverride' => $roleid));
    $DB->delete_records('role_names', array('roleid' => $roleid));
    $DB->delete_records('role_context_levels', array('roleid' => $roleid));
    // finally delete the role itself
    // get this before the name is gone for logging
    $rolename = $DB->get_field('role', 'name', array('id' => $roleid));
    $DB->delete_records('role', array('id' => $roleid));
    add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid=' . $roleid, $rolename, '');
    return true;
}
Example #24
0
 /**
  * add a single association for a blog entry
  * @param int contextid - id of context to associate with the blog entry
  */
 public function add_association($contextid, $action = 'add')
 {
     global $DB, $USER;
     $assocobject = new StdClass();
     $assocobject->contextid = $contextid;
     $assocobject->blogid = $this->id;
     $DB->insert_record('blog_association', $assocobject);
     $context = get_context_instance_by_id($contextid);
     $courseid = null;
     if ($context->contextlevel == CONTEXT_COURSE) {
         $courseid = $context->instanceid;
         add_to_log($courseid, 'blog', $action, 'index.php?userid=' . $this->userid . '&entryid=' . $this->id, $this->subject);
     } else {
         if ($context->contextlevel == CONTEXT_MODULE) {
             $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
             $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
             add_to_log($cm->course, 'blog', $action, 'index.php?userid=' . $this->userid . '&entryid=' . $this->id, $this->subject, $cm->id, $this->userid);
         }
     }
 }
Example #25
0
                    echo "</tr>\n";
                }
                if ($curUrl != null) {
                    echo "</tbody>\n";
                }
                echo "</table>\n";
                // print the page content
                //		echo "<p><a href='summary.php?course=$courseId'>Show all of my annotations for this course</a></p>\n";
            }
            //$moodlePath = getMoodlePath( );
            // Show link to parent search
            if (null != $query->parentSummaryTitle()) {
                $excludeFields = join('+', $excludeFields);
                $turl = $query->getSummaryUrl($query->parentSummaryUrl(), $searchUser, $searchOf, $searchQuery);
                echo "<p><a href='" . htmlspecialchars("{$turl}&exclude={$excludeFields}") . "'>Show " . htmlspecialchars($query->desc($query->parentSummaryTitle())) . "</a></p>\n";
            }
            // Provide a feed URL.  I don't know how to do authentication for the feed, so for now
            // if a login is required I won't include the feature.
            if (!ANNOTATION_REQUIRE_USER) {
                $turl = $query->getFeedUrl('atom');
                echo "<p class='feed' title='" . get_string('atom_feed', ANNOTATION_STRINGS) . "'><a href='" . htmlspecialchars($turl) . "'><img border='0' alt='" . get_string('atom_feed', ANNOTATION_STRINGS) . "' src='{$CFG->wwwroot}/annotation/images/atomicon.gif'/>" . '</a> ' . get_string('atom_feed_desc', ANNOTATION_STRINGS) . "</p>\n";
            }
            echo '<p id="smartcopy-help"><span class="tip">' . get_string('tip', ANNOTATION_STRINGS) . '</span> ' . get_string('smartcopy_help', ANNOTATION_STRINGS) . "</p>\n";
            print_footer($course);
            $logUrl = $_SERVER['REQUEST_URI'];
            $urlParts = parse_url($logUrl);
            $logUrl = array_key_exists('query', $urlParts) ? $urlParts['query'] : null;
            add_to_log(null, 'annotation', 'summary', 'summary.php' . ($logUrl ? '?' . $logUrl : ''), $query->desc(null));
        }
    }
}
 switch ($action) {
     case 'add':
         $dbView->userid = $USER->id;
         if ($dbView->id = insert_record('block_exabeporview', $dbView)) {
             add_to_log(SITEID, 'bookmark', 'add', 'views_mod.php?courseid=' . $courseid . '&id=' . $dbView->id . '&action=add', $dbView->name);
         } else {
             print_error('addposterror', 'block_exabis_eportfolio', $returnurl);
         }
         break;
     case 'edit':
         if (!$view) {
             print_error("bookmarknotfound", "block_exabis_eportfolio");
         }
         $dbView->id = $view->id;
         if (update_record('block_exabeporview', $dbView)) {
             add_to_log(SITEID, 'bookmark', 'update', 'item.php?courseid=' . $courseid . '&id=' . $dbView->id . '&action=edit', $dbView->name);
         } else {
             print_error('updateposterror', 'block_exabis_eportfolio', $returnurl);
         }
         break;
     default:
         print_error("unknownaction", "block_exabis_eportfolio");
         exit;
 }
 // delete all blocks
 delete_records('block_exabeporviewblock', 'viewid', $dbView->id);
 // add blocks
 $blocks = json_decode(stripslashes($formView->blocks));
 foreach ($blocks as $block) {
     $block->viewid = $dbView->id;
     insert_record('block_exabeporviewblock', $block);
Example #27
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
 *
 * @global object
 * @global object
 * @global object
 * @uses CONTEXT_MODULE
 * @uses CONTEXT_COURSE
 * @uses SITEID
 * @uses FORMAT_PLAIN
 * @return void
 */
function forum_cron() {
    global $CFG, $USER, $DB;

    $site = get_site();

    // All users that are subscribed to any post that needs sending,
    // please increase $CFG->extramemorylimit on large sites that
    // send notifications to a large number of users.
    $users = array();
    $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!

    // 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 = $DB->get_record('forum_discussions', array('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 = $DB->get_record('forum', array('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 = $DB->get_record('course', array('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 find course module for forum '.$forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }


            // caching subscribed users of each forum
            if (!isset($subscribedusers[$forumid])) {
                $modcontext = context_module::instance($coursemodules[$forumid]->id);
                if ($subusers = forum_subscribed_users($courses[$courseid], $forums[$forumid], 0, $modcontext, "u.*")) {
                    foreach ($subusers as $postuser) {
                        // this user is subscribed to this forum
                        $subscribedusers[$forumid][$postuser->id] = $postuser->id;
                        $userscount++;
                        if ($userscount > FORUM_CRON_USER_CACHE) {
                            // Store minimal user info.
                            $minuser = new stdClass();
                            $minuser->id = $postuser->id;
                            $users[$postuser->id] = $minuser;
                        } else {
                            // Cache full user record.
                            forum_cron_minimise_user_record($postuser);
                            $users[$postuser->id] = $postuser;
                        }
                    }
                    // Release memory.
                    unset($subusers);
                    unset($postuser);
                }
            }

            $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

            mtrace('Processing user '.$userto->id);

            // Init user caches - we keep the cache for one cycle only,
            // otherwise it could consume too much memory.
            if (isset($userto->username)) {
                $userto = clone($userto);
            } else {
                $userto = $DB->get_record('user', array('id' => $userto->id));
                forum_cron_minimise_user_record($userto);
            }
            $userto->viewfullnames = array();
            $userto->canpost       = array();
            $userto->markposts     = array();

            // set this so that the capabilities are cached, and environment matches receiving user
            cron_setup_user($userto);

            // reset the caches
            foreach ($coursemodules as $forumid=>$unused) {
                $coursemodules[$forumid]->cache       = new stdClass();
                $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
                // Only active enrolled users are in the list of subscribers
                if (!isset($subscribedusers[$forum->id][$userto->id])) {
                    continue; // user does not subscribe to this forum
                }

                // Don't send email if the forum is Q&A and the user has not posted
                // Initial topics are still mailed
                if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
                    mtrace('Did not email '.$userto->id.' because user has not posted in discussion');
                    continue;
                }

                // Get info about the sending user
                if (array_key_exists($post->userid, $users)) { // we might know him/her already
                    $userfrom = $users[$post->userid];
                    if (!isset($userfrom->idnumber)) {
                        // Minimalised user info, fetch full record.
                        $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
                        forum_cron_minimise_user_record($userfrom);
                    }

                } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
                    forum_cron_minimise_user_record($userfrom);
                    // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
                    if ($userscount <= FORUM_CRON_USER_CACHE) {
                        $userscount++;
                        $users[$userfrom->id] = $userfrom;
                    }

                } else {
                    mtrace('Could not find user '.$post->userid);
                    continue;
                }

                //if we want to check that userto and userfrom are not the same person this is probably the spot to do it

                // setup global $COURSE properly - needed for roles and languages
                cron_setup_user($userto, $course);

                // Fill caches
                if (!isset($userto->viewfullnames[$forum->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                if (!isset($userto->canpost[$discussion->id])) {
                    $modcontext = context_module::instance($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();
                        if (isset($users[$userfrom->id])) {
                            $users[$userfrom->id]->groups = array();
                        }
                    }
                    $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                    if (isset($users[$userfrom->id])) {
                        $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 stdClass();
                    $queue->userid       = $userto->id;
                    $queue->discussionid = $discussion->id;
                    $queue->postid       = $post->id;
                    $queue->timemodified = $post->created;
                    $DB->insert_record('forum_queue', $queue);
                    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 (  // Headers to make emails easier to track
                           'Precedence: Bulk',
                           'List-Id: "'.$cleanforumname.'" <moodleforum'.$forum->id.'@'.$hostname.'>',
                           'List-Help: '.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id,
                           'Message-ID: '.forum_get_email_message_id($post->id, $userto->id, $hostname),
                           'X-Course-Id: '.$course->id,
                           'X-Course-Name: '.format_string($course->fullname, true)
                );

                if ($post->parent) {  // This post is a reply, so add headers for threading (see MDL-22551)
                    $userfrom->customheaders[] = 'In-Reply-To: '.forum_get_email_message_id($post->parent, $userto->id, $hostname);
                    $userfrom->customheaders[] = 'References: '.forum_get_email_message_id($post->parent, $userto->id, $hostname);
                }

                $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));

                $postsubject = html_to_text("$shortname: ".format_string($post->subject, true));
                $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
                $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto);

                // Send the post now!

                mtrace('Sending ', '');

                $eventdata = new stdClass();
                $eventdata->component        = 'mod_forum';
                $eventdata->name             = 'posts';
                $eventdata->userfrom         = $userfrom;
                $eventdata->userto           = $userto;
                $eventdata->subject          = $postsubject;
                $eventdata->fullmessage      = $posttext;
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml  = $posthtml;
                $eventdata->notification = 1;

                // If forum_replytouser is not set then send mail using the noreplyaddress.
                if (empty($CFG->forum_replytouser)) {
                    // Clone userfrom as it is referenced by $users.
                    $cloneduserfrom = clone($userfrom);
                    $cloneduserfrom->email = $CFG->noreplyaddress;
                    $eventdata->userfrom = $cloneduserfrom;
                }

                $smallmessagestrings = new stdClass();
                $smallmessagestrings->user = fullname($userfrom);
                $smallmessagestrings->forumname = "$shortname: ".format_string($forum->name,true).": ".$discussion->name;
                $smallmessagestrings->message = $post->message;
                //make sure strings are in message recipients language
                $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);

                $eventdata->contexturl = "{$CFG->wwwroot}/mod/forum/discuss.php?d={$discussion->id}#p{$post->id}";
                $eventdata->contexturlname = $discussion->name;

                $mailresult = message_send($eventdata);
                if (!$mailresult){
                    mtrace("Error: mod/forum/lib.php forum_cron(): 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 {
                    $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);
            unset($userto);
        }
    }

    if ($posts) {
        foreach ($posts as $post) {
            mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
            if ($errorcount[$post->id]) {
                $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
            }
        }
    }

    // release some memory
    unset($subscribedusers);
    unset($mailcount);
    unset($errorcount);

    cron_setup_user();

    $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);
    $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
    mtrace ('Cleaned old digest records');

    if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {

        mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));

        $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));

        if ($digestposts_rs->valid()) {

            // We have work to do
            $usermailcount = 0;

            //caches - reuse the those filled before too
            $discussionposts = array();
            $userdiscussions = array();

            foreach ($digestposts_rs as $digestpost) {
                if (!isset($posts[$digestpost->postid])) {
                    if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
                        $posts[$digestpost->postid] = $post;
                    } else {
                        continue;
                    }
                }
                $discussionid = $digestpost->discussionid;
                if (!isset($discussions[$discussionid])) {
                    if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
                        $discussions[$discussionid] = $discussion;
                    } else {
                        continue;
                    }
                }
                $forumid = $discussions[$discussionid]->forum;
                if (!isset($forums[$forumid])) {
                    if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
                        $forums[$forumid] = $forum;
                    } else {
                        continue;
                    }
                }

                $courseid = $forums[$forumid]->course;
                if (!isset($courses[$courseid])) {
                    if ($course = $DB->get_record('course', array('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;
            }
            $digestposts_rs->close(); /// 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

                cron_setup_user();

                mtrace(get_string('processingdigest', 'forum', $userid), '... ');

                // First of all delete all the queue entries for this user
                $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));

                // Init user caches - we keep the cache for one cycle only,
                // otherwise it would unnecessarily consume memory.
                if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
                    $userto = clone($users[$userid]);
                } else {
                    $userto = $DB->get_record('user', array('id' => $userid));
                    forum_cron_minimise_user_record($userto);
                }
                $userto->viewfullnames = array();
                $userto->canpost       = array();
                $userto->markposts     = array();

                // Override the language and timezone of the "current" user, so that
                // mail is customised for the receiver.
                cron_setup_user($userto);

                $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));

                $headerdata = new stdClass();
                $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) {
                    //TODO: MDL-21120
                    $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
                    cron_setup_user($userto, $course);

                    // Fill caches
                    if (!isset($userto->viewfullnames[$forum->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                    }
                    if (!isset($userto->canpost[$discussion->id])) {
                        $modcontext = context_module::instance($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];
                    $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));

                    $posttext .= "\n \n";
                    $posttext .= '=====================================================================';
                    $posttext .= "\n \n";
                    $posttext .= "$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\">$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];
                            if (!isset($userfrom->idnumber)) {
                                $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
                                forum_cron_minimise_user_record($userfrom);
                            }

                        } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
                            forum_cron_minimise_user_record($userfrom);
                            if ($userscount <= FORUM_CRON_USER_CACHE) {
                                $userscount++;
                                $users[$userfrom->id] = $userfrom;
                            }

                        } else {
                            mtrace('Could not find user '.$post->userid);
                            continue;
                        }

                        if (!isset($userfrom->groups[$forum->id])) {
                            if (!isset($userfrom->groups)) {
                                $userfrom->groups = array();
                                if (isset($users[$userfrom->id])) {
                                    $users[$userfrom->id]->groups = array();
                                }
                            }
                            $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                            if (isset($users[$userfrom->id])) {
                                $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                            }
                        }

                        $userfrom->customheaders = array ("Precedence: Bulk");

                        if ($userto->maildigest == 2) {
                            // Subjects only
                            $by = new stdClass();
                            $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, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
                            $posthtml .= forum_make_mail_post($course, $cm, $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 class='mdl-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 class='mdl-right'><font size=\"1\">".get_string("everyoneissubscribed", "forum")."</font></div>";
                    }
                    $posthtml .= '<hr size="1" noshade="noshade" /></p>';
                }
                $posthtml .= '</body>';

                if (empty($userto->mailformat) || $userto->mailformat != 1) {
                    // This user DOESN'T want to receive HTML
                    $posthtml = '';
                }

                $attachment = $attachname='';
                // Directly email forum digests rather than sending them via messaging, use the
                // site shortname as 'from name', the noreply address will be used by email_to_user.
                $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname);

                if (!$mailresult) {
                    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 {
                    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);
    }

    cron_setup_user();

    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;
}
Example #28
0
} else {
    $quiz_reordertool = get_user_preferences('quiz_reordertab', 0);
}
$canaddrandom = $contexts->have_cap('moodle/question:useall');
$canaddquestion = (bool) $contexts->having_add_and_use();
$quizhasattempts = quiz_has_attempts($quiz->id);
$PAGE->set_url($thispageurl);
// Get the course object and related bits.
$course = $DB->get_record('course', array('id' => $quiz->course));
if (!$course) {
    print_error('invalidcourseid', 'error');
}
$questionbank = new quiz_question_bank_view($contexts, $thispageurl, $course, $cm, $quiz);
$questionbank->set_quiz_has_attempts($quizhasattempts);
// Log this visit.
add_to_log($cm->course, 'quiz', 'editquestions', "view.php?id={$cm->id}", "{$quiz->id}", $cm->id);
// You need mod/quiz:manage in addition to question capabilities to access this page.
require_capability('mod/quiz:manage', $contexts->lowest());
if (empty($quiz->grades)) {
    $quiz->grades = quiz_get_all_question_grades($quiz);
}
// Process commands ============================================================
if ($quiz->shufflequestions) {
    // Strip page breaks before processing actions, so that re-ordering works
    // as expected when shuffle questions is on.
    $quiz->questions = quiz_repaginate($quiz->questions, 0);
}
// Get the list of question ids had their check-boxes ticked.
$selectedquestionids = array();
$params = (array) data_submitted();
foreach ($params as $key => $value) {
Example #29
0
    print_error('cantunenrollinthisrole', '', $CFG->wwwroot . '/course/view.php?id=' . $course->id);
}
if ($confirm and confirm_sesskey()) {
    if ($userid) {
        if (!role_unassign(0, $userid, 0, $context->id)) {
            print_error("unenrolerror");
        }
        add_to_log($course->id, 'course', 'unenrol', "view.php?id={$course->id}", $course->id);
        redirect($CFG->wwwroot . '/user/index.php?id=' . $course->id);
    } else {
        if (!role_unassign(0, $USER->id, 0, $context->id)) {
            print_error("unenrolerror");
        }
        // force a refresh of mycourses
        unset($USER->mycourses);
        add_to_log($course->id, 'course', 'unenrol', "view.php?id={$course->id}", $course->id);
        redirect($CFG->wwwroot);
    }
}
$strunenrol = get_string('unenrol');
$navlinks = array();
$navlinks[] = array('name' => $strunenrol, 'link' => null, 'type' => 'misc');
$navigation = build_navigation($navlinks);
print_header("{$course->shortname}: {$strunenrol}", $course->fullname, $navigation);
if ($userid) {
    if (!($user = $DB->get_record('user', array('id' => $userid)))) {
        print_error('nousers');
    }
    $strunenrolsure = get_string('unenrolsure', '', fullname($user, true));
    echo $OUTPUT->confirm($strunenrolsure, "unenrol.php?id={$id}&user={$user->id}&confirm=yes", $PAGE->url);
} else {
Example #30
0
     if ($deleterecord = $DB->get_record('data_records', array('id' => $delete))) {
         // Need to check this is valid
         if ($deleterecord->dataid == $data->id) {
             // Must be from this database
             if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id))) {
                 foreach ($contents as $content) {
                     // Delete files or whatever else this field allows
                     if ($field = data_get_field_from_id($content->fieldid, $data)) {
                         // Might not be there
                         $field->delete_content($content->recordid);
                     }
                 }
             }
             $DB->delete_records('data_content', array('recordid' => $deleterecord->id));
             $DB->delete_records('data_records', array('id' => $deleterecord->id));
             add_to_log($course->id, 'data', 'record delete', "view.php?id={$cm->id}", $data->id, $cm->id);
             echo $OUTPUT->notification(get_string('recorddeleted', 'data'), 'notifysuccess');
         }
     }
 } else {
     // Print a confirmation page
     if ($deleterecord = $DB->get_record('data_records', array('id' => $delete))) {
         // Need to check this is valid
         if ($deleterecord->dataid == $data->id) {
             // Must be from this database
             $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d=' . $data->id . '&delete=' . $delete . '&confirm=1'), get_string('delete'), 'post');
             echo $OUTPUT->confirm(get_string('confirmdeleterecord', 'data'), $deletebutton, 'view.php?d=' . $data->id);
             $records[] = $deleterecord;
             echo data_print_template('singletemplate', $records, $data, '', 0, true);
             echo $OUTPUT->footer();
             exit;