Example #1
0
function bloglevelupgrade_entries($blogentries, $forum, $cm, $groupid = -1)
{
    $count = 0;
    $forumcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    foreach ($blogentries as $blogentry) {
        $discussion = new stdClass();
        $discussion->course = $forum->course;
        $discussion->forum = $forum->id;
        $discussion->name = $blogentry->subject;
        $discussion->assessed = $forum->assessed;
        $discussion->message = $blogentry->summary;
        $discussion->messageformat = $forum->introformat;
        $discussion->messagetrust = 0;
        $discussion->attachments = 0;
        $discussion->mailnow = false;
        $discussion->timemodified = $blogentry->created;
        $discussion->itemid = null;
        $discussion->groupid = $groupid;
        $message = '';
        $discussionid = forum_add_discussion($discussion, null, $message);
        // Copy file attachment records
        $fs = get_file_storage();
        $files = $fs->get_area_files($sitecontext->id, 'blog', 'attachment', $blogentry->id);
        if (!empty($files)) {
            foreach ($files as $storedfile) {
                $newfile = new stdClass();
                $newfile->component = 'mod_forum';
                $newfile->filearea = 'attachment';
                $newfile->itemid = $discussion->firstpost;
                $newfile->contextid = $forumcontext->id;
                $fs->create_file_from_storedfile($newfile, $storedfile->get_id());
            }
        }
        $files = $fs->get_area_files($sitecontext->id, 'blog', 'post', $blogentry->id);
        if (!empty($files)) {
            foreach ($files as $storedfile) {
                $newfile = new stdClass();
                $newfile->component = 'mod_forum';
                $newfile->filearea = 'post';
                $newfile->itemid = $discussion->firstpost;
                $newfile->contextid = $forumcontext->id;
                $fs->create_file_from_storedfile($newfile, $storedfile->get_id());
            }
        }
        $count++;
    }
    return $count;
}
Example #2
0
File: lib.php Project: r007/PMoodle
/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod.html) this function
 * will create a new instance and return the id number
 * of the new instance.
 * @param object $forum add forum instance (with magic quotes)
 * @return int intance id
 */
function forum_add_instance($forum)
{
    global $CFG;
    $forum->timemodified = time();
    if (empty($forum->assessed)) {
        $forum->assessed = 0;
    }
    if (empty($forum->ratingtime) or empty($forum->assessed)) {
        $forum->assesstimestart = 0;
        $forum->assesstimefinish = 0;
    }
    if (!($forum->id = insert_record('forum', $forum))) {
        return false;
    }
    if ($forum->type == 'single') {
        // Create related discussion.
        $discussion = new object();
        $discussion->course = $forum->course;
        $discussion->forum = $forum->id;
        $discussion->name = $forum->name;
        $discussion->intro = $forum->intro;
        $discussion->assessed = $forum->assessed;
        $discussion->format = $forum->type;
        $discussion->mailnow = false;
        $discussion->groupid = -1;
        if (!forum_add_discussion($discussion, $discussion->intro)) {
            error('Could not add the discussion for this forum');
        }
    }
    if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
        // all users should be subscribed initially
        $users = get_course_users($forum->course);
        foreach ($users as $user) {
            forum_subscribe($user->id, $forum->id);
        }
    }
    $forum = stripslashes_recursive($forum);
    forum_grade_item_update($forum);
    return $forum->id;
}
Example #3
0
/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will update an existing instance with new data.
 *
 * @global object
 * @param object $forum forum instance (with magic quotes)
 * @return bool success
 */
