function forumng_delete_instance($id, $ociskip = true)
{
    require_once dirname(__FILE__) . '/forum.php';
    try {
        $forum = forum::get_from_id($id, forum::CLONE_DIRECT);
        // avoid deleting OCI specific forum if running in upload block
        if ($ociskip) {
            global $restore;
            if (isset($restore) && $restore->restoreto == 0 && strpos($_SERVER['HTTP_REFERER'], 'blocks/versions/upload.php') !== false) {
                if ($forum->get_name() == get_string('newunitforumname', 'createcourse')) {
                    //Unit forum
                    echo ' found forumng ' . $forum->get_id() . ' ' . $forum->get_name();
                    return true;
                }
            }
        }
        $forum->delete_all_data();
        if (forum::search_installed()) {
            $cm = $forum->get_course_module();
            ousearch_document::delete_module_instance_data($cm);
        }
    } catch (Exception $e) {
        return false;
    }
    return delete_records('forumng', 'id', $id);
}
<?php

require_once '../../config.php';
require_once 'forum.php';
try {
    // Load draft and forum
    $draft = forum_draft::get_from_id(required_param('draft', PARAM_INT));
    $forum = forum::get_from_id($draft->get_forum_id(), optional_param('clone', 0, PARAM_INT));
    $course = $forum->get_course();
    $cm = $forum->get_course_module();
    // Check it belongs to current user
    if ($USER->id != $draft->get_user_id()) {
        print_error('draft_mismatch', 'forumng');
    }
    // If they are actually deleting it, go ahead
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $draft->delete();
        redirect($forum->get_url());
    }
    // Confirm page. Work out navigation for header
    $pagename = get_string('deletedraft', 'forumng');
    $navigation = array();
    $navigation[] = array('name' => $pagename, 'type' => 'forumng');
    $PAGEWILLCALLSKIPMAINDESTINATION = true;
    print_header_simple(format_string($forum->get_name()) . ': ' . $pagename, "", build_navigation($navigation, $cm), "", "", true, '', navmenu($course, $cm));
    print skip_main_destination();
    notice_yesno(get_string('confirmdeletedraft', 'forumng'), 'deletedraft.php', 'view.php', array('draft' => $draft->get_id()), array('id' => $cm->id), 'post', 'get');
    print '<div class="forumng-post">';
    print '<div class="forumng-1"></div>';
    print '<div class="forumng-2"></div>';
    print '<div class="forumng-pic">';
