public function load_all_pages(lesson $lesson) {
        global $DB;
        if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) {
            return array(); // Records returned empty.
        }
        foreach ($pages as $key=>$page) {
            $pagetype = get_class($this->types[$page->qtype]);
            $pages[$key] = new $pagetype($page, $lesson);
        }

        $orderedpages = array();
        $lastpageid = 0;
        $morepages = true;
        while ($morepages) {
            $morepages = false;
            foreach ($pages as $page) {
                if ((int)$page->prevpageid === (int)$lastpageid) {
                    // Check for errors in page ordering and fix them on the fly.
                    $prevpage = null;
                    if ($lastpageid !== 0) {
                        $prevpage = $orderedpages[$lastpageid];
                    }
                    $this->check_page_order($prevpage, $page);
                    $morepages = true;
                    $orderedpages[$page->id] = $page;
                    unset($pages[$page->id]);
                    $lastpageid = $page->id;
                    if ((int)$page->nextpageid===0) {
                        break 2;
                    } else {
                        break 1;
                    }
                }
            }
        }

        // Add remaining pages and fix the nextpageid links for each page.
        foreach ($pages as $page) {
            // Check for errors in page ordering and fix them on the fly.
            $prevpage = null;
            if ($lastpageid !== 0) {
                $prevpage = $orderedpages[$lastpageid];
            }
            $this->check_page_order($prevpage, $page);
            $orderedpages[$page->id] = $page;
            unset($pages[$page->id]);
            $lastpageid = $page->id;
        }

        if ($lastpageid !== 0) {
            $this->check_page_order($orderedpages[$lastpageid], null);
        }

        return $orderedpages;
    }