function forum_update_instance($forum, $mform) {
    global $DB, $OUTPUT, $USER;

    $forum->timemodified = time();
    $forum->id           = $forum->instance;

    if (empty($forum->assessed)) {
        $forum->assessed = 0;
    }

    if (empty($forum->ratingtime) or empty($forum->assessed)) {
        $forum->assesstimestart  = 0;
        $forum->assesstimefinish = 0;
    }

    $oldforum = $DB->get_record('forum', array('id'=>$forum->id));

    // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
    // if  scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
    // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
    if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
        forum_update_grades($forum); // recalculate grades for the forum
    }

    if ($forum->type == 'single') {  // Update related discussion and post.
        $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
        if (!empty($discussions)) {
            if (count($discussions) > 1) {
                echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
            }
            $discussion = array_pop($discussions);
        } else {
            // try to recover by creating initial discussion - MDL-16262
            $discussion = new stdClass();
            $discussion->course          = $forum->course;
            $discussion->forum           = $forum->id;
            $discussion->name            = $forum->name;
            $discussion->assessed        = $forum->assessed;
            $discussion->message         = $forum->intro;
            $discussion->messageformat   = $forum->introformat;
            $discussion->messagetrust    = true;
            $discussion->mailnow         = false;
            $discussion->groupid         = -1;

            $message = '';

            forum_add_discussion($discussion, null, $message);

            if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
                print_error('cannotadd', 'forum');
            }
        }
        if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
            print_error('cannotfindfirstpost', 'forum');
        }

        $cm         = get_coursemodule_from_instance('forum', $forum->id);
        $modcontext = context_module::instance($cm->id, MUST_EXIST);

        $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
        $post->subject       = $forum->name;
        $post->message       = $forum->intro;
        $post->messageformat = $forum->introformat;
        $post->messagetrust  = trusttext_trusted($modcontext);
        $post->modified      = $forum->timemodified;
        $post->userid        = $USER->id;    // MDL-18599, so that current teacher can take ownership of activities.

        if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
            // Ugly hack - we need to copy the files somehow.
            $options = array('subdirs'=>true); // Use the same options as intro field!
            $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
        }

        $DB->update_record('forum_posts', $post);
        $discussion->name = $forum->name;
        $DB->update_record('forum_discussions', $discussion);
    }

    $DB->update_record('forum', $forum);

    $modcontext = context_module::instance($forum->coursemodule);
    if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
        $users = forum_get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
        foreach ($users as $user) {
            forum_subscribe($user->id, $forum->id);
        }
    }

    forum_grade_item_update($forum);

    return true;
}
Example #4
0
    /**
     * Function to create a dummy discussion.
     *
     * @param array|stdClass $record
     * @return stdClass the discussion object
     */
    public function create_forum_discussion($record = null) {
        global $DB;

        // Increment the forum discussion count.
        $this->forumdiscussioncount++;

        $record = (array) $record;

        if (!isset($record['course'])) {
            throw new coding_exception('course must be present in phpunit_util::create_forum_discussion() $record');
        }

        if (!isset($record['forum'])) {
            throw new coding_exception('forum must be present in phpunit_util::create_forum_discussion() $record');
        }

        if (!isset($record['userid'])) {
            throw new coding_exception('userid must be present in phpunit_util::create_forum_discussion() $record');
        }

        if (!isset($record['name'])) {
            $record['name'] = "Discussion " . $this->forumdiscussioncount;
        }

        if (!isset($record['subject'])) {
            $record['subject'] = "Subject for discussion " . $this->forumdiscussioncount;
        }

        if (!isset($record['message'])) {
            $record['message'] = html_writer::tag('p', 'Message for discussion ' . $this->forumdiscussioncount);
        }

        if (!isset($record['messageformat'])) {
            $record['messageformat'] = editors_get_preferred_format();
        }

        if (!isset($record['messagetrust'])) {
            $record['messagetrust'] = "";
        }

        if (!isset($record['assessed'])) {
            $record['assessed'] = '1';
        }

        if (!isset($record['groupid'])) {
            $record['groupid'] = "-1";
        }

        if (!isset($record['timestart'])) {
            $record['timestart'] = "0";
        }

        if (!isset($record['timeend'])) {
            $record['timeend'] = "0";
        }

        if (!isset($record['mailnow'])) {
            $record['mailnow'] = "0";
        }

        $record = (object) $record;

        // Add the discussion.
        $record->id = forum_add_discussion($record, null, null, $record->userid);

        return $record;
    }
