public static function get_all_missing_plans($lastruntime = 0, $unlinkedaremissing = false) {
        global $DB;

        $planwhereclause = " WHERE (p.id is NULL
                               AND (cm.timeadded >= :lastruntime1
                                OR tc.timecreated >= :lastruntime3
                                OR t.timemodified >= :lastruntime4))";

        if ($unlinkedaremissing) {
            $planwhereclause .= " OR (p.origtemplateid IS NOT NULL AND cm.timeadded < :lastruntime2)";
        }

        $sql = "SELECT " . $DB->sql_concat('cm.userid', 'tc.templateid') . " as uniqueid, cm.userid, t.*
                  FROM {cohort_members} cm
                  JOIN {" . self::TABLE . "} tc ON cm.cohortid = tc.cohortid
                  JOIN {" . template::TABLE . "} t
                    ON (tc.templateid = t.id AND t.visible = 1)
                   AND (t.duedate = 0 OR t.duedate > :time1)
             LEFT JOIN {" . plan::TABLE . "} p ON (cm.userid = p.userid AND (t.id = p.templateid OR t.id = p.origtemplateid))
                  $planwhereclause
              ORDER BY t.id";

        $params = array('time1' => time(), 'time2' => time(),
                        'lastruntime1' => $lastruntime, 'lastruntime2' => $lastruntime,
                        'lastruntime3' => $lastruntime, 'lastruntime4' => $lastruntime);
        $results = $DB->get_records_sql($sql, $params);

        $missingplans = array();
        foreach ($results as $usertemplate) {
            $userid = $usertemplate->userid;

            // Check if template already exist in the array.
            if (isset($missingplans[$usertemplate->id])) {
                $missingplans[$usertemplate->id]['userids'][] = $userid;
            } else {
                unset($usertemplate->userid);
                unset($usertemplate->uniqueid);
                $template = new template(0, $usertemplate);
                $missingplans[$template->get('id')]['template'] = $template;
                $missingplans[$template->get('id')]['userids'][] = $userid;
            }
        }
        return array_values($missingplans);
    }