function make_forumng($courseid, $starttime, $discussions, $posts, $readpercent, $readusers, &$userids, $subscribepercent, $ratingpercent)
{
    $section = get_record('course_sections', 'course', $courseid, 'section', 0);
    forum_utils::start_transaction();
    // Create course modules record
    $mod = new StdClass();
    $mod->course = $courseid;
    $mod->module = get_field('modules', 'id', 'name', 'forumng');
    $mod->section = $section->section;
    // was $section->id; logical but incorrect!
    $mod->added = $starttime;
    $mod->visible = 1;
    // course_modules and course_sections each contain a reference
    // to each other, so we have to update one of them twice.
    // Note: This is unbelievable!!! $mod->section MUST BE section number (not id)
    //       Adds course_module with section number, add_mod_to_section uses
    //       section number (& course id) to get section id, which is returned
    //       course module record then updated to replace section number by id!!!
    if (!($mod->coursemodule = add_course_module($mod))) {
        throw new Exception("Could not add a new course module");
    }
    if (!($sectionid = add_mod_to_section($mod))) {
        throw new Exception("Could not add the new course module to that section");
    }
    // Create forum object
    $forumng = new StdClass();
    static $index = 0;
    $index++;
    $forumng->name = 'Perf test ' . date('Ymd H:j', $starttime) . ' ' . $index;
    $forumng->course = $courseid;
    $forumng->section = $section;
    $forumng->cmidnumber = $mod->coursemodule;
    if (!($forumng->id = forumng_add_instance($forumng))) {
        throw new forum_exception('Failed to add forum');
    }
    // Mark cm object as owning it
    $updatemod = new stdClass();
    $updatemod->id = $mod->coursemodule;
    $updatemod->instance = $forumng->id;
    $updatemod->section = $sectionid;
    forum_utils::update_record('course_modules', $updatemod);
    // Make it be random users included in the forum
    shuffle($userids);
    // OK, forum is created. Let's make discussions
    $forum = forum::get_from_id($forumng->id, forum::CLONE_DIRECT);
    $count = my_random($discussions);
    for ($i = 0; $i < $count; $i++) {
        make_discussion($forum, $posts, my_random_percentage($readpercent) ? $readusers : 0, $userids, $ratingpercent);
    }
    // Add subscribe users
    set_time_limit(200);
    for ($i = 0; $i < $readusers; $i++) {
        if (my_random_percentage($subscribepercent)) {
            $forum->subscribe($userids[$i]);
        }
    }
    forum_utils::finish_transaction();
}
 /**
  * Either delete or archive old discussions based on the forum setting
  */
 static function archive_old_discussions()
 {
     global $CFG;
     $now = time();
     $housekeepingquery = " \nFROM \n    {$CFG->prefix}forumng_discussions fd\n    INNER JOIN {$CFG->prefix}forumng_posts fp ON fd.lastpostid = fp.id\n    INNER JOIN {$CFG->prefix}forumng f ON fd.forumid = f.id\nWHERE\n    f.removeafter<>0  AND fd.sticky<>1 AND fp.modified<{$now} - f.removeafter \n";
     $count = forum_utils::count_records_sql("SELECT COUNT(1) {$housekeepingquery}");
     if ($count) {
         mtrace("\nBeginning processing {$count} discussion archiving/deleting requests");
         $housekeepingrs = forum_utils::get_recordset_sql("\nSELECT \n    fd.id AS discussionid, f.id AS forumid, f.removeafter, f.removeto {$housekeepingquery} ORDER BY f.removeto\n            ");
         $targetforum = null;
         $targetcourseid = null;
         $cron_log = '';
         $discussionmovecount = 0;
         $discussiondeletecount = 0;
         while ($rec = rs_fetch_next_record($housekeepingrs)) {
             $discussion = forum_discussion::get_from_id($rec->discussionid, forum::CLONE_DIRECT);
             if ($rec->removeto) {
                 //moving to a different forum
                 $forum = $discussion->get_forum();
                 $course = $forum->get_course();
                 $modinfo = get_fast_modinfo($course);
                 if ($forum->can_archive_forum($modinfo, $cron_log)) {
                     //Do not get the target forum and course id again if the target forum is the same
                     if (!$targetforum || $targetforum->get_id() != $rec->removeto) {
                         $targetforum = forum::get_from_id($rec->removeto, forum::CLONE_DIRECT);
                         $targetforum = $targetforum->get_real_forum();
                     }
                     //target discussion groupid must be the same as the original groupid
                     $targetgroupmode = $targetforum->get_group_mode();
                     $targetgroupid = $targetgroupmode ? $discussion->get_group_id() : null;
                     $discussion->move($targetforum, $targetgroupid);
                     $discussionmovecount++;
                 }
             } else {
                 //Delete all discussions and relevant data permanently
                 $discussion->permanently_delete();
                 $discussiondeletecount++;
             }
         }
         rs_close($housekeepingrs);
         mtrace("\n {$discussionmovecount} discussions have been archived and {$discussiondeletecount} discussions have been deleted permanently.");
     }
 }
 /**
  * Obtains a discussion from the cache.
  * @param object $info Object from session cache
  * @return forum_discussion New discussion object or null if there is a
  *   problem and you should re-cache
  */
 private static function create_from_cache($info)
 {
     $discussionfields = unserialize($info->discussionfields);
     $forum = forum::get_from_id($discussionfields->forumid, $info->cloneid);
     if ($forum->get_settings_hash() != $info->settingshash) {
         return null;
     }
     $result = new forum_discussion($forum, $discussionfields, true, $info->userid);
     $result->groupscache = unserialize($info->groupscache);
     $result->postscache = $info->postscache;
     $result->incache = true;
     return $result;
 }
/**
 * Get search results.
 * @param object $course
 * @param string $author
 * @param int $daterangefrom
 * @param int $daterangeto
 * @param int $page
 * @param int $resultsperpage (FORUMNG_SEARCH_RESULTSPERPAGE used as constant)
 * @return object
 */