Example #5
0
     $fromform->groupid = $fromform->groupinfo;
 }
 if (empty($fromform->groupid)) {
     $fromform->groupid = -1;
 }
 $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
 $discussion = $fromform;
 $discussion->name = $fromform->subject;
 $newstopic = false;
 if ($forum->type == 'news' && !$fromform->parent) {
     $newstopic = true;
 }
 $discussion->timestart = $fromform->timestart;
 $discussion->timeend = $fromform->timeend;
 $message = '';
 if ($discussion->id = forum_add_discussion($discussion, $mform_post, $message)) {
     add_to_log($course->id, "forum", "add discussion", "discuss.php?d={$discussion->id}", "{$discussion->id}", $cm->id);
     $timemessage = 2;
     if (!empty($message)) {
         // if we're printing stuff about the file upload
         $timemessage = 4;
     }
     if ($fromform->mailnow) {
         $message .= get_string("postmailnow", "forum");
         $timemessage = 4;
     } else {
         $message .= '<p>' . get_string("postaddedsuccess", "forum") . '</p>';
         $message .= '<p>' . get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
     }
     if ($subscribemessage = forum_post_subscription($discussion, $forum)) {
         $timemessage = 4;
 protected function after_execute()
 {
     global $DB;
     // Add forum related files, no need to match by itemname (just internally handled context)
     $this->add_related_files('mod_forum', 'intro', null);
     // If the forum is of type 'single' and no discussion has been ignited
     // (non-userinfo backup/restore) create the discussion here, using forum
     // information as base for the initial post.
     $forumid = $this->task->get_activityid();
     $forumrec = $DB->get_record('forum', array('id' => $forumid));
     if ($forumrec->type == 'single' && !$DB->record_exists('forum_discussions', array('forum' => $forumid))) {
         // Create single discussion/lead post from forum data
         $sd = new stdclass();
         $sd->course = $forumrec->course;
         $sd->forum = $forumrec->id;
         $sd->name = $forumrec->name;
         $sd->assessed = $forumrec->assessed;
         $sd->message = $forumrec->intro;
         $sd->messageformat = $forumrec->introformat;
         $sd->messagetrust = true;
         $sd->mailnow = false;
         $sdid = forum_add_discussion($sd, null, null, $this->task->get_userid());
         // Mark the post as mailed
         $DB->set_field('forum_posts', 'mailed', '1', array('discussion' => $sdid));
         // Copy all the files from mod_foum/intro to mod_forum/post
         $fs = get_file_storage();
         $files = $fs->get_area_files($this->task->get_contextid(), 'mod_forum', 'intro');
         foreach ($files as $file) {
             $newfilerecord = new stdclass();
             $newfilerecord->filearea = 'post';
             $newfilerecord->itemid = $DB->get_field('forum_discussions', 'firstpost', array('id' => $sdid));
             $fs->create_file_from_storedfile($newfilerecord, $file);
         }
     }
     // Add post related files, matching by itemname = 'forum_post'
     $this->add_related_files('mod_forum', 'post', 'forum_post');
     $this->add_related_files('mod_forum', 'attachment', 'forum_post');
 }
Example #7
0
/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will update an existing instance with new data.
 *
 * @global object
 * @param object $forum forum instance (with magic quotes)
 * @return bool success
 */
function forum_update_instance($forum, $mform)
{
    global $DB, $OUTPUT, $USER;
    $forum->timemodified = time();
    $forum->id = $forum->instance;
    if (empty($forum->assessed)) {
        $forum->assessed = 0;
    }
    if (empty($forum->ratingtime) or empty($forum->assessed)) {
        $forum->assesstimestart = 0;
        $forum->assesstimefinish = 0;
    }
    $oldforum = $DB->get_record('forum', array('id' => $forum->id));
    // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
    // if  scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
    // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
    if ($oldforum->assessed != $forum->assessed or $oldforum->scale != $forum->scale) {
        forum_update_grades($forum);
        // recalculate grades for the forum
    }
    if ($forum->type == 'single') {
        // Update related discussion and post.
        if (!($discussion = $DB->get_record('forum_discussions', array('forum' => $forum->id)))) {
            if ($discussions = $DB->get_records('forum_discussions', array('forum' => $forum->id), 'timemodified ASC')) {
                echo $OUTPUT->notification('Warning! There is more than one discussion in this forum - using the most recent');
                $discussion = array_pop($discussions);
            } else {
                // try to recover by creating initial discussion - MDL-16262
                $discussion = new stdClass();
                $discussion->course = $forum->course;
                $discussion->forum = $forum->id;
                $discussion->name = $forum->name;
                $discussion->assessed = $forum->assessed;
                $discussion->message = $forum->intro;
                $discussion->messageformat = $forum->introformat;
                $discussion->messagetrust = true;
                $discussion->mailnow = false;
                $discussion->groupid = -1;
                $message = '';
                forum_add_discussion($discussion, null, $message);
                if (!($discussion = $DB->get_record('forum_discussions', array('forum' => $forum->id)))) {
                    print_error('cannotadd', 'forum');
                }
            }
        }
        if (!($post = $DB->get_record('forum_posts', array('id' => $discussion->firstpost)))) {
            print_error('cannotfindfirstpost', 'forum');
        }
        $cm = get_coursemodule_from_instance('forum', $forum->id);
        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
        if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
            // ugly hack - we need to copy the files somehow
            $discussion = $DB->get_record('forum_discussions', array('id' => $discussion->id), '*', MUST_EXIST);
            $post = $DB->get_record('forum_posts', array('id' => $discussion->firstpost), '*', MUST_EXIST);
            $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, array('subdirs' => true), $post->message);
        }
        $post->subject = $forum->name;
        $post->message = $forum->intro;
        $post->messageformat = $forum->introformat;
        $post->messagetrust = trusttext_trusted($modcontext);
        $post->modified = $forum->timemodified;
        $post->userid = $USER->id;
        // MDL-18599, so that current teacher can take ownership of activities
        $DB->update_record('forum_posts', $post);
        $discussion->name = $forum->name;
        $DB->update_record('forum_discussions', $discussion);
    }
    $DB->update_record('forum', $forum);
    forum_grade_item_update($forum);
    return true;
}
Example #8
0
 public function generate_forum_posts($course_users, $modules)
 {
     global $CFG, $DB, $USER;
     if (in_array('forum', $this->modules_list) && $this->get('discussions_per_forum') && $this->get('posts_per_discussion') && isset($modules['forum'])) {
         $discussions_count = 0;
         $posts_count = 0;
         foreach ($modules['forum'] as $forum) {
             $forum_users = $course_users[$forum->course];
             for ($i = 0; $i < $this->get('discussions_per_forum'); $i++) {
                 $mform = new fake_form();
                 require_once $CFG->dirroot . '/mod/forum/lib.php';
                 $discussion = new stdClass();
                 $discussion->course = $forum->course;
                 $discussion->forum = $forum->id;
                 $discussion->name = 'Test discussion';
                 $discussion->intro = 'This is just a test forum discussion';
                 $discussion->assessed = 0;
                 $discussion->messageformat = 1;
                 $discussion->messagetrust = 0;
                 $discussion->mailnow = false;
                 $discussion->groupid = -1;
                 $discussion->attachments = null;
                 $discussion->itemid = 752157083;
                 $message = '';
                 $super_global_user = clone $USER;
                 $user_id = $forum_users[array_rand($forum_users)];
                 $USER = $DB->get_record('user', array('id' => $user_id));
                 if ($discussion_id = forum_add_discussion($discussion, $mform, $message)) {
                     $discussion = $DB->get_record('forum_discussions', array('id' => $discussion_id));
                     $discussions_count++;
                     // Add posts to this discussion
                     $post_ids = array($discussion->firstpost);
                     for ($j = 0; $j < $this->get('posts_per_discussion'); $j++) {
                         $global_user = clone $USER;
                         $user_id = $forum_users[array_rand($forum_users)];
                         $USER = $DB->get_record('user', array('id' => $user_id));
                         $post = new stdClass();
                         $post->discussion = $discussion_id;
                         $post->subject = 'Re: test discussion';
                         $post->message = '<p>Nothing much to say, since this is just a test...</p>';
                         $post->format = 1;
                         $post->attachments = null;
                         $post->itemid = 752157083;
                         $post->parent = $post_ids[array_rand($post_ids)];
                         if ($post_ids[] = forum_add_new_post($post, $mform, $message)) {
                             $posts_count++;
                         }
                         $USER = $global_user;
                     }
                 }
                 $USER = $super_global_user;
                 if ($forum->type == 'single') {
                     break;
                 }
             }
         }
         if ($discussions_count > 0 && !$this->get('quiet')) {
             echo "{$discussions_count} forum discussions have been generated.{$this->eolchar}";
         }
         if ($posts_count > 0 && !$this->get('quiet')) {
             echo "{$posts_count} forum posts have been generated.{$this->eolchar}";
         }
         return true;
     }
     return null;
 }
