public function reorder_activities() {
        course_create_sections_if_missing($this->courseid, array(0, 1));
        foreach ($this->get_sections() as $sectionnum => $section) {
            if (($sectionnum && $section->visible) ||
                    (!$sectionnum && !$section->visible)) {
                // Make sure that 0 section is visible and all others are hidden.
                set_section_visible($this->courseid, $sectionnum, $sectionnum == 0);
            }
        }
        $modinfo = get_fast_modinfo($this->courseid);

        // Find the current activity (first activity with the specified type in all course activities).
        $activitytype = $this->get_activitytype();
        $activity = null;
        if (!empty($activitytype)) {
            foreach ($modinfo->sections as $sectionnum => $cmlist) {
                foreach ($cmlist as $cmid) {
                    if ($modinfo->cms[$cmid]->modname === $activitytype) {
                        $activity = $modinfo->cms[$cmid];
                        break 2;
                    }
                }
            }
        }

        // Make sure the current activity is in the 0-section.
        $changed = false;
        if ($activity && $activity->sectionnum != 0) {
            moveto_module($activity, $modinfo->get_section_info(0));
            $changed = true;
        }
        if ($activity && !$activity->visible) {
            set_coursemodule_visible($activity->id, 1);
            $changed = true;
        }
        if ($changed) {
            // Cache was reset so get modinfo again.
            $modinfo = get_fast_modinfo($this->courseid);
        }

        // Move all other activities into section 1 (the order must be kept).
        $hasvisibleactivities = false;
        $firstorphanedcm = null;
        foreach ($modinfo->sections as $sectionnum => $cmlist) {
            if ($sectionnum && !empty($cmlist) && $firstorphanedcm === null) {
                $firstorphanedcm = reset($cmlist);
            }
            foreach ($cmlist as $cmid) {
                if ($sectionnum > 1) {
                    moveto_module($modinfo->get_cm($cmid), $modinfo->get_section_info(1));
                } else if (!$hasvisibleactivities && $sectionnum == 1 && $modinfo->get_cm($cmid)->visible) {
                    $hasvisibleactivities = true;
                }
            }
        }
        if (!empty($modinfo->sections[0])) {
            foreach ($modinfo->sections[0] as $cmid) {
                if (!$activity || $cmid != $activity->id) {
                    moveto_module($modinfo->get_cm($cmid), $modinfo->get_section_info(1), $firstorphanedcm);
                }
            }
        }
        if ($hasvisibleactivities) {
            set_section_visible($this->courseid, 1, false);
        }
        return $activity;
    }