function forumng_get_results_for_all_forums($course, $author = null, $daterangefrom = 0, $daterangeto = 0, $page, $resultsperpage = FORUMNG_SEARCH_RESULTSPERPAGE)
{
    $before = microtime(true);
    global $CFG, $USER;
    // Get all forums
    $modinfo = get_fast_modinfo($course);
    $visibleforums = array();
    $accessallgroups = array();
    foreach ($modinfo->cms as $cmid => $cm) {
        if ($cm->modname === 'forumng' && $cm->uservisible) {
            $visibleforums[$cm->instance] = $cm->groupmode;
            // Check access all groups for this forum, if they have it, add to list
            //$forum = forum::get_from_cmid($cm->id, 0);
            $forum = forum::get_from_id($cm->instance, 0);
            if ($forum->get_group_mode() == SEPARATEGROUPS) {
                if (has_capability('moodle/site:accessallgroups', $forum->get_context())) {
                    $accessallgroups[] = $cm->instance;
                }
            }
        }
    }
    $forumids = array_keys($visibleforums);
    $separategroupsforumids = array_keys($visibleforums, SEPARATEGROUPS);
    $inforumids = forum_utils::in_or_equals($forumids);
    $inseparategroups = forum_utils::in_or_equals($separategroupsforumids);
    $inaccessallgroups = forum_utils::in_or_equals($accessallgroups);
    $where = "WHERE d.forumid {$inforumids}";
    $where .= " AND (NOT (d.forumid {$inseparategroups})";
    $where .= " OR d.forumid {$inaccessallgroups}";
    $where .= " OR gm.id IS NOT NULL";
    $where .= " OR d.groupid IS NULL)";
    // Note: Even if you have capability to view the deleted or timed posts,
    // we don't show them for consistency with the full-text search.
    $currenttime = time();
    $where .= " AND ({$currenttime} >= d.timestart OR d.timestart = 0)";
    $where .= " AND ({$currenttime} < d.timeend OR d.timeend = 0)";
    //exclude older post versions
    $where .= " AND p.oldversion=0 ";
    $where .= " AND d.deleted=0 AND p.deleted=0 ";
    if ($author) {
        $where .= forumng_get_author_sql($author);
    }
    if ($daterangefrom && !is_array($daterangefrom)) {
        $where .= " AND p.modified>={$daterangefrom}";
    }
    if ($daterangeto && !is_array($daterangeto)) {
        $where .= " AND p.modified<={$daterangeto}";
    }
    $sql = "SELECT p.modified, p.id, p.discussionid, gm.id AS useringroup, p.userid, p.parentpostid, \n            p.subject AS title, p.message AS summary, u.username, u.firstname, \n            u.lastname, d.forumid, d.groupid, d.postid AS discussionpostid\n            FROM {$CFG->prefix}forumng_posts p\n            INNER JOIN {$CFG->prefix}forumng_discussions d ON d.id = p.discussionid\n            INNER JOIN {$CFG->prefix}user u ON p.userid = u.id\n            LEFT JOIN {$CFG->prefix}groups_members gm ON gm.groupid = d.groupid AND gm.userid = {$USER->id}\n            {$where}\n            ORDER BY p.modified DESC, p.id ASC";
    $results = new stdClass();
    $results->success = 1;
    $results->numberofentries = 0;
    $results->done = 0;
    if (!($posts = get_records_sql($sql, $page, $resultsperpage))) {
        $posts = array();
    }
    foreach ($posts as $post) {
        if (!$post->title) {
            // Ideally we would get the parent post that has a subject, but
            // this could involve a while loop that might make numeroous
            // queries, so instead, let's just use the discussion subject
            $post->title = get_string('re', 'forumng', get_field('forumng_posts', 'subject', 'id', $post->discussionpostid));
        }
        $post->title = s(strip_tags($post->title));
        $post->summary = s(strip_tags(shorten_text($post->summary, 250)));
        $post->url = $CFG->wwwroot . "/mod/forumng/discuss.php?d={$post->discussionid}#p{$post->id}";
    }
    $results->results = $posts;
    $results->searchtime = microtime(true) - $before;
    $results->numberofentries = count($results->results);
    if (count($results->results) < $resultsperpage) {
        $results->done = 1;
    } elseif (!($extrapost = get_records_sql($sql, $page + $resultsperpage, 1))) {
        $results->done = 1;
    }
    return $results;
}