Example #9
0
function forum_restore_mods($mod, $restore)
{
    global $CFG, $DB;
    $status = true;
    //Get record from backup_ids
    $data = backup_getid($restore->backup_unique_code, $mod->modtype, $mod->id);
    if ($data) {
        //Now get completed xmlized object
        $info = $data->info;
        //if necessary, write to restorelog and adjust date/time fields
        if ($restore->course_startdateoffset) {
            restore_log_date_changes('Forum', $restore, $info['MOD']['#'], array('ASSESSTIMESTART', 'ASSESSTIMEFINISH'));
        }
        //traverse_xmlize($info);                                                                     //Debug
        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
        //$GLOBALS['traverse_array']="";                                                              //Debug
        //Now, build the FORUM record structure
        $forum->course = $restore->course_id;
        $forum->type = backup_todb($info['MOD']['#']['TYPE']['0']['#']);
        $forum->name = backup_todb($info['MOD']['#']['NAME']['0']['#']);
        $forum->intro = backup_todb($info['MOD']['#']['INTRO']['0']['#']);
        // These get dropped in Moodle 1.7 when the new Roles System gets
        // set up. Therefore they might or not be there depending on whether
        // we are restoring a 1.6+ forum or a 1.7 or later forum backup.
        if (isset($info['MOD']['#']['OPEN']['0']['#'])) {
            $forum->open = backup_todb($info['MOD']['#']['OPEN']['0']['#']);
        }
        if (isset($info['MOD']['#']['ASSESSPUBLIC']['0']['#'])) {
            $forum->assesspublic = backup_todb($info['MOD']['#']['ASSESSPUBLIC']['0']['#']);
        }
        $forum->assessed = backup_todb($info['MOD']['#']['ASSESSED']['0']['#']);
        $forum->assesstimestart = backup_todb($info['MOD']['#']['ASSESSTIMESTART']['0']['#']);
        $forum->assesstimefinish = backup_todb($info['MOD']['#']['ASSESSTIMEFINISH']['0']['#']);
        $forum->maxbytes = backup_todb($info['MOD']['#']['MAXBYTES']['0']['#']);
        $forum->scale = backup_todb($info['MOD']['#']['SCALE']['0']['#']);
        $forum->forcesubscribe = backup_todb($info['MOD']['#']['FORCESUBSCRIBE']['0']['#']);
        $forum->trackingtype = backup_todb($info['MOD']['#']['TRACKINGTYPE']['0']['#']);
        $forum->rsstype = backup_todb($info['MOD']['#']['RSSTYPE']['0']['#']);
        $forum->rssarticles = backup_todb($info['MOD']['#']['RSSARTICLES']['0']['#']);
        $forum->timemodified = backup_todb($info['MOD']['#']['TIMEMODIFIED']['0']['#']);
        $forum->warnafter = isset($info['MOD']['#']['WARNAFTER']['0']['#']) ? backup_todb($info['MOD']['#']['WARNAFTER']['0']['#']) : '';
        $forum->blockafter = isset($info['MOD']['#']['BLOCKAFTER']['0']['#']) ? backup_todb($info['MOD']['#']['BLOCKAFTER']['0']['#']) : '';
        $forum->blockperiod = isset($info['MOD']['#']['BLOCKPERIOD']['0']['#']) ? backup_todb($info['MOD']['#']['BLOCKPERIOD']['0']['#']) : '';
        $forum->completiondiscussions = isset($info['MOD']['#']['COMPLETIONDISCUSSIONS']['0']['#']) ? backup_todb($info['MOD']['#']['COMPLETIONDISCUSSIONS']['0']['#']) : 0;
        $forum->completionreplies = isset($info['MOD']['#']['COMPLETIONREPLIES']['0']['#']) ? backup_todb($info['MOD']['#']['COMPLETIONREPLIES']['0']['#']) : 0;
        $forum->completionposts = isset($info['MOD']['#']['COMPLETIONPOSTS']['0']['#']) ? backup_todb($info['MOD']['#']['COMPLETIONPOSTS']['0']['#']) : 0;
        //We have to recode the scale field if it's <0 (positive is a grade, not a scale)
        if ($forum->scale < 0) {
            $scale = backup_getid($restore->backup_unique_code, "scale", abs($forum->scale));
            if ($scale) {
                $forum->scale = -$scale->new_id;
            }
        }
        $newid = $DB->insert_record("forum", $forum);
        //Do some output
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("modulename", "forum") . " \"" . format_string($forum->name, true) . "\"</li>";
        }
        backup_flush(300);
        if ($newid) {
            //We have the newid, update backup_ids
            backup_putid($restore->backup_unique_code, $mod->modtype, $mod->id, $newid);
            $forum->id = $newid;
            //Now check if want to restore user data and do it.
            if (restore_userdata_selected($restore, 'forum', $mod->id)) {
                //Restore forum_subscriptions
                $status = forum_subscriptions_restore_mods($newid, $info, $restore);
                if ($status) {
                    //Restore forum_discussions
                    $status = forum_discussions_restore_mods($newid, $info, $restore);
                }
                if ($status) {
                    //Restore forum_read
                    $status = forum_read_restore_mods($newid, $info, $restore);
                }
            }
            // If forum type is single, just recreate the initial discussion/post automatically
            // if it hasn't been created still (because no user data was selected on backup or
            // restore.
            if ($forum->type == 'single' && !$DB->record_exists('forum_discussions', array('forum' => $newid))) {
                //Load forum/lib.php
                require_once $CFG->dirroot . '/mod/forum/lib.php';
                // Calculate the default format
                if (can_use_html_editor()) {
                    $defaultformat = FORMAT_HTML;
                } else {
                    $defaultformat = FORMAT_MOODLE;
                }
                //Create discussion/post data
                $sd = new stdClass();
                $sd->course = $forum->course;
                $sd->forum = $newid;
                $sd->name = $forum->name;
                $sd->intro = $forum->intro;
                $sd->assessed = $forum->assessed;
                $sd->messageformat = $defaultformat;
                $sd->mailnow = false;
                //Insert dicussion/post data
                $sdid = forum_add_discussion($sd, $sd->intro, $forum);
                //Now, mark the initial post of the discussion as mailed!
                if ($sdid) {
                    $DB->set_field('forum_posts', 'mailed', '1', array('discussion' => $sdid));
                }
            }
        } else {
            $status = false;
        }
        // If the backup contained $forum->open and $forum->assesspublic,
        // we need to convert the forum to use Roles. It means the backup
        // was made pre Moodle 1.7.
        if (isset($forum->open) && isset($forum->assesspublic)) {
            $forummod = $DB->get_record('modules', array('name' => 'forum'));
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notice('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notice('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set.');
            }
            if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
                notice('Default guest role was not found. Roles and permissions ' . 'for teacher forums will have to be manually set.');
            }
            require_once $CFG->dirroot . '/mod/forum/lib.php';
            forum_convert_to_roles($forum, $forummod->id, $teacherroles, $studentroles, $guestroles, $restore->mods['forum']->instances[$mod->id]->restored_as_course_module);
        }
    } else {
        $status = false;
    }
    return $status;
}
Example #10
0
    /**
     * Add a new discussion into an existing forum.
     *
     * @param int $forumid the forum instance id
     * @param string $subject new discussion subject
     * @param string $message new discussion message (only html format allowed)
     * @param int $groupid the user course group
     * @param array $options optional settings
     * @return array of warnings and the new discussion id
     * @since Moodle 3.0
     * @throws moodle_exception
     */
    public static function add_discussion($forumid, $subject, $message, $groupid = -1, $options = array()) {
        global $DB, $CFG;
        require_once($CFG->dirroot . "/mod/forum/lib.php");

        $params = self::validate_parameters(self::add_discussion_parameters(),
                                            array(
                                                'forumid' => $forumid,
                                                'subject' => $subject,
                                                'message' => $message,
                                                'groupid' => $groupid,
                                                'options' => $options
                                            ));
        // Validate options.
        $options = array(
            'discussionsubscribe' => true
        );
        foreach ($params['options'] as $option) {
            $name = trim($option['name']);
            switch ($name) {
                case 'discussionsubscribe':
                    $value = clean_param($option['value'], PARAM_BOOL);
                    break;
                default:
                    throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
            }
            $options[$name] = $value;
        }

        $warnings = array();

        // Request and permission validation.
        $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        // Normalize group.
        if (!groups_get_activity_groupmode($cm)) {
            // Groups not supported, force to -1.
            $groupid = -1;
        } else {
            // Check if we receive the default or and empty value for groupid,
            // in this case, get the group for the user in the activity.
            if ($groupid === -1 or empty($params['groupid'])) {
                $groupid = groups_get_activity_group($cm);
            } else {
                // Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
                $groupid = $params['groupid'];
            }
        }

        if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
            throw new moodle_exception('cannotcreatediscussion', 'forum');
        }

        $thresholdwarning = forum_check_throttling($forum, $cm);
        forum_check_blocking_threshold($thresholdwarning);

        // Create the discussion.
        $discussion = new stdClass();
        $discussion->course = $course->id;
        $discussion->forum = $forum->id;
        $discussion->message = $params['message'];
        $discussion->messageformat = FORMAT_HTML;   // Force formatting for now.
        $discussion->messagetrust = trusttext_trusted($context);
        $discussion->itemid = 0;
        $discussion->groupid = $groupid;
        $discussion->mailnow = 0;
        $discussion->subject = $params['subject'];
        $discussion->name = $discussion->subject;
        $discussion->timestart = 0;
        $discussion->timeend = 0;

        if ($discussionid = forum_add_discussion($discussion)) {

            $discussion->id = $discussionid;

            // Trigger events and completion.

            $params = array(
                'context' => $context,
                'objectid' => $discussion->id,
                'other' => array(
                    'forumid' => $forum->id,
                )
            );
            $event = \mod_forum\event\discussion_created::create($params);
            $event->add_record_snapshot('forum_discussions', $discussion);
            $event->trigger();

            $completion = new completion_info($course);
            if ($completion->is_enabled($cm) &&
                    ($forum->completiondiscussions || $forum->completionposts)) {
                $completion->update_state($cm, COMPLETION_COMPLETE);
            }

            $settings = new stdClass();
            $settings->discussionsubscribe = $options['discussionsubscribe'];
            forum_post_subscription($settings, $forum, $discussion);
        } else {
            throw new moodle_exception('couldnotadd', 'forum');
        }

        $result = array();
        $result['discussionid'] = $discussionid;
        $result['warnings'] = $warnings;
        return $result;
    }
Example #11
0
 /**
  * Function to create a dummy discussion.
  *
  * @param array|stdClass $record
  * @return stdClass the discussion object
  */
 public function create_discussion($record = null)
 {
     global $DB;
     // Increment the forum discussion count.
     $this->forumdiscussioncount++;
     $record = (array) $record;
     if (!isset($record['course'])) {
         throw new coding_exception('course must be present in phpunit_util::create_discussion() $record');
     }
     if (!isset($record['forum'])) {
         throw new coding_exception('forum must be present in phpunit_util::create_discussion() $record');
     }
     if (!isset($record['userid'])) {
         throw new coding_exception('userid must be present in phpunit_util::create_discussion() $record');
     }
     if (!isset($record['name'])) {
         $record['name'] = "Discussion " . $this->forumdiscussioncount;
     }
     if (!isset($record['subject'])) {
         $record['subject'] = "Subject for discussion " . $this->forumdiscussioncount;
     }
     if (!isset($record['message'])) {
         $record['message'] = html_writer::tag('p', 'Message for discussion ' . $this->forumdiscussioncount);
     }
     if (!isset($record['messageformat'])) {
         $record['messageformat'] = editors_get_preferred_format();
     }
     if (!isset($record['messagetrust'])) {
         $record['messagetrust'] = "";
     }
     if (!isset($record['assessed'])) {
         $record['assessed'] = '1';
     }
     if (!isset($record['groupid'])) {
         $record['groupid'] = "-1";
     }
     if (!isset($record['timestart'])) {
         $record['timestart'] = "0";
     }
     if (!isset($record['timeend'])) {
         $record['timeend'] = "0";
     }
     if (!isset($record['mailnow'])) {
         $record['mailnow'] = "0";
     }
     if (isset($record['timemodified'])) {
         $timemodified = $record['timemodified'];
     }
     if (!isset($record['pinned'])) {
         $record['pinned'] = FORUM_DISCUSSION_UNPINNED;
     }
     $record = (object) $record;
     // Add the discussion.
     $record->id = forum_add_discussion($record, null, null, $record->userid);
     if (isset($timemodified)) {
         // Enforce the time modified.
         $post = $DB->get_record('forum_posts', array('discussion' => $record->id));
         $record->timemodified = $timemodified;
         $post->modified = $post->created = $timemodified;
         $DB->update_record('forum_discussions', $record);
         $DB->update_record('forum_posts', $post);
     }
     return $record;
 }
Example #12
0
/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod.html) this function
 * will update an existing instance with new data.
 * @param object $forum forum instance (with magic quotes)
 * @return bool success
 */
function forum_update_instance($forum)
{
    global $USER;
    $forum->timemodified = time();
    $forum->id = $forum->instance;
    if (empty($forum->assessed)) {
        $forum->assessed = 0;
    }
    if (empty($forum->ratingtime) or empty($forum->assessed)) {
        $forum->assesstimestart = 0;
        $forum->assesstimefinish = 0;
    }
    $oldforum = get_record('forum', 'id', $forum->id);
    // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
    // if  scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
    // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
    if ($oldforum->assessed != $forum->assessed or $oldforum->scale != $forum->scale) {
        forum_update_grades($forum);
        // recalculate grades for the forum
    }
    if ($forum->type == 'single') {
        // Update related discussion and post.
        if (!($discussion = get_record('forum_discussions', 'forum', $forum->id))) {
            if ($discussions = get_records('forum_discussions', 'forum', $forum->id, 'timemodified ASC')) {
                notify('Warning! There is more than one discussion in this forum - using the most recent');
                $discussion = array_pop($discussions);
            } else {
                // try to recover by creating initial discussion - MDL-16262
                $discussion = new object();
                $discussion->course = $forum->course;
                $discussion->forum = $forum->id;
                $discussion->name = $forum->name;
                $discussion->intro = $forum->intro;
                $discussion->assessed = $forum->assessed;
                $discussion->format = $forum->type;
                $discussion->mailnow = false;
                $discussion->groupid = -1;
                forum_add_discussion($discussion, $discussion->intro);
                if (!($discussion = get_record('forum_discussions', 'forum', $forum->id))) {
                    error('Could not add the discussion for this forum');
                }
            }
        }
        if (!($post = get_record('forum_posts', 'id', $discussion->firstpost))) {
            error('Could not find the first post in this forum discussion');
        }
        $post->subject = $forum->name;
        $post->message = $forum->intro;
        $post->modified = $forum->timemodified;
        $post->userid = $USER->id;
        // MDL-18599, so that current teacher can take ownership of activities
        if (!update_record('forum_posts', $post)) {
            error('Could not update the first post');
        }
        $discussion->name = $forum->name;
        if (!update_record('forum_discussions', $discussion)) {
            error('Could not update the discussion');
        }
    }
    if (!update_record('forum', $forum)) {
        error('Can not update forum');
    }
    $forum = stripslashes_recursive($forum);
    forum_grade_item_update($forum);
    return true;
}
Example #13
0
/**
 * This is a hacky way how to populate a forum at lang.moodle.org with commits into the core
 *
 * @param mlang_stage $stage
 * @param string $commitmsg
 * @param string $committer
 * @param string $committeremail
 * @param string $commithash
 * @param string $fullcommitmsg
 * @return void
 */
function amos_core_commit_notify(mlang_stage $stage, $commitmsg, $committer, $committeremail, $commithash, $fullcommitmsg)
{
    global $CFG;
    $DB;
    require_once $CFG->dirroot . '/mod/forum/lib.php';
    if ($CFG->wwwroot !== 'http://lang.moodle.org') {
        // this is intended for lang.moodle.org portal only
        return;
    }
    if (!$stage->has_component()) {
        // nothing to commit
        return;
    }
    // these are hard-coded values of a forum to inject commit messages into
    $courseid = 2;
    // course 'Translating Moodle'
    $cmid = 7;
    // forum 'Notification of string changes'
    $userid = 2;
    // user 'AMOS bot'
    $cm = get_coursemodule_from_id('forum', $cmid);
    $discussion = new stdclass();
    $discussion->course = $courseid;
    $discussion->forum = $cm->instance;
    $discussion->name = substr(s('[AMOS commit] ' . $commitmsg), 0, 255);
    $discussion->message = 'Author: ' . $committer . "\n";
    $discussion->message .= $fullcommitmsg . "\n\n";
    $discussion->message .= 'http://git.moodle.org/gw?p=moodle.git;a=commit;h=' . $commithash . "\n";
    $discussion->message .= 'http://github.com/moodle/moodle/commit/' . $commithash . "\n\n";
    $standardplugins = local_amos_standard_plugins();
    foreach ($stage->get_iterator() as $component) {
        foreach ($component->get_iterator() as $string) {
            if ($string->deleted) {
                $sign = '-  ';
            } else {
                $sign = '+  ';
            }
            if (isset($standardplugins[$component->version->dir][$component->name])) {
                $name = $standardplugins[$component->version->dir][$component->name];
            } else {
                $name = $component->name;
            }
            $discussion->message .= $sign . $component->version->dir . ' en [' . $string->id . ',' . $name . "]\n";
        }
    }
    $discussion->message = s($discussion->message);
    $discussion->messageformat = FORMAT_MOODLE;
    $discussion->messagetrust = 0;
    $discussion->attachments = null;
    $discussion->mailnow = 1;
    $message = null;
    forum_add_discussion($discussion, null, $message, $userid);
}
Example #14
0
             $redirectto->param('group', $fromform->groupid);
         } else {
             // Use the value for all participants instead.
             $groupstopostto[] = -1;
         }
     }
 }
 // Before we post this we must check that the user will not exceed the blocking threshold.
 forum_check_blocking_threshold($thresholdwarning);
 foreach ($groupstopostto as $group) {
     if (!forum_user_can_post_discussion($forum, $group, -1, $cm, $modcontext)) {
         print_error('cannotcreatediscussion', 'forum');
     }
     $discussion->groupid = $group;
     $message = '';
     if ($discussion->id = forum_add_discussion($discussion, $mform_post)) {
         $params = array('context' => $modcontext, 'objectid' => $discussion->id, 'other' => array('forumid' => $forum->id));
         $event = \mod_forum\event\discussion_created::create($params);
         $event->add_record_snapshot('forum_discussions', $discussion);
         $event->trigger();
         if ($fromform->mailnow) {
             $message .= get_string("postmailnow", "forum");
         } else {
             $message .= '<p>' . get_string("postaddedsuccess", "forum") . '</p>';
             $message .= '<p>' . get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
         }
         $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
     } else {
         print_error("couldnotadd", "forum", $errordestination);
     }
 }
Example #15
0
/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will update an existing instance with new data.
 *
 * @global object
 * @param object $forum forum instance (with magic quotes)
 * @return bool success
 */
function forum_update_instance($forum)
{
    global $DB, $OUTPUT;
    $forum->timemodified = time();
    $forum->id = $forum->instance;
    if (empty($forum->assessed)) {
        $forum->assessed = 0;
    }
    if (empty($forum->ratingtime) or empty($forum->assessed)) {
        $forum->assesstimestart = 0;
        $forum->assesstimefinish = 0;
    }
    $oldforum = $DB->get_record('forum', array('id' => $forum->id));
    // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
    // if  scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
    // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
    if ($oldforum->assessed != $forum->assessed or $oldforum->scale != $forum->scale) {
        forum_update_grades($forum);
        // recalculate grades for the forum
    }
    if ($forum->type == 'single') {
        // Update related discussion and post.
        if (!($discussion = $DB->get_record('forum_discussions', array('forum' => $forum->id)))) {
            if ($discussions = $DB->get_records('forum_discussions', array('forum' => $forum->id), 'timemodified ASC')) {
                echo $OUTPUT->notification('Warning! There is more than one discussion in this forum - using the most recent');
                $discussion = array_pop($discussions);
            } else {
                // try to recover by creating initial discussion - MDL-16262
                $discussion = new object();
                $discussion->course = $forum->course;
                $discussion->forum = $forum->id;
                $discussion->name = $forum->name;
                $discussion->intro = $forum->intro;
                $discussion->assessed = $forum->assessed;
                $discussion->messageformat = $forum->messageformat;
                $discussion->mailnow = false;
                $discussion->groupid = -1;
                forum_add_discussion($discussion, null, $message);
                if (!($discussion = $DB->get_record('forum_discussions', array('forum' => $forum->id)))) {
                    print_error('cannotadd', 'forum');
                }
            }
        }
        if (!($post = $DB->get_record('forum_posts', array('id' => $discussion->firstpost)))) {
            print_error('cannotfindfirstpost', 'forum');
        }
        $post->subject = $forum->name;
        $post->message = $forum->intro;
        $post->modified = $forum->timemodified;
        $DB->update_record('forum_posts', $post);
        $discussion->name = $forum->name;
        $DB->update_record('forum_discussions', $discussion);
    }
    $DB->update_record('forum', $forum);
    forum_grade_item_update($forum);
    return true;
}