Php7

<?php

/*************************************************

//  MPACT - Mentoring Impact Factor

//  Terrell Russell
//  2005 - 2010
//  unc@terrellrussell.com

*************************************************/

/*

splitting a person
 - give current list of A's and C's and names
 - allow A's and C's to be divided (all have to be moved to #1 or #2)
 - names need to be split, but can be in both (since that's the problem in the first place)

live search for entering new links
 - 2 characters and then hit DB

incoming suggestions/changes
 - just a big bucket
 - contact info and single big box to state their claim
 - should be the start of a conversation, we're not just taking their word
 - batch submissions?  just start a conversation

*/

require 'envsetup.php';

###############################################

$statuscodes = array(
  NULL => "N/A",
  "-1" => "N/A",
  "0"  => "Incomplete - Not_Inspected",
  "1"  => "Incomplete - Inspected",
  "2"  => "Incomplete - Ambiguous",
  "3"  => "Complete - Except Indecipherables",
  "4"  => "Fully Complete"
);

$inspectioncodes = array(
  NULL => "N/A",
  "0" => "No",
  "1" => "Yes"
);

$degree_types = array(
  "Unknown",
  "Unknown - Investigated",
  "A.L.A.",
  "B.A.",
  "B.S.",
  "B.L.S.",
  "L.L.B.",
  "H.A.",
  "M.A.",
  "M.S.",
  "M.F.A.",
  "M.P.A.",
  "D.E.A.",
  "Ed.M.",
  "F.L.A. (by thesis)",
  "LL.M.",
  "LL.D.",
  "M.L.S.",
  "D.S.N.",
  "D.S.W.",
  "D.Engr.",
  "D.Lib.",
  "Ed.D.",
  "Th.D.",
  "Pharm.D.",
  "D.Sc.",
  "D.L.S.",
  "J.D.",
  "M.D.",
  "Ph.D."
);

// Begin Session
session_start();

// Delete server session if client cookie doesn't exist
if (!isset($_COOKIE['MPACT_userid'])){
  unset($_SESSION['MPACT']);
}

// Check for good cookie (and expired session) - (re)set session values accordingly
if (isset($_COOKIE['MPACT_userid']) && !isset($_SESSION['MPACT'])){
  $query = "SELECT id, username, fullname FROM users WHERE id='".$_COOKIE['MPACT_userid']."'";
  $result = mysql_query($query) or die(mysql_error());
  $line = mysql_fetch_array($result);
  $_SESSION['MPACT']['userid'] = $line['id'];
  $_SESSION['MPACT']['username'] = $line['username'];
  $_SESSION['MPACT']['fullname'] = $line['fullname'];
}

###############################################
// DISPLAY SOMETHING - something from the URL
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
  // Display header
  xhtml_web_header();

//  echo "-----\n";
//  print_r($_COOKIE);
//  echo "-----\n";
//  print_r($_SESSION);
//  echo "-----\n";
  if (isset($_GET['op']))
  {
    switch ($_GET['op'])
    {
      ###############################################
      case "login";

        $host_info = get_environment_info();
        if ($host_info['hostname'] == "sils"){
          # no logins here - go to dev server
          action_box("No Logins Here...",2,$_SERVER['SCRIPT_NAME']);
        }
        else{
          if (!isset($_SESSION['MPACT']['userid'])){
            # login form
            echo "
Welcome
\n";
            echo "
Please login if you have an account.
\n";
            echo "<form id=\"loginform\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"login\">\n";
            echo "
\n";
            echo "

Username:
	<input type='text' name='username' />
\n";
            echo "

Password:
	<input type='password' name='password' />
\n";
            echo "
     <input type='submit' name='Submit' value='Login' />
\n";
            echo "
\n";
            echo "</form>";
          }
          else{
            # um, already logged in...
            action_box("Already Logged In...",2,$_SERVER['SCRIPT_NAME']);
          }
        }

        break;
      ###############################################
      case "logout";

        setcookie('MPACT_userid',$_SESSION['MPACT']['userid'],time()-1000);
        unset($_SESSION['MPACT']);
        action_box("Logged Out",2,$_SERVER['SCRIPT_NAME']);

        break;
      ###############################################
      case "glossary";

        if ( isset($_GET['id']) ){
          show_glossaryterm($_GET['id']);
        }
        else
        {
          show_glossary();
        }

        break;
      ###############################################
      case "admin";

        if (is_admin())
        {
          echo "
Administrator Pages
\n";

          echo "
\n";
          echo "
\n";

          echo "
\n";
          echo "Show Logs\n";
          echo "
\n";

          echo "
\n";
          echo "Show Orphans\n";
          echo "
\n";
          echo "Citation Correlation\n";
          echo "
\n";

          echo "
\n";
          echo "People with Multiple Dissertations (Errors in DB)\n";
          echo "
\n";
          echo "Year 0000\n";
          echo "
\n";

          echo "
\n";
          echo "Add a New Person to the Database\n";
          echo "
\n";

          echo "	\n";

          echo "
\n";
          echo "No Title/Abstract\n";
          echo "
\n";
          echo "LIS, No Title/Abstract\n";
          echo "
\n";
          echo "LIS, No Title\n";
          echo "
\n";
          echo "LIS, No Abstract\n";
          echo "
\n";
          echo "
\n";
          echo "LIS, No Committee\n";
          echo "
\n";

          echo "	\n";

          echo "
\n";
          echo "LIS, Graduates By Year\n";
          echo "
\n";
          echo "LIS History\n";
          echo "
\n";

          echo "
\n";
          echo "LIS Professors Summary\n";
          echo "
\n";
          echo "LIS Professors with MPACT\n";
          echo "
\n";
          echo "LIS Professors and their Degrees (large CSV)\n";
          echo "
\n";
          echo "LIS Professors with Unknown Degree\n";
          echo "
\n";
          echo "LIS Professors with Unknown-Investigated Degree\n";
          echo "
\n";
          echo "LIS Professors without Dissertations\n";
          echo "
\n";
          echo "LIS Professors without LIS Dissertations\n";
          echo "
\n";

          echo "
\n";
          echo "
\n";

          echo "
";

          show_alphabet();

        }
        else
        {
          not_admin();
        }

        break;
      ###############################################
      case "glossary_edit";

        if ( isset($_GET['id']) && is_admin() ){

          echo "
Edit a Glossary Definition
\n";

          $query = "SELECT id, term, definition FROM glossary WHERE id='".$_GET['id']."'";
          $result = mysql_query($query) or die(mysql_error());

          while ( $line = mysql_fetch_array($result)) {
            $results['term'] = $line['term'];
            $results['definition'] = $line['definition'];
          }

          echo "
";

          echo "<form id=\"glossaryedit\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"glossary_edit\">\n";
          echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">\n";
          echo "<input type=\"hidden\" name=\"term\" value=\"".$results['term']."\">\n";

          echo "".$results['term'].":
\n";
          echo "<textarea cols=\"50\" rows=\"8\" name=\"definition\">".$results['definition']."</textarea>\n";
          echo "
\n";
          echo "<input type=\"submit\" name=\"button\" value=\"Save\">";
          echo "</form>";

          echo "
";

        }
        else
        {
          not_admin();
        }

        break;
      ###############################################
      case "show_tree":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {
          draw_tree((int)$_GET['id']);
        }

        break;

      ###############################################
      case "show_graph":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {
          echo "

\n";
          echo "Advisors and Advisees of ".get_person_link($_GET['id']);
          echo "

\n";
          draw_graph((int)$_GET['id']);
        }

        break;

      ###############################################
      case "statistics":

        echo "
\n";
        echo "LIS Incomplete - \n";
        echo "Top A -\n";
        echo "Top C -\n";
        echo "Top A+C -\n";
        echo "Top T -\n";
        echo "Top G -\n";
        echo "Top W -\n";
        echo "Top TD -\n";
        echo "Top TA\n";
        echo "
\n";

        echo "
Overall MPACT Statistics
\n";

        echo "
\n";

        # disciplines
        $query = "SELECT count(*) as disciplinecount FROM disciplines";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
Disciplines	".$disciplinecount."
\n";

        # schools
        $query = "SELECT count(*) as schoolcount FROM schools";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
Schools	".$schoolcount."
\n";

        # diss
        $query = "SELECT count(*) as disscount FROM dissertations";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
Dissertations	".$disscount."
\n";

        # a
        $query = "SELECT count(*) as advisorcount FROM advisorships";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
Advisorships	".$advisorcount."
\n";

        # c
        $query = "SELECT count(*) as committeeshipscount FROM committeeships";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
Committeeships	".$committeeshipscount."
\n";

        # full
        $query = "SELECT count(*) as peoplecount FROM people";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
People	".$peoplecount."
\n";
        echo "
\n";

        # dissertations by country
        echo "

\n";
        echo "
Dissertations by Country:

\n";
        $query = "SELECT count(*) as dissnone FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \"\")";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        $query = "SELECT count(*) as dissusa FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \"USA\")";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        $query = "SELECT count(*) as disscanada FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \"Canada\")";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        $query = "SELECT count(*) as dissother FROM dissertations WHERE school_id IN
          (SELECT id FROM schools WHERE (country != \"\" AND country != \"USA\" AND country != \"Canada\"))";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }
        echo "
\n";
        echo "
USA	".$dissusa."
                  ".sprintf("%.2f",100*$dissusa/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa)/$disscount)."%
\n";
        echo "
Canada	".$disscanada."
                  ".sprintf("%.2f",100*$disscanada/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa+$disscanada)/$disscount)."%
\n";
        echo "
Other	".$dissother."
                  ".sprintf("%.2f",100*$dissother/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa+$disscanada+$dissother)/$disscount)."%
\n";
        echo "
None Listed	".$dissnone."
                  ".sprintf("%.2f",100*$dissnone/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa+$disscanada+$dissother+$dissnone)/$disscount)."%
\n";
        echo "
Total	".$disscount."
                  ".sprintf("%.2f",100*$disscount/$disscount)."%

\n";
        echo "
\n";

        # dissertations by year
        echo "

\n";
        echo "
Dissertations by Year:

\n";
        $query = "SELECT completedyear, count(*) as disscount FROM dissertations GROUP BY completedyear";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          $counts[$line['completedyear']] = $line['disscount'];
        }
        echo "
\n";
        echo "
\n";
        foreach ($counts as $one => $two)
        {
          echo "	\n";
        }
        echo "
";
        echo "
\n";
        foreach ($counts as $one => $two)
        {
          echo "";
          if ($one%10==0)
          {
            echo $one;
          }
          echo "	\n";
        }
        echo "
";
        echo "
\n";

        break;

      ###############################################
      case "show_logs":

        if (is_admin())
        {
          echo "
Recent Activity
\n";

          if (isset($_GET['offset']))
          {
            $entries = get_logs($_GET['offset']);
          }
          else
          {
            $entries = get_logs();
          }
          echo "
\n";
          foreach ($entries as $entry)
          {
            echo "
";
            echo "".$entry['logged_at']."
".$entry['ip']."	";
            echo "".$entry['user']."	";
            echo "".$entry['message']."	";
            echo "
\n";
          }
          echo "
\n";

        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_multi_dissertations":

        if (is_admin())
        {
          echo "
People With Multiple Dissertations (db needs to be edited by hand)
\n";

          $query = "SELECT
                count(d.id) as howmany,
                d.id, d.person_id, d.completedyear, d.status,
                d.title, d.abstract, d.notes, d.school_id, d.discipline_id
                FROM
                  dissertations d
                GROUP BY
                  d.person_id
                ORDER BY
                  howmany DESC
              ";
          $result = mysql_query($query) or die(mysql_error());

          $dissertations = array();
          while ( $line = mysql_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $multicount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            if ($d['howmany'] > 1)
            {
              print "person id = ".$d['person_id'];
              print "
";
              print "
";
              $multicount++;
            }
          }
          if ($multicount == 0)
          {
            print " - None - database is clear.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_zero_year":

        if (is_admin())
        {
          echo "
Dissertations from the year 0000
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.discipline_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.completedyear = '0000'
              ";
          $result = mysql_query($query) or die(mysql_error());

          $dissertations = array();
          while ( $line = mysql_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            # get school
            $query = "SELECT fullname
                        FROM
                          schools
                        WHERE id = '".$d['school_id']."'
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $schoolname = $line['fullname'];
            }
            # get degree
            $query = "SELECT degree
                        FROM
                          people
                        WHERE id = '".$d['person_id']."'
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $degree = $line['degree'];
            }
            $discipline = find_discipline($d['discipline_id']);
            echo "
";
            echo "$zerocount.	";
            echo "".get_person_link($d['person_id'])."	";
            print "$degree	";
            print "".$discipline['title']."	";
            print "$schoolname	";
            print "
";
          }
          if ($zerocount == 0)
          {
            print "
None - database is clear.
";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_title_lis":

        if (is_admin())
        {
          echo "
LIS Dissertations Without Title
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.discipline_id = 1 AND
                  ( d.title = '' )
                ORDER BY
                  d.school_id
              ";
          $result = mysql_query($query) or die(mysql_error());

          $dissertations = array();
          while ( $line = mysql_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All LIS dissertations have titles.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_abstract_lis":

        if (is_admin())
        {
          echo "
LIS Dissertations Without Abstract
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.discipline_id = 1 AND
                  ( d.abstract = '' )
                ORDER BY
                  d.school_id
              ";
          $result = mysql_query($query) or die(mysql_error());

          $dissertations = array();
          while ( $line = mysql_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All LIS dissertations have abstracts.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_title_abstract":

        if (is_admin())
        {
          echo "
Dissertations Without Title/Abstract
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.title = '' OR d.abstract = ''
                ORDER BY
                  d.school_id
              ";
          $result = mysql_query($query) or die(mysql_error());

          $dissertations = array();
          while ( $line = mysql_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All dissertations have titles and abstracts.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_title_abstract_lis":

        if (is_admin())
        {
          echo "
LIS Dissertations Without Title/Abstract
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.discipline_id = 1 AND
                  ( d.title = '' OR d.abstract = '' )
                ORDER BY
                  d.school_id
              ";
          $result = mysql_query($query) or die(mysql_error());

          $dissertations = array();
          while ( $line = mysql_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All LIS dissertations have titles and abstracts.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "lis_profs_unknown_degree":

        if (is_admin())
        {
          echo "
LIS Professors with Unknown Degree
\n";

          # advisors or committee members with unknown degree,
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          $lis_with_unknown = array();

          # get advisors for each diss, check for advisor's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $advisors = array();
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
            foreach($advisors as $aid){
              $adv = find_person($aid);
              if ($adv['degree'] == "Unknown"){
                $lis_with_unknown[] = $aid;
              }
            }
          }

          # get committeeships for each diss, check for comm's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $committeemembers = array();
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
            foreach($committeemembers as $cid){
              $com = find_person($cid);
              if ($com['degree'] == "Unknown"){
                $lis_with_unknown[] = $cid;
              }
            }
          }

          # uniquify
          $lis_with_unknown = array_unique($lis_with_unknown);

          # print them out
          echo "
\n";
          $count = 0;
          foreach($lis_with_unknown as $pid){
            $count++;
            $person = find_person($pid);
            print "$count. ";
            print get_person_link($pid);
            print "
\n";
          }
          if ($count == 0)
          {
            print " - None";
          }
          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_profs_unknowninvestigated":
        case "lis_profs_unknowninvestigated_degree":

#        if (is_admin())
#        {
          echo "
LIS Professors with Unknown-Investigated Degree
\n";

          # advisors or committee members with unknown-investigated degree,
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          $lis_with_unknown = array();

          # get advisors for each diss, check for advisor's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $advisors = array();
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
            foreach($advisors as $aid){
              $adv = find_person($aid);
              if ($adv['degree'] == "Unknown - Investigated"){
                $lis_with_unknown[] = $aid;
              }
            }
          }

          # get committeeships for each diss, check for comm's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $committeemembers = array();
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
            foreach($committeemembers as $cid){
              $com = find_person($cid);
              if ($com['degree'] == "Unknown - Investigated"){
                $lis_with_unknown[] = $cid;
              }
            }
          }

          # uniquify
          $lis_with_unknown = array_unique($lis_with_unknown);

          # print them out
          echo "
\n";
          $count = 0;
          foreach($lis_with_unknown as $pid){
            $count++;
            $person = find_person($pid);
            print "$count. ";
            print get_person_link($pid);
            $advisorcount = count(find_advisorships_under_person($pid));
            $commcount = count(find_committeeships_under_person($pid));
            $totalcommitteeships = $advisorcount + $commcount;
            if ($totalcommitteeships > 1){print "";}
            print " : $advisorcount + $commcount = $totalcommitteeships";
            if ($totalcommitteeships > 1){print "";}
            print "
\n";
            $allcommitteeships += $totalcommitteeships;
          }
          if ($count == 0)
          {
            print " - None";
          }

          print "
TOTAL COMMITTEESHIPS = $allcommitteeships
";

          echo "
\n";

#        }
#        else
#        {
#          not_admin();
#        }

        break;

        ###############################################
        case "lis_profswithoutdiss":

        if (is_admin())
        {
          echo "
LIS Professors without Dissertations
\n";

          # advisors or committee members with no dissertation,
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }
          # get advisors for each diss
          $advisors = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
          }
          # get committeeships for each diss
          $committeemembers = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
          }
          $total = array_merge($advisors,$committeemembers);
          $unique = array_unique($total);

          $unique_list = implode(",",$unique);
          $listed = array();
          $query = "SELECT person_id
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                    ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $listed[] = $line['person_id'];
          }
          $notlisted = array_diff($unique,$listed);

          # print them out
          echo "
\n";
          $count = 0;
          foreach($notlisted as $pid){
            $count++;
            print "$count. ";
            print get_person_link($pid);
            print "
\n";
          }
          if ($count == 0)
          {
            print " - None";
          }
          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_profs_degrees":

        if (is_admin())
        {
          echo "
LIS Professors and their Degrees
\n";

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          print "
Copy and Paste the text below into a .csv file.
";

          # big loop
          print "
\n";
          print "
";
          print "Count,DissID,DissYear,DissLastName,DissFirstName,DissSchool,DissCountry,AdvisorID,AdvisorType,AdvisorLastName,AdvisorFirstName,";
          print "AdvisorDegree,AdvisorYear,AdvisorDiscipline,AdvisorSchool,AdvisorCountry\n";
          $count = 0;
          foreach($lis_dissertations as $did){
            # loop through advisors
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $did
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {

              # advisor line

                # Count
                $count++;
                print "\"$count\",";
                # DissID
                print "\"$did\",";
                # DissYear
                $diss = find_dissertation($did);
                print "\"".$diss['completedyear']."\",";
                # DissLastName
                $author = find_person($diss['person_id']);
                print "\"".$author['lastname']."\",";
                # DissFirstName
                print "\"".$author['firstname']."\",";
                # DissSchool
                $school = find_school($diss['school_id']);
                print "\"".$school['fullname']."\",";
                # DissCountry
                print "\"".$school['country']."\",";
                # AdvisorID
                $pid = $line['person_id'];
                print "\"$pid\",";
                # AdvisorType
                print "\"Advisor\",";
                # AdvisorLastName
                $person = find_person($pid);
                print "\"".$person['lastname']."\",";
                # AdvisorFirstName
                print "\"".$person['firstname']."\",";
                # AdvisorDegree
                print "\"".$person['degree']."\",";
                $diss = find_dissertation_by_person($pid);
                if ($diss){
                  # AdvisorYear
                  print "\"".$diss['completedyear']."\",";
                  # AdvisorDiscipline
                  $disc = find_discipline($diss['discipline_id']);
                  print "\"".$disc['title']."\",";
                  # AdvisorSchool
                  $school = find_school($diss['school_id']);
                  print "\"".$school['fullname']."\",";
                  # AdvisorCountry
                  print "\"".$school['country']."\"";
                }
                else{
                  # no dissertation for this person
                  print "\"\",";
                  print "\"\",";
                  print "\"\",";
                  print "\"\"";
                }
                print "\n";

            }
            # loop through committeeships
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $did
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {

              # committeeship line

                # Count
                $count++;
                print "\"$count\",";
                # DissID
                print "\"$did\",";
                # DissYear
                $diss = find_dissertation($did);
                print "\"".$diss['completedyear']."\",";
                # DissLastName
                $author = find_person($diss['person_id']);
                print "\"".$author['lastname']."\",";
                # DissFirstName
                print "\"".$author['firstname']."\",";
                # DissSchool
                $school = find_school($diss['school_id']);
                print "\"".$school['fullname']."\",";
                # DissCountry
                print "\"".$school['country']."\",";
                # AdvisorID
                $pid = $line['person_id'];
                print "\"$pid\",";
                # AdvisorType
                print "\"Committee\",";
                # AdvisorLastName
                $person = find_person($pid);
                print "\"".$person['lastname']."\",";
                # AdvisorFirstName
                print "\"".$person['firstname']."\",";
                # AdvisorDegree
                print "\"".$person['degree']."\",";
                $diss = find_dissertation_by_person($pid);
                if ($diss){
                  # AdvisorYear
                  print "\"".$diss['completedyear']."\",";
                  # AdvisorDiscipline
                  $disc = find_discipline($diss['discipline_id']);
                  print "\"".$disc['title']."\",";
                  # AdvisorSchool
                  $school = find_school($diss['school_id']);
                  print "\"".$school['fullname']."\",";
                  # AdvisorCountry
                  print "\"".$school['country']."\"";
                }
                else{
                  # no dissertation for this person
                  print "\"\",";
                  print "\"\",";
                  print "\"\",";
                  print "\"\"";
                }
                print "\n";

            }
          }
          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_profsnotfromlis":

          if (is_admin())
          {

            echo "
LIS Professors without LIS Dissertations
\n";

            # and then once the data collection is done
            # cassidy wants a list of all the people who were advisors and committee
            # members for lis, but were not themselves lis

            # get list of LIS dissertations
            $query = "SELECT
                      d.id
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1'
                    ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $lis_dissertations[] = $line['id'];
            }
            # get advisors for each diss
            $advisors = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT person_id
                          FROM advisorships
                          WHERE dissertation_id = $id
                        ";
              $result = mysql_query($query) or die(mysql_error());
              while ( $line = mysql_fetch_array($result)) {
                $advisors[] = $line['person_id'];
              }
            }
            # get committeeships for each diss
            $committeemembers = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT person_id
                          FROM committeeships
                          WHERE dissertation_id = $id
                        ";
              $result = mysql_query($query) or die(mysql_error());
              while ( $line = mysql_fetch_array($result)) {
                $committeemembers[] = $line['person_id'];
              }
            }
            $total = array_merge($advisors,$committeemembers);
            $unique = array_unique($total);

            $unique_list = implode(",",$unique);
            $listed = array();
            $query = "SELECT person_id
                        FROM dissertations
                        WHERE
                          person_id IN ($unique_list)
                          AND
                          discipline_id = '1'
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $listed[] = $line['person_id'];
            }
            $notlisted = array_diff($unique,$listed);

            # print them out
            echo "
\n";
            $count = 0;
            foreach($notlisted as $pid){
              $count++;
              print "$count. ";
              print get_person_link($pid);
              print "
\n";
            }
            if ($count == 0)
            {
              print " - None";
            }
            echo "
\n";

          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_nocommittee":

          if (is_admin())
          {

            echo "
LIS Dissertations with no committee
\n";

            # get list of LIS dissertations
            $query = "SELECT
                      d.id
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1'
                    ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $lis_dissertations[] = $line['id'];
            }
            # get advisors for each diss
            $advisors = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT count(*) as howmany
                          FROM advisorships
                          WHERE dissertation_id = $id
                        ";
              $result = mysql_query($query) or die(mysql_error());
              while ( $line = mysql_fetch_array($result)) {
                if ($line['howmany'] > 0){$hascomm[] = $id;};
              }
            }
            # get committeeships for each diss
            $committeemembers = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT count(*) as howmany
                          FROM committeeships
                          WHERE dissertation_id = $id
                        ";
              $result = mysql_query($query) or die(mysql_error());
              while ( $line = mysql_fetch_array($result)) {
                if ($line['howmany'] > 0){$hascomm[] = $id;};
              }
            }
            $unique = array_unique($hascomm);
            $nocomm = array_diff($lis_dissertations,$unique);

            # print them out
            echo "
\n";
            $count = 0;
            foreach($nocomm as $did){
              $count++;
              print "$count. ";
              $d = find_dissertation($did);
              print get_person_link($d['person_id']);
              print "
\n";
            }
            if ($count == 0)
            {
              print " - None";
            }
            echo "
\n";

          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_profs_with_mpact":

        if (is_admin())
        {
          echo "
LIS Professors With MPACT
\n";

          # advisors or committee members
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          # get advisors for each diss
          $advisors = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
          }

          # get committeeships for each diss
          $committeemembers = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
          }

          $total = array_merge($advisors,$committeemembers);

          $unique = array_unique($total);

          echo "
\n";
          echo "Count|Name|Year|A|C|A+C|T\n";
          foreach ($unique as $prof){
            $mpact = mpact_scores($prof);
            $person = find_person($prof);
            $dissertation = find_dissertation_by_person($prof);
            # count
            $count += 1;
            echo "$count";
            echo "|";
            # name
            echo $person['fullname'];
            echo "|";
            # year
            echo $dissertation['completedyear'];
            echo "|";
            # a
            echo $mpact['A'];
            echo "|";
            # c
            echo $mpact['C'];
            echo "|";
            # a+c
            echo $mpact['AC'];
            echo "|";
            # t
            echo $mpact['T'];
            echo "\n";
          }
          echo "
\n";
        }

        break;

        ###############################################
        case "lis_profs_summary":

        if (is_admin())
        {
          echo "
LIS Professors Summary
\n";

          # advisors or committee members
          # that served on an lis dissertation

          echo "
\n";

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }
          echo "
Total LIS Dissertations	".count($lis_dissertations)."
\n";

          # get advisors for each diss
          $advisors = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
          }
          echo "
Total LIS Dissertation Advisorships	";
          echo count($advisors);
          echo "
\n";

          # get committeeships for each diss
          $committeemembers = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
          }
          echo "
Total LIS Dissertation Committeeships	";
          echo count($committeemembers);
          echo "
\n";

          $total = array_merge($advisors,$committeemembers);
          echo "
Total LIS Dissertation Advisorships and Committeeships:	";
          echo count($total);
          echo "
\n";

          $unique = array_unique($total);
          echo "
Total number of unique advisor/committee members on LIS dissertations:	";

          echo count($unique);
          echo "
\n";

          $unique_list = implode(",",$unique);
          $known = array();
          $query = "SELECT person_id
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                    ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $known[] = $line['person_id'];
          }
          echo "
";
          echo "Subset of ".count($unique)." without a listed dissertation:	";
          echo count(array_diff($unique,$known));
          echo "
\n";
          echo "
Subset of ".count($unique)." with a listed dissertation:	";
          echo count($known);
          echo "
\n";

          $query = "SELECT count(*) as howmany
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                        AND
                        discipline_id != 16
                    ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $howmany = $line['howmany'];
          }
          echo "
 - Subset of ".count($known)." with known discipline:	";
          echo $howmany;
          echo "
\n";

          $query = "SELECT count(*) as howmany
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                        AND
                        completedyear != 0000
                    ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $howmany = $line['howmany'];
          }
          echo "
 - Subset of ".count($known)." with known year:	";
          echo $howmany;
          echo "
\n";

          $query = "SELECT count(*) as howmany
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                        AND
                        completedyear != 107
                    ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $howmany = $line['howmany'];
          }
          echo "
 - Subset of ".count($known)." with known school:	";
          echo $howmany;
          echo "
\n";

          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_allyears":

          if (is_admin())
          {
            echo "
LIS, Graduates By Year
\n";
            print "
\n";

            # get list of dissertations
            $query = "SELECT
                      d.id, d.person_id, d.completedyear
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1'
                    ORDER BY
                      d.completedyear ASC,
                      d.school_id ASC
                    ";
            $result = mysql_query($query) or die(mysql_error());
            $schools = array();
            $count = 0;
            while ( $line = mysql_fetch_array($result)) {
              $dissertation = find_dissertation($line['id']);
              $person = find_person($line['person_id']);
              $schoolinfo = find_persons_school($line['person_id']);
              $count++;
              print $count;
              print "|";
              print $line['completedyear'];
              print "|";
              print $schoolinfo['school'];
              print "|";
              print $person['fullname'];
#              print "|";
#              print $dissertation['title'];
#              print "|";
#              print $dissertation['abstract'];
              print "\n";
            }

            print "
\n";
          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_history":

          if (is_admin())
          {
            echo "
LIS Dissertations by School by Year
\n";

            $firstyear = 1920;
            $lastyear = 2008;

            print "
\n";
            print "school|";
            for ($i = $firstyear; $i <= $lastyear; $i++)
            {
                print "$i|";
            }
            print "\n";

            # get list of schools (all of them)
            $query = "SELECT
                    s.id, s.fullname
                    FROM
                      schools s
                    ORDER BY
                      s.fullname
                    ";
            $result = mysql_query($query) or die(mysql_error());
            $schools = array();
            while ( $line = mysql_fetch_array($result)) {
              $schools[] = $line;
            }
            foreach ($schools as $s)
            {
              # loop through each school and find count by year
              $query = "SELECT
                    d.id, d.person_id, d.completedyear, COUNT(d.completedyear) AS yeartotal
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1' AND
                      d.school_id = '".$s['id']."'
                    GROUP BY
                      d.completedyear
                  ";
              $result = mysql_query($query) or die(mysql_error());

              print $s['fullname']."|";
              $d = array();
              while ( $line = mysql_fetch_array($result)) {
                $d[$s['id']][$line['completedyear']] = $line['yeartotal'];
              }

              # walk through all years, and print out counts for this school
              for ($i = $firstyear; $i <= $lastyear; $i++)
              {
                if ($d[$s['id']][$i] > 0)
                  print $d[$s['id']][$i]."|";
                else
                  print "0|";
              }
              print "\n";
            }

            print "
";
          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_incomplete":

          echo "
Incomplete LIS Dissertation Listings
\n";

          $discipline_id = 1; # hard coded for LIS
          $schools = find_schools($discipline_id);

          foreach ($schools as $one => $two)
          {

            $year_conferred = array();
            $degree_status = array();

            $query = "SELECT d.person_id, d.completedyear, d.status
                  FROM
                    dissertations d,
                    schools s,
                    people p,
                    names n
                  WHERE
                    s.id = '$one' AND
                    d.discipline_id = '$discipline_id' AND
                    d.school_id = s.id AND
                    d.person_id = p.id AND
                    p.preferred_name_id = n.id AND
                    d.status < 4
                  ORDER BY
                    s.id ASC, d.completedyear ASC, n.lastname ASC, n.firstname ASC
                ";

            $result = mysql_query($query) or die(mysql_error());
            $resultcount = 0;

            while ( $line = mysql_fetch_array($result)) {
              $resultcount++;
              extract($line);
              $year_conferred[$person_id] = $completedyear;
              $degree_status[$person_id] = $status;
            }

            if ($resultcount > 0)
            {
              echo "
$two
\n";
            }

            $incompletecount = 0;
            echo "
";
            foreach ($year_conferred as $person => $year)
            {
              $incompletecount++;
              $printme = "
\n";
              $printme .= "$incompletecount. ";
              $printme .= "".get_person_link($person)." ($year)	\n";

              $printme .= "".$statuscodes[$degree_status[$person]]."	\n";
              $printme .= "
\n";

              echo $printme;
            }
            echo "
";

          }
          echo "

";

        break;

        ###############################################
        case "all_edges":

          if (is_admin())
          {
            echo "
All Dissertations and Mentor Relationships
\n";

            print "
\n";
            print "mentor|role|protege|year|school\n";

            # each dissertation
            $query = "SELECT id, person_id, completedyear, school_id FROM dissertations";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              extract($line);
              $student = find_person($person_id);
              $query2 = "SELECT fullname as schoolname FROM schools WHERE id = '$school_id'";
              $result2 = mysql_query($query2) or die(mysql_error());
              $line2 = mysql_fetch_array($result2);
              extract($line2);
              print $student['fullname']."|dissertation|null|$completedyear|$schoolname\n";
              # get advisorships
              $advisors = find_advisors_for_person($person_id);
              foreach ($advisors as $mentor_id){
                $mentor = find_person($mentor_id);
                print $mentor['fullname']."|advisorship|".$student['fullname']."|$completedyear|$schoolname\n";
              }
              # get committeeships
              $committee = find_committee_for_person($person_id);
              foreach ($committee as $mentor_id){
                $mentor = find_person($mentor_id);
                print $mentor['fullname']."|committeeship|".$student['fullname']."|$completedyear|$schoolname\n";
              }
            }
            print "
";
          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "citation_correlation":

          if (is_admin())
          {
            echo "
Citation Correlation Data
\n";

            $correlated_ids = array(
              953,
              2098,
#              5086,   bc
              3659,
#              1329,  dalhousie
              5087,
              478,
              3094,
              3497,
              4784,
              1250,
              5088,
              5089,
              5090,
              4657,
#              5091,  mcdowell, not phd yet
              5092,
              5093,
              5094,
              2668,
              4076,
              2683,
              3978,
              2425,
              3645,
              2660,
              2233,
              2665,
              1310,
              2548,
              2708,
              2592,
              4648,
              5095,
              5096,
              4654,
              5097,
              5098,
              1234,
              1299,
              1294,
              3062,
              3110,
              1283,
              1220,
              874,
              584,
              3127,
              1142,
              3116,
              5099,
              5100,
              1025,
              486,
              3130,
              1321,
              5101,
              4502,
              5102,
              535,
              5160,   # koohang
              2673,
              5103,
              5104,
              1950,
              3972,
              3278,
              5105,
              3571,
              5106,
              3994,
              1504,
              4181,
              3140,
              2323,   # benoit added
              5107,
              800,
              4438,
              5108,
              5109,
              4760,
              2570,
              1866,
              3238,
              1846,
              1806,
              2527,
              3703,
              4758,
              3683,
              3846,
              2603,
              4011,
              2343,
              2329,
              5110,
              5111,
              4706,
              2761,
              1413,
              3028,
              3590,
              3668,
              2883,
              3063,
              3091,
              1705,
              3031,
# gary again  486,
              3979,
              3018,
              1855,
              3409,
              2747,
              3093,
              3065,
              3060,
              1685,
              2114,
              5112,
# moore rm    5113,
              2309,
# liu rm      2215,
              4086,
              4013,
              1573
            );

            echo "
\n";
            echo "

              -
              Name
              A
              C
              A+C
              FMI
              FME
              FMI/(A+C)
              FME/(A+C)

\n";
            $counter = 0;
            foreach ($correlated_ids as $one)
            {
              $counter++;
              echo "
";
              echo "$counter.	";
              echo "";
              echo get_person_link($one);
              echo "	";
              $scores = mpact_scores($one);
              echo "".$scores['A']."	";
              echo "".$scores['C']."	";
              echo "".$scores['AC']."	";
              echo "".$scores['FMI']."	";
              echo "".$scores['FME']."	";
              echo "".$scores['FMIdivFULL']."	";
              echo "".$scores['FMEdivFULL']."	";
              echo "
\n";
            }
            echo "
\n";

          }
          else
          {
             not_admin();
          }

          break;

        ###############################################
        case "top_a":
        case "top_c":
        case "top_ac":
        case "top_g":
        case "top_td":
        case "top_w":
        case "top_t":
        case "top_ta":

        $list_type = strtoupper(substr($_GET['op'],4));
        echo "
Top ";
        if ($list_type == "TD"){echo "TD";}
        else if ($list_type == "TA"){echo "TA";}
        else if ($list_type == "AC"){echo "A+C";}
        else {echo $list_type;}
        echo " List
\n";
        $score_type = strtolower($list_type)."_score";
        $people = find_all_people();
        foreach ($people as $p)
        {
          $scores[$p] = find_mpact_score($p,$score_type);
        }
        # zero out indecipherables
        $scores[28] = 0;
        $scores[391] = 0;
        asort($scores);
        $scores = array_reverse($scores, true);
        $top = narray_slice($scores, 0, 100); #calls custom function, end of mpact_include (passes true)
        $count = 0;
        $lasttotal = 0;
        echo "
\n";
        foreach ($top as $one => $two)
        {
          $count++;
          echo "
";
          echo "";
          if ($two != $lasttotal){echo $count.".";}
          echo "	";
          echo "";
          echo get_person_link($one);
          echo "	";
          echo "";
          echo $two;
          echo "	";
          echo "
\n";
          $lasttotal = $two;
        }
        echo "
\n";
        break;

        ###############################################
        case "create_discipline":

        if (is_admin())
        {
          echo "
Creating a New Discipline
\n";

          echo "
";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"create_discipline\">\n";

          echo "
";
          echo "
Title
";

          echo "
";
          echo "<input type=\"text\" size=\"70\" name=\"title\">	";
          echo "
";

          echo "
";

          echo "<input type=\"submit\" name=\"button\" value=\"Create\">";
          echo "</form>";

          echo "
";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "edit_discipline":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          elseif (!is_empty_discipline($_GET['id']))
          {
            action_box("Discipline must be empty to edit...",2,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");
          }
          else{

            $query = "SELECT title FROM disciplines WHERE id=".$_GET['id'];
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              extract($line);
            }

            echo "
Editing a Discipline
\n";

            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"discipline_id\" value=\"".$_GET['id']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_discipline\">\n";

            echo "
";
            echo "
Title
";

            echo "
";
            echo "<input type=\"text\" size=\"70\" name=\"title\" value=\"$title\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"button\" value=\"Save\">";
            echo "</form>";

            echo "
";
          }
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "create_school":

        if (is_admin())
        {
          echo "
Creating a New School
\n";

          echo "
";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"create_school\">\n";

          echo "
";
          echo "
Fullname	Country
";

          echo "
";
          echo "<input type=\"text\" size=\"70\" name=\"fullname\">	";
          echo "<input type=\"text\" size=\"25\" name=\"country\" value=\"USA\">	";
          echo "
";

          echo "
";

          echo "<input type=\"submit\" name=\"button\" value=\"Create\">";
          echo "</form>";

          echo "
";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "edit_school":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          elseif (!is_empty_school($_GET['id']))
          {
            action_box("School must be empty to edit...",2,$_SERVER['SCRIPT_NAME']."?op=show_schools");
          }
          else{

            $query = "SELECT fullname, country FROM schools WHERE id=".$_GET['id'];
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              extract($line);
            }

            echo "
Editing a School
\n";

            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"school_id\" value=\"".$_GET['id']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_school\">\n";

            echo "
";
            echo "
Fullname	Country
";

            echo "
";
            echo "<input type=\"text\" size=\"70\" name=\"fullname\" value=\"$fullname\">	";
            echo "<input type=\"text\" size=\"25\" name=\"country\" value=\"$country\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"button\" value=\"Save\">";
            echo "</form>";

            echo "
";
          }
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "create_person":

        if (is_admin())
        {
          echo "
Creating a New Person
\n";

          echo "
";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"create_person\">\n";

          echo "
";
          echo "
First	Middle	Last	Suffix	Degree
";

          echo "
";
          echo "<input type=\"text\" size=\"10\" name=\"firstname\">	";
          echo "<input type=\"text\" size=\"10\" name=\"middlename\">	";
          echo "<input type=\"text\" size=\"12\" name=\"lastname\">	";
          echo "<input type=\"text\" size=\"5\" name=\"suffix\">	";
          echo "";
          echo "<select name=\"degree\">\n";
          foreach ($degree_types as $one){
            echo "<option value=\"$one\"";
            echo ">$one</option>\n";
          }
          echo "</select>\n";
          echo "	";
          echo "
";

          echo "
";

          echo "<input type=\"submit\" name=\"button\" value=\"Create\">";
          echo "</form>";

          echo "
";
        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_mentor":

        if (is_admin())
        {
          echo "
Add a New Person to the Database
\n";

          echo "
Adding a Mentor
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"add_mentor\">\n";
          echo "<input type=\"hidden\" name=\"student_id\" value=\"".$_GET['id']."\">\n";

          echo "
";

          echo "Mentor Type:
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"A\"";
          if ($_GET['type'] == "A"){echo " checked";}
          echo "> Advisor
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"C\"";
          if ($_GET['type'] == "C"){echo " checked";}
          echo "> Committee Member\n";
          echo "

\n";

          echo "Mentor:
\n";
          echo "<select name=\"mentor_id\">\n";
          $people = find_all_people_for_selectbox();
          foreach ($people as $person_id => $person)
          {
            echo "<option value=\"$person_id\">".$person['lastname'];
            if ($person['suffix'] != ""){echo " ".$person['suffix'];}
            echo ", ".$person['firstname']." ".$person['middlename']."</option>\n";
          }
          echo "</select>\n";

          echo "

\n";

          echo "Student:
\n". get_person_link($_GET['id']);
          echo "

\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Add Mentor\">";

          echo "
";
          echo "</form>";

          draw_tree($_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_student":

        if (is_admin())
        {
          echo "
Add a New Person to the Database
\n";

          echo "
Adding a Student
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"add_student\">\n";
          echo "<input type=\"hidden\" name=\"mentor_id\" value=\"".$_GET['id']."\">\n";

          echo "
";

          echo "Mentor Type:
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"A\"";
          if ($_GET['type'] == "A"){echo " checked";}
          echo "> Advisor
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"C\"";
          if ($_GET['type'] == "C"){echo " checked";}
          echo "> Committee Member\n";
          echo "

\n";

          echo "Mentor:
\n". get_person_link($_GET['id']);
          echo "

\n";

          echo "Student:
\n";
          echo "<select name=\"student_id\">\n";
          $people = find_all_people_for_selectbox("1"); # the 1 is to only get people with dissertations
          foreach ($people as $person_id => $person)
          {
            echo "<option value=\"$person_id\">".$person['lastname'];
            if ($person['suffix'] != ""){echo " ".$person['suffix'];}
            echo ", ".$person['firstname']." ".$person['middlename']."</option>\n";
          }
          echo "</select>\n";

          echo "

\n";
          echo "<input type=\"submit\" name=\"button\" value=\"Add Student\">";

          echo "
";
          echo "</form>";

          draw_tree($_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "remove_mentor":

        if (is_admin())
        {
          echo "
Removing a Mentor
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"remove_mentor\">\n";
          echo "<input type=\"hidden\" name=\"student_id\" value=\"".intval($_GET['student_id'])."\">\n";
          echo "<input type=\"hidden\" name=\"mentor_id\" value=\"".intval($_GET['mentor_id'])."\">\n";
          echo "<input type=\"hidden\" name=\"mentor_type\" value=\"".$_GET['type']."\">\n";

          echo "
";

          echo "Are you sure you want to remove this mentor relationship?

\n";
          if ($_GET['type'] == "A"){echo "Advisor: ";}
          if ($_GET['type'] == "C"){echo "Commitee Member: ";}
          echo get_person_link(intval($_GET['mentor_id']))."
\n";
          echo "Student: ".get_person_link(intval($_GET['student_id']))."
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Yes, remove this relationship.\">";
          echo " If NOT, please go BACK";

          echo "
";
          echo "</form>";

          draw_tree(intval($_GET['student_id']));

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_url";

        if (is_admin())
        {
          echo "
Adding a Reference URL
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"add_url\">\n";
          echo "<input type=\"hidden\" name=\"person_id\" value=\"".intval($_GET['id'])."\">\n";

          echo "
";

          echo "
\n";
          echo "
URL:	<input type=\"text\" name=\"url\" size=\"70\">
\n";
          echo "
Description:	<textarea rows=\"4\" cols=\"68\" name=\"description\"></textarea>
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Add this URL\">";

          echo "
";
          echo "</form>";

          draw_tree(intval($_GET['id']));

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "edit_url";

        if (is_admin())
        {
          $url = find_url(intval($_GET['id']));
          echo "
Editing a Reference URL
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"edit_url\">\n";
          echo "<input type=\"hidden\" name=\"id\" value=\"".intval($_GET['id'])."\">\n";

          echo "
";

          echo "
\n";
          echo "
URL:	<input type=\"text\" name=\"url\" size=\"70\" value=\"".$url['url']."\">
\n";
          echo "
Description:	<textarea rows=\"4\" cols=\"68\" name=\"description\">".$url['description']."</textarea>
\n";
          echo "
Last Updated:	".$url['updated_at']."
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Edit this URL\">";

          echo "
";
          echo "</form>";

          draw_tree($url['person_id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "delete_url";

        if (is_admin())
        {
          $url = find_url(intval($_GET['id']));
          echo "
Deleting a Reference URL
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"delete_url\">\n";
          echo "<input type=\"hidden\" name=\"id\" value=\"".intval($_GET['id'])."\">\n";

          echo "
";

          echo "Are you sure you want to delete this Reference URL?

\n";
          echo "
\n";
          echo "
URL:	".$url['url']."
\n";
          echo "
Description:	".$url['description']."
\n";
          echo "
Last Updated:	".$url['updated_at']."
\n";
          echo "
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Yes, delete this Reference URL\">";
          echo " If NOT, please go BACK";

          echo "
";
          echo "</form>";

          draw_tree($url['person_id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "edit_degree":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_person($_GET['id']);

            echo "
Editing a Degree
";
            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_degree\">";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">";

            echo "
";
            echo "
Name	Degree
";

            echo "
";
            echo "".$person['fullname']."	";
            echo "";
            echo "<select name=\"degree\">\n";
            foreach ($degree_types as $one){
              echo "<option value=\"$one\"";
              if ($person['degree'] == $one){
                echo " selected";
              }
              echo ">$one</option>\n";
            }
            echo "</select>\n";
            echo "	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";

            echo "</form>";

            echo "
";

            echo "

";
            draw_tree($_GET['id']);
            echo "

";

          }
        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_name":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_person($_GET['id']);

            echo "
Adding an Alias
";
            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
            echo "<input type=\"hidden\" name=\"op\" value=\"add_name\">";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">";

            echo "
";
            echo "
First	Middle	Last	Suffix
";

            echo "
";
            echo "<input type=\"text\" size=\"10\" name=\"firstname\">	";
            echo "<input type=\"text\" size=\"10\" name=\"middlename\">	";
            echo "<input type=\"text\" size=\"10\" name=\"lastname\">	";
            echo "<input type=\"text\" size=\"10\" name=\"suffix\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"submit\" value=\"Add\">";

            echo "</form>";

            echo "
";

            echo "

";
            draw_tree($_GET['id']);
            echo "

";

          }
            }
            else
            {
               not_admin();
            }

        break;

      ###############################################
      case "edit_name":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_person($_GET['id']);

            echo "
Editing a Name
";
            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_name\">";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">";
            echo "<input type=\"hidden\" name=\"name_id\" value=\"".$person['preferred_name_id']."\">";

            echo "
";
            echo "
First	Middle	Last	Suffix
";

            echo "
";
            echo "<input type=\"text\" size=\"10\" name=\"firstname\" value=\"".$person['firstname']."\">	";
            echo "<input type=\"text\" size=\"10\" name=\"middlename\" value=\"".$person['middlename']."\">	";
            echo "<input type=\"text\" size=\"12\" name=\"lastname\" value=\"".$person['lastname']."\">	";
            echo "<input type=\"text\" size=\"5\" name=\"suffix\" value=\"".$person['suffix']."\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";

            echo "</form>";

            echo "
";

            echo "

";
            draw_tree($_GET['id']);
            echo "

";

          }
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "create_dissertation":

          if (is_admin())
          {

            $disciplines = find_disciplines();
            $schools = find_schools();

            if (!$_GET['person_id']){action_box("No ID given.");}
            else
            {

              $person = find_person($_GET['person_id']);
              if (!$person)
              {
                action_box("Person not found.");
              }
              else{

                echo "
CREATE DISSERTATION
\n";

                echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
                echo "<input type=\"hidden\" name=\"op\" value=\"create_dissertation\">";
                echo "<input type=\"hidden\" name=\"person_id\" value=\"".intval($person['id'])."\">";

                echo "
";
                echo get_person_link($person['id']);
                echo "
";

                echo "Degree: <select name=\"degree\">\n";
                foreach ($degree_types as $one)
                {
                  echo "<option value=\"$one\"";
                  if ($one == "Ph.D."){
                    echo " selected";
                  }
                  echo ">$one</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Status: <select name=\"status\">\n";
                foreach (range(0,4) as $one)
                {
                  echo "<option value=\"$one\"";
                  echo ">".$statuscodes[$one]."</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Discipline: <select name=\"discipline_id\">\n";
                foreach ($disciplines as $one => $two)
                {
                  echo "<option value=\"$one\">$two</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "School: ";
                echo "<select name=\"school_id\">\n";
                foreach ($schools as $one => $two)
                {
                  echo "<option value=\"$one\"";
                  echo ">$two</option>\n";
                }
                echo "</select>\n";
                echo "
Year:\n";
                echo "<input type=\"text\" size=\"10\" name=\"completedyear\">
";
                echo "Title:
<textarea cols=\"60\" rows=\"3\" name=\"title\"></textarea>
";
                echo "Abstract:
<textarea cols=\"60\" rows=\"7\" name=\"abstract\"></textarea>
";
                echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";
                echo "
";

                echo "</form>";

                echo "
";
                echo "Currently:";
                echo "
";
                echo "

";
                draw_tree($person['id']);
                echo "

";
              }

            }
          }
          else
          {
             not_admin();
          }

          break;

        ###############################################
        case "edit_dissertation":

          if (is_admin())
          {
            if (!$_GET['id']){action_box("No ID given.");}
            else
            {

              $disciplines = find_disciplines();
              $schools = find_schools();
              $dissertation = find_dissertation(intval($_GET['id']));
              if (!$dissertation)
              {
                action_box("Dissertation not found.");
              }
              else{

                $person = find_person($dissertation['person_id']);

                echo "
EDIT DISSERTATION DETAILS
\n";

                echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
                echo "<input type=\"hidden\" name=\"op\" value=\"edit_dissertation\">";
                echo "<input type=\"hidden\" name=\"id\" value=\"".intval($_GET['id'])."\">";
                echo "<input type=\"hidden\" name=\"person_id\" value=\"".intval($person['id'])."\">";

                echo "
";
                echo get_person_link($person['id']);
                echo "
";

                echo "Degree: <select name=\"degree\">\n";
                foreach ($degree_types as $one)
                {
                  echo "<option value=\"$one\"";
                  if ($person['degree'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">$one</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Status: <select name=\"status\">\n";
                foreach (range(0,4) as $one)
                {
                  echo "<option value=\"$one\"";
                  if ($dissertation['status'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">".$statuscodes[$one]."</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Discipline: <select name=\"discipline_id\">\n";
                foreach ($disciplines as $one => $two)
                {
                  echo "<option value=\"$one\"";
                  if ($dissertation['discipline_id'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">$two</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "School: <select name=\"school_id\">\n";
                foreach ($schools as $one => $two)
                {
                  echo "<option value=\"$one\"";
                  if ($dissertation['school_id'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">$two</option>\n";
                }
                echo "</select>\n";

                echo "
Year:\n";
                echo "<input type=\"text\" size=\"10\" name=\"completedyear\" value=\"".$dissertation['completedyear']."\">
";
                echo "Title:
<textarea cols=\"60\" rows=\"3\" name=\"title\">".$dissertation['title']."</textarea>
";
                echo "Abstract:
<textarea cols=\"60\" rows=\"7\" name=\"abstract\">".$dissertation['abstract']."</textarea>
";
                echo "Admin Notes:
<textarea cols=\"60\" rows=\"7\" name=\"notes\">".$dissertation['notes']."</textarea>
";
                echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";
                echo "
";

                echo "</form>";

                echo "
";
                echo "Currently:";
                echo "
";
                echo "

";
                draw_tree($person['id']);
                echo "

";
              }

            }
          }
          else
          {
             not_admin();
          }

          break;

      ###############################################
      case "delete_name":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_name($_GET['name']);

            echo "
";

            echo "Are you sure you want to delete this name?";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"delete_name\">\n";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">\n";
            echo "<input type=\"hidden\" name=\"name_id\" value=\"".$_GET['name']."\">";

            echo "
";
            echo "[ ".$person['firstname']." ".$person['middlename']." ".$person['lastname']." ".$person['suffix']." ]
";
            echo "
";

            echo "
";
            echo "<input type=\"submit\" name=\"submit\" value=\"Yes\">";
            echo "   Cancel
";

            echo "</form>";

            echo "
";

          }
            }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "set_preferred_name":

        if (is_admin())
        {

          set_preferred_name($_GET['id'],$_GET['name']);

          action_box("Preferred Name Selected",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "recalculate_mpact":

        if (is_admin()){

          # recalculate MPACT scores for passed person id
          calculate_scores($_GET['id']);

          action_box("MPACT Scores Recalculated",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "show_orphans":

        if (is_admin())
        {

          $orphans = find_orphans();

          echo "
Orphans
\n";

          echo "
\n";
          $counter = 0;
          foreach ($orphans as $orphan)
          {
            $counter++;
            echo $counter." ";
            echo get_person_link($orphan['person_id']);
            echo " (Delete from Database)";
            echo "
\n";
          }
          if ($counter < 1){echo " - No orphans at this time.";}
          echo "
\n";

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "delete_person":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            if (is_orphan($_GET['id']))
            {
              echo "
";

              echo "Are you sure you want to delete this person?";

              echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
              echo "<input type=\"hidden\" name=\"op\" value=\"delete_person\">\n";
              echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">\n";

              echo "
";
              echo get_person_link($_GET['id']);
              echo "
";

              echo "
";
              echo "

\n";
              echo "<input type=\"submit\" name=\"submit\" value=\"Yes, Delete this person completely.\">";
              echo "   Cancel
";

              echo "</form>";

              echo "
";
            }
            else
            {
              action_box("This person cannot be deleted.");
            }
          }
        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "show_disciplines":

        $statustotals = array(0,0,0,0,0);
        $disciplines = find_disciplines();
        $disciplinecounts = find_discipline_counts();

        if (is_admin()){
          echo "
Add a New Discipline to the Database
\n";
        }

        echo "
Disciplines Represented Across All Schools
\n";

        echo "
\n";
        echo "
\n";
        echo "
";
        echo "Discipline	";
        foreach (range(0,4) as $one)
        {
          echo "$statuscodes[$one]	";
        }
        echo "
";
        foreach ($disciplines as $one => $two)
        {
          echo "
";
          echo "$two (".intval($disciplinecounts[$one]).")	";
          $statuscounts = find_discipline_statuses($one);
          foreach (range(0,4) as $three)
          {
            $statustotals[$three] += $statuscounts[$three];
            if (!isset($disciplinecounts[$one]) || $disciplinecounts[$one]==0)
            {
              $fraction = 0;
            }
            else
            {
              $fraction = 100*$statuscounts[$three]/intval($disciplinecounts[$one]);
            }
            echo "".$statuscounts[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
\n";
        }
        # summary line
        echo "
------------------
";
        echo "
";
        echo "";
        echo count($disciplines)." Disciplines (".array_sum($disciplinecounts)." dissertations)";
        echo "	";
        foreach (range(0,4) as $three)
        {
          $fraction = 100*$statustotals[$three]/array_sum($disciplinecounts);
          echo "".$statustotals[$three];
          if ($fraction != 0)
          {
            echo " (".sprintf("%.1f",$fraction)."%)";
          }
          echo "	";
        }
        echo "
";
        echo "
\n";
        echo "
\n";

        break;

        ###############################################
        case "show_discipline":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {

          $discipline_id = intval($_GET['id']);

          # Show Discipline Name
          $query = "SELECT d.title as disciplinename
                FROM disciplines d
                WHERE
                  d.id = '$discipline_id'
              ";

          $result = mysql_query($query) or die(mysql_error());

          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }

          echo "
$disciplinename
";

          # Show Histograph
          $counts = array();
          echo "
\n";
          echo "Dissertations by Year:
\n";
          $query = "SELECT completedyear, count(*) as disscount FROM dissertations WHERE discipline_id='$discipline_id' GROUP BY completedyear";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $counts[$line['completedyear']] = $line['disscount'];
          }
          if (count($counts)>0)
          {
            $bigyear = max($counts);
            echo "
\n";
            echo "
\n";
              foreach ($counts as $one => $two)
              {
                $height=$two*intval(200/$bigyear);
                echo "	\n";
              }
            echo "
";
            echo "
\n";
            foreach ($counts as $one => $two)
            {
              echo "";
              if ($one%10==0)
              {
                echo $one;
              }
              echo "	\n";
            }
            echo "
";
            echo "
\n";
          }
          echo "
\n";
        }

        $schools = find_schools($discipline_id);
        $dissertation_count = 0;
        $statustotals = array(0,0,0,0,0);
        echo "
Schools Represented
\n";

        echo "
\n";
        echo "
\n";
        echo "
";
        echo "School	";
        foreach (range(0,4) as $one)
        {
          echo "$statuscodes[$one]	";
        }
        echo "
";
        foreach ($schools as $one => $two)
        {
          $statuscounts = find_dept_statuses($one,$discipline_id);
          $dissertation_count += array_sum($statuscounts);
          echo "
";
          echo "$two (".array_sum($statuscounts).")	";
          foreach (range(0,4) as $three)
          {
            $statustotals[$three] += $statuscounts[$three];
            $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);
            echo "".$statuscounts[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
\n";
        }
        # summary line
        echo "
------------------
";
        echo "
";
        echo "";
        echo count($schools)." Schools ($dissertation_count dissertations)";
        echo "	";
        foreach (range(0,4) as $three)
        {

          if (array_sum($statustotals)==0)
          {
            $fraction = 0;
          }
          else
          {
            $fraction = 100*$statustotals[$three]/array_sum($statustotals);
          }
          echo "".$statustotals[$three];
          if ($fraction != 0)
          {
            echo " (".sprintf("%.1f",$fraction)."%)";
          }
          echo "	";
        }
        echo "
";
        echo "
\n";
        echo "
\n";

        # link to edit the discipline name
        if (is_empty_discipline($_GET['id']))
        {
          echo "

";
          echo "
Edit Discipline Name
\n";
        }

        break;

      ###############################################
      case "show_school":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {

          $school_id = intval($_GET['id']);

          # Show School Name
          $query = "SELECT s.fullname as schoolname, s.country
                FROM schools s
                WHERE
                  s.id = '$school_id'
              ";

          $result = mysql_query($query) or die(mysql_error());

          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }

          echo "
$schoolname ($country)
";

          # Show Histograph
          echo "
\n";
          echo "Dissertations by Year:
\n";
          $query = "SELECT completedyear, count(*) as disscount FROM dissertations WHERE school_id='$school_id' GROUP BY completedyear";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $counts[$line['completedyear']] = $line['disscount'];
          }
          $bigyear = max($counts);
          echo "
\n";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            $height=$two*intval(200/$bigyear);
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            echo "";
            if ($one%10==0)
            {
              echo $one;
            }
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          echo "
\n";

          $disciplines = find_disciplines($school_id);
          $dissertation_count = 0;
          $statustotals = array(0,0,0,0,0);
          echo "
Disciplines Represented
\n";

          echo "
\n";
          echo "
\n";
          echo "
";
          echo "Discipline	";
          foreach (range(0,4) as $one)
          {
            echo "$statuscodes[$one]	";
          }
          echo "
";
          foreach ($disciplines as $one => $two)
          {
            $statuscounts = find_dept_statuses($school_id,$one);
            $dissertation_count += array_sum($statuscounts);
            echo "
";
            echo "$two (".array_sum($statuscounts).")	";
            foreach (range(0,4) as $three)
            {
              $statustotals[$three] += $statuscounts[$three];
              $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);
              echo "".$statuscounts[$three];
              if ($fraction != 0)
              {
                echo " (".sprintf("%.1f",$fraction)."%)";
              }
              echo "	";
            }
            echo "
\n";
          }
          # summary line
          echo "
------------------
";
          echo "
";
          echo "";
          echo count($disciplines)." Disciplines ($dissertation_count dissertations)";
          echo "	";
          foreach (range(0,4) as $three)
          {
            $fraction = 100*$statustotals[$three]/array_sum($statustotals);
            echo "".$statustotals[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
";
          echo "
\n";
          echo "
\n";
        }

        # link to edit the school info
        if (is_empty_school($_GET['id']))
        {
          echo "

";
          echo "
Edit School Information
\n";
        }

        break;

      ###############################################
      case "show_schools":

        $statustotals = array(0,0,0,0,0);
        $schools = find_schools();
        $schoolcounts = find_school_counts();

        if (is_admin()){
          echo "
Add a New School to the Database
\n";
        }
        echo "
Schools Represented Across All Disciplines
\n";

        echo "
\n";
        echo "
\n";
        echo "
";
        echo "School	";
        foreach (range(0,4) as $one)
        {
          echo "$statuscodes[$one]	";
        }
        echo "
";
        foreach ($schools as $one => $two)
        {
          echo "
";
          echo "$two (".intval($schoolcounts[$one]).")	";
          $statuscounts = find_school_statuses($one);
          foreach (range(0,4) as $three)
          {
            $statustotals[$three] += $statuscounts[$three];
            if (intval($schoolcounts[$one]) == 0){
              $fraction = 0;
            }
            else{
              $fraction = 100*$statuscounts[$three]/intval($schoolcounts[$one]);
            }
            echo "".$statuscounts[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
\n";
        }
        # summary line
        echo "
------------------
";
        echo "
";
        echo "";
        echo count($schools)." Schools (".array_sum($schoolcounts)." dissertations)";
        echo "	";
        foreach (range(0,4) as $three)
        {
          $fraction = 100*$statustotals[$three]/array_sum($schoolcounts);
          echo "".$statustotals[$three];
          if ($fraction != 0)
          {
            echo " (".sprintf("%.1f",$fraction)."%)";
          }
          echo "	";
        }
        echo "
";
        echo "
\n";
        echo "
\n";

        break;

      ###############################################
      case "show_department":

        if (!$_GET['d'] || !$_GET['s']){action_box("No ID given.");}
        else
        {

          $school_id = $_GET['s'];
          $discipline_id = $_GET['d'];

          # Show Discipline Name
          $query = "SELECT d.title as disciplinename
                FROM disciplines d
                WHERE
                  d.id = '$discipline_id'
              ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }
          # Show School Name
          $query = "SELECT s.fullname as schoolname, s.country
                FROM schools s
                WHERE
                  s.id = '$school_id'
              ";
          $result = mysql_query($query) or die(mysql_error());

          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }

          echo "

          $disciplinename
          @
          $schoolname ($country)

          ";

          # Advisor and Committee Activity
          echo "
Dissertation Activity and MPACT Scores (click table headings to sort)
";

          echo "
";
          $theprofs = find_profs_at_dept($school_id,$discipline_id);
          if (count($theprofs)>0)
          {
            $sortedprofs = array();
            $proflist = "";
            $query = "SELECT id FROM people WHERE id IN (";
            foreach ($theprofs as $prof){$proflist .= "$prof,";}
            $proflist = rtrim($proflist, ",");
            $query .= "$proflist) ORDER BY ac_score DESC";
            $result = mysql_query($query) or die(mysql_error());
            while ( $line = mysql_fetch_array($result)) {
              $sortedprofs[] = $line['id'];
            }
            $profcount = 0;
            echo "
\n";
            echo "

              -
              Name
              A
              C
              A+C
              G
              T
              TA
              TD
              W

\n";
            foreach ($sortedprofs as $one)
            {
              echo "
";
              $profcount++;
              echo "$profcount.	";
              echo "";
              echo get_person_link($one);
              echo "	";
              $scores = mpact_scores($one);
              echo "".$scores['A']."	";
              echo "".$scores['C']."	";
              echo "".$scores['AC']."	";
              echo "".$scores['G']."	";
              echo "".$scores['T']."	";
              echo "".$scores['TA']."	";
              echo "".$scores['TD']."	";
              echo "".$scores['W']."	";
              echo "
\n";
            }
            echo "
\n";
            echo "
";
          }
          else
          {
            echo "
- None Listed
\n";
          }
          echo "
";

          # Dissertations Conferred
          echo "
Dissertations Conferred
";

          # Show Histograph
          echo "
\n";
          echo "Dissertations by Year:
\n";
          $query = "SELECT completedyear, count(*) as disscount
                      FROM dissertations
                      WHERE
                        school_id='$school_id' AND
                        discipline_id=$discipline_id
                      GROUP BY
                        completedyear";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            $counts[$line['completedyear']] = $line['disscount'];
          }
          echo "
\n";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            $height=$two*10;
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            echo "";
            if ($one%10==0)
            {
              echo $one;
            }
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          echo "
\n";

          $query = "SELECT d.person_id, d.completedyear, d.status
                FROM
                  dissertations d,
                  schools s,
                  people p,
                  names n
                WHERE
                  s.id = '$school_id' AND
                  d.discipline_id = '$discipline_id' AND
                  d.school_id = s.id AND
                  d.person_id = p.id AND
                  p.preferred_name_id = n.id
                ORDER BY
                  d.completedyear ASC, n.lastname ASC, n.firstname ASC
              ";

          $result = mysql_query($query) or die(mysql_error());

          while ( $line = mysql_fetch_array($result)) {
            extract($line);
            $year_conferred[$person_id] = $completedyear;
            $degree_status[$person_id] = $status;
          }

          $schoolcount = 0;
          echo "
";
          foreach ($year_conferred as $person => $year)
          {
            $schoolcount++;
            echo "
$schoolcount. ";
            echo get_person_link($person);
            echo " ($year)";
            if ($degree_status[$person] < 4)
            {
              echo " ---------------------------------- ".$statuscodes[$degree_status[$person]];
            }
          }
          echo "
";

        }

        break;

      ###############################################
      default:
        // oops - not supposed to be here
        action_box("invalid action",1);
    }
  }
  else
  {

    if (isset($_GET['show']))
    {
      if ($_GET['show'] == "all")
      {
        $alphabet_limiter = ""; // set it to show everything
      }
      else
      {
        $alphabet_limiter = $_GET['show'];
      }

      show_alphabet();

      if (is_admin())
      {
        echo "
Add a New Person to the Database
\n";
      }

      if (is_admin()){
        echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
        echo "<input type=\"hidden\" name=\"op\" value=\"merge_confirm\">";
        echo "<input type=\"hidden\" name=\"show\" value=\"$alphabet_limiter\">";
        echo "<input type=\"submit\" name=\"submit\" value=\"Merge These People\">";
      }

      // GET ALL DISSERTATIONS IN A HASH
      $disciplines = find_disciplines();
      $query = "SELECT id, person_id, discipline_id FROM dissertations";
      $result = mysql_query($query) or die(mysql_error());
      while ( $line = mysql_fetch_array($result)) {
        $graduates[$line['person_id']] = $line['discipline_id'];
      }

      // LOOP THROUGH ALL PEOPLE FOR THIS LETTER
      echo "
\n";
      echo "
\n";
      if (is_admin()){echo "Merge	\n";}
      echo "Count	\n";
      echo "Last Name	\n";
      echo "Full Name	\n";
      echo "Dissertation Discipline	\n";
      echo "
\n";

      $query = "SELECT n.id, n.firstname,
            n.middlename, n.lastname, n.suffix,
            p.id as person_id
            FROM names n, people p
            WHERE
              n.id = p.preferred_name_id AND
              n.lastname LIKE '".$alphabet_limiter."%'
            ORDER BY n.lastname ASC, n.firstname ASC
            ";

      $result = mysql_query($query) or die(mysql_error());

      $rowcount = 0;
      while ( $line = mysql_fetch_array($result)) {
        extract($line);

        $rowcount++;

        echo "
";
           if (is_admin()){
          echo "<input type=\"checkbox\" name=\"mergers[]\" value=\"$person_id\">	";
           }
        echo "$rowcount.	";
        echo "$lastname	";
        $discipline = isset($graduates[$person_id]) ? $disciplines[$graduates[$person_id]] : "";
        echo "$firstname $middlename $lastname $suffix	";
        echo "$discipline	";
        echo "
";

        if (is_admin()){
          if ($rowcount % 25 == 0){
            echo "
	<input type=\"submit\" name=\"submit\" value=\"Merge These People\">
";
          }
        }

      }

      echo "
\n";

      if (is_admin()){
        echo "<input type=\"submit\" name=\"submit\" value=\"Merge These People\">";
        echo "</form>";
       }

      echo "

\n";

      show_alphabet();

    }
    else
    {
      // DISPLAY THE FRONT PAGE

      action_box("Front Page...",0.1,"./");

    }

  }

}

###############################################
// SOMETHING WAS SUBMITTED - through a form
else
{

  if ($_POST['op'] != "login"){
    // Display header
    xhtml_web_header();
  }

  switch ($_POST['op'])
  {
    ###############################################
    case "login";

      $host_info = get_environment_info();
      if ($host_info['hostname'] == "sils"){
        # no logins here - go to dev server
        action_box("No Logins Here...",2,$_SERVER['SCRIPT_NAME']);
      }
      else{
        # check credentials / start session
        $query = "SELECT id, username, fullname FROM users
                    WHERE username = '".addslashes($_POST['username'])."'
                    AND password = '".addslashes($_POST['password'])."'";
        $result = mysql_query($query) or die(mysql_error());
        $line = mysql_fetch_array($result);
        if (isset($line['id'])){
          # save cookie info for one week
          setcookie('MPACT_userid',$line['id'],time()+60*60*24*7);
          # redirect
          header("Location: ".$_SERVER['SCRIPT_NAME']);
        }
        else{
          // Display header
          xhtml_web_header();
          # incorrect credentials
          action_box("Please try again...",2,$_SERVER['SCRIPT_NAME']."?op=login");
        }
      }

      break;

    ###############################################
    case "glossary_edit";
      if (is_admin())
      {

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $query = "UPDATE glossary
              SET
                definition = '".$_POST['definition']."'
              WHERE
                id = '".$_POST['id']."'
            ";
        $result = mysql_query($query) or die(mysql_error());

        # log it
        mpact_logger("updated glossary [".$_POST['term']." (".$_POST['id'].")] to (".$_POST['definition'].")");

        action_box("Definition Saved",2,$_SERVER['SCRIPT_NAME']."?op=glossary");
      }
      else
      {
        not_admin();
      }
      break;

    ###############################################
    case "merge_confirm":

      if (is_admin()){

        echo "<form id=\"merge_em\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
        echo "<input type=\"hidden\" name=\"op\" value=\"merge_doit\">";
        echo "<input type=\"hidden\" name=\"show\" value=\"".$_POST['show']."\">";

        foreach ($_POST['mergers'] as $one)
        {
          echo "

";
          echo "
[$one]
";
          echo draw_tree( $one );
          echo "<input type=\"hidden\" name=\"mergers[]\" value=\"$one\">";
          echo "

";
        }

        echo "<input type=\"submit\" name=\"submit\" value=\"YES, THESE ARE THE SAME PERSON - MERGE THEM NOW\">";
        echo "</form>";

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "search":

      $results = people_search($_POST['q']);

      if (count($results) > 0)
      {
        echo "
People Search Results for [".$_POST['q']."]:
";
      }

      echo "
\n";
      $count = 0;
      foreach ($results as $person_id)
      {
        $count++;
        $schoolinfo = find_persons_school($person_id);
        echo "$count. ".get_person_link($person_id);
        if ($schoolinfo['completedyear'])
        {
          echo " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
        }
        echo "
\n";
      }
      if ($count < 1)
      {
        echo "
\n";
        echo "There were no results for [".$_POST['q']."].";
        if (strlen($_POST['q']) < 2)
        {
          echo "

\n";
          echo "Please use at least two characters to search.";
        }
        else
        {
          if (is_admin()){
            echo "

\n";
            echo "
Add a New Person to the Database
\n";
          }
        }
        echo "
\n";
      }

      echo "
\n";

      break;

    ###############################################
    case "search_title_abstract":

      $results = title_abstract_search($_POST['qta']);

      if (count($results) > 0)
      {
        echo "
Title/Abstract Search Results for [".$_POST['qta']."]:
";
      }

      echo "
\n";
      $count = 0;
      foreach ($results as $person_id)
      {
        $count++;
        $schoolinfo = find_persons_school($person_id);
        echo "$count. ".get_person_link($person_id);
        if ($schoolinfo['completedyear'])
        {
          echo " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
        }
        echo "
\n";
      }
      if ($count < 1)
      {
        echo "
\n";
        echo "There were no results for [".$_POST['qta']."].";
        if (strlen($_POST['qta']) < 2)
        {
          echo "

\n";
          echo "Please use at least two characters to search.";
        }
        else
        {
          if (is_admin()){
            echo "

\n";
          }
        }
        echo "
\n";
      }

      echo "
\n";

      break;

      ###############################################
      case "search_notes":

        if (is_admin()){

          $results = notes_search($_POST['qn']);

          if (count($results) > 0)
          {
            echo "
Admin Notes Search Results for [".$_POST['qn']."]:
";
          }

          echo "
\n";
          $count = 0;
          foreach ($results as $person_id)
          {
            $count++;
            $schoolinfo = find_persons_school($person_id);
            echo "$count. ".get_person_link($person_id);
            if ($schoolinfo['completedyear'])
            {
              echo " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
            }
            echo "
\n";
          }
          if ($count < 1)
          {
            echo "
\n";
            echo "There were no results for [".$_POST['qm']."].";
            if (strlen($_POST['qn']) < 2)
            {
              echo "

\n";
              echo "Please use at least two characters to search.";
            }
            else
            {
              if (is_admin()){
                echo "

\n";
              }
            }
            echo "
\n";
          }

          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

    ###############################################
    case "merge_doit":

      if (is_admin()){

        # delete the family tree's dotgraphs of each person
        foreach ($_POST['mergers'] as $one)
        {
          delete_associated_dotgraphs($one);
        }

        # pop off one of the people_ids
        $into = array_pop($_POST['mergers']);

        # merge each remaining person into the one above
        foreach ($_POST['mergers'] as $one)
        {
          merge_two_people($one,$into);
        }

        # recalculate MPACT scores for merged person id
        calculate_scores($into);

        action_box("Merge was Successful",2,$_SERVER['SCRIPT_NAME']."?show=".$_POST['show']);

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_discipline":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['title'] == "")
        {
          action_box("Need to have at least a Discipline Title.",3,$_SERVER['SCRIPT_NAME']."?op=create_discipline");
        }
        elseif (is_duplicate_discipline($_POST['title']))
        {
          action_box("Discipline (".$_POST['title'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");
        }
        else
        {

          # Create Discipline
          $query = "INSERT disciplines
                SET
                  title   = '".$_POST['title']."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          # Get the just created discipline_id
          $query = "SELECT id as new_discipline_id, title FROM disciplines
                WHERE
                  title   = '".$_POST['title']."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }
          # log it
          mpact_logger("created discipline[".$new_discipline_id."] (".$title.")");

          action_box("Discipline Created",2,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_discipline":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['title'] == "")
        {
          action_box("Need to have at least a Discipline Title.",3,$_SERVER['SCRIPT_NAME']."?op=edit_discipline&id=".$_POST['discipline_id']."");
        }
        elseif (is_duplicate_discipline($_POST['title']))
        {
          action_box("Discipline (".$_POST['title'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");
        }
        else
        {

          # Edit Discipline
          $query = "UPDATE disciplines
                SET
                  title   = '".$_POST['title']."'
                WHERE
                  id = '".$_POST['discipline_id']."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          # log it
          mpact_logger("edited discipline[".$_POST['discipline_id']."] (".$_POST['title'].")");

          action_box("Discipline Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_school":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $_POST = array_map('trim',$_POST);

        if ($_POST['fullname'] == "" || $_POST['country'] == "")
        {
          action_box("Need to have at least a School name and Country.",3,$_SERVER['SCRIPT_NAME']."?op=create_school");
        }
        elseif (is_duplicate_school($_POST['fullname']))
        {
          action_box("School (".$_POST['fullname'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_schools");
        }
        else
        {

          # Create School
          $query = "INSERT schools
                SET
                  fullname   = '".$_POST['fullname']."',
                  country   = '".$_POST['country']."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          # Get the just created school_id
          $query = "SELECT id as new_school_id, fullname FROM schools
                WHERE
                  fullname   = '".$_POST['fullname']."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }
          # log it
          mpact_logger("created school[".$new_school_id."] (".$fullname.")");

          action_box("School Created",2,$_SERVER['SCRIPT_NAME']."?op=show_schools");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_school":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['fullname'] == "" || $_POST['country'] == "")
        {
          action_box("Need to have at least a School name and Country.",3,$_SERVER['SCRIPT_NAME']."?op=edit_school&id=".$_POST['school_id']."");
        }
        elseif (is_duplicate_school($_POST['fullname']))
        {
          action_box("School (".$_POST['fullname'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_schools");
        }
        else
        {

          # Edit School
          $query = "UPDATE schools
                SET
                  fullname   = '".$_POST['fullname']."',
                  country    = '".$_POST['country']."'
                WHERE
                  id = '".$_POST['school_id']."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          # log it
          mpact_logger("edited school[".$_POST['school_id']."] (".$_POST['fullname'].")");

          action_box("School Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_schools");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_person":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['lastname'] == "")
        {
          action_box("Need to have at least a Last Name.",3,$_SERVER['SCRIPT_NAME']."?op=create_person");
        }
        else
        {
          # Create Name
          $query = "INSERT names
                SET
                  firstname   = '".$_POST['firstname']."',
                  middlename  = '".$_POST['middlename']."',
                  lastname    = '".$_POST['lastname']."',
                  suffix      = '".$_POST['suffix']."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          # Get the just created name_id
          $query = "SELECT id as new_name_id FROM names
                WHERE
                  firstname   = '".$_POST['firstname']."' AND
                  middlename  = '".$_POST['middlename']."' AND
                  lastname    = '".$_POST['lastname']."' AND
                  suffix      = '".$_POST['suffix']."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }

          # Create Person with new_name_id
          $query = "INSERT people
                SET
                  preferred_name_id = '".$new_name_id."',
                  degree = '".$_POST['degree']."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          # Get the just created person_id
          $query = "SELECT id as new_person_id FROM people
                WHERE
                  preferred_name_id = '".$new_name_id."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysql_query($query) or die(mysql_error());
          while ( $line = mysql_fetch_array($result)) {
            extract($line);
          }

          # Sync them together with new_person_id
          $query = "UPDATE names
                SET
                  person_id = '".$new_person_id."'
                WHERE
                  id = '".$new_name_id."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          $after = find_person($new_person_id);

          action_box("Person Created",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$new_person_id);

          # log it
          mpact_logger("created person[".$new_person_id."] (".$after['fullname'].")");

       }
     }
     else
     {
        not_admin();
     }

     break;

   ###############################################
   case "remove_mentor":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if (remove_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']))
        {
          action_box("Mentor Removed",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['student_id']);
        }
        else
        {
          action_box("Nope.");
        }

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "add_mentor":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);

        action_box("Mentor Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['student_id']);

      }
      else
      {
        not_admin();
      }

      break;

     ###############################################
     case "add_student":

        if (is_admin()){

          if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

          add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);

          action_box("Student Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['mentor_id']);

        }
        else
        {
           not_admin();
        }

        break;

    ###############################################
    case "add_name":

     if (is_admin()){

       if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $person = find_person($_POST['id']);

        $query = "INSERT names
              SET
                firstname   = '".$_POST['firstname']."',
                middlename  = '".$_POST['middlename']."',
                lastname    = '".$_POST['lastname']."',
                suffix      = '".$_POST['suffix']."',
                person_id   = '".$_POST['id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        # get the just created name_id
        $query = "SELECT id as new_name_id FROM names
              WHERE
                firstname   = '".$_POST['firstname']."' AND
                middlename  = '".$_POST['middlename']."' AND
                lastname    = '".$_POST['lastname']."' AND
                suffix      = '".$_POST['suffix']."'
              ORDER BY id DESC
              LIMIT 1
            ";
        $result = mysql_query($query) or die(mysql_error());
        while ( $line = mysql_fetch_array($result)) {
          extract($line);
        }

        # find that full name from the DB
        $added = find_name($new_name_id);

        action_box("Name Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);
        # log it
        mpact_logger("added name (".$added['fullname'].") for person[".$_POST['id']."] (".$person['fullname'].")");
     }
     else
     {
        not_admin();
     }

     break;

    ###############################################
    case "edit_name":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $before = find_name($_POST['name_id']);

        $query = "UPDATE names
              SET
                firstname   = '".$_POST['firstname']."',
                middlename  = '".$_POST['middlename']."',
                lastname    = '".$_POST['lastname']."',
                suffix      = '".$_POST['suffix']."'
              WHERE
                id = '".$_POST['name_id']."' AND
                person_id = '".$_POST['id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        $after = find_name($_POST['name_id']);

        # delete dotgraph for this person
        delete_associated_dotgraphs($_POST['id']);

        action_box("Name Saved",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);
        # log it
        mpact_logger("edited name[".$_POST['name_id']."] for person[".$_POST['id']."] from (".$before['fullname'].") to (".$after['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "add_url":

     if (is_admin()){

       if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $person = find_person(intval($_POST['person_id']));

        $query = "INSERT urls
              SET
                url         = '".$_POST['url']."',
                description = '".$_POST['description']."',
                updated_at  = now(),
                person_id   = '".$_POST['person_id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Reference URL Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['person_id']."#urls");
        # log it
        mpact_logger("added URL[".substr($_POST['url'], 0, 30)."] for person[".$_POST['person_id']."] (".$person['fullname'].")");
     }
     else
     {
        not_admin();
     }

     break;

    ###############################################
    case "edit_url":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $url = find_url(intval($_POST['id']));
        $person = find_person($url['person_id']);

        $query = "UPDATE urls
              SET
                url         = '".$_POST['url']."',
                description = '".$_POST['description']."',
                updated_at  = now()
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Reference URL Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$url['person_id']."#urls");
        # log it
        mpact_logger("edited URL[".substr($_POST['url'], 0, 30)."] for person[".$url['person_id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "delete_url":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $url = find_url(intval($_POST['id']));
        $person = find_person($url['person_id']);

        $query = "DELETE FROM urls
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Reference URL Deleted",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$url['person_id']."#urls");
        # log it
        mpact_logger("deleted URL[".substr($url['url'], 0, 30)."] for person[".$url['person_id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_degree":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $person = find_person(intval($_POST['id']));

        $query = "UPDATE people
              SET
                degree         = '".$_POST['degree']."'
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Degree Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$person['id']);
        # log it
        mpact_logger("edited degree[".$_POST['degree']."] for person[".$person['id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_dissertation":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $schools = find_schools();

        $person = find_person($_POST['person_id']);

        $query = "INSERT INTO dissertations
              SET
                person_id           = '".$_POST['person_id']."',
                discipline_id       = '".$_POST['discipline_id']."',
                school_id           = '".$_POST['school_id']."',
                completedyear       = '".$_POST['completedyear']."',
                status              = '".$_POST['status']."',
                title               = '".$_POST['title']."',
                abstract            = '".$_POST['abstract']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        $query = "UPDATE people
                  SET degree = '".$_POST['degree']."'
                  WHERE
                    id = '".$_POST['person_id']."'";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Dissertation Created",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['person_id']);
        # log it
        $dissertation = find_dissertation_by_person($_POST['person_id']);
        mpact_logger("create dissertation[".$dissertation['id']."] (".$person['fullname'].") with school[".$dissertation['school_id']."] (".$schools[$dissertation['school_id']].") in year(".$dissertation['completedyear'].") with status (".$statuscodes[$_POST['status']].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_dissertation":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $disciplines = find_disciplines();
        $schools = find_schools();

        $dissertation = find_dissertation($_POST['id']);
        $person = find_person($dissertation['person_id']);

        $query = "UPDATE dissertations
              SET
                school_id           = '".$_POST['school_id']."',
                discipline_id       = '".$_POST['discipline_id']."',
                completedyear       = '".$_POST['completedyear']."',
                status              = '".$_POST['status']."',
                notes               = '".$_POST['notes']."',
                title               = '".$_POST['title']."',
                abstract            = '".$_POST['abstract']."'
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysql_query($query) or die(mysql_error());

        $query = "UPDATE people
                  SET degree = '".$_POST['degree']."'
                  WHERE
                    id = '".$_POST['person_id']."'";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Dissertation Saved",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['person_id']);
        # log it
        mpact_logger("edit dissertation[".$_POST['id']."] (".$person['fullname'].") from school[".$dissertation['school_id']."] (".$schools[$dissertation['school_id']].") in year(".$dissertation['completedyear'].") to school[".$_POST['school_id']."] (".$schools[$_POST['school_id']].") in year(".$_POST['completedyear'].")");
        # look for changes
          # degree
          if ($person['degree'] != $_POST['degree'])
          {
            mpact_logger($dissertation['id']." updated degree [".$_POST['degree']."]","dissertation");
          }
          # discipline
          if ($dissertation['discipline_id'] != $_POST['discipline_id'])
          {
            mpact_logger($dissertation['id']." updated discipline [".$_POST['discipline_id']." (".$disciplines[$_POST['discipline_id']].")]","dissertation");
          }
          # school
          if ($dissertation['school_id'] != $_POST['school_id'])
          {
            mpact_logger($dissertation['id']." updated school [".$_POST['school_id']." (".$schools[$_POST['school_id']].")]","dissertation");
          }
          # year
          if ($dissertation['completedyear'] != $_POST['completedyear'])
          {
            mpact_logger($dissertation['id']." updated completedyear [".$_POST['completedyear']."]","dissertation");
          }
          # title
          if ($dissertation['title'] != $_POST['title'])
          {
            mpact_logger($dissertation['id']." updated title [".$_POST['title']."]","dissertation");
          }
          # abstract
          if ($dissertation['abstract'] != $_POST['abstract'])
          {
            mpact_logger($dissertation['id']." updated abstract [".$_POST['abstract']."]","dissertation");
          }
          # status
          if ($dissertation['status'] != $_POST['status'])
          {
            mpact_logger($dissertation['id']." updated status [".$statuscodes[$_POST['status']]."]","dissertation");
          }
          # status
          if ($dissertation['notes'] != $_POST['notes'])
          {
            mpact_logger($dissertation['id']." updated notes [".$_POST['notes']."]","dissertation");
          }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "delete_person":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if (delete_person($_POST['id']))
        {
          action_box("Person Deleted",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);
        }

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "delete_name":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $name = find_name($_POST['name_id']);
        $person = find_person($_POST['id']);

        $query = "DELETE FROM names
            WHERE
              id = '".$_POST['name_id']."' AND
              person_id = '".$_POST['id']."'
          ";

        $result = mysql_query($query) or die(mysql_error());

        action_box("Name Deleted",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);

        # log it
        mpact_logger("deleted name[".$_POST['name_id']."] (".$name['fullname'].") from person[".$person['id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_school":

      break;

    ###############################################
    default:
      // oops - not supposed to be here
      action_box("oops, back to the front page...",2);

  }

}

xhtml_web_footer();

?>

<?php

###########    INCLUDE FUNCTIONS     ####################

# -------------------------------------------------------------------------------
function is_admin(){
  if (isset($_SESSION['MPACT']['username']))
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

# -------------------------------------------------------------------------------
function not_admin(){
   action_box("Action Not Permitted.");
   mpact_logger("not admin");
}

# -------------------------------------------------------------------------------
# from http://www.richardlord.net/blog/php-password-security
// get a new salt - 8 hexadecimal characters long
// current PHP installations should not exceed 8 characters
// on dechex( mt_rand() )
// but we future proof it anyway with substr()
function generate_PasswordSalt(){
  return substr( str_pad( dechex( mt_rand() ), 8, '0', STR_PAD_LEFT ), -8 );
}

# -------------------------------------------------------------------------------
# from http://www.richardlord.net/blog/php-password-security
// calculate the hash from a salt and a password
function generate_PasswordHash( $salt, $password ){
  return $salt . ( sha1( $salt . $password ) );
}

# -------------------------------------------------------------------------------
# from http://www.richardlord.net/blog/php-password-security
// compare a password to a hash
function comparePassword( $password, $hashed ){
  $salt = substr( $hashed, 0, 8 );
  return $hashed == generate_PasswordHash( $salt, $password );
}

# -------------------------------------------------------------------------------
function mpact_logger($message,$type="general"){
  $ip = ($_SERVER['REMOTE_ADDR'] == "127.0.0.1") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
  if (!get_magic_quotes_gpc()) {$message = addslashes($message);}
  $query = "INSERT logs
              SET
              logged_at = now(),
              ip        = '".$ip."',
              user      = '".$_SESSION['MPACT']['username']."',
              type      = '".$type."',
              message   = '".$message."',
              action    = '".$_SERVER['REQUEST_URI']."',
              agent     = '".$_SERVER['HTTP_USER_AGENT']."'
            ";
  $result = mysql_query($query) or die(mysql_error());
}

# -------------------------------------------------------------------------------
# http://us2.php.net/manual/en/function.array-diff.php#29808
function array_key_diff($ar1, $ar2) {  // , $ar3, $ar4, ...
   // returns copy of array $ar1 with those entries removed
   // whose keys appear as keys in any of the other function args
   $aSubtrahends = array_slice(func_get_args(),1);
   foreach ($ar1 as $key => $val)
       foreach ($aSubtrahends as $aSubtrahend)
           if (array_key_exists($key, $aSubtrahend))
               unset ($ar1[$key]);
   return $ar1;
}

# -------------------------------------------------------------------------------
function action_box($message,$bounce = "0",$location = "index.php"){

  echo "

  $message

  ";

  if ($bounce != "0"){
    echo "
    <meta http-equiv=\"Refresh\" content=\"$bounce;url=$location\">

    Forwarding in $bounce seconds (or click here to do the same)

    ";
  }

}

# -------------------------------------------------------------------------------
function xhtml_orig_web_header(){

  # make search box happy
  if (!isset($_POST['q'])){$_POST['q'] = "";}
  if (!isset($_POST['qta'])){$_POST['qta'] = "";}
  if (!isset($_POST['qn'])){$_POST['qn'] = "";}

  # print out header info
  echo "

  <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">

  <title>MPACT</title>

  <link rel=\"stylesheet\" type=\"text/css\" href=\"mpact.css\">

          <form id=\"main_mpact\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
            MPACT -
            Database -
            <input type=\"hidden\" name=\"op\" value=\"search\">
            People Search: <input type=\"text\" name=\"q\" size=\"10\" value=\"".$_POST['q']."\">
          </form> -
          <form id=\"main_mpact_title_abstract\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
          <input type=\"hidden\" name=\"op\" value=\"search_title_abstract\">
          Title/Abstract Search: <input type=\"text\" name=\"qta\" size=\"10\" value=\"".$_POST['qta']."\">
          </form>
";
  if (is_admin()){
    echo " - <form id=\"main_mpact_notes\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
    <input type=\"hidden\" name=\"op\" value=\"search_notes\">
    Admin Notes Search: <input type=\"text\" name=\"qn\" size=\"10\" value=\"".$_POST['qn']."\">
    </form>";
  }
  echo "

";
  if (is_admin()){
    echo $_SESSION['MPACT']['fullname']." (".$_SESSION['MPACT']['username'].") - Logout";
  }
  else{
    $host_info = get_environment_info();
    if ($host_info['hostname'] != "sils"){
      echo "Login";
    }
  }
echo "

  ";

}

# -------------------------------------------------------------------------------
function xhtml_web_header(){

  # make search box happy
  if (!isset($_POST['q'])){$_POST['q'] = "";}
  if (!isset($_POST['qta'])){$_POST['qta'] = "";}
  if (!isset($_POST['qn'])){$_POST['qn'] = "";}

  # print out header info
  echo "

  <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">

  <title>MPACT</title>
  <link rel=\"stylesheet\" type=\"text/css\" href=\"mpact.css\">

";

echo "

";
if (is_admin()){
  echo $_SESSION['MPACT']['fullname']." (".$_SESSION['MPACT']['username'].") - Logout";
}
else{
  echo "Login";
}
echo "

";
echo "

";

echo "

      Publications  •
      Project Statistics

      Glossary  •
      Schools  •
      Disciplines

      <form id=\"main_mpact\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
        <input type=\"hidden\" name=\"op\" value=\"search\">
        People Search: <input type=\"text\" name=\"q\" size=\"13\" value=\"".$_POST['q']."\">
      </form>

      <form id=\"main_mpact_title_abstract\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
        <input type=\"hidden\" name=\"op\" value=\"search_title_abstract\">
        Title/Abstract Search: <input type=\"text\" name=\"qta\" size=\"13\" value=\"".$_POST['qta']."\">
      </form>";
if (is_admin()){
  echo "

Administrator Pages";
  echo "<form id=\"main_mpact_notes\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
  <input type=\"hidden\" name=\"op\" value=\"search_notes\">
  Admin Notes Search: <input type=\"text\" name=\"qn\" size=\"13\" value=\"".$_POST['qn']."\">
  </form>";
}
echo "

  ";

}

# -------------------------------------------------------------------------------
function xhtml_web_footer(){
  echo "

";
}

# -------------------------------------------------------------------------------
function is_email_valid ($address)
{

	# http://www.zend.com/codex.php?id=285&single=1

    return (preg_match(
        '/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+'.   // the user name
        '@'.                                     // the ubiquitous at-sign
        '([-0-9A-Z]+\.)+' .                      // host, sub-, and domain names
        '([0-9A-Z]){2,4}$/i',                    // top-level domain (TLD)
        trim($address)));
}

# -------------------------------------------------------------------------------
function find_glossaryterms()
{
  $query = "SELECT id, term, definition FROM glossary";
  $result = mysql_query($query) or die(mysql_error());
  $glossaryterms = array();
  while ( $line = mysql_fetch_array($result)) {
    $glossaryterms['ids'][$line['term']] = $line['id'];
    $glossaryterms['defs'][$line['id']] = $line['definition'];
  }
  return $glossaryterms;
}

# -------------------------------------------------------------------------------
function show_glossary()
{
  $query = "SELECT id, term, definition FROM glossary ORDER BY term ASC";
  $result = mysql_query($query) or die(mysql_error());

  $results = array();
  while ( $line = mysql_fetch_array($result)) {
    array_push($results,$line);
  }

  echo "
Glossary
\n";

  echo "
\n";

  foreach ($results as $one)
  {
    echo "".$one['term'].": ";
    echo $one['definition'];
    if (is_admin())
    {
      echo " EDIT ";
    }
    echo "

";
  }

  echo "
\n";

}

# -------------------------------------------------------------------------------
function show_glossaryterm($id)
{
  $query = "SELECT id, term, definition FROM glossary WHERE id = $id";
  $result = mysql_query($query) or die(mysql_error());

  $results = array();
  while ( $line = mysql_fetch_array($result)) {
    $glossaryterm = $line;
  }

  echo "
Full Glossary Listing
";

  echo "
Glossary
\n";

  echo "
\n";

  echo "".$glossaryterm['term'].": ";
  echo $glossaryterm['definition'];
  if (is_admin())
  {
    echo " EDIT ";
  }
  echo "

";

  echo "
\n";

}

# -------------------------------------------------------------------------------
function show_alphabet()
{

  $alphabet_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $alphabet = preg_split('//', $alphabet_letters, -1, PREG_SPLIT_NO_EMPTY);

  echo "
\n";
  echo "
Dissertation Authors and Mentors by Last Name
";
  echo "
";
  foreach ($alphabet as $letter)
  {
    if ($letter != "A"){echo " - ";}
    echo "$letter";
  }
  echo "
";
   echo "
\n";
}

# -------------------------------------------------------------------------------
function search_box($q="")
{
  echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
  echo "<input type=\"hidden\" name=\"op\" value=\"search\">\n";
  echo "
People Search: ";
  if ($q)
  {
    echo "<input type=\"text\" name=\"q\" value=\"$q\">\n";
  }
  else
  {
    echo "<input type=\"text\" name=\"q\">\n";
  }
  echo "
\n";
  echo "</form>\n";
}

# -------------------------------------------------------------------------------
function people_search($q)
{
  $q = trim($q);
  if (!get_magic_quotes_gpc()) {$q = addslashes($q);}
  $results = array();
  if (strlen($q) < 2){
    return $results;
  }

  $pieces = split(" ",$q);
#  print_r($pieces);
  if (count($pieces) == 2)
  {
#    echo " ---------  two pieces";
    $query = "SELECT n.id as name_id, p.id as person_id
                FROM
                  names n, people p
                WHERE
                  (

                    (n.firstname  LIKE '%".$pieces[0]."%' OR
                    n.middlename LIKE '%".$pieces[0]."%' OR
                    n.lastname   LIKE '%".$pieces[0]."%' OR
                    n.suffix     LIKE '%".$pieces[0]."%')

                  AND

                    (n.firstname  LIKE '%".$pieces[1]."%' OR
                    n.middlename LIKE '%".$pieces[1]."%' OR
                    n.lastname   LIKE '%".$pieces[1]."%' OR
                    n.suffix     LIKE '%".$pieces[1]."%')

                  )
                  AND
                  n.person_id = p.id
                GROUP BY
                  p.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  elseif (count($pieces) == 3)
  {
#    echo " ---------  three pieces";
    $query = "SELECT n.id as name_id, p.id as person_id
                FROM
                  names n, people p
                WHERE
                  (

                    (n.firstname  LIKE '%".$pieces[0]."%' OR
                    n.middlename LIKE '%".$pieces[0]."%' OR
                    n.lastname   LIKE '%".$pieces[0]."%' OR
                    n.suffix     LIKE '%".$pieces[0]."%')

                  AND

                    (n.firstname  LIKE '%".$pieces[1]."%' OR
                    n.middlename LIKE '%".$pieces[1]."%' OR
                    n.lastname   LIKE '%".$pieces[1]."%' OR
                    n.suffix     LIKE '%".$pieces[1]."%')

                  AND

                    (n.firstname  LIKE '%".$pieces[2]."%' OR
                    n.middlename LIKE '%".$pieces[2]."%' OR
                    n.lastname   LIKE '%".$pieces[2]."%' OR
                    n.suffix     LIKE '%".$pieces[2]."%')

                  )
                  AND
                  n.person_id = p.id
                GROUP BY
                  p.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  else
  {
#    echo " ---  regular search - single piece";
    $query = "SELECT n.id as name_id, p.id as person_id
                FROM
                  names n, people p
                WHERE
                  (

                    (n.firstname  LIKE '%".$q."%' OR
                    n.middlename LIKE '%".$q."%' OR
                    n.lastname   LIKE '%".$q."%' OR
                    n.suffix     LIKE '%".$q."%')

                  )
                  AND
                  n.person_id = p.id
                GROUP BY
                  p.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    array_push($results,$line['person_id']);
  }
  return $results;
}

# -------------------------------------------------------------------------------
function title_abstract_search($q)
{
  $q = trim($q);
  if (!get_magic_quotes_gpc()) {$q = addslashes($q);}
  $results = array();
  if (strlen($q) < 2){
    return $results;
  }

  $pieces = split(" ",$q);
#  print_r($pieces);
  if (count($pieces) == 2)
  {
#    echo " ---------  two pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.title   LIKE '%".$pieces[0]."%' OR
                    d.abstract LIKE '%".$pieces[0]."%')

                  AND

                    (d.title   LIKE '%".$pieces[1]."%' OR
                    d.abstract LIKE '%".$pieces[1]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  elseif (count($pieces) == 3)
  {
#    echo " ---------  three pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.title   LIKE '%".$pieces[0]."%' OR
                    d.abstract LIKE '%".$pieces[0]."%')

                  AND

                    (d.title   LIKE '%".$pieces[1]."%' OR
                    d.abstract LIKE '%".$pieces[1]."%')

                  AND

                    (d.title   LIKE '%".$pieces[2]."%' OR
                    d.abstract LIKE '%".$pieces[2]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  else
  {
#    echo " ---  regular search - single piece";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.title   LIKE '%".$q."%' OR
                    d.abstract LIKE '%".$q."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    array_push($results,$line['person_id']);
  }
  return $results;
}

# -------------------------------------------------------------------------------
function notes_search($q)
{
  $q = trim($q);
  if (!get_magic_quotes_gpc()) {$q = addslashes($q);}
  $results = array();
  if (strlen($q) < 2){
    return $results;
  }

  $pieces = split(" ",$q);
#  print_r($pieces);
  if (count($pieces) == 2)
  {
#    echo " ---------  two pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.notes    LIKE '%".$pieces[0]."%')

                  AND

                    (d.notes    LIKE '%".$pieces[1]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  elseif (count($pieces) == 3)
  {
#    echo " ---------  three pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.notes    LIKE '%".$pieces[0]."%')

                  AND

                    (d.notes    LIKE '%".$pieces[1]."%')

                  AND

                    (d.notes    LIKE '%".$pieces[2]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  else
  {
#    echo " ---  regular search - single piece";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.notes    LIKE '%".$q."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    array_push($results,$line['person_id']);
  }
  return $results;
}

# -------------------------------------------------------------------------------
function encode_linebreaks($bigtext)
{
  # from http://us3.php.net/str_replace
  $order   = array("\r\n", "\n", "\r");
  $replace = '
';
  // Processes \r\n's first so they aren't converted twice.
  $with_breaks = str_replace($order, $replace, $bigtext);
  return $with_breaks;
}

# -------------------------------------------------------------------------------
function get_logs($offset="0")
{
#  echo "[$offset]";
  $query = "SELECT * FROM logs ORDER BY id DESC LIMIT 100";
  if ($offset != ""){$query .= " OFFSET $offset";}
  $result = mysql_query($query) or die(mysql_error());

#  echo $query;
  $entries = array();
  $counter = 0;
  while ( $line = mysql_fetch_array($result)) {
    $counter++;
    $entries[$counter] = $line;
  }
  return $entries;
}

# -------------------------------------------------------------------------------
function get_dissertation_history($id)
{
  $query = "SELECT * FROM logs
              WHERE type='dissertation' AND message LIKE '$id %'
              ORDER BY id DESC";
  $result = mysql_query($query) or die(mysql_error());

#  echo $query;
  $entries = array();
  $counter = 0;
  while ( $line = mysql_fetch_array($result)) {
    $counter++;
    $entries[$counter] = $line;
  }
  return $entries;
}

# -------------------------------------------------------------------------------
function find_all_people()
{
  # return array of all people_ids in database (slow....)
    # all people
    $query = "SELECT id as person_id FROM people";
    $result = mysql_query($query) or die(mysql_error());
    while ( $line = mysql_fetch_array($result)) {
      $people[] = $line['person_id'];
    }
    return $people;
}

# -------------------------------------------------------------------------------
function get_person_link($person_id)
{

  $disciplines = find_disciplines();
  $person = find_person($person_id);

  $fullname = trim($person['firstname']." ".$person['middlename']." ".$person['lastname']." ".$person['suffix']);

  $dissertation = find_dissertation_by_person($person_id);
  $discipline = isset($dissertation['discipline_id']) ? $disciplines[$dissertation['discipline_id']] : "";

  $link = "".$fullname."";

  return $link;

}

# -------------------------------------------------------------------------------
function find_orphans()
{

  # finding people with no dissertation and no students

  # all people
  $query = "SELECT
              p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix
            FROM
              people p, names n
            WHERE
              p.preferred_name_id = n.id
            ORDER BY n.lastname,n.firstname,n.middlename
          ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $people[$line['person_id']] = $line;
#    echo " ".$line['person_id']."
\n";
  }

  echo "people: ".count($people)."
\n";

  # with dissertations only
  $query = "SELECT
              p.id as person_id
            FROM
              people p, dissertations d
            WHERE
              d.person_id = p.id
          ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $with_dissertations[$line['person_id']] = $line;
#    echo " ".$line['person_id']."
\n";
  }

  echo "dissertations: ".count($with_dissertations)."
\n";

  # all people - dissertations = teachers only
  $potentialmentors = array_key_diff($people,$with_dissertations);

  echo "potential mentors: ".count($potentialmentors)."
\n";

  # orphans = teachers who don't have students
  # get advisorships
  $query = "SELECT person_id FROM advisorships";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    $advisors[$line['person_id']] = $line;
  }
  echo "advisors: ".count($advisors)."
\n";
  # get committeeships
  $query = "SELECT person_id FROM committeeships";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    $committeemembers[$line['person_id']] = $line;
  }
  echo "committeemembers: ".count($committeemembers)."
\n";
  # subtract advisorships from teachers
  $potentialmentors = array_key_diff($potentialmentors,$advisors);
  # subtract committeeships from remaining teachers
  $orphans = array_key_diff($potentialmentors,$committeemembers);
  echo "orphans: ".count($orphans)."
\n";

  return $orphans;

}

# -------------------------------------------------------------------------------
function is_orphan($person_id)
{
  # confirm person exists
  $query = "SELECT * FROM people WHERE id = '".$person_id."'";
  $result = mysql_query($query) or die(mysql_error());
  $line = mysql_fetch_array($result);
  if (!$line['id']){echo "not a person";return 0;}
  # confirm no dissertation
  $query = "SELECT * FROM dissertations WHERE person_id = '".$person_id."'";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    echo "found a dissertation";
    return 0;
  }
  # confirm not a committeemember
  $query = "SELECT * FROM committeeships WHERE person_id = '".$person_id."'";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    echo "found a committeeship";
    return 0;
  }
  # confirm not an advisor
  $query = "SELECT * FROM advisorships WHERE person_id = '".$person_id."'";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    echo "found an advisorship";
    return 0;
  }
  return 1;
}
# -------------------------------------------------------------------------------
function delete_person($person_id)
{
  if (is_orphan($person_id))
  {
    $before = find_person($person_id);
    # delete all names
    $query = "DELETE FROM names WHERE person_id = '".$person_id."'";
    $result = mysql_query($query) or die(mysql_error());
    # delete the person
    $query = "DELETE FROM people WHERE id = '".$person_id."' LIMIT 1";
    $result = mysql_query($query) or die(mysql_error());
    # log it
    mpact_logger("deleted person[".$person_id."] (".$before['fullname'].")");
    return 1;
  }
  else
  {
    action_box("Not an orphan - Cannot delete this person.");
    return 0;
  }
}
# -------------------------------------------------------------------------------
function remove_duplicate_names($person_id)
{

  $names = array();
  $deleteme = array();

  $before = find_person($person_id);

  // get the preferred_name_id
  $query = "SELECT preferred_name_id
        FROM people
        WHERE id = '".$person_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    extract($line);
  }

  // get the full preferred_name
  $query = "SELECT * FROM names
        WHERE
          id = '".$preferred_name_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $fullname = "".$line['firstname']." ".$line['middlename']." ".$line['lastname']." ".$line['suffix']."";
    $names[$fullname] = $line['id'];
  }

  // get the rest of the names for this person
  $query = "SELECT * FROM names
        WHERE
          person_id = '".$person_id."' AND
          id != '".$preferred_name_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $fullname = "".$line['firstname']." ".$line['middlename']." ".$line['lastname']." ".$line['suffix']."";
    if (isset($names[$fullname]))
    {
      $deleteme[] = $line['id'];
    }
    else
    {
      $names[$fullname] = $line['id'];
    }
  }

  // delete each deleteme id
  foreach ($deleteme as $one)
  {
    $query = "DELETE FROM names
          WHERE
            id = '".$one."'
        ";

    $result = mysql_query($query) or die(mysql_error());
  }

  # log it
  mpact_logger("removed duplicate names for person[".$person_id."] (".$before['fullname'].")");

}

# -------------------------------------------------------------------------------
function add_mentor($type,$student_id,$mentor_id)
{
  $student = find_person($student_id);
  $mentor = find_person($mentor_id);
  $dissertation = find_dissertation_by_person($student_id);

  if ($type == "A")
  {
    # find existing advisors for this student
    $advisors = find_advisors_for_person($student_id);
    # if new/different - then add them to the student's dissertation
    if (in_array($mentor_id,$advisors))
    {
      # skip - already listed as advisor
    }
    else
    {
      $query = "INSERT advisorships
                  SET
                  dissertation_id = '".$dissertation['id']."',
                  person_id       = '".$mentor_id."'
                ";
#      echo $query;
      $result = mysql_query($query) or die(mysql_error());
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("add advisorship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
      # delete existing dotgraphs - they'll need to be regenerated
      # has to happen after we add the advisor link itself
      delete_associated_dotgraphs($student_id);
    }
  }
  elseif ($type == "C")
  {
    # find existing committee members for this student
    $committee = find_committee_for_person($student_id);
    # if new/different - then add them to the student's dissertation
    if (in_array($mentor_id,$committee))
    {
      # skip - already on committee
    }
    else
    {
      $query = "INSERT committeeships
                  SET
                  dissertation_id = '".$dissertation['id']."',
                  person_id       = '".$mentor_id."'
                ";
#      echo $query;
      $result = mysql_query($query) or die(mysql_error());
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("add committeeship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
    }
  }
  else
  {
    # nothing
  }
}

# -------------------------------------------------------------------------------
function remove_mentor($type,$student_id,$mentor_id)
{
  $dissertation = find_dissertation_by_person($student_id);

  $student = find_person($student_id);
  $mentor = find_person($mentor_id);

  if ($type == "A")
  {
    # find dissertation id
    $dissertation = find_dissertation_by_person($student_id);
    # find existing advisors for this student
    $advisors = find_advisors_for_person($student_id);
    # if found in db, remove them
    if (!in_array($mentor_id,$advisors))
    {
      echo "not an advisor for this student";
      return 0;
    }
    else
    {
      # delete existing dotgraphs - they'll need to be regenerated
      # has to happen before we delete the advisor link itself
      delete_associated_dotgraphs($student_id);
      # delete the advisorship
      $query = "DELETE FROM advisorships
            WHERE
              person_id = '".$mentor_id."' AND
              dissertation_id = '".$dissertation['id']."'
            LIMIT 1
          ";
      $result = mysql_query($query) or die(mysql_error());
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("remove advisorship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
      return 1;
    }
  }
  elseif ($type == "C")
  {
    # find dissertation id
    $dissertation = find_dissertation_by_person($student_id);
    # find existing committee members for this student
    $committee = find_committee_for_person($student_id);
    # if found in db, remove them
    if (!in_array($mentor_id,$committee))
    {
      echo "not on committee for this student";
      return 0;
    }
    else
    {
      $query = "DELETE FROM committeeships
            WHERE
              person_id = '".$mentor_id."' AND
              dissertation_id = '".$dissertation['id']."'
            LIMIT 1
          ";
      $result = mysql_query($query) or die(mysql_error());
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("remove advisorship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
      return 1;
    }
  }
  else
  {
    echo "has to be A or C, dude";
    return 0;
  }

}

# -------------------------------------------------------------------------------
function find_all_people_for_selectbox($with_dissertation="0")
{
  if ($with_dissertation == "0")
  {
    $query = "SELECT
                p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix
              FROM
                people p, names n
              WHERE
                p.preferred_name_id = n.id
              ORDER BY n.lastname,n.firstname,n.middlename
            ";
  }
  else
  {
    $query = "SELECT
                p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix
              FROM
                people p, names n, dissertations d
              WHERE
                p.preferred_name_id = n.id AND
                d.person_id = p.id
              ORDER BY n.lastname,n.firstname,n.middlename
            ";
  }
  // echo $query;
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $people[$line['person_id']] = $line;
  }

  return $people;
}

# -------------------------------------------------------------------------------
function merge_two_people($from_id, $into_id)
{

  $from_person = find_person($from_id);
  $into_person = find_person($into_id);

  $query = "UPDATE advisorships
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  $query = "UPDATE dissertations
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  $query = "UPDATE committeeships
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  $query = "UPDATE urls
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  // move each 'from' name to the 'into' person

  $query = "UPDATE names
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  // remove any new duplicates in the names table

  remove_duplicate_names($into_person['id']);

  // remove 'from' person from the database

  $query = "DELETE FROM people
        WHERE
          id = '".$from_person['id']."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  # log it
  mpact_logger("merged two people [".$from_id."] (".$from_person['fullname'].") and [".$into_id."] (".$into_person['fullname'].")");

}

# -------------------------------------------------------------------------------
function find_aliases($person_id)
{

  $query = "SELECT preferred_name_id
        FROM people
        WHERE id = '".$person_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    extract($line);
  }

  $names = array();
  $query = "SELECT
        n.firstname, n.middlename,
        n.lastname, n.suffix, n.id
        FROM
          names n
        WHERE
          n.person_id = '".$person_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $names[$line['id']] = $line;
  }

  unset($names[$preferred_name_id]);

  return $names;
}

# -------------------------------------------------------------------------------
function find_person($person_id)
{
  $query = "SELECT
        n.firstname, n.middlename,
        n.lastname, n.suffix, p.degree,
        p.id, p.preferred_name_id
        FROM
          names n, people p
        WHERE
          p.preferred_name_id = n.id AND
          p.id = ".$person_id."
      ";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $person = $line;
    $person['fullname'] = $person['firstname'];
    if ($person['middlename'] != ""){$person['fullname'] .= " ".$person['middlename'];}
    if ($person['lastname'] != ""){$person['fullname'] .= " ".$person['lastname'];}
    if ($person['suffix'] != ""){$person['fullname'] .= " ".$person['suffix'];}
  }

  return $person;
}

# -------------------------------------------------------------------------------
function find_url($url_id)
{

  $url_id = intval($url_id);
  $query = "SELECT
        u.id, u.url, u.description, u.updated_at, u.person_id
        FROM
          urls u
        WHERE
          u.id = '".$url_id."'
      ";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $url = $line;
  }

  return $url;

}

# -------------------------------------------------------------------------------
function find_urls_by_person($person_id)
{

  $person_id = intval($person_id);
  $query = "SELECT
        u.id, u.url, u.description, u.updated_at, u.person_id
        FROM
          urls u
        WHERE
          u.person_id = '".$person_id."'
      ";
  $result = mysql_query($query) or die(mysql_error());

  $urls = array();
  while ( $line = mysql_fetch_array($result)) {
    $urls[$line['id']] = $line;
  }

  return $urls;

}

# -------------------------------------------------------------------------------
function find_dissertation($dissertation_id)
{

  $dissertation_id = intval($dissertation_id);
  $query = "SELECT
        d.id, d.person_id, d.completedyear, d.status,
        d.title, d.abstract, d.notes, d.school_id, d.discipline_id
        FROM
          dissertations d
        WHERE
          d.id = '".$dissertation_id."'
      ";
  $result = mysql_query($query) or die(mysql_error());

  $dissertation = array();
  while ( $line = mysql_fetch_array($result)) {
    $dissertation = $line;
  }

  return $dissertation;
}

# -------------------------------------------------------------------------------
function find_dissertation_by_person($person_id)
{

  $person_id = intval($person_id);
  $query = "SELECT
        d.id, d.person_id, d.completedyear, d.status,
        d.title, d.abstract, d.notes, d.school_id, d.discipline_id
        FROM
          dissertations d
        WHERE
          d.person_id = '".$person_id."'
      ";
  $result = mysql_query($query) or die(mysql_error());

  $dissertation = array();
  while ( $line = mysql_fetch_array($result)) {
    $dissertation = $line;
  }

  return $dissertation;
}

# -------------------------------------------------------------------------------
function find_name($name_id)
{
  $query = "SELECT
        n.firstname, n.middlename,
        n.lastname, n.suffix
        FROM
          names n
        WHERE
          n.id = ".$name_id."
      ";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $name = $line;
    $name['fullname'] = $name['firstname'];
    if ($name['middlename'] != ""){$name['fullname'] .= " ".$name['middlename'];}
    if ($name['lastname'] != ""){$name['fullname'] .= " ".$name['lastname'];}
    if ($name['suffix'] != ""){$name['fullname'] .= " ".$name['suffix'];}
  }

  return $name;
}

# -------------------------------------------------------------------------------
function find_discipline($discipline_id)
{
  $discipline_id = intval($discipline_id);
  $query = "SELECT
        d.title, d.description
        FROM
          disciplines d
        WHERE
          d.id = ".$discipline_id."
      ";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $discipline = $line;
  }

  return $discipline;
}

# -------------------------------------------------------------------------------
function find_ancestors_for_group($groupofpeople)
{
  $originalgroup = $groupofpeople;
  // find advisors, and if they're new, add them to the list and recurse
  foreach ($originalgroup as $person)
  {
    $advisors = find_advisors_for_person($person);
    foreach ($advisors as $one)
    {
      $groupofpeople[] = $one;
    }
  }
  $groupofpeople = array_unique($groupofpeople);
  if (count(array_diff($groupofpeople,$originalgroup)) > 0)
  {
    return find_ancestors_for_group($groupofpeople);
  }
  else
  {
    return $originalgroup;
  }
}

# -------------------------------------------------------------------------------
function find_descendents_for_group($groupofpeople)
{
  $originalgroup = $groupofpeople;
  // find descendents, and if they're new, add them to the list and recurse
  foreach ($originalgroup as $person)
  {
    $advisees = find_advisorships_under_person($person);
    foreach ($advisees as $one)
    {
      $groupofpeople[] = $one;
    }
  }
  $groupofpeople = array_unique($groupofpeople);
  if (count(array_diff($groupofpeople,$originalgroup)) > 0)
  {
    return find_descendents_for_group($groupofpeople);
  }
  else
  {
    return $originalgroup;
  }
}

# -------------------------------------------------------------------------------
function T_score($person)
{
  # total number of descendants (nodes) in a person's tree
  $group = array($person);
  $total = count(find_descendents_for_group($group)); # including self
  $descendents = $total - 1; # minus self
  return $descendents;
}

# -------------------------------------------------------------------------------
function find_mpact_score($person,$score_type)
{
  $query = "SELECT $score_type as score FROM people WHERE id='$person'";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    extract($line);
  }
  return $score;
}

# -------------------------------------------------------------------------------
function FMI_score($person)
{
    $FMI_score = count(find_advisorships_under_person($person));
#    print "person $person -- fmi $FMI_score
";
    $committeeships = find_committeeships_under_person($person);
    foreach ($committeeships as $one)
    {
      $numA = count(find_advisors_for_person($one));
#      echo " - #A [$numA] ----
";
      $numC = count(find_committee_for_person($one));
#      echo "#C [$numC] ---- \n";
      $FMI_score += 1/($numA + $numC);
#      echo "
";
    }
  //  echo "fractional mentorship, inclusive (FMI =  A + eachC(1/(#A+#C)) )
\n";
    return round($FMI_score,3);
}

# -------------------------------------------------------------------------------
function FME_score($person)
{
    $FME_score = count(find_advisorships_under_person($person));
#    print "person $person -- fme $FME_score
";
    $committeeships = find_committeeships_under_person($person);
    foreach ($committeeships as $one)
    {
      $numC = count(find_committee_for_person($one));
#      echo "#C [$numC] ---- \n";
      $FME_score += 1/($numC);
#      echo "
";
    }
  //  echo "fractional mentorship, inclusive (FMI =  A + eachC(1/(#A+#C)) )
\n";
    return round($FME_score,3);
}

# -------------------------------------------------------------------------------
function TA_score($person)
{
  # total number of descendants who have advised students themselves
  $without_students = array();
  $descendents = find_descendents_for_group(array($person)); # including self
  foreach ($descendents as $d)
  {
    if (count(find_descendents_for_group(array($d))) == 1)
    {
      $without_students[] = $d;
    }
  }
  $descendents_who_advised = array_diff($descendents,$without_students); # including self
  return max(count($descendents_who_advised) - 1,0); # minus self
}

# -------------------------------------------------------------------------------
function W_score($person)
{
  # should handle multigenerational advisorships correctly...

  # return the max of the widths of each generation of descendents
  $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16
  $gencount = 1;
  $advisees = find_advisorships_under_person($person); #5
  $gen_widths[$gencount] = count($advisees);
  $remaining = array_diff($descendents,$advisees); # 11
#  print "$gencount <-- gen
";
#  print count($advisees)." advisees - ";
#  print_r($advisees);
#  print "
";
#  print "
";
#  print count($remaining)." remaining - ";
#  print_r($remaining);
#  print "
";
#  print "
";
  while (count($remaining) > 0)
  {
    $gencount++;
#    print "$gencount <-- gen
";
    $advisees = advisees_of_group($advisees);
    $gen_widths[$gencount] = count($advisees);
    $remaining = array_diff($remaining,$advisees);
#    print count($advisees)." advisees - ";
#    print_r($advisees);
#    print "
";
#    print "
";
#    print count($remaining)." remaining - ";
#    print_r($remaining);
#    print "
";
#    print "
";
  }
#  print_r($gen_widths);
  return max($gen_widths);
}

# -------------------------------------------------------------------------------
function TD_score($person)
{
  # there is currently a bug in this implementation
  # if a student has two advisors, and they, themselves are related by mentorship
  # this algorithm currently counts gen_width based on advisee count only
  # since $td is calculated based on gen_width values, TD will be missing data
  # A is advisor to B and C
  # B is advisor to C
  # A should have a TD score of 2 (full credit for both advisees)
  # upon further reflection, perhaps this is working correctly, by accident

  # return the decayed score
  $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16
  $gencount = 1;
  $advisees = find_advisorships_under_person($person); #5
  $gen_widths[$gencount] = count($advisees);
  $remaining = array_diff($descendents,$advisees); # 11
  while (count($remaining) > 0)
  {
    $gencount++;
    $advisees = advisees_of_group($advisees);
    $gen_widths[$gencount] = count($advisees);
    $remaining = array_diff($remaining,$advisees);
  }
#  print_r($gen_widths);
  $td = 0;
  foreach($gen_widths as $one => $two)
  {
    $num = $two;
    $den = (pow(2,($one-1)));
    $f = $num/$den;
#    print "$num/$den = $f
";
    $td = $td + $f;
  }
  return $td;
}

# -------------------------------------------------------------------------------
function G_score($person)
{
  # there is currently a bug in this implementation
  # if a student has two advisors, and they, themselves are related by mentorship
  # this algorithm currently misses a generation in the calculation of G
  # A is advisor to B and C
  # B is advisor to C
  # A should have a G score of 2, but will only be calculated a 1

  # return the number of generations of descendents
  $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16
  $gencount = 1;
  $advisees = find_advisorships_under_person($person); #5
  $gen_widths[$gencount] = count($advisees);
  $remaining = array_diff($descendents,$advisees); # 11
  while (count($remaining) > 0)
  {
    $gencount++;
    $advisees = advisees_of_group($advisees);
    $gen_widths[$gencount] = count($advisees);
    $remaining = array_diff($remaining,$advisees);
  }
  if ($gen_widths[1] == 0)
  {
    return 0;
  }
  else
  {
    return count($gen_widths);
  }
}

# -------------------------------------------------------------------------------
function advisees_of_group($group)
{
  # W helper function
  $advisees = array();
  foreach ($group as $one)
  {
    $advisees[] = find_advisorships_under_person($one);
  }
  $advisees = flattenArray($advisees);
#  print_r($advisees);
#  print " <-- advisees of group
";
  return $advisees;
}

# -------------------------------------------------------------------------------
function flattenArray($array)
{
   $flatArray = array();
   foreach( $array as $subElement ) {
       if( is_array($subElement) )
           $flatArray = array_merge($flatArray, flattenArray($subElement));
       else
           $flatArray[] = $subElement;
   }
   return $flatArray;
}

# -------------------------------------------------------------------------------
function calculate_scores($person_id)
{
  $A_score = count(find_advisorships_under_person($person_id));
  $C_score = count(find_committeeships_under_person($person_id));
  $AC_score = $A_score + $C_score;
  $G_score = G_score($person_id);
  $W_score = W_score($person_id);
  $T_score = T_score($person_id);
  $TA_score = TA_score($person_id);
  $TD_score = TD_score($person_id);
  $FMI_score = FMI_score($person_id);
  $FME_score = FME_score($person_id);

  $query = "UPDATE people
              SET
                a_score = '$A_score',
                c_score = '$C_score',
                ac_score = '$AC_score',
                g_score = '$G_score',
                w_score = '$W_score',
                t_score = '$T_score',
                ta_score = '$TA_score',
                td_score = '$TD_score',
                fmi_score = '$FMI_score',
                fme_score = '$FME_score',
                scores_calculated = now()
              WHERE
                id = ".$person_id."
            ";
  $result = mysql_query($query) or die(mysql_error());
}

# -------------------------------------------------------------------------------
function mpact_scores($passed_person)
{
  $glossaryterms = find_glossaryterms();

  $query = "SELECT
              a_score, c_score, ac_score, g_score, w_score,
              t_score, ta_score, td_score, fmi_score, fme_score,
              scores_calculated
              FROM people
              WHERE id = ".$passed_person."
            ";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result)) {
    extract($line);
  }

  $mpact['A'] = $a_score;
  $mpact['C'] = $c_score;
  $mpact['AC'] = $ac_score;
  $scores_output = "A = $a_score
\n";
  $scores_output .= "C = $c_score
\n";
  $scores_output .= "A+C = $ac_score
\n";

  $mpact['FMI'] = $fmi_score;
  $mpact['FME'] = $fme_score;
  $FMIdivFULL = ($ac_score>0) ? $fmi_score / $ac_score : 0;
  $FMIdivFULL = round($FMIdivFULL,3);
  $mpact['FMIdivFULL'] = $FMIdivFULL;
  $FMEdivFULL = ($ac_score>0) ? $fme_score / $ac_score : 0;
  $FMEdivFULL = round($FMEdivFULL,3);
  $mpact['FMEdivFULL'] = $FMEdivFULL;
  if (is_admin())
  {
    $scores_output .= "FMI = $fmi_score
\n";
    $scores_output .= "FME = $fme_score
\n";
    $scores_output .= "FMI/(A+C) = $FMIdivFULL
\n";
    $scores_output .= "FME/(A+C) = $FMEdivFULL
\n";
  }

  $mpact['T'] = $t_score;
  $scores_output .= "T = $t_score
\n";
  $mpact['G'] = $g_score;
  $scores_output .= "G = $g_score
\n";
  $mpact['W'] = $w_score;
  $scores_output .= "W = $w_score
\n";
  $mpact['TD'] = $td_score;
  $scores_output .= "<a href=\"".$_SERVER['SCRIPT_NAME']."?op=glossary\" title=\"".$glossaryterms['defs'][$glossaryterms['ids']['TD']]."\">TD = $td_score
\n";
  $mpact['TA'] = $ta_score;
  $scores_output .= "<a href=\"".$_SERVER['SCRIPT_NAME']."?op=glossary\" title=\"".$glossaryterms['defs'][$glossaryterms['ids']['TA']]."\">TA = $ta_score
\n";
  $scores_output .= "calculated $scores_calculated
\n";
  $mpact['output'] = $scores_output;

  return $mpact;
}

# -------------------------------------------------------------------------------
function find_advisors_for_person($person_id)
{

  // get person's own advisor(s)

  $listing = array();

  $query = "SELECT a.person_id
        FROM
          dissertations d,
          advisorships a
        WHERE
          d.person_id = ".$person_id." AND
          a.dissertation_id = d.id
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function find_committee_for_person($person_id)
{

  // get person's own committee member(s)

  $listing = array();

  $query = "SELECT c.person_id
        FROM
          dissertations d,
          committeeships c
        WHERE
          d.person_id = ".$person_id." AND
          c.dissertation_id = d.id
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function find_advisorships_under_person($person_id)
{

  // get person's advisorships (below)

  $listing = array();

  $query = "SELECT d.person_id
        FROM
          dissertations d,
          advisorships a
        WHERE
          a.person_id = ".$person_id." AND
          a.dissertation_id = d.id
        ORDER BY
          d.completedyear ASC
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function find_committeeships_under_person($person_id)
{

  // get person's committeeships (below)

  $listing = array();

  $query = "SELECT d.person_id
        FROM
          dissertations d,
          committeeships c
        WHERE
          c.person_id = '".$person_id."' AND
          c.dissertation_id = d.id
        ORDER BY
          d.completedyear
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function set_preferred_name($person_id,$name_id)
{

  # delete current family tree of dotgraphs
  delete_associated_dotgraphs($person_id);

  # set it

  $listing = array();

  $before = find_person($person_id);

  $query = "UPDATE people
        SET
          preferred_name_id = '".$name_id."'
        WHERE
          id = '".$person_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  $after = find_person($person_id);

  # log it
  mpact_logger("set preferred name for person[".$person_id."] from name[".$before['preferred_name_id']."] (".$before['fullname'].") to name[".$name_id."] (".$after['fullname'].")");
}

# -------------------------------------------------------------------------------
function generate_profs_at_dept($school_id,$discipline_id)
{

  $dissertations = array();
  $listing = array();
  $advisors = array();
  $committeemembers = array();

  // get all dissertations at this dept

  $query = "SELECT d.id
        FROM dissertations d, schools s
        WHERE
          d.school_id = s.id AND
          s.id = '".$school_id."' AND
          d.discipline_id = '".$discipline_id."'
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $dissertations[] = $line['id'];
  }

  if (count($dissertations)>0)
  {
    // get all advisors for these dissertations

    $query = "SELECT a.person_id
          FROM dissertations d, advisorships a
          WHERE
            a.dissertation_id IN (";
    $query .= implode(", ", $dissertations);
    $query .= ") AND
            a.dissertation_id = d.id";

    $result = mysql_query($query) or die(mysql_error());

    while ( $line = mysql_fetch_array($result))
    {
      $advisors[$line['person_id']] = $line['person_id'];
    }

    // get all committeemembers for these dissertations

    $query = "SELECT c.person_id
          FROM dissertations d, committeeships c
          WHERE
            c.dissertation_id IN (";
    $query .= implode(", ", $dissertations);
    $query .= ") AND
            c.dissertation_id = d.id";

    $result = mysql_query($query) or die(mysql_error());

    while ( $line = mysql_fetch_array($result))
    {
      $committeemembers[$line['person_id']] = $line['person_id'];
    }
  }

  // return the combined list (uniquified when combined)

//  echo "\na - ".count($advisors);
//  echo "\nc - ".count($committeemembers);
  $listing = $advisors + $committeemembers;
//  echo "\ncombined before - ".count($listing);
  return $listing;

}

# -------------------------------------------------------------------------------
function find_profs_at_dept($school_id,$discipline_id)
{
  $query = "SELECT professors
              FROM profs_at_dept
              WHERE
                school_id     = '$school_id' AND
                discipline_id = '$discipline_id'
            ";
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result))
  {
    $listing = unserialize($line['professors']);
  }
  return $listing;

}

# -------------------------------------------------------------------------------
function find_disciplines($school_id=null)
{

  $disciplines = array();
  if ($school_id)
  {
    // get all disciplines at this school
    $query = "SELECT d.id, d.title
                FROM
                  disciplines d, schools s, dissertations diss
                WHERE
                  diss.school_id = s.id AND
                  diss.discipline_id = d.id AND
                  s.id = '$school_id'
                ORDER BY
                  d.title
             ";
  }
  else
  {
    $query = "SELECT id, title
                FROM
                  disciplines d
                ORDER BY
                  title
              ";
  }
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $disciplines[$line['id']] = $line['title'];
  }

  if (isset($disciplines))
  {
    return $disciplines;
  }
}

# -------------------------------------------------------------------------------
function is_duplicate_discipline($title)
{
  $disciplinefound = 0;

  $query = "SELECT id FROM disciplines WHERE title = '$title'";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $disciplinefound = $line['id'];
  }

  if ($disciplinefound > 0){
    return true;
  }

  return false;
}

# -------------------------------------------------------------------------------
function is_empty_discipline($discipline_id)
{
  $query = "SELECT count(*) as howmany FROM dissertations WHERE discipline_id = $discipline_id";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    extract($line);
  }

  if ($howmany > 0){
    return false;
  }

  return true;
}

# -------------------------------------------------------------------------------
function is_duplicate_school($fullname)
{
  $schoolfound = 0;

  $query = "SELECT id FROM schools WHERE fullname = '$fullname'";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    $schoolfound = $line['id'];
  }

  if ($schoolfound > 0){
    return true;
  }

  return false;
}

# -------------------------------------------------------------------------------
function is_empty_school($school_id)
{
  $query = "SELECT count(*) as howmany FROM dissertations WHERE school_id = $school_id";
  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result))
  {
    extract($line);
  }

  if ($howmany > 0){
    return false;
  }

  return true;
}

# -------------------------------------------------------------------------------
function find_discipline_counts()
{

   // get all discipline counts from the database

   $disciplinecounts = array();

   $query = "SELECT discipline_id, count(*) as disciplinecount
               FROM dissertations
               GROUP BY discipline_id
            ";

   $result = mysql_query($query) or die(mysql_error());

   while ( $line = mysql_fetch_array($result))
   {
    $disciplinecounts[$line['discipline_id']] = $line['disciplinecount'];
   }

   if (isset($disciplinecounts))
   {
     return $disciplinecounts;
   }
}

# -------------------------------------------------------------------------------
function find_discipline_statuses($discipline_id)
{

   // get status counts for this discipline

   GLOBAL $statuscodes;

   $statuscounts = array();

   $query = "SELECT status, count(*) as disciplinecount
               FROM dissertations
               WHERE discipline_id='$discipline_id'
               GROUP BY status
            ";

   $result = mysql_query($query) or die(mysql_error());

   while ( $line = mysql_fetch_array($result))
   {
    $statuscounts[$line['status']] = $line['disciplinecount'];
   }

   foreach (range(0,4) as $one)
   {
     if (!isset($statuscounts[$one]))
     {
       $statuscounts[$one] = 0;
     }
   }
   return $statuscounts;
}

# -------------------------------------------------------------------------------
function find_dept_counts($school_id,$discipline_id)
{

   // get all department counts from the database

   $deptcounts = array();

   $query = "SELECT discipline_id, count(*) as disciplinecount
               FROM dissertations
               GROUP BY discipline_id
            ";

   $result = mysql_query($query) or die(mysql_error());

   while ( $line = mysql_fetch_array($result))
   {
    $deptcounts[$line['discipline_id']] = $line['disciplinecount'];
   }

   if (isset($deptcounts))
   {
     return $deptcounts;
   }
}

# -------------------------------------------------------------------------------
function find_dept_statuses($school_id,$discipline_id)
{

   // get status counts for this school in this discipline

   GLOBAL $statuscodes;

   $statuscounts = array();

   $query = "SELECT status, count(*) as disciplinecount
               FROM dissertations
               WHERE
                discipline_id='$discipline_id' AND
                school_id='$school_id'
               GROUP BY status
            ";

   $result = mysql_query($query) or die(mysql_error());

   while ( $line = mysql_fetch_array($result))
   {
    $statuscounts[$line['status']] = $line['disciplinecount'];
   }

   foreach (range(0,4) as $one)
   {
     if (!isset($statuscounts[$one]))
     {
       $statuscounts[$one] = 0;
     }
   }
   return $statuscounts;
}

# -------------------------------------------------------------------------------
function find_schools($discipline_id=null)
{
  // get all schools in a discipline (or all disciplines)
  $schools = array();
  if ($discipline_id)
  {
    // look up schools at dissertations in this discipline
    $query = "SELECT s.id, s.fullname
              FROM
                dissertations d, schools s
              WHERE
                d.school_id = s.id AND
                d.discipline_id = '$discipline_id'
              GROUP BY
                d.school_id
              ORDER BY
                s.fullname ASC
            ";
  }
  else
  {
    $query = "SELECT id, fullname
                FROM
                  schools s
                ORDER BY fullname
              ";
  }
  $result = mysql_query($query) or die(mysql_error());
  while ( $line = mysql_fetch_array($result))
  {
    $schools[$line['id']] = $line['fullname'];
  }

  if (isset($schools))
  {
    return $schools;
  }
}

# -------------------------------------------------------------------------------
function find_school_counts()
{

   // get all school dissertation counts from the database

   $schoolcounts = array();

   $query = "SELECT school_id, count(*) as disscount
               FROM dissertations
               GROUP BY school_id
            ";

   $result = mysql_query($query) or die(mysql_error());

   while ( $line = mysql_fetch_array($result))
   {
    $schoolcounts[$line['school_id']] = $line['disscount'];
   }

   if (isset($schoolcounts))
   {
     return $schoolcounts;
   }
}

# -------------------------------------------------------------------------------
function find_school_statuses($school_id)
{

   // get status counts for this school

   GLOBAL $statuscodes;

   $statuscounts = array();

   $query = "SELECT status, count(*) as disscount
               FROM dissertations
               WHERE school_id='$school_id'
               GROUP BY status
            ";

   $result = mysql_query($query) or die(mysql_error());

   while ( $line = mysql_fetch_array($result))
   {
    $statuscounts[$line['status']] = $line['disscount'];
   }

   foreach (range(0,4) as $one)
   {
     if (!isset($statuscounts[$one]))
     {
       $statuscounts[$one] = 0;
     }
   }
   return $statuscounts;
}

# -------------------------------------------------------------------------------
function find_persons_school($passed_person)
{

  // get person's degree school

  $query = "SELECT
              d.id as dissertation_id,
              d.completedyear,
              d.title,
              d.abstract,
              s.fullname,
              s.country,
              s.id as schoolid
        FROM
          dissertations d,
          schools s
        WHERE
          d.person_id = ".$passed_person." AND
          d.school_id = s.id
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $thisperson['dissertation_id']  = $line['dissertation_id'];
    $thisperson['completedyear']  = $line['completedyear'];
    $thisperson['title']  = $line['title'];
    $thisperson['abstract']  = $line['abstract'];
    $thisperson['country'] = $line['country'];
    $thisperson['school'] = $line['fullname'];
    $thisperson['schoolid'] = $line['schoolid'];
  }

  if (isset($thisperson))
  {
    return $thisperson;
  }
}

# -------------------------------------------------------------------------------
function find_school($school_id)
{

  // get school

  $query = "SELECT
              s.fullname,
              s.country
        FROM
          schools s
        WHERE
          s.id = ".$school_id."
      ";

  $result = mysql_query($query) or die(mysql_error());

  while ( $line = mysql_fetch_array($result)) {
    $school['country'] = $line['country'];
    $school['fullname'] = $line['fullname'];
  }

  if (isset($school))
  {
    return $school;
  }
}

# -------------------------------------------------------------------------------
function get_environment_info()
{
  $host_info = array();
  $hostname = $_SERVER['SERVER_NAME'];
  if ($hostname == ""){$hostname = exec(hostname);}
#  echo "hostname = [$hostname]
";
  if ($hostname == "www.ibiblio.org" || $hostname == "www-dev.ibiblio.org" || $hostname == "login1.ibiblio.org")
  {
    # the main install on ibiblio
    $host_info['hostname']    = "ibiblio";
    $host_info['ownername']   = "mpact";
    $host_info['dotlocation'] = "/export/sunsite/users/mpact/terrelllocal/bin/dot";
    $host_info['appdir']      = "/public/html/mpact";
    $host_info['webdir']      = "http://www.ibiblio.org/mpact";
    $host_info['dotcachedir'] = "dotgraphs";
    $host_info['dotfiletype'] = "png";
    $host_info['dotfontface'] = "Times-Roman";
  }
  else if ($hostname == "trel.dyndns.org")
  {
    # my local development machine
    $host_info['hostname']    = "home";
    $host_info['ownername']   = "trel";
    $host_info['dotlocation'] = "/sw/bin/dot";
    $host_info['appdir']      = "/Library/WebServer/Documents/MPACTlocal/app";
    $host_info['webdir']      = "http://trel.dyndns.org:9000/mpactlocal/app";
    $host_info['dotcachedir'] = "dotgraphs";
    $host_info['dotfiletype'] = "png";
    $host_info['dotfontface'] = "cour";
  }
  else if ($hostname == "localhost.com" || $hostname == "trelpancake")
  {
    # my laptop
    $host_info['hostname']    = "laptop";
    $host_info['ownername']   = "trel";
    $host_info['dotlocation'] = "/opt/local/bin/dot";
    $host_info['appdir']      = "/Users/trel/Sites/MPACT";
    $host_info['webdir']      = "http://localhost.com/~trel/MPACT";
    $host_info['dotcachedir'] = "dotgraphs";
    $host_info['dotfiletype'] = "png";
    $host_info['dotfontface'] = "cour";
  }
  else
  {
    # unknown host
    #exit;
  }

  return $host_info;
}

# -------------------------------------------------------------------------------
function delete_associated_dotgraphs($passed_person)
{
  $host_info = get_environment_info();
  $group = array($passed_person);
  $ancestors = find_ancestors_for_group($group);
  $descendents = find_descendents_for_group($group);
  $entire_family_tree = array_unique($ancestors + $descendents);
  foreach ($entire_family_tree as $one)
  {
    # set the filenames
    $dotfilename = $host_info['appdir']."/".$host_info['dotcachedir']."/$one.dot";
    $imagefilename = $host_info['appdir']."/".$host_info['dotcachedir']."/$one.".$host_info['dotfiletype'];
    $imagemapfilename = $host_info['appdir']."/".$host_info['dotcachedir']."/$one.map";
    # delete each if they exist
    if (file_exists($dotfilename))
    {
      `rm $dotfilename`;
    }
    if (file_exists($imagefilename))
    {
      `rm $imagefilename`;
    }
    if (file_exists($imagemapfilename))
    {
      `rm $imagemapfilename`;
    }
    # mark as 'dirty' so cronjob can recreate images
    mark_record_as_dirty($one);
  }
}

# -------------------------------------------------------------------------------
function mark_record_as_dirty($passed_person)
{
  # mark database record for this person as dirty
  # a cronjob will pick these up and regenerate their dotgraphs
  # gets around permission issues on the server if necessary
  $query = "UPDATE people SET regenerate_dotgraph = '1' WHERE id = '".$passed_person."'";
  $result = mysql_query($query) or die(mysql_error());
}

# -------------------------------------------------------------------------------
function narray_slice($array, $offset, $length) {
    # http://us3.php.net/manual/en/function.array-slice.php#73882

  //Check if this version already supports it
  if (str_replace('.', '', PHP_VERSION) >= 502)
    return array_slice($array, $offset, $length, true);

  foreach ($array as $key => $value) {

    if ($a >= $offset && $a - $offset <= $length)
      $output_array[$key] = $value;
    $a++;

  }
  return $output_array;
}

# -------------------------------------------------------------------------------
function generate_dotfile($passed_person){
  $a = find_person($passed_person);
  if ($a == null)
  {
    return 0;
  }
  else
  {
    $dotfilecontents = "";
    $dotfilecontents .= "digraph familytree\n";
    $dotfilecontents .= "{\n";
    $dotfilecontents .= "rankdir=\"LR\"\n";
    $dotfilecontents .= "node [fontname = Times, fontsize=10, shape = rect, height=.15]\n";
    # ancestors
    $upgroup = array();
    $upgroup[] = $passed_person;
    $ancestors = find_ancestors_for_group($upgroup);
    foreach ($ancestors as $one)
    {
      $person = find_person($one);
      $dotfilecontents .= "$one [label = \"".$person['fullname']."\" URL=\"mpact.php?op=show_tree&id=".$one."\"];\n";
      $advisors = find_advisors_for_person($one);
      foreach ($advisors as $adv)
      {
        $dotfilecontents .= "$adv -> $one;\n";
      }
    }
    # descendents
    $downgroup = array();
    $downgroup[] = $passed_person;
    $descendents = find_descendents_for_group($downgroup);
    foreach ($descendents as $one)
    {
      $person = find_person($one);
      $dotfilecontents .= "$one [label = \"".$person['fullname']."\" URL=\"mpact.php?op=show_tree&id=".$one."\"";
      if ($one == $passed_person){
        $dotfilecontents .= " color=\"red\" style=\"filled\" fillcolor=\"grey\"";
      }
      $dotfilecontents .= "];\n";
      $advisees = find_advisorships_under_person($one);
      foreach ($advisees as $adv)
      {
        $dotfilecontents .= "$one -> $adv;\n";
      }
    }
    $dotfilecontents .= "}\n";

    return $dotfilecontents;
  }
}

# -------------------------------------------------------------------------------
function draw_tree_dotgraph($passed_person)
{
  $person = $passed_person;
  $host_info = get_environment_info();
  if (isset($host_info['appdir']))
  {
    $webfilename = generate_dotgraph($person);
    if ($webfilename == "marked_as_dirty"){
      echo "generating graph, please reload";
    }
    else{
      echo "
";
    }
  }
  else
  {
    echo "graphics libraries are not configured";
  }
}

# -------------------------------------------------------------------------------
function generate_dotgraph($passed_person, $forcenew="no")
{
  $person = $passed_person;
  $host_info = get_environment_info();
#  print_r($host_info);
  $appcache = $host_info['appdir']."/".$host_info['dotcachedir'];
  $webcache = $host_info['webdir']."/".$host_info['dotcachedir'];
  $appfilename = "$appcache/$person.".$host_info['dotfiletype'];
#  echo "appfilename = $appfilename
\n";
  $dotfilename = "$appcache/$person.dot";
#  echo "dotfilename = $dotfilename
\n";
  $webfilename = "$webcache/$person.".$host_info['dotfiletype'];
#  echo "webfilename = $webfilename
\n";
  $appimagemap = "$appcache/$person.map";
#  echo "appimagemap = $appimagemap
\n";

  if (!file_exists($appfilename)) {
    # assumption is that the cachedir exists... (run setupmpact.sh)
    # generate dotfile
    if (!file_exists($dotfilename) or $forcenew == "force") {
#      print " - creating dotfile...\n";
      $dotfilecontents = generate_dotfile($person);
      $fh = fopen($dotfilename, 'w');
      fwrite($fh, $dotfilecontents);
      fclose($fh);
      exec("chmod 666 $dotfilename");
    }
    # generate graph
    $getandgenerategraph = "/bin/cat $dotfilename | ".$host_info['dotlocation']." -Nfontname=".$host_info['dotfontface']." -Gcharset=latin1 -Tcmapx -o$appimagemap -T".$host_info['dotfiletype']." -o$appfilename 2>&1";
#      echo "getandgenerategraph = $getandgenerategraph
";
    exec($getandgenerategraph);
    exec("chmod 666 $appimagemap");
    exec("chmod 666 $appfilename");
    if (!file_exists($appfilename)) {
      # mark as dirty if it didn't work
      mark_record_as_dirty($person);
      return "marked_as_dirty";
    }
  }
  else
  {
#    echo "SHOWING CACHED COPY
";
  }

  return $webfilename;
}

# -------------------------------------------------------------------------------
function draw_graph($passed_person)
{
  if (!$passed_person){action_box("No ID given.");}

    $person = $passed_person;
    $host_info = get_environment_info();
    if (isset($host_info['appdir']))
    {
      $appcache = $host_info['appdir']."/".$host_info['dotcachedir'];
      $webcache = $host_info['webdir']."/".$host_info['dotcachedir'];
      $appfilename = "$appcache/$person.".$host_info['dotfiletype'];
      #echo "appfilename = $appfilename
";
      $webfilename = "$webcache/$person.".$host_info['dotfiletype'];
      #echo "webfilename = $webfilename
";
      $appimagemap = "$appcache/$person.map";
      #echo "appimagemap = $appimagemap
";

      echo "";
      echo file_get_contents($appimagemap);
    }
    else
    {
      echo "graphics libraries are not configured";
    }
}

# -------------------------------------------------------------------------------
function draw_tree($passed_person)
{
        GLOBAL $statuscodes;
        GLOBAL $inspectioncodes;

        // shows a person

        if (!$passed_person){action_box("No ID given.");}
        else
        {
          $personcount = 0;
          $thisperson = array();
          $dissertation = array();

          // get person's preferred name

          $query = "SELECT
                n.firstname, n.middlename,
                n.lastname, n.suffix, p.degree
                FROM
                  names n, people p
                WHERE
                  p.preferred_name_id = n.id AND
                  p.id = '".$passed_person."'
              ";
          $result = mysql_query($query) or die(mysql_error());

          while ( $line = mysql_fetch_array($result)) {
            $thisperson['firstname']  = $line['firstname'];
            $thisperson['middlename'] = $line['middlename'];
            $thisperson['lastname']   = $line['lastname'];
            $thisperson['suffix']     = $line['suffix'];
            $thisperson['degree']     = $line['degree'];
            $personcount++;
          }

          $schoolinfo = find_persons_school($passed_person);
          $thisperson['dissertation_id'] = $schoolinfo['dissertation_id'];
          $thisperson['completedyear'] = $schoolinfo['completedyear'];
          $thisperson['country'] = $schoolinfo['country'];
          $thisperson['school'] = $schoolinfo['school'];
          $thisperson['schoolid'] = $schoolinfo['schoolid'];

          if ($thisperson['dissertation_id'] == "")
          {
            $thisperson['status'] = "";
            $thisperson['notes'] = "";
            $thisperson['title'] = "N/A";
            $thisperson['abstract'] = "N/A";
            $thisperson['abstract_html'] = "N/A";
          }
          else
          {
            $dissertation = find_dissertation($thisperson['dissertation_id']);
            $thisperson['status'] = $dissertation['status'];
            $thisperson['notes'] = $dissertation['notes'];
            $thisperson['discipline_id'] = $dissertation['discipline_id'];
            $thisperson['title'] = $dissertation['title'];
            $thisperson['abstract'] = $dissertation['abstract'];
            $thisperson['abstract_html'] = encode_linebreaks($dissertation['abstract']);
            if ($thisperson['title'] == "") { $thisperson['title'] = "N/A";}
            if ($thisperson['abstract'] == "")
            {
              $thisperson['abstract'] = "N/A";
              $thisperson['abstract_html'] = "N/A";
            }
          }

          $thisperson['advisors'] = find_advisors_for_person($passed_person);
          $thisperson['cmembers'] = find_committee_for_person($passed_person);
          $thisperson['advisorships'] = find_advisorships_under_person($passed_person);
          $thisperson['committeeships'] = find_committeeships_under_person($passed_person);

          if ($personcount < 1)
          {
            action_box("Person ".$passed_person." Not Found");
          }
          else
          {

            echo "

\n";

            # Name / Aliases
            $count = 0;
            $printme = "";
            $fullname = $thisperson['firstname']." ".$thisperson['middlename']." ".$thisperson['lastname']." ".$thisperson['suffix'];
            $printme .= "
Dissertation Information for $fullname
";
            $printme .= "
";
            if (is_admin())
            {
              if (isset($thisperson['completedyear']))
              {
                $printme .= " (Edit)";
              }
              else
              {
                $printme .= " (Create Dissertation for $fullname)";
              }
              $printme .= "
\n";
            }
            $printme .= "
";
            $printme .= "
";
            $printme .= "NAME: ";
            if (is_admin())
            {
              $printme .= "(Add)";
            }
            $printme .= "
";
            $printme .= " - ";
            $printme .= get_person_link($passed_person);
            if (is_admin())
            {
              $printme .= " (Edit)";
            }
            $printme .= "
\n";

            $aliases = 0;
            foreach (find_aliases($passed_person) as $one)
            {
              $printme .= " - (Alias) ";
              $printme .= $one['firstname']." ";
              $printme .= $one['middlename']." ";
              $printme .= $one['lastname']." ";
              $printme .= $one['suffix']." ";
              if (is_admin())
              {
                $printme .= "(Set as Primary)";
                $printme .= " (Delete)";
              }
              $printme .= "
";
              $aliases++;
            }
            $printme .=  "
";
            echo $printme;

            # Degree
            $printme = "
\n";
            $printme .= "DEGREE:
\n";
            $printme .= " - ".$thisperson['degree'];
            if (is_admin())
            {
              $printme .= " (Edit)";
            }
            $printme .=  "
";
            echo $printme;

            # Discipline
            $printme = "
\n";
            $printme .= "DISCIPLINE:
\n";
            if (isset($thisperson['discipline_id']))
            {
              $discipline = find_discipline($thisperson['discipline_id']);
              $printme .= " - ".$discipline['title']."";
              if (is_admin())
              {
                $printme .= " (Edit)";
              }
            }
            else
            {
              $printme .= " - None";
              if (is_admin())
              {
                $printme .= " (Create Dissertation for $fullname)";
              }
            }
            $printme .=  "
";
            echo $printme;

            # School
            $printme = "
\n";
            $printme .= "SCHOOL:
\n";
            if (isset($thisperson['completedyear']))
            {
              $printme .= " - ".$thisperson['school']." (".$thisperson['country'].") (".$thisperson['completedyear'].")";
              if (is_admin())
              {
                $printme .= " (Edit)";
              }
            }
            else
            {
              $printme .= " - None";
              if (is_admin())
              {
                $printme .= " (Create Dissertation for $fullname)";
              }
            }
            $printme .= "
\n";
            echo $printme;

            # Advisors
            $count = 0;
            $printme = "";
            $printme .= "
";
            $printme .=  "ADVISORS: ";
            if (is_admin() && isset($thisperson['completedyear']))
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['advisors'])){
              foreach ($thisperson['advisors'] as $one)
              {
                $printme .=  " - ";
                $printme .=  get_person_link($one);
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .=  "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
";
            echo $printme;

            # Committee Members
            $count = 0;
            $printme = "";
            $printme .= "
";
            $printme .= "COMMITTEE MEMBERS: ";
            if (is_admin() && isset($thisperson['completedyear']))
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['cmembers'])){
              foreach ($thisperson['cmembers'] as $one)
              {
                $printme .= " - ";
                $printme .= get_person_link($one);
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .= "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
\n\n";

            # Admin Notes
            if (is_admin())
            {
              if ($thisperson['notes'] != "")
              {
                $printme .=  "
";
                $printme .= "
\n";
                $printme .= "
\n";
                $printme .= "Admin Notes: ".$thisperson['notes']."
\n";
                $printme .= "</tdr>
\n";
                $printme .= "
\n";
                $printme .=  "
\n\n";
              }
            }

            $glossaryterms = find_glossaryterms();
            # Status and Inspection
            $printme .=  "
";
            $printme .= "MPACT Status: ".$statuscodes[$thisperson['status']]."
\n";
            $printme .=  "
\n\n";

            # Title and Abstract
            $printme .=  "
";
            $printme .= "Title: ".$thisperson['title']."
";
            $printme .=  "
\n";
            $printme .=  "
";
            $printme .= "Abstract: ".$thisperson['abstract_html']."
";
            $printme .=  "
\n\n";

            # print it all out...
            echo $printme;

            # URLS

            if (is_admin())
            {
              $urls = find_urls_by_person($passed_person);
              echo "
\n";
              echo "REFERENCE URLS";
              echo " (Add)";
              echo "
\n";
              if (count($urls) > 0)
              {
                echo "
\n";
              }
              else
              {
                echo " - None\n";
              }
              foreach ($urls as $one)
              {
                echo "
Updated: ".$one['updated_at']."";
                echo " (Edit)";
                echo " (Delete)";
                echo "
\n";
                echo "
".$one['url']."
\n";
                echo "
".$one['description']."
\n";
              }
              if (count($urls) > 0)
              {
                echo "
\n";
              }
              echo "
\n";
            }

            # EDIT HISTORY

            if (is_admin())
            {
              $entries = get_dissertation_history($thisperson['dissertation_id']);
              if (count($entries) > 0)
              {
                echo "
\n";
                echo "EDIT HISTORY (Show/Hide)\n";
                echo "";
                echo "
\n";
              }

              foreach ($entries as $one)
              {
                echo "
";
                echo "".$one['logged_at']."	";
                echo "".$one['user']."	";
                echo "".$one['message']."	";
                echo "
\n";
              }
              if (count($entries) > 0)
              {
                echo "
\n";
                echo "
\n";
              }
            }

            echo "		\n";

            # MPACT Scores
            $printme = "";
            $printme .=  "
MPACT Scores for $fullname
";
            $printme .=  "
";
            $mpact = mpact_scores($passed_person);
            $printme .= $mpact['output'];
            $printme .=  "
\n";
            if (is_admin())
            {
              $printme .=  "
(Recalculate)
";
            }
            echo $printme;

            # Draw FamilyTree Graph for this person
            echo "
Advisors and Advisees Graph
\n";
            echo "
";
            draw_tree_dotgraph($passed_person);
            echo "
";

            echo "

\n";

            # Students
            echo  "
Students under $fullname
\n\n";

            # Advisees
            $count = 0;
            $printme = "";
            $printme .= "
";
            $printme .= "ADVISEES: ";
            if (is_admin())
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['advisorships'])){
              foreach ($thisperson['advisorships'] as $one)
              {
                $printme .= " - ";
                $printme .= get_person_link($one);
                $schoolinfo = find_persons_school($one);
                if (isset($schoolinfo['completedyear']))
                {
                  $printme .= " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
                }
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .= "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
\n";
            echo $printme;

            # Committeeships
            $ccount = 0;
            $printme = "";
            $printme .= "
";
            $printme .= "COMMITTEESHIPS: ";
            if (is_admin())
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['committeeships'])){
              foreach ($thisperson['committeeships'] as $one)
              {
                $printme .= " - ";
                $printme .= get_person_link($one);
                $schoolinfo = find_persons_school($one);
                if (isset($schoolinfo['completedyear']))
                {
                  $printme .= " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
                }
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .= "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
";
            echo $printme;

          }

        }

}

?>

<?php

/*************************************************

//  MPACT - Mentoring Impact Factor

//  Terrell Russell
//  2005 - 2010
//  unc@terrellrussell.com

*************************************************/

/*

splitting a person
 - give current list of A's and C's and names
 - allow A's and C's to be divided (all have to be moved to #1 or #2)
 - names need to be split, but can be in both (since that's the problem in the first place)

live search for entering new links
 - 2 characters and then hit DB

incoming suggestions/changes
 - just a big bucket
 - contact info and single big box to state their claim
 - should be the start of a conversation, we're not just taking their word
 - batch submissions?  just start a conversation

*/

require 'envsetup.php';

###############################################

$statuscodes = array(
  NULL => "N/A",
  "-1" => "N/A",
  "0"  => "Incomplete - Not_Inspected",
  "1"  => "Incomplete - Inspected",
  "2"  => "Incomplete - Ambiguous",
  "3"  => "Complete - Except Indecipherables",
  "4"  => "Fully Complete"
);

$inspectioncodes = array(
  NULL => "N/A",
  "0" => "No",
  "1" => "Yes"
);

$degree_types = array(
  "Unknown",
  "Unknown - Investigated",
  "A.L.A.",
  "B.A.",
  "B.S.",
  "B.L.S.",
  "L.L.B.",
  "H.A.",
  "M.A.",
  "M.S.",
  "M.F.A.",
  "M.P.A.",
  "D.E.A.",
  "Ed.M.",
  "F.L.A. (by thesis)",
  "LL.M.",
  "LL.D.",
  "M.L.S.",
  "D.S.N.",
  "D.S.W.",
  "D.Engr.",
  "D.Lib.",
  "Ed.D.",
  "Th.D.",
  "Pharm.D.",
  "D.Sc.",
  "D.L.S.",
  "J.D.",
  "M.D.",
  "Ph.D."
);

// Begin Session
session_start();

// Delete server session if client cookie doesn't exist
if (!isset($_COOKIE['MPACT_userid'])){
  unset($_SESSION['MPACT']);
}

// Check for good cookie (and expired session) - (re)set session values accordingly
if (isset($_COOKIE['MPACT_userid']) && !isset($_SESSION['MPACT'])){
  $query = "SELECT id, username, fullname FROM users WHERE id='".$_COOKIE['MPACT_userid']."'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  $line = mysqli_fetch_array($result);
  $_SESSION['MPACT']['userid'] = $line['id'];
  $_SESSION['MPACT']['username'] = $line['username'];
  $_SESSION['MPACT']['fullname'] = $line['fullname'];
}

###############################################
// DISPLAY SOMETHING - something from the URL
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
  // Display header
  xhtml_web_header();

//  echo "-----\n";
//  print_r($_COOKIE);
//  echo "-----\n";
//  print_r($_SESSION);
//  echo "-----\n";
  if (isset($_GET['op']))
  {
    switch ($_GET['op'])
    {
      ###############################################
      case "login";

        $host_info = get_environment_info();
        if ($host_info['hostname'] == "sils"){
          # no logins here - go to dev server
          action_box("No Logins Here...",2,$_SERVER['SCRIPT_NAME']);
        }
        else{
          if (!isset($_SESSION['MPACT']['userid'])){
            # login form
            echo "
Welcome
\n";
            echo "
Please login if you have an account.
\n";
            echo "<form id=\"loginform\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"login\">\n";
            echo "
\n";
            echo "

Username:
	<input type='text' name='username' />
\n";
            echo "

Password:
	<input type='password' name='password' />
\n";
            echo "
     <input type='submit' name='Submit' value='Login' />
\n";
            echo "
\n";
            echo "</form>";
          }
          else{
            # um, already logged in...
            action_box("Already Logged In...",2,$_SERVER['SCRIPT_NAME']);
          }
        }

        break;
      ###############################################
      case "logout";

        setcookie('MPACT_userid',$_SESSION['MPACT']['userid'],time()-1000);
        unset($_SESSION['MPACT']);
        action_box("Logged Out",2,$_SERVER['SCRIPT_NAME']);

        break;
      ###############################################
      case "glossary";

        if ( isset($_GET['id']) ){
          show_glossaryterm($_GET['id']);
        }
        else
        {
          show_glossary();
        }

        break;
      ###############################################
      case "admin";

        if (is_admin())
        {
          echo "
Administrator Pages
\n";

          echo "
\n";
          echo "
\n";

          echo "
\n";
          echo "Show Logs\n";
          echo "
\n";

          echo "
\n";
          echo "Show Orphans\n";
          echo "
\n";
          echo "Citation Correlation\n";
          echo "
\n";

          echo "
\n";
          echo "People with Multiple Dissertations (Errors in DB)\n";
          echo "
\n";
          echo "Year 0000\n";
          echo "
\n";

          echo "
\n";
          echo "Add a New Person to the Database\n";
          echo "
\n";

          echo "	\n";

          echo "
\n";
          echo "No Title/Abstract\n";
          echo "
\n";
          echo "LIS, No Title/Abstract\n";
          echo "
\n";
          echo "LIS, No Title\n";
          echo "
\n";
          echo "LIS, No Abstract\n";
          echo "
\n";
          echo "
\n";
          echo "LIS, No Committee\n";
          echo "
\n";

          echo "	\n";

          echo "
\n";
          echo "LIS, Graduates By Year\n";
          echo "
\n";
          echo "LIS History\n";
          echo "
\n";

          echo "
\n";
          echo "LIS Professors Summary\n";
          echo "
\n";
          echo "LIS Professors with MPACT\n";
          echo "
\n";
          echo "LIS Professors and their Degrees (large CSV)\n";
          echo "
\n";
          echo "LIS Professors with Unknown Degree\n";
          echo "
\n";
          echo "LIS Professors with Unknown-Investigated Degree\n";
          echo "
\n";
          echo "LIS Professors without Dissertations\n";
          echo "
\n";
          echo "LIS Professors without LIS Dissertations\n";
          echo "
\n";

          echo "
\n";
          echo "
\n";

          echo "
";

          show_alphabet();

        }
        else
        {
          not_admin();
        }

        break;
      ###############################################
      case "glossary_edit";

        if ( isset($_GET['id']) && is_admin() ){

          echo "
Edit a Glossary Definition
\n";

          $query = "SELECT id, term, definition FROM glossary WHERE id='".$_GET['id']."'";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          while ( $line = mysqli_fetch_array($result)) {
            $results['term'] = $line['term'];
            $results['definition'] = $line['definition'];
          }

          echo "
";

          echo "<form id=\"glossaryedit\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"glossary_edit\">\n";
          echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">\n";
          echo "<input type=\"hidden\" name=\"term\" value=\"".$results['term']."\">\n";

          echo "".$results['term'].":
\n";
          echo "<textarea cols=\"50\" rows=\"8\" name=\"definition\">".$results['definition']."</textarea>\n";
          echo "
\n";
          echo "<input type=\"submit\" name=\"button\" value=\"Save\">";
          echo "</form>";

          echo "
";

        }
        else
        {
          not_admin();
        }

        break;
      ###############################################
      case "show_tree":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {
          draw_tree((int)$_GET['id']);
        }

        break;

      ###############################################
      case "show_graph":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {
          echo "

\n";
          echo "Advisors and Advisees of ".get_person_link($_GET['id']);
          echo "

\n";
          draw_graph((int)$_GET['id']);
        }

        break;

      ###############################################
      case "statistics":

        echo "
\n";
        echo "LIS Incomplete - \n";
        echo "Top A -\n";
        echo "Top C -\n";
        echo "Top A+C -\n";
        echo "Top T -\n";
        echo "Top G -\n";
        echo "Top W -\n";
        echo "Top TD -\n";
        echo "Top TA\n";
        echo "
\n";

        echo "
Overall MPACT Statistics
\n";

        echo "
\n";

        # disciplines
        $query = "SELECT count(*) as disciplinecount FROM disciplines";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
Disciplines	".$disciplinecount."
\n";

        # schools
        $query = "SELECT count(*) as schoolcount FROM schools";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
Schools	".$schoolcount."
\n";

        # diss
        $query = "SELECT count(*) as disscount FROM dissertations";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
Dissertations	".$disscount."
\n";

        # a
        $query = "SELECT count(*) as advisorcount FROM advisorships";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
Advisorships	".$advisorcount."
\n";

        # c
        $query = "SELECT count(*) as committeeshipscount FROM committeeships";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
Committeeships	".$committeeshipscount."
\n";

        # full
        $query = "SELECT count(*) as peoplecount FROM people";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
People	".$peoplecount."
\n";
        echo "
\n";

        # dissertations by country
        echo "

\n";
        echo "
Dissertations by Country:

\n";
        $query = "SELECT count(*) as dissnone FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \"\")";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        $query = "SELECT count(*) as dissusa FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \"USA\")";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        $query = "SELECT count(*) as disscanada FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \"Canada\")";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        $query = "SELECT count(*) as dissother FROM dissertations WHERE school_id IN
          (SELECT id FROM schools WHERE (country != \"\" AND country != \"USA\" AND country != \"Canada\"))";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }
        echo "
\n";
        echo "
USA	".$dissusa."
                  ".sprintf("%.2f",100*$dissusa/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa)/$disscount)."%
\n";
        echo "
Canada	".$disscanada."
                  ".sprintf("%.2f",100*$disscanada/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa+$disscanada)/$disscount)."%
\n";
        echo "
Other	".$dissother."
                  ".sprintf("%.2f",100*$dissother/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa+$disscanada+$dissother)/$disscount)."%
\n";
        echo "
None Listed	".$dissnone."
                  ".sprintf("%.2f",100*$dissnone/$disscount)."%
                  ".sprintf("%.2f",100*($dissusa+$disscanada+$dissother+$dissnone)/$disscount)."%
\n";
        echo "
Total	".$disscount."
                  ".sprintf("%.2f",100*$disscount/$disscount)."%

\n";
        echo "
\n";

        # dissertations by year
        echo "

\n";
        echo "
Dissertations by Year:

\n";
        $query = "SELECT completedyear, count(*) as disscount FROM dissertations GROUP BY completedyear";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          $counts[$line['completedyear']] = $line['disscount'];
        }
        ksort($counts);
        echo "
\n";
        echo "
\n";
        foreach ($counts as $one => $two)
        {
          echo "	\n";
        }
        echo "
";
        echo "
\n";
        foreach ($counts as $one => $two)
        {
          echo "";
          if ($one%10==0)
          {
            echo $one;
          }
          echo "	\n";
        }
        echo "
";
        echo "
\n";

        break;

      ###############################################
      case "show_logs":

        if (is_admin())
        {
          echo "
Recent Activity
\n";

          if (isset($_GET['offset']))
          {
            $entries = get_logs($_GET['offset']);
          }
          else
          {
            $entries = get_logs();
          }
          echo "
\n";
          foreach ($entries as $entry)
          {
            echo "
";
            echo "".$entry['logged_at']."
".$entry['ip']."	";
            echo "".$entry['user']."	";
            echo "".$entry['message']."	";
            echo "
\n";
          }
          echo "
\n";

        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_multi_dissertations":

        if (is_admin())
        {
          echo "
People With Multiple Dissertations (db needs to be edited by hand)
\n";

          $query = "SELECT
                count(d.id) as howmany,
                d.id, d.person_id, d.completedyear, d.status,
                d.title, d.abstract, d.notes, d.school_id, d.discipline_id
                FROM
                  dissertations d
                GROUP BY
                  d.person_id
                ORDER BY
                  howmany DESC
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $dissertations = array();
          while ( $line = mysqli_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $multicount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            if ($d['howmany'] > 1)
            {
              print "person id = ".$d['person_id'];
              print "
";
              print "
";
              $multicount++;
            }
          }
          if ($multicount == 0)
          {
            print " - None - database is clear.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_zero_year":

        if (is_admin())
        {
          echo "
Dissertations from the year 0000
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.discipline_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.completedyear = '0000'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $dissertations = array();
          while ( $line = mysqli_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            # get school
            $query = "SELECT fullname
                        FROM
                          schools
                        WHERE id = '".$d['school_id']."'
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $schoolname = $line['fullname'];
            }
            # get degree
            $query = "SELECT degree
                        FROM
                          people
                        WHERE id = '".$d['person_id']."'
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $degree = $line['degree'];
            }
            $discipline = find_discipline($d['discipline_id']);
            echo "
";
            echo "$zerocount.	";
            echo "".get_person_link($d['person_id'])."	";
            print "$degree	";
            print "".$discipline['title']."	";
            print "$schoolname	";
            print "
";
          }
          if ($zerocount == 0)
          {
            print "
None - database is clear.
";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_title_lis":

        if (is_admin())
        {
          echo "
LIS Dissertations Without Title
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.discipline_id = 1 AND
                  ( d.title = '' )
                ORDER BY
                  d.school_id
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $dissertations = array();
          while ( $line = mysqli_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All LIS dissertations have titles.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_abstract_lis":

        if (is_admin())
        {
          echo "
LIS Dissertations Without Abstract
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.discipline_id = 1 AND
                  ( d.abstract = '' )
                ORDER BY
                  d.school_id
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $dissertations = array();
          while ( $line = mysqli_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All LIS dissertations have abstracts.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_title_abstract":

        if (is_admin())
        {
          echo "
Dissertations Without Title/Abstract
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.title = '' OR d.abstract = ''
                ORDER BY
                  d.school_id
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $dissertations = array();
          while ( $line = mysqli_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All dissertations have titles and abstracts.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "find_no_title_abstract_lis":

        if (is_admin())
        {
          echo "
LIS Dissertations Without Title/Abstract
\n";

          $query = "SELECT
                d.id, d.person_id, d.school_id, d.completedyear
                FROM
                  dissertations d
                WHERE
                  d.discipline_id = 1 AND
                  ( d.title = '' OR d.abstract = '' )
                ORDER BY
                  d.school_id
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $dissertations = array();
          while ( $line = mysqli_fetch_array($result)) {
            $dissertations[] = $line;
          }
          $zerocount = 0;
          echo "
\n";
          foreach ($dissertations as $d)
          {
            $zerocount++;
            print "$zerocount. ";
            echo get_person_link($d['person_id']);
            $thisperson = find_persons_school($d['person_id']);
            print " - ".$thisperson['school'];
            print " (".$d['completedyear'].")";
            print "
";
          }
          if ($zerocount == 0)
          {
            print " - None - All LIS dissertations have titles and abstracts.";
          }
          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "lis_profs_unknown_degree":

        if (is_admin())
        {
          echo "
LIS Professors with Unknown Degree
\n";

          # advisors or committee members with unknown degree,
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          $lis_with_unknown = array();

          # get advisors for each diss, check for advisor's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $advisors = array();
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
            foreach($advisors as $aid){
              $adv = find_person($aid);
              if ($adv['degree'] == "Unknown"){
                $lis_with_unknown[] = $aid;
              }
            }
          }

          # get committeeships for each diss, check for comm's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $committeemembers = array();
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
            foreach($committeemembers as $cid){
              $com = find_person($cid);
              if ($com['degree'] == "Unknown"){
                $lis_with_unknown[] = $cid;
              }
            }
          }

          # uniquify
          $lis_with_unknown = array_unique($lis_with_unknown);

          # print them out
          echo "
\n";
          $count = 0;
          foreach($lis_with_unknown as $pid){
            $count++;
            $person = find_person($pid);
            print "$count. ";
            print get_person_link($pid);
            print "
\n";
          }
          if ($count == 0)
          {
            print " - None";
          }
          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_profs_unknowninvestigated":
        case "lis_profs_unknowninvestigated_degree":

#        if (is_admin())
#        {
          echo "
LIS Professors with Unknown-Investigated Degree
\n";

          # advisors or committee members with unknown-investigated degree,
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          $lis_with_unknown = array();

          # get advisors for each diss, check for advisor's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $advisors = array();
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
            foreach($advisors as $aid){
              $adv = find_person($aid);
              if ($adv['degree'] == "Unknown - Investigated"){
                $lis_with_unknown[] = $aid;
              }
            }
          }

          # get committeeships for each diss, check for comm's degree
          # if unknown degree, save
          foreach ($lis_dissertations as $id){
            $committeemembers = array();
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
            foreach($committeemembers as $cid){
              $com = find_person($cid);
              if ($com['degree'] == "Unknown - Investigated"){
                $lis_with_unknown[] = $cid;
              }
            }
          }

          # uniquify
          $lis_with_unknown = array_unique($lis_with_unknown);

          # print them out
          echo "
\n";
          $count = 0;
          foreach($lis_with_unknown as $pid){
            $count++;
            $person = find_person($pid);
            print "$count. ";
            print get_person_link($pid);
            $advisorcount = count(find_advisorships_under_person($pid));
            $commcount = count(find_committeeships_under_person($pid));
            $totalcommitteeships = $advisorcount + $commcount;
            if ($totalcommitteeships > 1){print "";}
            print " : $advisorcount + $commcount = $totalcommitteeships";
            if ($totalcommitteeships > 1){print "";}
            print "
\n";
            $allcommitteeships += $totalcommitteeships;
          }
          if ($count == 0)
          {
            print " - None";
          }

          print "
TOTAL COMMITTEESHIPS = $allcommitteeships
";

          echo "
\n";

#        }
#        else
#        {
#          not_admin();
#        }

        break;

        ###############################################
        case "lis_profswithoutdiss":

        if (is_admin())
        {
          echo "
LIS Professors without Dissertations
\n";

          # advisors or committee members with no dissertation,
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }
          # get advisors for each diss
          $advisors = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
          }
          # get committeeships for each diss
          $committeemembers = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
          }
          $total = array_merge($advisors,$committeemembers);
          $unique = array_unique($total);

          $unique_list = implode(",",$unique);
          $listed = array();
          $query = "SELECT person_id
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                    ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $listed[] = $line['person_id'];
          }
          $notlisted = array_diff($unique,$listed);

          # print them out
          echo "
\n";
          $count = 0;
          foreach($notlisted as $pid){
            $count++;
            print "$count. ";
            print get_person_link($pid);
            print "
\n";
          }
          if ($count == 0)
          {
            print " - None";
          }
          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_profs_degrees":

        if (is_admin())
        {
          echo "
LIS Professors and their Degrees
\n";

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          print "
Copy and Paste the text below into a .csv file.
";

          # big loop
          print "
\n";
          print "
";
          print "Count,DissID,DissYear,DissLastName,DissFirstName,DissSchool,DissCountry,AdvisorID,AdvisorType,AdvisorLastName,AdvisorFirstName,";
          print "AdvisorDegree,AdvisorYear,AdvisorDiscipline,AdvisorSchool,AdvisorCountry\n";
          $count = 0;
          foreach($lis_dissertations as $did){
            # loop through advisors
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $did
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {

              # advisor line

                # Count
                $count++;
                print "\"$count\",";
                # DissID
                print "\"$did\",";
                # DissYear
                $diss = find_dissertation($did);
                print "\"".$diss['completedyear']."\",";
                # DissLastName
                $author = find_person($diss['person_id']);
                print "\"".$author['lastname']."\",";
                # DissFirstName
                print "\"".$author['firstname']."\",";
                # DissSchool
                $school = find_school($diss['school_id']);
                print "\"".$school['fullname']."\",";
                # DissCountry
                print "\"".$school['country']."\",";
                # AdvisorID
                $pid = $line['person_id'];
                print "\"$pid\",";
                # AdvisorType
                print "\"Advisor\",";
                # AdvisorLastName
                $person = find_person($pid);
                print "\"".$person['lastname']."\",";
                # AdvisorFirstName
                print "\"".$person['firstname']."\",";
                # AdvisorDegree
                print "\"".$person['degree']."\",";
                $diss = find_dissertation_by_person($pid);
                if ($diss){
                  # AdvisorYear
                  print "\"".$diss['completedyear']."\",";
                  # AdvisorDiscipline
                  $disc = find_discipline($diss['discipline_id']);
                  print "\"".$disc['title']."\",";
                  # AdvisorSchool
                  $school = find_school($diss['school_id']);
                  print "\"".$school['fullname']."\",";
                  # AdvisorCountry
                  print "\"".$school['country']."\"";
                }
                else{
                  # no dissertation for this person
                  print "\"\",";
                  print "\"\",";
                  print "\"\",";
                  print "\"\"";
                }
                print "\n";

            }
            # loop through committeeships
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $did
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {

              # committeeship line

                # Count
                $count++;
                print "\"$count\",";
                # DissID
                print "\"$did\",";
                # DissYear
                $diss = find_dissertation($did);
                print "\"".$diss['completedyear']."\",";
                # DissLastName
                $author = find_person($diss['person_id']);
                print "\"".$author['lastname']."\",";
                # DissFirstName
                print "\"".$author['firstname']."\",";
                # DissSchool
                $school = find_school($diss['school_id']);
                print "\"".$school['fullname']."\",";
                # DissCountry
                print "\"".$school['country']."\",";
                # AdvisorID
                $pid = $line['person_id'];
                print "\"$pid\",";
                # AdvisorType
                print "\"Committee\",";
                # AdvisorLastName
                $person = find_person($pid);
                print "\"".$person['lastname']."\",";
                # AdvisorFirstName
                print "\"".$person['firstname']."\",";
                # AdvisorDegree
                print "\"".$person['degree']."\",";
                $diss = find_dissertation_by_person($pid);
                if ($diss){
                  # AdvisorYear
                  print "\"".$diss['completedyear']."\",";
                  # AdvisorDiscipline
                  $disc = find_discipline($diss['discipline_id']);
                  print "\"".$disc['title']."\",";
                  # AdvisorSchool
                  $school = find_school($diss['school_id']);
                  print "\"".$school['fullname']."\",";
                  # AdvisorCountry
                  print "\"".$school['country']."\"";
                }
                else{
                  # no dissertation for this person
                  print "\"\",";
                  print "\"\",";
                  print "\"\",";
                  print "\"\"";
                }
                print "\n";

            }
          }
          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_profsnotfromlis":

          if (is_admin())
          {

            echo "
LIS Professors without LIS Dissertations
\n";

            # and then once the data collection is done
            # cassidy wants a list of all the people who were advisors and committee
            # members for lis, but were not themselves lis

            # get list of LIS dissertations
            $query = "SELECT
                      d.id
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1'
                    ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $lis_dissertations[] = $line['id'];
            }
            # get advisors for each diss
            $advisors = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT person_id
                          FROM advisorships
                          WHERE dissertation_id = $id
                        ";
              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
              while ( $line = mysqli_fetch_array($result)) {
                $advisors[] = $line['person_id'];
              }
            }
            # get committeeships for each diss
            $committeemembers = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT person_id
                          FROM committeeships
                          WHERE dissertation_id = $id
                        ";
              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
              while ( $line = mysqli_fetch_array($result)) {
                $committeemembers[] = $line['person_id'];
              }
            }
            $total = array_merge($advisors,$committeemembers);
            $unique = array_unique($total);

            $unique_list = implode(",",$unique);
            $listed = array();
            $query = "SELECT person_id
                        FROM dissertations
                        WHERE
                          person_id IN ($unique_list)
                          AND
                          discipline_id = '1'
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $listed[] = $line['person_id'];
            }
            $notlisted = array_diff($unique,$listed);

            # print them out
            echo "
\n";
            $count = 0;
            foreach($notlisted as $pid){
              $count++;
              print "$count. ";
              print get_person_link($pid);
              print "
\n";
            }
            if ($count == 0)
            {
              print " - None";
            }
            echo "
\n";

          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_nocommittee":

          if (is_admin())
          {

            echo "
LIS Dissertations with no committee
\n";

            # get list of LIS dissertations
            $query = "SELECT
                      d.id
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1'
                    ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $lis_dissertations[] = $line['id'];
            }
            # get advisors for each diss
            $advisors = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT count(*) as howmany
                          FROM advisorships
                          WHERE dissertation_id = $id
                        ";
              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
              while ( $line = mysqli_fetch_array($result)) {
                if ($line['howmany'] > 0){$hascomm[] = $id;};
              }
            }
            # get committeeships for each diss
            $committeemembers = array();
            foreach ($lis_dissertations as $id){
              $query = "SELECT count(*) as howmany
                          FROM committeeships
                          WHERE dissertation_id = $id
                        ";
              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
              while ( $line = mysqli_fetch_array($result)) {
                if ($line['howmany'] > 0){$hascomm[] = $id;};
              }
            }
            $unique = array_unique($hascomm);
            $nocomm = array_diff($lis_dissertations,$unique);

            # print them out
            echo "
\n";
            $count = 0;
            foreach($nocomm as $did){
              $count++;
              print "$count. ";
              $d = find_dissertation($did);
              print get_person_link($d['person_id']);
              print "
\n";
            }
            if ($count == 0)
            {
              print " - None";
            }
            echo "
\n";

          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_profs_with_mpact":

        if (is_admin())
        {
          echo "
LIS Professors With MPACT
\n";

          # advisors or committee members
          # that served on an lis dissertation

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }

          # get advisors for each diss
          $advisors = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
          }

          # get committeeships for each diss
          $committeemembers = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
          }

          $total = array_merge($advisors,$committeemembers);

          $unique = array_unique($total);

          echo "
\n";
          echo "Count|Name|Year|A|C|A+C|T\n";
          foreach ($unique as $prof){
            $mpact = mpact_scores($prof);
            $person = find_person($prof);
            $dissertation = find_dissertation_by_person($prof);
            # count
            $count += 1;
            echo "$count";
            echo "|";
            # name
            echo $person['fullname'];
            echo "|";
            # year
            echo $dissertation['completedyear'];
            echo "|";
            # a
            echo $mpact['A'];
            echo "|";
            # c
            echo $mpact['C'];
            echo "|";
            # a+c
            echo $mpact['AC'];
            echo "|";
            # t
            echo $mpact['T'];
            echo "\n";
          }
          echo "
\n";
        }

        break;

        ###############################################
        case "lis_profs_summary":

        if (is_admin())
        {
          echo "
LIS Professors Summary
\n";

          # advisors or committee members
          # that served on an lis dissertation

          echo "
\n";

          # get list of LIS dissertations
          $query = "SELECT
                    d.id
                  FROM
                    dissertations d
                  WHERE
                    d.discipline_id = '1'
                  ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $lis_dissertations[] = $line['id'];
          }
          echo "
Total LIS Dissertations	".count($lis_dissertations)."
\n";

          # get advisors for each diss
          $advisors = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM advisorships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $advisors[] = $line['person_id'];
            }
          }
          echo "
Total LIS Dissertation Advisorships	";
          echo count($advisors);
          echo "
\n";

          # get committeeships for each diss
          $committeemembers = array();
          foreach ($lis_dissertations as $id){
            $query = "SELECT person_id
                        FROM committeeships
                        WHERE dissertation_id = $id
                      ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $committeemembers[] = $line['person_id'];
            }
          }
          echo "
Total LIS Dissertation Committeeships	";
          echo count($committeemembers);
          echo "
\n";

          $total = array_merge($advisors,$committeemembers);
          echo "
Total LIS Dissertation Advisorships and Committeeships:	";
          echo count($total);
          echo "
\n";

          $unique = array_unique($total);
          echo "
Total number of unique advisor/committee members on LIS dissertations:	";

          echo count($unique);
          echo "
\n";

          $unique_list = implode(",",$unique);
          $known = array();
          $query = "SELECT person_id
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                    ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $known[] = $line['person_id'];
          }
          echo "
";
          echo "Subset of ".count($unique)." without a listed dissertation:	";
          echo count(array_diff($unique,$known));
          echo "
\n";
          echo "
Subset of ".count($unique)." with a listed dissertation:	";
          echo count($known);
          echo "
\n";

          $query = "SELECT count(*) as howmany
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                        AND
                        discipline_id != 16
                    ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $howmany = $line['howmany'];
          }
          echo "
 - Subset of ".count($known)." with known discipline:	";
          echo $howmany;
          echo "
\n";

          $query = "SELECT count(*) as howmany
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                        AND
                        completedyear != 0000
                    ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $howmany = $line['howmany'];
          }
          echo "
 - Subset of ".count($known)." with known year:	";
          echo $howmany;
          echo "
\n";

          $query = "SELECT count(*) as howmany
                      FROM dissertations
                      WHERE
                        person_id IN ($unique_list)
                        AND
                        completedyear != 107
                    ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $howmany = $line['howmany'];
          }
          echo "
 - Subset of ".count($known)." with known school:	";
          echo $howmany;
          echo "
\n";

          echo "
\n";

        }
        else
        {
          not_admin();
        }

        break;

        ###############################################
        case "lis_allyears":

          if (is_admin())
          {
            echo "
LIS, Graduates By Year
\n";
            print "
\n";

            # get list of dissertations
            $query = "SELECT
                      d.id, d.person_id, d.completedyear
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1'
                    ORDER BY
                      d.completedyear ASC,
                      d.school_id ASC
                    ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            $schools = array();
            $count = 0;
            while ( $line = mysqli_fetch_array($result)) {
              $dissertation = find_dissertation($line['id']);
              $person = find_person($line['person_id']);
              $schoolinfo = find_persons_school($line['person_id']);
              $count++;
              print $count;
              print "|";
              print $line['completedyear'];
              print "|";
              print $schoolinfo['school'];
              print "|";
              print $person['fullname'];
#              print "|";
#              print $dissertation['title'];
#              print "|";
#              print $dissertation['abstract'];
              print "\n";
            }

            print "
\n";
          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_history":

          if (is_admin())
          {
            echo "
LIS Dissertations by School by Year
\n";

            $firstyear = 1920;
            $lastyear = 2008;

            print "
\n";
            print "school|";
            for ($i = $firstyear; $i <= $lastyear; $i++)
            {
                print "$i|";
            }
            print "\n";

            # get list of schools (all of them)
            $query = "SELECT
                    s.id, s.fullname
                    FROM
                      schools s
                    ORDER BY
                      s.fullname
                    ";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            $schools = array();
            while ( $line = mysqli_fetch_array($result)) {
              $schools[] = $line;
            }
            foreach ($schools as $s)
            {
              # loop through each school and find count by year
              $query = "SELECT
                    d.id, d.person_id, d.completedyear, COUNT(d.completedyear) AS yeartotal
                    FROM
                      dissertations d
                    WHERE
                      d.discipline_id = '1' AND
                      d.school_id = '".$s['id']."'
                    GROUP BY
                      d.completedyear
                  ";
              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

              print $s['fullname']."|";
              $d = array();
              while ( $line = mysqli_fetch_array($result)) {
                $d[$s['id']][$line['completedyear']] = $line['yeartotal'];
              }

              # walk through all years, and print out counts for this school
              for ($i = $firstyear; $i <= $lastyear; $i++)
              {
                if ($d[$s['id']][$i] > 0)
                  print $d[$s['id']][$i]."|";
                else
                  print "0|";
              }
              print "\n";
            }

            print "
";
          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "lis_incomplete":

          echo "
Incomplete LIS Dissertation Listings
\n";

          $discipline_id = 1; # hard coded for LIS
          $schools = find_schools($discipline_id);

          foreach ($schools as $one => $two)
          {

            $year_conferred = array();
            $degree_status = array();

            $query = "SELECT d.person_id, d.completedyear, d.status
                  FROM
                    dissertations d,
                    schools s,
                    people p,
                    names n
                  WHERE
                    s.id = '$one' AND
                    d.discipline_id = '$discipline_id' AND
                    d.school_id = s.id AND
                    d.person_id = p.id AND
                    p.preferred_name_id = n.id AND
                    d.status < 4
                  ORDER BY
                    s.id ASC, d.completedyear ASC, n.lastname ASC, n.firstname ASC
                ";

            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            $resultcount = 0;

            while ( $line = mysqli_fetch_array($result)) {
              $resultcount++;
              extract($line);
              $year_conferred[$person_id] = $completedyear;
              $degree_status[$person_id] = $status;
            }

            if ($resultcount > 0)
            {
              echo "
$two
\n";
            }

            $incompletecount = 0;
            echo "
";
            foreach ($year_conferred as $person => $year)
            {
              $incompletecount++;
              $printme = "
\n";
              $printme .= "$incompletecount. ";
              $printme .= "".get_person_link($person)." ($year)	\n";

              $printme .= "".$statuscodes[$degree_status[$person]]."	\n";
              $printme .= "
\n";

              echo $printme;
            }
            echo "
";

          }
          echo "

";

        break;

        ###############################################
        case "all_edges":

          if (is_admin())
          {
            echo "
All Dissertations and Mentor Relationships
\n";

            print "
\n";
            print "mentor|role|protege|year|school\n";

            # each dissertation
            $query = "SELECT id, person_id, completedyear, school_id FROM dissertations";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              extract($line);
              $student = find_person($person_id);
              $query2 = "SELECT fullname as schoolname FROM schools WHERE id = '$school_id'";
              $result2 = mysql_query($query2) or die(mysql_error());
              $line2 = mysqli_fetch_array($result2);
              extract($line2);
              print $student['fullname']."|dissertation|null|$completedyear|$schoolname\n";
              # get advisorships
              $advisors = find_advisors_for_person($person_id);
              foreach ($advisors as $mentor_id){
                $mentor = find_person($mentor_id);
                print $mentor['fullname']."|advisorship|".$student['fullname']."|$completedyear|$schoolname\n";
              }
              # get committeeships
              $committee = find_committee_for_person($person_id);
              foreach ($committee as $mentor_id){
                $mentor = find_person($mentor_id);
                print $mentor['fullname']."|committeeship|".$student['fullname']."|$completedyear|$schoolname\n";
              }
            }
            print "
";
          }
          else
          {
             not_admin();
          }

        break;

        ###############################################
        case "citation_correlation":

          if (is_admin())
          {
            echo "
Citation Correlation Data
\n";

            $correlated_ids = array(
              953,
              2098,
#              5086,   bc
              3659,
#              1329,  dalhousie
              5087,
              478,
              3094,
              3497,
              4784,
              1250,
              5088,
              5089,
              5090,
              4657,
#              5091,  mcdowell, not phd yet
              5092,
              5093,
              5094,
              2668,
              4076,
              2683,
              3978,
              2425,
              3645,
              2660,
              2233,
              2665,
              1310,
              2548,
              2708,
              2592,
              4648,
              5095,
              5096,
              4654,
              5097,
              5098,
              1234,
              1299,
              1294,
              3062,
              3110,
              1283,
              1220,
              874,
              584,
              3127,
              1142,
              3116,
              5099,
              5100,
              1025,
              486,
              3130,
              1321,
              5101,
              4502,
              5102,
              535,
              5160,   # koohang
              2673,
              5103,
              5104,
              1950,
              3972,
              3278,
              5105,
              3571,
              5106,
              3994,
              1504,
              4181,
              3140,
              2323,   # benoit added
              5107,
              800,
              4438,
              5108,
              5109,
              4760,
              2570,
              1866,
              3238,
              1846,
              1806,
              2527,
              3703,
              4758,
              3683,
              3846,
              2603,
              4011,
              2343,
              2329,
              5110,
              5111,
              4706,
              2761,
              1413,
              3028,
              3590,
              3668,
              2883,
              3063,
              3091,
              1705,
              3031,
# gary again  486,
              3979,
              3018,
              1855,
              3409,
              2747,
              3093,
              3065,
              3060,
              1685,
              2114,
              5112,
# moore rm    5113,
              2309,
# liu rm      2215,
              4086,
              4013,
              1573
            );

            echo "
\n";
            echo "

              -
              Name
              A
              C
              A+C
              FMI
              FME
              FMI/(A+C)
              FME/(A+C)

\n";
            $counter = 0;
            foreach ($correlated_ids as $one)
            {
              $counter++;
              echo "
";
              echo "$counter.	";
              echo "";
              echo get_person_link($one);
              echo "	";
              $scores = mpact_scores($one);
              echo "".$scores['A']."	";
              echo "".$scores['C']."	";
              echo "".$scores['AC']."	";
              echo "".$scores['FMI']."	";
              echo "".$scores['FME']."	";
              echo "".$scores['FMIdivFULL']."	";
              echo "".$scores['FMEdivFULL']."	";
              echo "
\n";
            }
            echo "
\n";

          }
          else
          {
             not_admin();
          }

          break;

        ###############################################
        case "top_a":
        case "top_c":
        case "top_ac":
        case "top_g":
        case "top_td":
        case "top_w":
        case "top_t":
        case "top_ta":

        $list_type = strtoupper(substr($_GET['op'],4));
        echo "
Top ";
        if ($list_type == "TD"){echo "TD";}
        else if ($list_type == "TA"){echo "TA";}
        else if ($list_type == "AC"){echo "A+C";}
        else {echo $list_type;}
        echo " List
\n";
        $score_type = strtolower($list_type)."_score";
        $people = find_all_people();
        foreach ($people as $p)
        {
          $scores[$p] = find_mpact_score($p,$score_type);
        }
        # zero out indecipherables
        $scores[28] = 0;
        $scores[391] = 0;
        asort($scores);
        $scores = array_reverse($scores, true);
        $top = narray_slice($scores, 0, 100); #calls custom function, end of mpact_include (passes true)
        $count = 0;
        $lasttotal = 0;
        echo "
\n";
        foreach ($top as $one => $two)
        {
          $count++;
          echo "
";
          echo "";
          if ($two != $lasttotal){echo $count.".";}
          echo "	";
          echo "";
          echo get_person_link($one);
          echo "	";
          echo "";
          echo $two;
          echo "	";
          echo "
\n";
          $lasttotal = $two;
        }
        echo "
\n";
        break;

        ###############################################
        case "create_discipline":

        if (is_admin())
        {
          echo "
Creating a New Discipline
\n";

          echo "
";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"create_discipline\">\n";

          echo "
";
          echo "
Title
";

          echo "
";
          echo "<input type=\"text\" size=\"70\" name=\"title\">	";
          echo "
";

          echo "
";

          echo "<input type=\"submit\" name=\"button\" value=\"Create\">";
          echo "</form>";

          echo "
";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "edit_discipline":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          elseif (!is_empty_discipline($_GET['id']))
          {
            action_box("Discipline must be empty to edit...",2,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");
          }
          else{

            $query = "SELECT title FROM disciplines WHERE id=".$_GET['id'];
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              extract($line);
            }

            echo "
Editing a Discipline
\n";

            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"discipline_id\" value=\"".$_GET['id']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_discipline\">\n";

            echo "
";
            echo "
Title
";

            echo "
";
            echo "<input type=\"text\" size=\"70\" name=\"title\" value=\"$title\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"button\" value=\"Save\">";
            echo "</form>";

            echo "
";
          }
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "create_school":

        if (is_admin())
        {
          echo "
Creating a New School
\n";

          echo "
";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"create_school\">\n";

          echo "
";
          echo "
Fullname	Country
";

          echo "
";
          echo "<input type=\"text\" size=\"70\" name=\"fullname\">	";
          echo "<input type=\"text\" size=\"25\" name=\"country\" value=\"USA\">	";
          echo "
";

          echo "
";

          echo "<input type=\"submit\" name=\"button\" value=\"Create\">";
          echo "</form>";

          echo "
";
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "edit_school":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          elseif (!is_empty_school($_GET['id']))
          {
            action_box("School must be empty to edit...",2,$_SERVER['SCRIPT_NAME']."?op=show_schools");
          }
          else{

            $query = "SELECT fullname, country FROM schools WHERE id=".$_GET['id'];
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              extract($line);
            }

            echo "
Editing a School
\n";

            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"school_id\" value=\"".$_GET['id']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_school\">\n";

            echo "
";
            echo "
Fullname	Country
";

            echo "
";
            echo "<input type=\"text\" size=\"70\" name=\"fullname\" value=\"$fullname\">	";
            echo "<input type=\"text\" size=\"25\" name=\"country\" value=\"$country\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"button\" value=\"Save\">";
            echo "</form>";

            echo "
";
          }
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "create_person":

        if (is_admin())
        {
          echo "
Creating a New Person
\n";

          echo "
";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"create_person\">\n";

          echo "
";
          echo "
First	Middle	Last	Suffix	Degree
";

          echo "
";
          echo "<input type=\"text\" size=\"10\" name=\"firstname\">	";
          echo "<input type=\"text\" size=\"10\" name=\"middlename\">	";
          echo "<input type=\"text\" size=\"12\" name=\"lastname\">	";
          echo "<input type=\"text\" size=\"5\" name=\"suffix\">	";
          echo "";
          echo "<select name=\"degree\">\n";
          foreach ($degree_types as $one){
            echo "<option value=\"$one\"";
            echo ">$one</option>\n";
          }
          echo "</select>\n";
          echo "	";
          echo "
";

          echo "
";

          echo "<input type=\"submit\" name=\"button\" value=\"Create\">";
          echo "</form>";

          echo "
";
        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_mentor":

        if (is_admin())
        {
          echo "
Add a New Person to the Database
\n";

          echo "
Adding a Mentor
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"add_mentor\">\n";
          echo "<input type=\"hidden\" name=\"student_id\" value=\"".$_GET['id']."\">\n";

          echo "
";

          echo "Mentor Type:
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"A\"";
          if ($_GET['type'] == "A"){echo " checked";}
          echo "> Advisor
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"C\"";
          if ($_GET['type'] == "C"){echo " checked";}
          echo "> Committee Member\n";
          echo "

\n";

          echo "Mentor:
\n";
          echo "<select name=\"mentor_id\">\n";
          $people = find_all_people_for_selectbox();
          foreach ($people as $person_id => $person)
          {
            echo "<option value=\"$person_id\">".$person['lastname'];
            if ($person['suffix'] != ""){echo " ".$person['suffix'];}
            echo ", ".$person['firstname']." ".$person['middlename']."</option>\n";
          }
          echo "</select>\n";

          echo "

\n";

          echo "Student:
\n". get_person_link($_GET['id']);
          echo "

\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Add Mentor\">";

          echo "
";
          echo "</form>";

          draw_tree($_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_student":

        if (is_admin())
        {
          echo "
Add a New Person to the Database
\n";

          echo "
Adding a Student
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"add_student\">\n";
          echo "<input type=\"hidden\" name=\"mentor_id\" value=\"".$_GET['id']."\">\n";

          echo "
";

          echo "Mentor Type:
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"A\"";
          if ($_GET['type'] == "A"){echo " checked";}
          echo "> Advisor
\n";
          echo "<input type=\"radio\" name=\"mentor_type\" value=\"C\"";
          if ($_GET['type'] == "C"){echo " checked";}
          echo "> Committee Member\n";
          echo "

\n";

          echo "Mentor:
\n". get_person_link($_GET['id']);
          echo "

\n";

          echo "Student:
\n";
          echo "<select name=\"student_id\">\n";
          $people = find_all_people_for_selectbox("1"); # the 1 is to only get people with dissertations
          foreach ($people as $person_id => $person)
          {
            echo "<option value=\"$person_id\">".$person['lastname'];
            if ($person['suffix'] != ""){echo " ".$person['suffix'];}
            echo ", ".$person['firstname']." ".$person['middlename']."</option>\n";
          }
          echo "</select>\n";

          echo "

\n";
          echo "<input type=\"submit\" name=\"button\" value=\"Add Student\">";

          echo "
";
          echo "</form>";

          draw_tree($_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "remove_mentor":

        if (is_admin())
        {
          echo "
Removing a Mentor
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"remove_mentor\">\n";
          echo "<input type=\"hidden\" name=\"student_id\" value=\"".intval($_GET['student_id'])."\">\n";
          echo "<input type=\"hidden\" name=\"mentor_id\" value=\"".intval($_GET['mentor_id'])."\">\n";
          echo "<input type=\"hidden\" name=\"mentor_type\" value=\"".$_GET['type']."\">\n";

          echo "
";

          echo "Are you sure you want to remove this mentor relationship?

\n";
          if ($_GET['type'] == "A"){echo "Advisor: ";}
          if ($_GET['type'] == "C"){echo "Commitee Member: ";}
          echo get_person_link(intval($_GET['mentor_id']))."
\n";
          echo "Student: ".get_person_link(intval($_GET['student_id']))."
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Yes, remove this relationship.\">";
          echo " If NOT, please go BACK";

          echo "
";
          echo "</form>";

          draw_tree(intval($_GET['student_id']));

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_url";

        if (is_admin())
        {
          echo "
Adding a Reference URL
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"add_url\">\n";
          echo "<input type=\"hidden\" name=\"person_id\" value=\"".intval($_GET['id'])."\">\n";

          echo "
";

          echo "
\n";
          echo "
URL:	<input type=\"text\" name=\"url\" size=\"70\">
\n";
          echo "
Description:	<textarea rows=\"4\" cols=\"68\" name=\"description\"></textarea>
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Add this URL\">";

          echo "
";
          echo "</form>";

          draw_tree(intval($_GET['id']));

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "edit_url";

        if (is_admin())
        {
          $url = find_url(intval($_GET['id']));
          echo "
Editing a Reference URL
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"edit_url\">\n";
          echo "<input type=\"hidden\" name=\"id\" value=\"".intval($_GET['id'])."\">\n";

          echo "
";

          echo "
\n";
          echo "
URL:	<input type=\"text\" name=\"url\" size=\"70\" value=\"".$url['url']."\">
\n";
          echo "
Description:	<textarea rows=\"4\" cols=\"68\" name=\"description\">".$url['description']."</textarea>
\n";
          echo "
Last Updated:	".$url['updated_at']."
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Edit this URL\">";

          echo "
";
          echo "</form>";

          draw_tree($url['person_id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "delete_url";

        if (is_admin())
        {
          $url = find_url(intval($_GET['id']));
          echo "
Deleting a Reference URL
\n";

          echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
          echo "<input type=\"hidden\" name=\"op\" value=\"delete_url\">\n";
          echo "<input type=\"hidden\" name=\"id\" value=\"".intval($_GET['id'])."\">\n";

          echo "
";

          echo "Are you sure you want to delete this Reference URL?

\n";
          echo "
\n";
          echo "
URL:	".$url['url']."
\n";
          echo "
Description:	".$url['description']."
\n";
          echo "
Last Updated:	".$url['updated_at']."
\n";
          echo "
\n";
          echo "
\n";

          echo "<input type=\"submit\" name=\"button\" value=\"Yes, delete this Reference URL\">";
          echo " If NOT, please go BACK";

          echo "
";
          echo "</form>";

          draw_tree($url['person_id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "edit_degree":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_person($_GET['id']);

            echo "
Editing a Degree
";
            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_degree\">";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">";

            echo "
";
            echo "
Name	Degree
";

            echo "
";
            echo "".$person['fullname']."	";
            echo "";
            echo "<select name=\"degree\">\n";
            foreach ($degree_types as $one){
              echo "<option value=\"$one\"";
              if ($person['degree'] == $one){
                echo " selected";
              }
              echo ">$one</option>\n";
            }
            echo "</select>\n";
            echo "	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";

            echo "</form>";

            echo "
";

            echo "

";
            draw_tree($_GET['id']);
            echo "

";

          }
        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "add_name":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_person($_GET['id']);

            echo "
Adding an Alias
";
            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
            echo "<input type=\"hidden\" name=\"op\" value=\"add_name\">";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">";

            echo "
";
            echo "
First	Middle	Last	Suffix
";

            echo "
";
            echo "<input type=\"text\" size=\"10\" name=\"firstname\">	";
            echo "<input type=\"text\" size=\"10\" name=\"middlename\">	";
            echo "<input type=\"text\" size=\"10\" name=\"lastname\">	";
            echo "<input type=\"text\" size=\"10\" name=\"suffix\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"submit\" value=\"Add\">";

            echo "</form>";

            echo "
";

            echo "

";
            draw_tree($_GET['id']);
            echo "

";

          }
            }
            else
            {
               not_admin();
            }

        break;

      ###############################################
      case "edit_name":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_person($_GET['id']);

            echo "
Editing a Name
";
            echo "
";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
            echo "<input type=\"hidden\" name=\"op\" value=\"edit_name\">";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">";
            echo "<input type=\"hidden\" name=\"name_id\" value=\"".$person['preferred_name_id']."\">";

            echo "
";
            echo "
First	Middle	Last	Suffix
";

            echo "
";
            echo "<input type=\"text\" size=\"10\" name=\"firstname\" value=\"".$person['firstname']."\">	";
            echo "<input type=\"text\" size=\"10\" name=\"middlename\" value=\"".$person['middlename']."\">	";
            echo "<input type=\"text\" size=\"12\" name=\"lastname\" value=\"".$person['lastname']."\">	";
            echo "<input type=\"text\" size=\"5\" name=\"suffix\" value=\"".$person['suffix']."\">	";
            echo "
";

            echo "
";

            echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";

            echo "</form>";

            echo "
";

            echo "

";
            draw_tree($_GET['id']);
            echo "

";

          }
        }
        else
        {
           not_admin();
        }

        break;

        ###############################################
        case "create_dissertation":

          if (is_admin())
          {

            $disciplines = find_disciplines();
            $schools = find_schools();

            if (!$_GET['person_id']){action_box("No ID given.");}
            else
            {

              $person = find_person($_GET['person_id']);
              if (!$person)
              {
                action_box("Person not found.");
              }
              else{

                echo "
CREATE DISSERTATION
\n";

                echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
                echo "<input type=\"hidden\" name=\"op\" value=\"create_dissertation\">";
                echo "<input type=\"hidden\" name=\"person_id\" value=\"".intval($person['id'])."\">";

                echo "
";
                echo get_person_link($person['id']);
                echo "
";

                echo "Degree: <select name=\"degree\">\n";
                foreach ($degree_types as $one)
                {
                  echo "<option value=\"$one\"";
                  if ($one == "Ph.D."){
                    echo " selected";
                  }
                  echo ">$one</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Status: <select name=\"status\">\n";
                foreach (range(0,4) as $one)
                {
                  echo "<option value=\"$one\"";
                  echo ">".$statuscodes[$one]."</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Discipline: <select name=\"discipline_id\">\n";
                foreach ($disciplines as $one => $two)
                {
                  echo "<option value=\"$one\">$two</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "School: ";
                echo "<select name=\"school_id\">\n";
                foreach ($schools as $one => $two)
                {
                  echo "<option value=\"$one\"";
                  echo ">$two</option>\n";
                }
                echo "</select>\n";
                echo "
Year:\n";
                echo "<input type=\"text\" size=\"10\" name=\"completedyear\">
";
                echo "Title:
<textarea cols=\"60\" rows=\"3\" name=\"title\"></textarea>
";
                echo "Abstract:
<textarea cols=\"60\" rows=\"7\" name=\"abstract\"></textarea>
";
                echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";
                echo "
";

                echo "</form>";

                echo "
";
                echo "Currently:";
                echo "
";
                echo "

";
                draw_tree($person['id']);
                echo "

";
              }

            }
          }
          else
          {
             not_admin();
          }

          break;

        ###############################################
        case "edit_dissertation":

          if (is_admin())
          {
            if (!$_GET['id']){action_box("No ID given.");}
            else
            {

              $disciplines = find_disciplines();
              $schools = find_schools();
              $dissertation = find_dissertation(intval($_GET['id']));
              if (!$dissertation)
              {
                action_box("Dissertation not found.");
              }
              else{

                $person = find_person($dissertation['person_id']);

                echo "
EDIT DISSERTATION DETAILS
\n";

                echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
                echo "<input type=\"hidden\" name=\"op\" value=\"edit_dissertation\">";
                echo "<input type=\"hidden\" name=\"id\" value=\"".intval($_GET['id'])."\">";
                echo "<input type=\"hidden\" name=\"person_id\" value=\"".intval($person['id'])."\">";

                echo "
";
                echo get_person_link($person['id']);
                echo "
";

                echo "Degree: <select name=\"degree\">\n";
                foreach ($degree_types as $one)
                {
                  echo "<option value=\"$one\"";
                  if ($person['degree'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">$one</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Status: <select name=\"status\">\n";
                foreach (range(0,4) as $one)
                {
                  echo "<option value=\"$one\"";
                  if ($dissertation['status'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">".$statuscodes[$one]."</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "Discipline: <select name=\"discipline_id\">\n";
                foreach ($disciplines as $one => $two)
                {
                  echo "<option value=\"$one\"";
                  if ($dissertation['discipline_id'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">$two</option>\n";
                }
                echo "</select>\n";
                echo "
";

                echo "School: <select name=\"school_id\">\n";
                foreach ($schools as $one => $two)
                {
                  echo "<option value=\"$one\"";
                  if ($dissertation['school_id'] == $one)
                  {
                    echo " selected";
                  }
                  echo ">$two</option>\n";
                }
                echo "</select>\n";

                echo "
Year:\n";
                echo "<input type=\"text\" size=\"10\" name=\"completedyear\" value=\"".$dissertation['completedyear']."\">
";
                echo "Title:
<textarea cols=\"60\" rows=\"3\" name=\"title\">".$dissertation['title']."</textarea>
";
                echo "Abstract:
<textarea cols=\"60\" rows=\"7\" name=\"abstract\">".$dissertation['abstract']."</textarea>
";
                echo "Admin Notes:
<textarea cols=\"60\" rows=\"7\" name=\"notes\">".$dissertation['notes']."</textarea>
";
                echo "<input type=\"submit\" name=\"submit\" value=\"Save\">";
                echo "
";

                echo "</form>";

                echo "
";
                echo "Currently:";
                echo "
";
                echo "

";
                draw_tree($person['id']);
                echo "

";
              }

            }
          }
          else
          {
             not_admin();
          }

          break;

      ###############################################
      case "delete_name":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            $person = find_name($_GET['name']);

            echo "
";

            echo "Are you sure you want to delete this name?";

            echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
            echo "<input type=\"hidden\" name=\"op\" value=\"delete_name\">\n";
            echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">\n";
            echo "<input type=\"hidden\" name=\"name_id\" value=\"".$_GET['name']."\">";

            echo "
";
            echo "[ ".$person['firstname']." ".$person['middlename']." ".$person['lastname']." ".$person['suffix']." ]
";
            echo "
";

            echo "
";
            echo "<input type=\"submit\" name=\"submit\" value=\"Yes\">";
            echo "   Cancel
";

            echo "</form>";

            echo "
";

          }
            }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "set_preferred_name":

        if (is_admin())
        {

          set_preferred_name($_GET['id'],$_GET['name']);

          action_box("Preferred Name Selected",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "recalculate_mpact":

        if (is_admin()){

          # recalculate MPACT scores for passed person id
          calculate_scores($_GET['id']);

          action_box("MPACT Scores Recalculated",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_GET['id']);

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "show_orphans":

        if (is_admin())
        {

          $orphans = find_orphans();

          echo "
Orphans
\n";

          echo "
\n";
          $counter = 0;
          foreach ($orphans as $orphan)
          {
            $counter++;
            echo $counter." ";
            echo get_person_link($orphan['person_id']);
            echo " (Delete from Database)";
            echo "
\n";
          }
          if ($counter < 1){echo " - No orphans at this time.";}
          echo "
\n";

        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "delete_person":

        if (is_admin())
        {
          if (!$_GET['id']){action_box("No ID given.");}
          else
          {

            if (is_orphan($_GET['id']))
            {
              echo "
";

              echo "Are you sure you want to delete this person?";

              echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
              echo "<input type=\"hidden\" name=\"op\" value=\"delete_person\">\n";
              echo "<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">\n";

              echo "
";
              echo get_person_link($_GET['id']);
              echo "
";

              echo "
";
              echo "

\n";
              echo "<input type=\"submit\" name=\"submit\" value=\"Yes, Delete this person completely.\">";
              echo "   Cancel
";

              echo "</form>";

              echo "
";
            }
            else
            {
              action_box("This person cannot be deleted.");
            }
          }
        }
        else
        {
           not_admin();
        }

        break;

      ###############################################
      case "show_disciplines":

        $statustotals = array(0,0,0,0,0);
        $disciplines = find_disciplines();
        $disciplinecounts = find_discipline_counts();

        if (is_admin()){
          echo "
Add a New Discipline to the Database
\n";
        }

        echo "
Disciplines Represented Across All Schools
\n";

        echo "
\n";
        echo "
\n";
        echo "
";
        echo "Discipline	";
        foreach (range(0,4) as $one)
        {
          echo "$statuscodes[$one]	";
        }
        echo "
";
        foreach ($disciplines as $one => $two)
        {
          echo "
";
          echo "$two (".intval($disciplinecounts[$one]).")	";
          $statuscounts = find_discipline_statuses($one);
          foreach (range(0,4) as $three)
          {
            $statustotals[$three] += $statuscounts[$three];
            if (!isset($disciplinecounts[$one]) || $disciplinecounts[$one]==0)
            {
              $fraction = 0;
            }
            else
            {
              $fraction = 100*$statuscounts[$three]/intval($disciplinecounts[$one]);
            }
            echo "".$statuscounts[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
\n";
        }
        # summary line
        echo "
------------------
";
        echo "
";
        echo "";
        echo count($disciplines)." Disciplines (".array_sum($disciplinecounts)." dissertations)";
        echo "	";
        foreach (range(0,4) as $three)
        {
          $fraction = 100*$statustotals[$three]/array_sum($disciplinecounts);
          echo "".$statustotals[$three];
          if ($fraction != 0)
          {
            echo " (".sprintf("%.1f",$fraction)."%)";
          }
          echo "	";
        }
        echo "
";
        echo "
\n";
        echo "
\n";

        break;

        ###############################################
        case "show_discipline":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {

          $discipline_id = intval($_GET['id']);

          # Show Discipline Name
          $query = "SELECT d.title as disciplinename
                FROM disciplines d
                WHERE
                  d.id = '$discipline_id'
              ";

          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }

          echo "
$disciplinename
";

          # Show Histograph
          $counts = array();
          echo "
\n";
          echo "Dissertations by Year:
\n";
          $query = "SELECT completedyear, count(*) as disscount FROM dissertations WHERE discipline_id='$discipline_id' GROUP BY completedyear";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $counts[$line['completedyear']] = $line['disscount'];
          }
          if (count($counts)>0)
          {
            $bigyear = max($counts);
            echo "
\n";
            echo "
\n";
              foreach ($counts as $one => $two)
              {
                $height=$two*intval(200/$bigyear);
                echo "	\n";
              }
            echo "
";
            echo "
\n";
            foreach ($counts as $one => $two)
            {
              echo "";
              if ($one%10==0)
              {
                echo $one;
              }
              echo "	\n";
            }
            echo "
";
            echo "
\n";
          }
          echo "
\n";
        }

        $schools = find_schools($discipline_id);
        $dissertation_count = 0;
        $statustotals = array(0,0,0,0,0);
        echo "
Schools Represented
\n";

        echo "
\n";
        echo "
\n";
        echo "
";
        echo "School	";
        foreach (range(0,4) as $one)
        {
          echo "$statuscodes[$one]	";
        }
        echo "
";
        foreach ($schools as $one => $two)
        {
          $statuscounts = find_dept_statuses($one,$discipline_id);
          $dissertation_count += array_sum($statuscounts);
          echo "
";
          echo "$two (".array_sum($statuscounts).")	";
          foreach (range(0,4) as $three)
          {
            $statustotals[$three] += $statuscounts[$three];
            $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);
            echo "".$statuscounts[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
\n";
        }
        # summary line
        echo "
------------------
";
        echo "
";
        echo "";
        echo count($schools)." Schools ($dissertation_count dissertations)";
        echo "	";
        foreach (range(0,4) as $three)
        {

          if (array_sum($statustotals)==0)
          {
            $fraction = 0;
          }
          else
          {
            $fraction = 100*$statustotals[$three]/array_sum($statustotals);
          }
          echo "".$statustotals[$three];
          if ($fraction != 0)
          {
            echo " (".sprintf("%.1f",$fraction)."%)";
          }
          echo "	";
        }
        echo "
";
        echo "
\n";
        echo "
\n";

        # link to edit the discipline name
        if (is_empty_discipline($_GET['id']))
        {
          echo "

";
          echo "
Edit Discipline Name
\n";
        }

        break;

      ###############################################
      case "show_school":

        if (!$_GET['id']){action_box("No ID given.");}
        else
        {

          $school_id = intval($_GET['id']);

          # Show School Name
          $query = "SELECT s.fullname as schoolname, s.country
                FROM schools s
                WHERE
                  s.id = '$school_id'
              ";

          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }

          echo "
$schoolname ($country)
";

          # Show Histograph
          echo "
\n";
          echo "Dissertations by Year:
\n";
          $query = "SELECT completedyear, count(*) as disscount FROM dissertations WHERE school_id='$school_id' GROUP BY completedyear";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $counts[$line['completedyear']] = $line['disscount'];
          }
          $bigyear = max($counts);
          echo "
\n";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            $height=$two*intval(200/$bigyear);
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            echo "";
            if ($one%10==0)
            {
              echo $one;
            }
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          echo "
\n";

          $disciplines = find_disciplines($school_id);
          $dissertation_count = 0;
          $statustotals = array(0,0,0,0,0);
          echo "
Disciplines Represented
\n";

          echo "
\n";
          echo "
\n";
          echo "
";
          echo "Discipline	";
          foreach (range(0,4) as $one)
          {
            echo "$statuscodes[$one]	";
          }
          echo "
";
          foreach ($disciplines as $one => $two)
          {
            $statuscounts = find_dept_statuses($school_id,$one);
            $dissertation_count += array_sum($statuscounts);
            echo "
";
            echo "$two (".array_sum($statuscounts).")	";
            foreach (range(0,4) as $three)
            {
              $statustotals[$three] += $statuscounts[$three];
              $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);
              echo "".$statuscounts[$three];
              if ($fraction != 0)
              {
                echo " (".sprintf("%.1f",$fraction)."%)";
              }
              echo "	";
            }
            echo "
\n";
          }
          # summary line
          echo "
------------------
";
          echo "
";
          echo "";
          echo count($disciplines)." Disciplines ($dissertation_count dissertations)";
          echo "	";
          foreach (range(0,4) as $three)
          {
            $fraction = 100*$statustotals[$three]/array_sum($statustotals);
            echo "".$statustotals[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
";
          echo "
\n";
          echo "
\n";
        }

        # link to edit the school info
        if (is_empty_school($_GET['id']))
        {
          echo "

";
          echo "
Edit School Information
\n";
        }

        break;

      ###############################################
      case "show_schools":

        $statustotals = array(0,0,0,0,0);
        $schools = find_schools();
        $schoolcounts = find_school_counts();

        if (is_admin()){
          echo "
Add a New School to the Database
\n";
        }
        echo "
Schools Represented Across All Disciplines
\n";

        echo "
\n";
        echo "
\n";
        echo "
";
        echo "School	";
        foreach (range(0,4) as $one)
        {
          echo "$statuscodes[$one]	";
        }
        echo "
";
        foreach ($schools as $one => $two)
        {
          echo "
";
          echo "$two (".intval($schoolcounts[$one]).")	";
          $statuscounts = find_school_statuses($one);
          foreach (range(0,4) as $three)
          {
            $statustotals[$three] += $statuscounts[$three];
            if (intval($schoolcounts[$one]) == 0){
              $fraction = 0;
            }
            else{
              $fraction = 100*$statuscounts[$three]/intval($schoolcounts[$one]);
            }
            echo "".$statuscounts[$three];
            if ($fraction != 0)
            {
              echo " (".sprintf("%.1f",$fraction)."%)";
            }
            echo "	";
          }
          echo "
\n";
        }
        # summary line
        echo "
------------------
";
        echo "
";
        echo "";
        echo count($schools)." Schools (".array_sum($schoolcounts)." dissertations)";
        echo "	";
        foreach (range(0,4) as $three)
        {
          $fraction = 100*$statustotals[$three]/array_sum($schoolcounts);
          echo "".$statustotals[$three];
          if ($fraction != 0)
          {
            echo " (".sprintf("%.1f",$fraction)."%)";
          }
          echo "	";
        }
        echo "
";
        echo "
\n";
        echo "
\n";

        break;

      ###############################################
      case "show_department":

        if (!$_GET['d'] || !$_GET['s']){action_box("No ID given.");}
        else
        {

          $school_id = $_GET['s'];
          $discipline_id = $_GET['d'];

          # Show Discipline Name
          $query = "SELECT d.title as disciplinename
                FROM disciplines d
                WHERE
                  d.id = '$discipline_id'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }
          # Show School Name
          $query = "SELECT s.fullname as schoolname, s.country
                FROM schools s
                WHERE
                  s.id = '$school_id'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }

          echo "

          $disciplinename
          @
          $schoolname ($country)

          ";

          # Advisor and Committee Activity
          echo "
Dissertation Activity and MPACT Scores (click table headings to sort)
";

          echo "
";
          $theprofs = find_profs_at_dept($school_id,$discipline_id);
          if (count($theprofs)>0)
          {
            $sortedprofs = array();
            $proflist = "";
            $query = "SELECT id FROM people WHERE id IN (";
            foreach ($theprofs as $prof){$proflist .= "$prof,";}
            $proflist = rtrim($proflist, ",");
            $query .= "$proflist) ORDER BY ac_score DESC";
            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
            while ( $line = mysqli_fetch_array($result)) {
              $sortedprofs[] = $line['id'];
            }
            $profcount = 0;
            echo "
\n";
            echo "

              -
              Name
              A
              C
              A+C
              G
              T
              TA
              TD
              W

\n";
            foreach ($sortedprofs as $one)
            {
              echo "
";
              $profcount++;
              echo "$profcount.	";
              echo "";
              echo get_person_link($one);
              echo "	";
              $scores = mpact_scores($one);
              echo "".$scores['A']."	";
              echo "".$scores['C']."	";
              echo "".$scores['AC']."	";
              echo "".$scores['G']."	";
              echo "".$scores['T']."	";
              echo "".$scores['TA']."	";
              echo "".$scores['TD']."	";
              echo "".$scores['W']."	";
              echo "
\n";
            }
            echo "
\n";
            echo "
";
          }
          else
          {
            echo "
- None Listed
\n";
          }
          echo "
";

          # Dissertations Conferred
          echo "
Dissertations Conferred
";

          # Show Histograph
          echo "
\n";
          echo "Dissertations by Year:
\n";
          $query = "SELECT completedyear, count(*) as disscount
                      FROM dissertations
                      WHERE
                        school_id='$school_id' AND
                        discipline_id=$discipline_id
                      GROUP BY
                        completedyear";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            $counts[$line['completedyear']] = $line['disscount'];
          }
          echo "
\n";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            $height=$two*10;
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          foreach ($counts as $one => $two)
          {
            echo "";
            if ($one%10==0)
            {
              echo $one;
            }
            echo "	\n";
          }
          echo "
";
          echo "
\n";
          echo "
\n";

          $query = "SELECT d.person_id, d.completedyear, d.status
                FROM
                  dissertations d,
                  schools s,
                  people p,
                  names n
                WHERE
                  s.id = '$school_id' AND
                  d.discipline_id = '$discipline_id' AND
                  d.school_id = s.id AND
                  d.person_id = p.id AND
                  p.preferred_name_id = n.id
                ORDER BY
                  d.completedyear ASC, n.lastname ASC, n.firstname ASC
              ";

          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
            $year_conferred[$person_id] = $completedyear;
            $degree_status[$person_id] = $status;
          }

          $schoolcount = 0;
          echo "
";
          foreach ($year_conferred as $person => $year)
          {
            $schoolcount++;
            echo "
$schoolcount. ";
            echo get_person_link($person);
            echo " ($year)";
            if ($degree_status[$person] < 4)
            {
              echo " ---------------------------------- ".$statuscodes[$degree_status[$person]];
            }
          }
          echo "
";

        }

        break;

      ###############################################
      default:
        // oops - not supposed to be here
        action_box("invalid action",1);
    }
  }
  else
  {

    if (isset($_GET['show']))
    {
      if ($_GET['show'] == "all")
      {
        $alphabet_limiter = ""; // set it to show everything
      }
      else
      {
        $alphabet_limiter = $_GET['show'];
      }

      show_alphabet();

      if (is_admin())
      {
        echo "
Add a New Person to the Database
\n";
      }

      if (is_admin()){
        echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
        echo "<input type=\"hidden\" name=\"op\" value=\"merge_confirm\">";
        echo "<input type=\"hidden\" name=\"show\" value=\"$alphabet_limiter\">";
        echo "<input type=\"submit\" name=\"submit\" value=\"Merge These People\">";
      }

      // GET ALL DISSERTATIONS IN A HASH
      $disciplines = find_disciplines();
      $query = "SELECT id, person_id, discipline_id FROM dissertations";
      $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
      while ( $line = mysqli_fetch_array($result)) {
        $graduates[$line['person_id']] = $line['discipline_id'];
      }

      // LOOP THROUGH ALL PEOPLE FOR THIS LETTER
      echo "
\n";
      echo "
\n";
      if (is_admin()){echo "Merge	\n";}
      echo "Count	\n";
      echo "Last Name	\n";
      echo "Full Name	\n";
      echo "Dissertation Discipline	\n";
      echo "
\n";

      $query = "SELECT n.id, n.firstname,
            n.middlename, n.lastname, n.suffix,
            p.id as person_id
            FROM names n, people p
            WHERE
              n.id = p.preferred_name_id AND
              n.lastname LIKE '".$alphabet_limiter."%'
            ORDER BY n.lastname ASC, n.firstname ASC
            ";

      $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

      $rowcount = 0;
      while ( $line = mysqli_fetch_array($result)) {
        extract($line);

        $rowcount++;

        echo "
";
           if (is_admin()){
          echo "<input type=\"checkbox\" name=\"mergers[]\" value=\"$person_id\">	";
           }
        echo "$rowcount.	";
        echo "$lastname	";
        $discipline = isset($graduates[$person_id]) ? $disciplines[$graduates[$person_id]] : "";
        echo "$firstname $middlename $lastname $suffix	";
        echo "$discipline	";
        echo "
";

        if (is_admin()){
          if ($rowcount % 25 == 0){
            echo "
	<input type=\"submit\" name=\"submit\" value=\"Merge These People\">
";
          }
        }

      }

      echo "
\n";

      if (is_admin()){
        echo "<input type=\"submit\" name=\"submit\" value=\"Merge These People\">";
        echo "</form>";
       }

      echo "

\n";

      show_alphabet();

    }
    else
    {
      // DISPLAY THE FRONT PAGE

      action_box("Front Page...",0.1,"./");

    }

  }

}

###############################################
// SOMETHING WAS SUBMITTED - through a form
else
{

  if ($_POST['op'] != "login"){
    // Display header
    xhtml_web_header();
  }

  switch ($_POST['op'])
  {
    ###############################################
    case "login";

      $host_info = get_environment_info();
      if ($host_info['hostname'] == "sils"){
        # no logins here - go to dev server
        action_box("No Logins Here...",2,$_SERVER['SCRIPT_NAME']);
      }
      else{
        # check credentials / start session
        $query = "SELECT id, username, fullname FROM users
                    WHERE username = '".addslashes($_POST['username'])."'
                    AND password = '".addslashes($_POST['password'])."'";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        $line = mysqli_fetch_array($result);
        if (isset($line['id'])){
          # save cookie info for one week
          setcookie('MPACT_userid',$line['id'],time()+60*60*24*7);
          # redirect
          header("Location: ".$_SERVER['SCRIPT_NAME']);
        }
        else{
          // Display header
          xhtml_web_header();
          # incorrect credentials
          action_box("Please try again...",2,$_SERVER['SCRIPT_NAME']."?op=login");
        }
      }

      break;

    ###############################################
    case "glossary_edit";
      if (is_admin())
      {

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $query = "UPDATE glossary
              SET
                definition = '".$_POST['definition']."'
              WHERE
                id = '".$_POST['id']."'
            ";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        # log it
        mpact_logger("updated glossary [".$_POST['term']." (".$_POST['id'].")] to (".$_POST['definition'].")");

        action_box("Definition Saved",2,$_SERVER['SCRIPT_NAME']."?op=glossary");
      }
      else
      {
        not_admin();
      }
      break;

    ###############################################
    case "merge_confirm":

      if (is_admin()){

        echo "<form id=\"merge_em\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">";
        echo "<input type=\"hidden\" name=\"op\" value=\"merge_doit\">";
        echo "<input type=\"hidden\" name=\"show\" value=\"".$_POST['show']."\">";

        foreach ($_POST['mergers'] as $one)
        {
          echo "

";
          echo "
[$one]
";
          echo draw_tree( $one );
          echo "<input type=\"hidden\" name=\"mergers[]\" value=\"$one\">";
          echo "

";
        }

        echo "<input type=\"submit\" name=\"submit\" value=\"YES, THESE ARE THE SAME PERSON - MERGE THEM NOW\">";
        echo "</form>";

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "search":

      $results = people_search($_POST['q']);

      if (count($results) > 0)
      {
        echo "
People Search Results for [".$_POST['q']."]:
";
      }

      echo "
\n";
      $count = 0;
      foreach ($results as $person_id)
      {
        $count++;
        $schoolinfo = find_persons_school($person_id);
        echo "$count. ".get_person_link($person_id);
        if ($schoolinfo['completedyear'])
        {
          echo " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
        }
        echo "
\n";
      }
      if ($count < 1)
      {
        echo "
\n";
        echo "There were no results for [".$_POST['q']."].";
        if (strlen($_POST['q']) < 2)
        {
          echo "

\n";
          echo "Please use at least two characters to search.";
        }
        else
        {
          if (is_admin()){
            echo "

\n";
            echo "
Add a New Person to the Database
\n";
          }
        }
        echo "
\n";
      }

      echo "
\n";

      break;

    ###############################################
    case "search_title_abstract":

      $results = title_abstract_search($_POST['qta']);

      if (count($results) > 0)
      {
        echo "
Title/Abstract Search Results for [".$_POST['qta']."]:
";
      }

      echo "
\n";
      $count = 0;
      foreach ($results as $person_id)
      {
        $count++;
        $schoolinfo = find_persons_school($person_id);
        echo "$count. ".get_person_link($person_id);
        if ($schoolinfo['completedyear'])
        {
          echo " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
        }
        echo "
\n";
      }
      if ($count < 1)
      {
        echo "
\n";
        echo "There were no results for [".$_POST['qta']."].";
        if (strlen($_POST['qta']) < 2)
        {
          echo "

\n";
          echo "Please use at least two characters to search.";
        }
        else
        {
          if (is_admin()){
            echo "

\n";
          }
        }
        echo "
\n";
      }

      echo "
\n";

      break;

      ###############################################
      case "search_notes":

        if (is_admin()){

          $results = notes_search($_POST['qn']);

          if (count($results) > 0)
          {
            echo "
Admin Notes Search Results for [".$_POST['qn']."]:
";
          }

          echo "
\n";
          $count = 0;
          foreach ($results as $person_id)
          {
            $count++;
            $schoolinfo = find_persons_school($person_id);
            echo "$count. ".get_person_link($person_id);
            if ($schoolinfo['completedyear'])
            {
              echo " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
            }
            echo "
\n";
          }
          if ($count < 1)
          {
            echo "
\n";
            echo "There were no results for [".$_POST['qm']."].";
            if (strlen($_POST['qn']) < 2)
            {
              echo "

\n";
              echo "Please use at least two characters to search.";
            }
            else
            {
              if (is_admin()){
                echo "

\n";
              }
            }
            echo "
\n";
          }

          echo "
\n";
        }
        else
        {
           not_admin();
        }

        break;

    ###############################################
    case "merge_doit":

      if (is_admin()){

        # delete the family tree's dotgraphs of each person
        foreach ($_POST['mergers'] as $one)
        {
          delete_associated_dotgraphs($one);
        }

        # pop off one of the people_ids
        $into = array_pop($_POST['mergers']);

        # merge each remaining person into the one above
        foreach ($_POST['mergers'] as $one)
        {
          merge_two_people($one,$into);
        }

        # recalculate MPACT scores for merged person id
        calculate_scores($into);

        action_box("Merge was Successful",2,$_SERVER['SCRIPT_NAME']."?show=".$_POST['show']);

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_discipline":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['title'] == "")
        {
          action_box("Need to have at least a Discipline Title.",3,$_SERVER['SCRIPT_NAME']."?op=create_discipline");
        }
        elseif (is_duplicate_discipline($_POST['title']))
        {
          action_box("Discipline (".$_POST['title'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");
        }
        else
        {

          # Create Discipline
          $query = "INSERT disciplines
                SET
                  title   = '".$_POST['title']."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          # Get the just created discipline_id
          $query = "SELECT id as new_discipline_id, title FROM disciplines
                WHERE
                  title   = '".$_POST['title']."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }
          # log it
          mpact_logger("created discipline[".$new_discipline_id."] (".$title.")");

          action_box("Discipline Created",2,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_discipline":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['title'] == "")
        {
          action_box("Need to have at least a Discipline Title.",3,$_SERVER['SCRIPT_NAME']."?op=edit_discipline&id=".$_POST['discipline_id']."");
        }
        elseif (is_duplicate_discipline($_POST['title']))
        {
          action_box("Discipline (".$_POST['title'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");
        }
        else
        {

          # Edit Discipline
          $query = "UPDATE disciplines
                SET
                  title   = '".$_POST['title']."'
                WHERE
                  id = '".$_POST['discipline_id']."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          # log it
          mpact_logger("edited discipline[".$_POST['discipline_id']."] (".$_POST['title'].")");

          action_box("Discipline Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_disciplines");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_school":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $_POST = array_map('trim',$_POST);

        if ($_POST['fullname'] == "" || $_POST['country'] == "")
        {
          action_box("Need to have at least a School name and Country.",3,$_SERVER['SCRIPT_NAME']."?op=create_school");
        }
        elseif (is_duplicate_school($_POST['fullname']))
        {
          action_box("School (".$_POST['fullname'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_schools");
        }
        else
        {

          # Create School
          $query = "INSERT schools
                SET
                  fullname   = '".$_POST['fullname']."',
                  country   = '".$_POST['country']."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          # Get the just created school_id
          $query = "SELECT id as new_school_id, fullname FROM schools
                WHERE
                  fullname   = '".$_POST['fullname']."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }
          # log it
          mpact_logger("created school[".$new_school_id."] (".$fullname.")");

          action_box("School Created",2,$_SERVER['SCRIPT_NAME']."?op=show_schools");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_school":

      if (is_admin()){
        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['fullname'] == "" || $_POST['country'] == "")
        {
          action_box("Need to have at least a School name and Country.",3,$_SERVER['SCRIPT_NAME']."?op=edit_school&id=".$_POST['school_id']."");
        }
        elseif (is_duplicate_school($_POST['fullname']))
        {
          action_box("School (".$_POST['fullname'].") already exists.",3,$_SERVER['SCRIPT_NAME']."?op=show_schools");
        }
        else
        {

          # Edit School
          $query = "UPDATE schools
                SET
                  fullname   = '".$_POST['fullname']."',
                  country    = '".$_POST['country']."'
                WHERE
                  id = '".$_POST['school_id']."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          # log it
          mpact_logger("edited school[".$_POST['school_id']."] (".$_POST['fullname'].")");

          action_box("School Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_schools");

        }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_person":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if ($_POST['lastname'] == "")
        {
          action_box("Need to have at least a Last Name.",3,$_SERVER['SCRIPT_NAME']."?op=create_person");
        }
        else
        {
          # Create Name
          $query = "INSERT names
                SET
                  firstname   = '".$_POST['firstname']."',
                  middlename  = '".$_POST['middlename']."',
                  lastname    = '".$_POST['lastname']."',
                  suffix      = '".$_POST['suffix']."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          # Get the just created name_id
          $query = "SELECT id as new_name_id FROM names
                WHERE
                  firstname   = '".$_POST['firstname']."' AND
                  middlename  = '".$_POST['middlename']."' AND
                  lastname    = '".$_POST['lastname']."' AND
                  suffix      = '".$_POST['suffix']."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }

          # Create Person with new_name_id
          $query = "INSERT people
                SET
                  preferred_name_id = '".$new_name_id."',
                  degree = '".$_POST['degree']."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          # Get the just created person_id
          $query = "SELECT id as new_person_id FROM people
                WHERE
                  preferred_name_id = '".$new_name_id."'
                ORDER BY id DESC
                LIMIT 1
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
          while ( $line = mysqli_fetch_array($result)) {
            extract($line);
          }

          # Sync them together with new_person_id
          $query = "UPDATE names
                SET
                  person_id = '".$new_person_id."'
                WHERE
                  id = '".$new_name_id."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          $after = find_person($new_person_id);

          action_box("Person Created",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$new_person_id);

          # log it
          mpact_logger("created person[".$new_person_id."] (".$after['fullname'].")");

       }
     }
     else
     {
        not_admin();
     }

     break;

   ###############################################
   case "remove_mentor":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if (remove_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']))
        {
          action_box("Mentor Removed",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['student_id']);
        }
        else
        {
          action_box("Nope.");
        }

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "add_mentor":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);

        action_box("Mentor Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['student_id']);

      }
      else
      {
        not_admin();
      }

      break;

     ###############################################
     case "add_student":

        if (is_admin()){

          if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

          add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);

          action_box("Student Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['mentor_id']);

        }
        else
        {
           not_admin();
        }

        break;

    ###############################################
    case "add_name":

     if (is_admin()){

       if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $person = find_person($_POST['id']);

        $query = "INSERT names
              SET
                firstname   = '".$_POST['firstname']."',
                middlename  = '".$_POST['middlename']."',
                lastname    = '".$_POST['lastname']."',
                suffix      = '".$_POST['suffix']."',
                person_id   = '".$_POST['id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        # get the just created name_id
        $query = "SELECT id as new_name_id FROM names
              WHERE
                firstname   = '".$_POST['firstname']."' AND
                middlename  = '".$_POST['middlename']."' AND
                lastname    = '".$_POST['lastname']."' AND
                suffix      = '".$_POST['suffix']."'
              ORDER BY id DESC
              LIMIT 1
            ";
        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
        while ( $line = mysqli_fetch_array($result)) {
          extract($line);
        }

        # find that full name from the DB
        $added = find_name($new_name_id);

        action_box("Name Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);
        # log it
        mpact_logger("added name (".$added['fullname'].") for person[".$_POST['id']."] (".$person['fullname'].")");
     }
     else
     {
        not_admin();
     }

     break;

    ###############################################
    case "edit_name":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $before = find_name($_POST['name_id']);

        $query = "UPDATE names
              SET
                firstname   = '".$_POST['firstname']."',
                middlename  = '".$_POST['middlename']."',
                lastname    = '".$_POST['lastname']."',
                suffix      = '".$_POST['suffix']."'
              WHERE
                id = '".$_POST['name_id']."' AND
                person_id = '".$_POST['id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        $after = find_name($_POST['name_id']);

        # delete dotgraph for this person
        delete_associated_dotgraphs($_POST['id']);

        action_box("Name Saved",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);
        # log it
        mpact_logger("edited name[".$_POST['name_id']."] for person[".$_POST['id']."] from (".$before['fullname'].") to (".$after['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "add_url":

     if (is_admin()){

       if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $person = find_person(intval($_POST['person_id']));

        $query = "INSERT urls
              SET
                url         = '".$_POST['url']."',
                description = '".$_POST['description']."',
                updated_at  = now(),
                person_id   = '".$_POST['person_id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Reference URL Added",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['person_id']."#urls");
        # log it
        mpact_logger("added URL[".substr($_POST['url'], 0, 30)."] for person[".$_POST['person_id']."] (".$person['fullname'].")");
     }
     else
     {
        not_admin();
     }

     break;

    ###############################################
    case "edit_url":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $url = find_url(intval($_POST['id']));
        $person = find_person($url['person_id']);

        $query = "UPDATE urls
              SET
                url         = '".$_POST['url']."',
                description = '".$_POST['description']."',
                updated_at  = now()
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Reference URL Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$url['person_id']."#urls");
        # log it
        mpact_logger("edited URL[".substr($_POST['url'], 0, 30)."] for person[".$url['person_id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "delete_url":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $url = find_url(intval($_POST['id']));
        $person = find_person($url['person_id']);

        $query = "DELETE FROM urls
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Reference URL Deleted",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$url['person_id']."#urls");
        # log it
        mpact_logger("deleted URL[".substr($url['url'], 0, 30)."] for person[".$url['person_id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_degree":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $person = find_person(intval($_POST['id']));

        $query = "UPDATE people
              SET
                degree         = '".$_POST['degree']."'
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Degree Edited",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$person['id']);
        # log it
        mpact_logger("edited degree[".$_POST['degree']."] for person[".$person['id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "create_dissertation":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $schools = find_schools();

        $person = find_person($_POST['person_id']);

        $query = "INSERT INTO dissertations
              SET
                person_id           = '".$_POST['person_id']."',
                discipline_id       = '".$_POST['discipline_id']."',
                school_id           = '".$_POST['school_id']."',
                completedyear       = '".$_POST['completedyear']."',
                status              = '".$_POST['status']."',
                title               = '".$_POST['title']."',
                abstract            = '".$_POST['abstract']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        $query = "UPDATE people
                  SET degree = '".$_POST['degree']."'
                  WHERE
                    id = '".$_POST['person_id']."'";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Dissertation Created",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['person_id']);
        # log it
        $dissertation = find_dissertation_by_person($_POST['person_id']);
        mpact_logger("create dissertation[".$dissertation['id']."] (".$person['fullname'].") with school[".$dissertation['school_id']."] (".$schools[$dissertation['school_id']].") in year(".$dissertation['completedyear'].") with status (".$statuscodes[$_POST['status']].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_dissertation":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $disciplines = find_disciplines();
        $schools = find_schools();

        $dissertation = find_dissertation($_POST['id']);
        $person = find_person($dissertation['person_id']);

        $query = "UPDATE dissertations
              SET
                school_id           = '".$_POST['school_id']."',
                discipline_id       = '".$_POST['discipline_id']."',
                completedyear       = '".$_POST['completedyear']."',
                status              = '".$_POST['status']."',
                notes               = '".$_POST['notes']."',
                title               = '".$_POST['title']."',
                abstract            = '".$_POST['abstract']."'
              WHERE
                id = '".$_POST['id']."'
            ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        $query = "UPDATE people
                  SET degree = '".$_POST['degree']."'
                  WHERE
                    id = '".$_POST['person_id']."'";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Dissertation Saved",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['person_id']);
        # log it
        mpact_logger("edit dissertation[".$_POST['id']."] (".$person['fullname'].") from school[".$dissertation['school_id']."] (".$schools[$dissertation['school_id']].") in year(".$dissertation['completedyear'].") to school[".$_POST['school_id']."] (".$schools[$_POST['school_id']].") in year(".$_POST['completedyear'].")");
        # look for changes
          # degree
          if ($person['degree'] != $_POST['degree'])
          {
            mpact_logger($dissertation['id']." updated degree [".$_POST['degree']."]","dissertation");
          }
          # discipline
          if ($dissertation['discipline_id'] != $_POST['discipline_id'])
          {
            mpact_logger($dissertation['id']." updated discipline [".$_POST['discipline_id']." (".$disciplines[$_POST['discipline_id']].")]","dissertation");
          }
          # school
          if ($dissertation['school_id'] != $_POST['school_id'])
          {
            mpact_logger($dissertation['id']." updated school [".$_POST['school_id']." (".$schools[$_POST['school_id']].")]","dissertation");
          }
          # year
          if ($dissertation['completedyear'] != $_POST['completedyear'])
          {
            mpact_logger($dissertation['id']." updated completedyear [".$_POST['completedyear']."]","dissertation");
          }
          # title
          if ($dissertation['title'] != $_POST['title'])
          {
            mpact_logger($dissertation['id']." updated title [".$_POST['title']."]","dissertation");
          }
          # abstract
          if ($dissertation['abstract'] != $_POST['abstract'])
          {
            mpact_logger($dissertation['id']." updated abstract [".$_POST['abstract']."]","dissertation");
          }
          # status
          if ($dissertation['status'] != $_POST['status'])
          {
            mpact_logger($dissertation['id']." updated status [".$statuscodes[$_POST['status']]."]","dissertation");
          }
          # status
          if ($dissertation['notes'] != $_POST['notes'])
          {
            mpact_logger($dissertation['id']." updated notes [".$_POST['notes']."]","dissertation");
          }
      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "delete_person":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        if (delete_person($_POST['id']))
        {
          action_box("Person Deleted",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);
        }

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "delete_name":

      if (is_admin()){

        if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}

        $name = find_name($_POST['name_id']);
        $person = find_person($_POST['id']);

        $query = "DELETE FROM names
            WHERE
              id = '".$_POST['name_id']."' AND
              person_id = '".$_POST['id']."'
          ";

        $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

        action_box("Name Deleted",2,$_SERVER['SCRIPT_NAME']."?op=show_tree&id=".$_POST['id']);

        # log it
        mpact_logger("deleted name[".$_POST['name_id']."] (".$name['fullname'].") from person[".$person['id']."] (".$person['fullname'].")");

      }
      else
      {
         not_admin();
      }

      break;

    ###############################################
    case "edit_school":

      break;

    ###############################################
    default:
      // oops - not supposed to be here
      action_box("oops, back to the front page...",2);

  }

}

xhtml_web_footer();

?>

<?php

###########    INCLUDE FUNCTIONS     ####################

# -------------------------------------------------------------------------------
function is_admin(){
  if (isset($_SESSION['MPACT']['username']))
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

# -------------------------------------------------------------------------------
function not_admin(){
   action_box("Action Not Permitted.");
   mpact_logger("not admin");
}

# -------------------------------------------------------------------------------
# from http://www.richardlord.net/blog/php-password-security
// get a new salt - 8 hexadecimal characters long
// current PHP installations should not exceed 8 characters
// on dechex( mt_rand() )
// but we future proof it anyway with substr()
function generate_PasswordSalt(){
  return substr( str_pad( dechex( mt_rand() ), 8, '0', STR_PAD_LEFT ), -8 );
}

# -------------------------------------------------------------------------------
# from http://www.richardlord.net/blog/php-password-security
// calculate the hash from a salt and a password
function generate_PasswordHash( $salt, $password ){
  return $salt . ( sha1( $salt . $password ) );
}

# -------------------------------------------------------------------------------
# from http://www.richardlord.net/blog/php-password-security
// compare a password to a hash
function comparePassword( $password, $hashed ){
  $salt = substr( $hashed, 0, 8 );
  return $hashed == generate_PasswordHash( $salt, $password );
}

# -------------------------------------------------------------------------------
function mpact_logger($message,$type="general"){
  global $dbh;
  $ip = ($_SERVER['REMOTE_ADDR'] == "127.0.0.1") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
  if (!get_magic_quotes_gpc()) {$message = addslashes($message);}
  $query = "INSERT logs
              SET
              logged_at = now(),
              ip        = '".$ip."',
              user      = '".$_SESSION['MPACT']['username']."',
              type      = '".$type."',
              message   = '".$message."',
              action    = '".$_SERVER['REQUEST_URI']."',
              agent     = '".$_SERVER['HTTP_USER_AGENT']."'
            ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
}

# -------------------------------------------------------------------------------
# http://us2.php.net/manual/en/function.array-diff.php#29808
function array_key_diff($ar1, $ar2) {  // , $ar3, $ar4, ...
   // returns copy of array $ar1 with those entries removed
   // whose keys appear as keys in any of the other function args
   $aSubtrahends = array_slice(func_get_args(),1);
   foreach ($ar1 as $key => $val)
       foreach ($aSubtrahends as $aSubtrahend)
           if (array_key_exists($key, $aSubtrahend))
               unset ($ar1[$key]);
   return $ar1;
}

# -------------------------------------------------------------------------------
function action_box($message,$bounce = "0",$location = "index.php"){

  echo "

  $message

  ";

  if ($bounce != "0"){
    echo "
    <meta http-equiv=\"Refresh\" content=\"$bounce;url=$location\">

    Forwarding in $bounce seconds (or click here to do the same)

    ";
  }

}

# -------------------------------------------------------------------------------
function xhtml_orig_web_header(){

  # make search box happy
  if (!isset($_POST['q'])){$_POST['q'] = "";}
  if (!isset($_POST['qta'])){$_POST['qta'] = "";}
  if (!isset($_POST['qn'])){$_POST['qn'] = "";}

  # print out header info
  echo "

  <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">

  <title>MPACT</title>

  <link rel=\"stylesheet\" type=\"text/css\" href=\"mpact.css\">

          <form id=\"main_mpact\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
            MPACT -
            Database -
            <input type=\"hidden\" name=\"op\" value=\"search\">
            People Search: <input type=\"text\" name=\"q\" size=\"10\" value=\"".$_POST['q']."\">
          </form> -
          <form id=\"main_mpact_title_abstract\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
          <input type=\"hidden\" name=\"op\" value=\"search_title_abstract\">
          Title/Abstract Search: <input type=\"text\" name=\"qta\" size=\"10\" value=\"".$_POST['qta']."\">
          </form>
";
  if (is_admin()){
    echo " - <form id=\"main_mpact_notes\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
    <input type=\"hidden\" name=\"op\" value=\"search_notes\">
    Admin Notes Search: <input type=\"text\" name=\"qn\" size=\"10\" value=\"".$_POST['qn']."\">
    </form>";
  }
  echo "

";
  if (is_admin()){
    echo $_SESSION['MPACT']['fullname']." (".$_SESSION['MPACT']['username'].") - Logout";
  }
  else{
    $host_info = get_environment_info();
    if ($host_info['hostname'] != "sils"){
      echo "Login";
    }
  }
echo "

  ";

}

# -------------------------------------------------------------------------------
function xhtml_web_header(){

  # make search box happy
  if (!isset($_POST['q'])){$_POST['q'] = "";}
  if (!isset($_POST['qta'])){$_POST['qta'] = "";}
  if (!isset($_POST['qn'])){$_POST['qn'] = "";}

  # print out header info
  echo "

  <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">

  <title>MPACT</title>
  <link rel=\"stylesheet\" type=\"text/css\" href=\"mpact.css\">

";

echo "

";
if (is_admin()){
  echo $_SESSION['MPACT']['fullname']." (".$_SESSION['MPACT']['username'].") - Logout";
}
else{
  echo "Login";
}
echo "

";
echo "

";

echo "

      Publications  •
      Project Statistics

      Glossary  •
      Schools  •
      Disciplines

      <form id=\"main_mpact\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
        <input type=\"hidden\" name=\"op\" value=\"search\">
        People Search: <input type=\"text\" name=\"q\" size=\"13\" value=\"".$_POST['q']."\">
      </form>

      <form id=\"main_mpact_title_abstract\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
        <input type=\"hidden\" name=\"op\" value=\"search_title_abstract\">
        Title/Abstract Search: <input type=\"text\" name=\"qta\" size=\"13\" value=\"".$_POST['qta']."\">
      </form>";
if (is_admin()){
  echo "

Administrator Pages";
  echo "<form id=\"main_mpact_notes\" method=\"post\" action=\"mpact.php\" class=\"inlinesearchbox\">
  <input type=\"hidden\" name=\"op\" value=\"search_notes\">
  Admin Notes Search: <input type=\"text\" name=\"qn\" size=\"13\" value=\"".$_POST['qn']."\">
  </form>";
}
echo "

  ";

}

# -------------------------------------------------------------------------------
function xhtml_web_footer(){
  echo "

";
}

# -------------------------------------------------------------------------------
function is_email_valid ($address)
{

	# http://www.zend.com/codex.php?id=285&single=1

    return (preg_match(
        '/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+'.   // the user name
        '@'.                                     // the ubiquitous at-sign
        '([-0-9A-Z]+\.)+' .                      // host, sub-, and domain names
        '([0-9A-Z]){2,4}$/i',                    // top-level domain (TLD)
        trim($address)));
}

# -------------------------------------------------------------------------------
function find_glossaryterms()
{
  global $dbh;
  $query = "SELECT id, term, definition FROM glossary";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  $glossaryterms = array();
  while ( $line = mysqli_fetch_array($result)) {
    $glossaryterms['ids'][$line['term']] = $line['id'];
    $glossaryterms['defs'][$line['id']] = $line['definition'];
  }
  return $glossaryterms;
}

# -------------------------------------------------------------------------------
function show_glossary()
{
  global $dbh;
  $query = "SELECT id, term, definition FROM glossary ORDER BY term ASC";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $results = array();
  while ( $line = mysqli_fetch_array($result)) {
    array_push($results,$line);
  }

  echo "
Glossary
\n";

  echo "
\n";

  foreach ($results as $one)
  {
    echo "".$one['term'].": ";
    echo $one['definition'];
    if (is_admin())
    {
      echo " EDIT ";
    }
    echo "

";
  }

  echo "
\n";

}

# -------------------------------------------------------------------------------
function show_glossaryterm($id)
{
  global $dbh;
  $query = "SELECT id, term, definition FROM glossary WHERE id = $id";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $results = array();
  while ( $line = mysqli_fetch_array($result)) {
    $glossaryterm = $line;
  }

  echo "
Full Glossary Listing
";

  echo "
Glossary
\n";

  echo "
\n";

  echo "".$glossaryterm['term'].": ";
  echo $glossaryterm['definition'];
  if (is_admin())
  {
    echo " EDIT ";
  }
  echo "

";

  echo "
\n";

}

# -------------------------------------------------------------------------------
function show_alphabet()
{

  $alphabet_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $alphabet = preg_split('//', $alphabet_letters, -1, PREG_SPLIT_NO_EMPTY);

  echo "
\n";
  echo "
Dissertation Authors and Mentors by Last Name
";
  echo "
";
  foreach ($alphabet as $letter)
  {
    if ($letter != "A"){echo " - ";}
    echo "$letter";
  }
  echo "
";
   echo "
\n";
}

# -------------------------------------------------------------------------------
function search_box($q="")
{
  echo "<form id=\"main_mpact\" method=\"post\" action=\"".$_SERVER['SCRIPT_NAME']."\">\n";
  echo "<input type=\"hidden\" name=\"op\" value=\"search\">\n";
  echo "
People Search: ";
  if ($q)
  {
    echo "<input type=\"text\" name=\"q\" value=\"$q\">\n";
  }
  else
  {
    echo "<input type=\"text\" name=\"q\">\n";
  }
  echo "
\n";
  echo "</form>\n";
}

# -------------------------------------------------------------------------------
function people_search($q)
{
  global $dbh;
  $q = trim($q);
  if (!get_magic_quotes_gpc()) {$q = addslashes($q);}
  $results = array();
  if (strlen($q) < 2){
    return $results;
  }

  $pieces = explode(" ",$q);
#  print_r($pieces);
  if (count($pieces) == 2)
  {
#    echo " ---------  two pieces";
    $query = "SELECT n.id as name_id, p.id as person_id
                FROM
                  names n, people p
                WHERE
                  (

                    (n.firstname  LIKE '%".$pieces[0]."%' OR
                    n.middlename LIKE '%".$pieces[0]."%' OR
                    n.lastname   LIKE '%".$pieces[0]."%' OR
                    n.suffix     LIKE '%".$pieces[0]."%')

                  AND

                    (n.firstname  LIKE '%".$pieces[1]."%' OR
                    n.middlename LIKE '%".$pieces[1]."%' OR
                    n.lastname   LIKE '%".$pieces[1]."%' OR
                    n.suffix     LIKE '%".$pieces[1]."%')

                  )
                  AND
                  n.person_id = p.id
                GROUP BY
                  p.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  elseif (count($pieces) == 3)
  {
#    echo " ---------  three pieces";
    $query = "SELECT n.id as name_id, p.id as person_id
                FROM
                  names n, people p
                WHERE
                  (

                    (n.firstname  LIKE '%".$pieces[0]."%' OR
                    n.middlename LIKE '%".$pieces[0]."%' OR
                    n.lastname   LIKE '%".$pieces[0]."%' OR
                    n.suffix     LIKE '%".$pieces[0]."%')

                  AND

                    (n.firstname  LIKE '%".$pieces[1]."%' OR
                    n.middlename LIKE '%".$pieces[1]."%' OR
                    n.lastname   LIKE '%".$pieces[1]."%' OR
                    n.suffix     LIKE '%".$pieces[1]."%')

                  AND

                    (n.firstname  LIKE '%".$pieces[2]."%' OR
                    n.middlename LIKE '%".$pieces[2]."%' OR
                    n.lastname   LIKE '%".$pieces[2]."%' OR
                    n.suffix     LIKE '%".$pieces[2]."%')

                  )
                  AND
                  n.person_id = p.id
                GROUP BY
                  p.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  else
  {
#    echo " ---  regular search - single piece";
    $query = "SELECT n.id as name_id, p.id as person_id
                FROM
                  names n, people p
                WHERE
                  (

                    (n.firstname  LIKE '%".$q."%' OR
                    n.middlename LIKE '%".$q."%' OR
                    n.lastname   LIKE '%".$q."%' OR
                    n.suffix     LIKE '%".$q."%')

                  )
                  AND
                  n.person_id = p.id
                GROUP BY
                  p.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    array_push($results,$line['person_id']);
  }
  return $results;
}

# -------------------------------------------------------------------------------
function title_abstract_search($q)
{
  global $dbh;
  $q = trim($q);
  if (!get_magic_quotes_gpc()) {$q = addslashes($q);}
  $results = array();
  if (strlen($q) < 2){
    return $results;
  }

  $pieces = explode(" ",$q);
#  print_r($pieces);
  if (count($pieces) == 2)
  {
#    echo " ---------  two pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.title   LIKE '%".$pieces[0]."%' OR
                    d.abstract LIKE '%".$pieces[0]."%')

                  AND

                    (d.title   LIKE '%".$pieces[1]."%' OR
                    d.abstract LIKE '%".$pieces[1]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  elseif (count($pieces) == 3)
  {
#    echo " ---------  three pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.title   LIKE '%".$pieces[0]."%' OR
                    d.abstract LIKE '%".$pieces[0]."%')

                  AND

                    (d.title   LIKE '%".$pieces[1]."%' OR
                    d.abstract LIKE '%".$pieces[1]."%')

                  AND

                    (d.title   LIKE '%".$pieces[2]."%' OR
                    d.abstract LIKE '%".$pieces[2]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  else
  {
#    echo " ---  regular search - single piece";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.title   LIKE '%".$q."%' OR
                    d.abstract LIKE '%".$q."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    array_push($results,$line['person_id']);
  }
  return $results;
}

# -------------------------------------------------------------------------------
function notes_search($q)
{
  global $dbh;
  $q = trim($q);
  if (!get_magic_quotes_gpc()) {$q = addslashes($q);}
  $results = array();
  if (strlen($q) < 2){
    return $results;
  }

  $pieces = explode(" ",$q);
#  print_r($pieces);
  if (count($pieces) == 2)
  {
#    echo " ---------  two pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.notes    LIKE '%".$pieces[0]."%')

                  AND

                    (d.notes    LIKE '%".$pieces[1]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  elseif (count($pieces) == 3)
  {
#    echo " ---------  three pieces";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.notes    LIKE '%".$pieces[0]."%')

                  AND

                    (d.notes    LIKE '%".$pieces[1]."%')

                  AND

                    (d.notes    LIKE '%".$pieces[2]."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  else
  {
#    echo " ---  regular search - single piece";
    $query = "SELECT d.person_id
                FROM
                  names n, dissertations d
                WHERE
                  (

                    (d.notes    LIKE '%".$q."%')

                  )
                  AND
                  n.person_id = d.person_id
                GROUP BY
                  d.id
                ORDER BY
                  n.lastname, n.suffix, n.firstname, n.middlename
              ";
  }
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    array_push($results,$line['person_id']);
  }
  return $results;
}

# -------------------------------------------------------------------------------
function encode_linebreaks($bigtext)
{
  # from http://us3.php.net/str_replace
  $order   = array("\r\n", "\n", "\r");
  $replace = '
';
  // Processes \r\n's first so they aren't converted twice.
  $with_breaks = str_replace($order, $replace, $bigtext);
  return $with_breaks;
}

# -------------------------------------------------------------------------------
function get_logs($offset="0")
{
  global $dbh;
#  echo "[$offset]";
  $query = "SELECT * FROM logs ORDER BY id DESC LIMIT 100";
  if ($offset != ""){$query .= " OFFSET $offset";}
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

#  echo $query;
  $entries = array();
  $counter = 0;
  while ( $line = mysqli_fetch_array($result)) {
    $counter++;
    $entries[$counter] = $line;
  }
  return $entries;
}

# -------------------------------------------------------------------------------
function get_dissertation_history($id)
{
  global $dbh;
  $query = "SELECT * FROM logs
              WHERE type='dissertation' AND message LIKE '$id %'
              ORDER BY id DESC";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

#  echo $query;
  $entries = array();
  $counter = 0;
  while ( $line = mysqli_fetch_array($result)) {
    $counter++;
    $entries[$counter] = $line;
  }
  return $entries;
}

# -------------------------------------------------------------------------------
function find_all_people()
{
  global $dbh;
  # return array of all people_ids in database (slow....)
    # all people
    $query = "SELECT id as person_id FROM people";
    $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
    while ( $line = mysqli_fetch_array($result)) {
      $people[] = $line['person_id'];
    }
    return $people;
}

# -------------------------------------------------------------------------------
function get_person_link($person_id)
{

  $disciplines = find_disciplines();
  $person = find_person($person_id);

  $fullname = trim($person['firstname']." ".$person['middlename']." ".$person['lastname']." ".$person['suffix']);

  $dissertation = find_dissertation_by_person($person_id);
  $discipline = isset($dissertation['discipline_id']) ? $disciplines[$dissertation['discipline_id']] : "";

  $link = "".$fullname."";

  return $link;

}

# -------------------------------------------------------------------------------
function find_orphans()
{
  global $dbh;

  # finding people with no dissertation and no students

  # all people
  $query = "SELECT
              p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix
            FROM
              people p, names n
            WHERE
              p.preferred_name_id = n.id
            ORDER BY n.lastname,n.firstname,n.middlename
          ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $people[$line['person_id']] = $line;
#    echo " ".$line['person_id']."
\n";
  }

  echo "people: ".count($people)."
\n";

  # with dissertations only
  $query = "SELECT
              p.id as person_id
            FROM
              people p, dissertations d
            WHERE
              d.person_id = p.id
          ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $with_dissertations[$line['person_id']] = $line;
#    echo " ".$line['person_id']."
\n";
  }

  echo "dissertations: ".count($with_dissertations)."
\n";

  # all people - dissertations = teachers only
  $potentialmentors = array_key_diff($people,$with_dissertations);

  echo "potential mentors: ".count($potentialmentors)."
\n";

  # orphans = teachers who don't have students
  # get advisorships
  $query = "SELECT person_id FROM advisorships";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    $advisors[$line['person_id']] = $line;
  }
  echo "advisors: ".count($advisors)."
\n";
  # get committeeships
  $query = "SELECT person_id FROM committeeships";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    $committeemembers[$line['person_id']] = $line;
  }
  echo "committeemembers: ".count($committeemembers)."
\n";
  # subtract advisorships from teachers
  $potentialmentors = array_key_diff($potentialmentors,$advisors);
  # subtract committeeships from remaining teachers
  $orphans = array_key_diff($potentialmentors,$committeemembers);
  echo "orphans: ".count($orphans)."
\n";

  return $orphans;

}

# -------------------------------------------------------------------------------
function is_orphan($person_id)
{
  global $dbh;
  # confirm person exists
  $query = "SELECT * FROM people WHERE id = '".$person_id."'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  $line = mysqli_fetch_array($result);
  if (!$line['id']){echo "not a person";return 0;}
  # confirm no dissertation
  $query = "SELECT * FROM dissertations WHERE person_id = '".$person_id."'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    echo "found a dissertation";
    return 0;
  }
  # confirm not a committeemember
  $query = "SELECT * FROM committeeships WHERE person_id = '".$person_id."'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    echo "found a committeeship";
    return 0;
  }
  # confirm not an advisor
  $query = "SELECT * FROM advisorships WHERE person_id = '".$person_id."'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    echo "found an advisorship";
    return 0;
  }
  return 1;
}
# -------------------------------------------------------------------------------
function delete_person($person_id)
{
  global $dbh;
  if (is_orphan($person_id))
  {
    $before = find_person($person_id);
    # delete all names
    $query = "DELETE FROM names WHERE person_id = '".$person_id."'";
    $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
    # delete the person
    $query = "DELETE FROM people WHERE id = '".$person_id."' LIMIT 1";
    $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
    # log it
    mpact_logger("deleted person[".$person_id."] (".$before['fullname'].")");
    return 1;
  }
  else
  {
    action_box("Not an orphan - Cannot delete this person.");
    return 0;
  }
}
# -------------------------------------------------------------------------------
function remove_duplicate_names($person_id)
{
  global $dbh;

  $names = array();
  $deleteme = array();

  $before = find_person($person_id);

  // get the preferred_name_id
  $query = "SELECT preferred_name_id
        FROM people
        WHERE id = '".$person_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    extract($line);
  }

  // get the full preferred_name
  $query = "SELECT * FROM names
        WHERE
          id = '".$preferred_name_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $fullname = "".$line['firstname']." ".$line['middlename']." ".$line['lastname']." ".$line['suffix']."";
    $names[$fullname] = $line['id'];
  }

  // get the rest of the names for this person
  $query = "SELECT * FROM names
        WHERE
          person_id = '".$person_id."' AND
          id != '".$preferred_name_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $fullname = "".$line['firstname']." ".$line['middlename']." ".$line['lastname']." ".$line['suffix']."";
    if (isset($names[$fullname]))
    {
      $deleteme[] = $line['id'];
    }
    else
    {
      $names[$fullname] = $line['id'];
    }
  }

  // delete each deleteme id
  foreach ($deleteme as $one)
  {
    $query = "DELETE FROM names
          WHERE
            id = '".$one."'
        ";

    $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  }

  # log it
  mpact_logger("removed duplicate names for person[".$person_id."] (".$before['fullname'].")");

}

# -------------------------------------------------------------------------------
function add_mentor($type,$student_id,$mentor_id)
{
  global $dbh;
  $student = find_person($student_id);
  $mentor = find_person($mentor_id);
  $dissertation = find_dissertation_by_person($student_id);

  if ($type == "A")
  {
    # find existing advisors for this student
    $advisors = find_advisors_for_person($student_id);
    # if new/different - then add them to the student's dissertation
    if (in_array($mentor_id,$advisors))
    {
      # skip - already listed as advisor
    }
    else
    {
      $query = "INSERT advisorships
                  SET
                  dissertation_id = '".$dissertation['id']."',
                  person_id       = '".$mentor_id."'
                ";
#      echo $query;
      $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("add advisorship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
      # delete existing dotgraphs - they'll need to be regenerated
      # has to happen after we add the advisor link itself
      delete_associated_dotgraphs($student_id);
    }
  }
  elseif ($type == "C")
  {
    # find existing committee members for this student
    $committee = find_committee_for_person($student_id);
    # if new/different - then add them to the student's dissertation
    if (in_array($mentor_id,$committee))
    {
      # skip - already on committee
    }
    else
    {
      $query = "INSERT committeeships
                  SET
                  dissertation_id = '".$dissertation['id']."',
                  person_id       = '".$mentor_id."'
                ";
#      echo $query;
      $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("add committeeship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
    }
  }
  else
  {
    # nothing
  }
}

# -------------------------------------------------------------------------------
function remove_mentor($type,$student_id,$mentor_id)
{
  global $dbh;
  $dissertation = find_dissertation_by_person($student_id);

  $student = find_person($student_id);
  $mentor = find_person($mentor_id);

  if ($type == "A")
  {
    # find dissertation id
    $dissertation = find_dissertation_by_person($student_id);
    # find existing advisors for this student
    $advisors = find_advisors_for_person($student_id);
    # if found in db, remove them
    if (!in_array($mentor_id,$advisors))
    {
      echo "not an advisor for this student";
      return 0;
    }
    else
    {
      # delete existing dotgraphs - they'll need to be regenerated
      # has to happen before we delete the advisor link itself
      delete_associated_dotgraphs($student_id);
      # delete the advisorship
      $query = "DELETE FROM advisorships
            WHERE
              person_id = '".$mentor_id."' AND
              dissertation_id = '".$dissertation['id']."'
            LIMIT 1
          ";
      $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("remove advisorship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
      return 1;
    }
  }
  elseif ($type == "C")
  {
    # find dissertation id
    $dissertation = find_dissertation_by_person($student_id);
    # find existing committee members for this student
    $committee = find_committee_for_person($student_id);
    # if found in db, remove them
    if (!in_array($mentor_id,$committee))
    {
      echo "not on committee for this student";
      return 0;
    }
    else
    {
      $query = "DELETE FROM committeeships
            WHERE
              person_id = '".$mentor_id."' AND
              dissertation_id = '".$dissertation['id']."'
            LIMIT 1
          ";
      $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
      # recalculate scores for both
      calculate_scores($student_id);
      calculate_scores($mentor_id);
      # log it
      mpact_logger("remove advisorship between mentor[".$mentor_id."] (".$mentor['fullname'].") to dissertation[".$dissertation['id']."] (".$student['fullname'].")");
      return 1;
    }
  }
  else
  {
    echo "has to be A or C, dude";
    return 0;
  }

}

# -------------------------------------------------------------------------------
function find_all_people_for_selectbox($with_dissertation="0")
{
  global $dbh;
  if ($with_dissertation == "0")
  {
    $query = "SELECT
                p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix
              FROM
                people p, names n
              WHERE
                p.preferred_name_id = n.id
              ORDER BY n.lastname,n.firstname,n.middlename
            ";
  }
  else
  {
    $query = "SELECT
                p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix
              FROM
                people p, names n, dissertations d
              WHERE
                p.preferred_name_id = n.id AND
                d.person_id = p.id
              ORDER BY n.lastname,n.firstname,n.middlename
            ";
  }
  // echo $query;
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $people[$line['person_id']] = $line;
  }

  return $people;
}

# -------------------------------------------------------------------------------
function merge_two_people($from_id, $into_id)
{
  global $dbh;

  $from_person = find_person($from_id);
  $into_person = find_person($into_id);

  $query = "UPDATE advisorships
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $query = "UPDATE dissertations
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $query = "UPDATE committeeships
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $query = "UPDATE urls
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  // move each 'from' name to the 'into' person

  $query = "UPDATE names
        SET
          person_id = '".$into_person['id']."'
        WHERE
          person_id = '".$from_person['id']."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  // remove any new duplicates in the names table

  remove_duplicate_names($into_person['id']);

  // remove 'from' person from the database

  $query = "DELETE FROM people
        WHERE
          id = '".$from_person['id']."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  # log it
  mpact_logger("merged two people [".$from_id."] (".$from_person['fullname'].") and [".$into_id."] (".$into_person['fullname'].")");

}

# -------------------------------------------------------------------------------
function find_aliases($person_id)
{
  global $dbh;

  $query = "SELECT preferred_name_id
        FROM people
        WHERE id = '".$person_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    extract($line);
  }

  $names = array();
  $query = "SELECT
        n.firstname, n.middlename,
        n.lastname, n.suffix, n.id
        FROM
          names n
        WHERE
          n.person_id = '".$person_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $names[$line['id']] = $line;
  }

  unset($names[$preferred_name_id]);

  return $names;
}

# -------------------------------------------------------------------------------
function find_person($person_id)
{
  global $dbh;
  $query = "SELECT
        n.firstname, n.middlename,
        n.lastname, n.suffix, p.degree,
        p.id, p.preferred_name_id
        FROM
          names n, people p
        WHERE
          p.preferred_name_id = n.id AND
          p.id = ".$person_id."
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $person = $line;
    $person['fullname'] = $person['firstname'];
    if ($person['middlename'] != ""){$person['fullname'] .= " ".$person['middlename'];}
    if ($person['lastname'] != ""){$person['fullname'] .= " ".$person['lastname'];}
    if ($person['suffix'] != ""){$person['fullname'] .= " ".$person['suffix'];}
  }

  return $person;
}

# -------------------------------------------------------------------------------
function find_url($url_id)
{
  global $dbh;

  $url_id = intval($url_id);
  $query = "SELECT
        u.id, u.url, u.description, u.updated_at, u.person_id
        FROM
          urls u
        WHERE
          u.id = '".$url_id."'
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $url = $line;
  }

  return $url;

}

# -------------------------------------------------------------------------------
function find_urls_by_person($person_id)
{
  global $dbh;

  $person_id = intval($person_id);
  $query = "SELECT
        u.id, u.url, u.description, u.updated_at, u.person_id
        FROM
          urls u
        WHERE
          u.person_id = '".$person_id."'
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $urls = array();
  while ( $line = mysqli_fetch_array($result)) {
    $urls[$line['id']] = $line;
  }

  return $urls;

}

# -------------------------------------------------------------------------------
function find_dissertation($dissertation_id)
{
  global $dbh;

  $dissertation_id = intval($dissertation_id);
  $query = "SELECT
        d.id, d.person_id, d.completedyear, d.status,
        d.title, d.abstract, d.notes, d.school_id, d.discipline_id
        FROM
          dissertations d
        WHERE
          d.id = '".$dissertation_id."'
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $dissertation = array();
  while ( $line = mysqli_fetch_array($result)) {
    $dissertation = $line;
  }

  return $dissertation;
}

# -------------------------------------------------------------------------------
function find_dissertation_by_person($person_id)
{
  global $dbh;

  $person_id = intval($person_id);
  $query = "SELECT
        d.id, d.person_id, d.completedyear, d.status,
        d.title, d.abstract, d.notes, d.school_id, d.discipline_id
        FROM
          dissertations d
        WHERE
          d.person_id = '".$person_id."'
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $dissertation = array();
  while ( $line = mysqli_fetch_array($result)) {
    $dissertation = $line;
  }

  return $dissertation;
}

# -------------------------------------------------------------------------------
function find_name($name_id)
{
  global $dbh;
  $query = "SELECT
        n.firstname, n.middlename,
        n.lastname, n.suffix
        FROM
          names n
        WHERE
          n.id = ".$name_id."
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $name = $line;
    $name['fullname'] = $name['firstname'];
    if ($name['middlename'] != ""){$name['fullname'] .= " ".$name['middlename'];}
    if ($name['lastname'] != ""){$name['fullname'] .= " ".$name['lastname'];}
    if ($name['suffix'] != ""){$name['fullname'] .= " ".$name['suffix'];}
  }

  return $name;
}

# -------------------------------------------------------------------------------
function find_discipline($discipline_id)
{
  global $dbh;
  $discipline_id = intval($discipline_id);
  $query = "SELECT
        d.title, d.description
        FROM
          disciplines d
        WHERE
          d.id = ".$discipline_id."
      ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $discipline = $line;
  }

  return $discipline;
}

# -------------------------------------------------------------------------------
function find_ancestors_for_group($groupofpeople)
{
  $originalgroup = $groupofpeople;
  // find advisors, and if they're new, add them to the list and recurse
  foreach ($originalgroup as $person)
  {
    $advisors = find_advisors_for_person($person);
    foreach ($advisors as $one)
    {
      $groupofpeople[] = $one;
    }
  }
  $groupofpeople = array_unique($groupofpeople);
  if (count(array_diff($groupofpeople,$originalgroup)) > 0)
  {
    return find_ancestors_for_group($groupofpeople);
  }
  else
  {
    return $originalgroup;
  }
}

# -------------------------------------------------------------------------------
function find_descendents_for_group($groupofpeople)
{
  $originalgroup = $groupofpeople;
  // find descendents, and if they're new, add them to the list and recurse
  foreach ($originalgroup as $person)
  {
    $advisees = find_advisorships_under_person($person);
    foreach ($advisees as $one)
    {
      $groupofpeople[] = $one;
    }
  }
  $groupofpeople = array_unique($groupofpeople);
  if (count(array_diff($groupofpeople,$originalgroup)) > 0)
  {
    return find_descendents_for_group($groupofpeople);
  }
  else
  {
    return $originalgroup;
  }
}

# -------------------------------------------------------------------------------
function T_score($person)
{
  # total number of descendants (nodes) in a person's tree
  $group = array($person);
  $total = count(find_descendents_for_group($group)); # including self
  $descendents = $total - 1; # minus self
  return $descendents;
}

# -------------------------------------------------------------------------------
function find_mpact_score($person,$score_type)
{
  global $dbh;
  $query = "SELECT $score_type as score FROM people WHERE id='$person'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    extract($line);
  }
  return $score;
}

# -------------------------------------------------------------------------------
function FMI_score($person)
{
    $FMI_score = count(find_advisorships_under_person($person));
#    print "person $person -- fmi $FMI_score
";
    $committeeships = find_committeeships_under_person($person);
    foreach ($committeeships as $one)
    {
      $numA = count(find_advisors_for_person($one));
#      echo " - #A [$numA] ----
";
      $numC = count(find_committee_for_person($one));
#      echo "#C [$numC] ---- \n";
      $FMI_score += 1/($numA + $numC);
#      echo "
";
    }
  //  echo "fractional mentorship, inclusive (FMI =  A + eachC(1/(#A+#C)) )
\n";
    return round($FMI_score,3);
}

# -------------------------------------------------------------------------------
function FME_score($person)
{
    $FME_score = count(find_advisorships_under_person($person));
#    print "person $person -- fme $FME_score
";
    $committeeships = find_committeeships_under_person($person);
    foreach ($committeeships as $one)
    {
      $numC = count(find_committee_for_person($one));
#      echo "#C [$numC] ---- \n";
      $FME_score += 1/($numC);
#      echo "
";
    }
  //  echo "fractional mentorship, inclusive (FMI =  A + eachC(1/(#A+#C)) )
\n";
    return round($FME_score,3);
}

# -------------------------------------------------------------------------------
function TA_score($person)
{
  # total number of descendants who have advised students themselves
  $without_students = array();
  $descendents = find_descendents_for_group(array($person)); # including self
  foreach ($descendents as $d)
  {
    if (count(find_descendents_for_group(array($d))) == 1)
    {
      $without_students[] = $d;
    }
  }
  $descendents_who_advised = array_diff($descendents,$without_students); # including self
  return max(count($descendents_who_advised) - 1,0); # minus self
}

# -------------------------------------------------------------------------------
function W_score($person)
{
  # should handle multigenerational advisorships correctly...

  # return the max of the widths of each generation of descendents
  $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16
  $gencount = 1;
  $advisees = find_advisorships_under_person($person); #5
  $gen_widths[$gencount] = count($advisees);
  $remaining = array_diff($descendents,$advisees); # 11
#  print "$gencount <-- gen
";
#  print count($advisees)." advisees - ";
#  print_r($advisees);
#  print "
";
#  print "
";
#  print count($remaining)." remaining - ";
#  print_r($remaining);
#  print "
";
#  print "
";
  while (count($remaining) > 0)
  {
    $gencount++;
#    print "$gencount <-- gen
";
    $advisees = advisees_of_group($advisees);
    $gen_widths[$gencount] = count($advisees);
    $remaining = array_diff($remaining,$advisees);
#    print count($advisees)." advisees - ";
#    print_r($advisees);
#    print "
";
#    print "
";
#    print count($remaining)." remaining - ";
#    print_r($remaining);
#    print "
";
#    print "
";
  }
#  print_r($gen_widths);
  return max($gen_widths);
}

# -------------------------------------------------------------------------------
function TD_score($person)
{
  # there is currently a bug in this implementation
  # if a student has two advisors, and they, themselves are related by mentorship
  # this algorithm currently counts gen_width based on advisee count only
  # since $td is calculated based on gen_width values, TD will be missing data
  # A is advisor to B and C
  # B is advisor to C
  # A should have a TD score of 2 (full credit for both advisees)
  # upon further reflection, perhaps this is working correctly, by accident

  # return the decayed score
  $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16
  $gencount = 1;
  $advisees = find_advisorships_under_person($person); #5
  $gen_widths[$gencount] = count($advisees);
  $remaining = array_diff($descendents,$advisees); # 11
  while (count($remaining) > 0)
  {
    $gencount++;
    $advisees = advisees_of_group($advisees);
    $gen_widths[$gencount] = count($advisees);
    $remaining = array_diff($remaining,$advisees);
  }
#  print_r($gen_widths);
  $td = 0;
  foreach($gen_widths as $one => $two)
  {
    $num = $two;
    $den = (pow(2,($one-1)));
    $f = $num/$den;
#    print "$num/$den = $f
";
    $td = $td + $f;
  }
  return $td;
}

# -------------------------------------------------------------------------------
function G_score($person)
{
  # there is currently a bug in this implementation
  # if a student has two advisors, and they, themselves are related by mentorship
  # this algorithm currently misses a generation in the calculation of G
  # A is advisor to B and C
  # B is advisor to C
  # A should have a G score of 2, but will only be calculated a 1

  # return the number of generations of descendents
  $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16
  $gencount = 1;
  $advisees = find_advisorships_under_person($person); #5
  $gen_widths[$gencount] = count($advisees);
  $remaining = array_diff($descendents,$advisees); # 11
  while (count($remaining) > 0)
  {
    $gencount++;
    $advisees = advisees_of_group($advisees);
    $gen_widths[$gencount] = count($advisees);
    $remaining = array_diff($remaining,$advisees);
  }
  if ($gen_widths[1] == 0)
  {
    return 0;
  }
  else
  {
    return count($gen_widths);
  }
}

# -------------------------------------------------------------------------------
function advisees_of_group($group)
{
  # W helper function
  $advisees = array();
  foreach ($group as $one)
  {
    $advisees[] = find_advisorships_under_person($one);
  }
  $advisees = flattenArray($advisees);
#  print_r($advisees);
#  print " <-- advisees of group
";
  return $advisees;
}

# -------------------------------------------------------------------------------
function flattenArray($array)
{
   $flatArray = array();
   foreach( $array as $subElement ) {
       if( is_array($subElement) )
           $flatArray = array_merge($flatArray, flattenArray($subElement));
       else
           $flatArray[] = $subElement;
   }
   return $flatArray;
}

# -------------------------------------------------------------------------------
function calculate_scores($person_id)
{
  global $dbh;
  $A_score = count(find_advisorships_under_person($person_id));
  $C_score = count(find_committeeships_under_person($person_id));
  $AC_score = $A_score + $C_score;
  $G_score = G_score($person_id);
  $W_score = W_score($person_id);
  $T_score = T_score($person_id);
  $TA_score = TA_score($person_id);
  $TD_score = TD_score($person_id);
  $FMI_score = FMI_score($person_id);
  $FME_score = FME_score($person_id);

  $query = "UPDATE people
              SET
                a_score = '$A_score',
                c_score = '$C_score',
                ac_score = '$AC_score',
                g_score = '$G_score',
                w_score = '$W_score',
                t_score = '$T_score',
                ta_score = '$TA_score',
                td_score = '$TD_score',
                fmi_score = '$FMI_score',
                fme_score = '$FME_score',
                scores_calculated = now()
              WHERE
                id = ".$person_id."
            ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
}

# -------------------------------------------------------------------------------
function mpact_scores($passed_person)
{
  global $dbh;
  $glossaryterms = find_glossaryterms();

  $query = "SELECT
              a_score, c_score, ac_score, g_score, w_score,
              t_score, ta_score, td_score, fmi_score, fme_score,
              scores_calculated
              FROM people
              WHERE id = ".$passed_person."
            ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result)) {
    extract($line);
  }

  $mpact['A'] = $a_score;
  $mpact['C'] = $c_score;
  $mpact['AC'] = $ac_score;
  $scores_output = "A = $a_score
\n";
  $scores_output .= "C = $c_score
\n";
  $scores_output .= "A+C = $ac_score
\n";

  $mpact['FMI'] = $fmi_score;
  $mpact['FME'] = $fme_score;
  $FMIdivFULL = ($ac_score>0) ? $fmi_score / $ac_score : 0;
  $FMIdivFULL = round($FMIdivFULL,3);
  $mpact['FMIdivFULL'] = $FMIdivFULL;
  $FMEdivFULL = ($ac_score>0) ? $fme_score / $ac_score : 0;
  $FMEdivFULL = round($FMEdivFULL,3);
  $mpact['FMEdivFULL'] = $FMEdivFULL;
  if (is_admin())
  {
    $scores_output .= "FMI = $fmi_score
\n";
    $scores_output .= "FME = $fme_score
\n";
    $scores_output .= "FMI/(A+C) = $FMIdivFULL
\n";
    $scores_output .= "FME/(A+C) = $FMEdivFULL
\n";
  }

  $mpact['T'] = $t_score;
  $scores_output .= "T = $t_score
\n";
  $mpact['G'] = $g_score;
  $scores_output .= "G = $g_score
\n";
  $mpact['W'] = $w_score;
  $scores_output .= "W = $w_score
\n";
  $mpact['TD'] = $td_score;
  $scores_output .= "<a href=\"".$_SERVER['SCRIPT_NAME']."?op=glossary\" title=\"".$glossaryterms['defs'][$glossaryterms['ids']['TD']]."\">TD = $td_score
\n";
  $mpact['TA'] = $ta_score;
  $scores_output .= "<a href=\"".$_SERVER['SCRIPT_NAME']."?op=glossary\" title=\"".$glossaryterms['defs'][$glossaryterms['ids']['TA']]."\">TA = $ta_score
\n";
  $scores_output .= "calculated $scores_calculated
\n";
  $mpact['output'] = $scores_output;

  return $mpact;
}

# -------------------------------------------------------------------------------
function find_advisors_for_person($person_id)
{
  global $dbh;

  // get person's own advisor(s)

  $listing = array();

  $query = "SELECT a.person_id
        FROM
          dissertations d,
          advisorships a
        WHERE
          d.person_id = ".$person_id." AND
          a.dissertation_id = d.id
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function find_committee_for_person($person_id)
{
  global $dbh;

  // get person's own committee member(s)

  $listing = array();

  $query = "SELECT c.person_id
        FROM
          dissertations d,
          committeeships c
        WHERE
          d.person_id = ".$person_id." AND
          c.dissertation_id = d.id
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function find_advisorships_under_person($person_id)
{
  global $dbh;

  // get person's advisorships (below)

  $listing = array();

  $query = "SELECT d.person_id
        FROM
          dissertations d,
          advisorships a
        WHERE
          a.person_id = ".$person_id." AND
          a.dissertation_id = d.id
        ORDER BY
          d.completedyear ASC
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function find_committeeships_under_person($person_id)
{
  global $dbh;

  // get person's committeeships (below)

  $listing = array();

  $query = "SELECT d.person_id
        FROM
          dissertations d,
          committeeships c
        WHERE
          c.person_id = '".$person_id."' AND
          c.dissertation_id = d.id
        ORDER BY
          d.completedyear
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $listing[] = $line['person_id'];
  }

  return $listing;
}

# -------------------------------------------------------------------------------
function set_preferred_name($person_id,$name_id)
{
  global $dbh;

  # delete current family tree of dotgraphs
  delete_associated_dotgraphs($person_id);

  # set it

  $listing = array();

  $before = find_person($person_id);

  $query = "UPDATE people
        SET
          preferred_name_id = '".$name_id."'
        WHERE
          id = '".$person_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  $after = find_person($person_id);

  # log it
  mpact_logger("set preferred name for person[".$person_id."] from name[".$before['preferred_name_id']."] (".$before['fullname'].") to name[".$name_id."] (".$after['fullname'].")");
}

# -------------------------------------------------------------------------------
function generate_profs_at_dept($school_id,$discipline_id)
{
  global $dbh;

  $dissertations = array();
  $listing = array();
  $advisors = array();
  $committeemembers = array();

  // get all dissertations at this dept

  $query = "SELECT d.id
        FROM dissertations d, schools s
        WHERE
          d.school_id = s.id AND
          s.id = '".$school_id."' AND
          d.discipline_id = '".$discipline_id."'
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $dissertations[] = $line['id'];
  }

  if (count($dissertations)>0)
  {
    // get all advisors for these dissertations

    $query = "SELECT a.person_id
          FROM dissertations d, advisorships a
          WHERE
            a.dissertation_id IN (";
    $query .= implode(", ", $dissertations);
    $query .= ") AND
            a.dissertation_id = d.id";

    $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

    while ( $line = mysqli_fetch_array($result))
    {
      $advisors[$line['person_id']] = $line['person_id'];
    }

    // get all committeemembers for these dissertations

    $query = "SELECT c.person_id
          FROM dissertations d, committeeships c
          WHERE
            c.dissertation_id IN (";
    $query .= implode(", ", $dissertations);
    $query .= ") AND
            c.dissertation_id = d.id";

    $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

    while ( $line = mysqli_fetch_array($result))
    {
      $committeemembers[$line['person_id']] = $line['person_id'];
    }
  }

  // return the combined list (uniquified when combined)

//  echo "\na - ".count($advisors);
//  echo "\nc - ".count($committeemembers);
  $listing = $advisors + $committeemembers;
//  echo "\ncombined before - ".count($listing);
  return $listing;

}

# -------------------------------------------------------------------------------
function find_profs_at_dept($school_id,$discipline_id)
{
  global $dbh;
  $query = "SELECT professors
              FROM profs_at_dept
              WHERE
                school_id     = '$school_id' AND
                discipline_id = '$discipline_id'
            ";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result))
  {
    $listing = unserialize($line['professors']);
  }
  return $listing;

}

# -------------------------------------------------------------------------------
function find_disciplines($school_id=null)
{
  global $dbh;

  $disciplines = array();
  if ($school_id)
  {
    // get all disciplines at this school
    $query = "SELECT d.id, d.title
                FROM
                  disciplines d, schools s, dissertations diss
                WHERE
                  diss.school_id = s.id AND
                  diss.discipline_id = d.id AND
                  s.id = '$school_id'
                ORDER BY
                  d.title
             ";
  }
  else
  {
    $query = "SELECT id, title
                FROM
                  disciplines d
                ORDER BY
                  title
              ";
  }
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $disciplines[$line['id']] = $line['title'];
  }

  if (isset($disciplines))
  {
    return $disciplines;
  }
}

# -------------------------------------------------------------------------------
function is_duplicate_discipline($title)
{
  global $dbh;
  $disciplinefound = 0;

  $query = "SELECT id FROM disciplines WHERE title = '$title'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $disciplinefound = $line['id'];
  }

  if ($disciplinefound > 0){
    return true;
  }

  return false;
}

# -------------------------------------------------------------------------------
function is_empty_discipline($discipline_id)
{
  global $dbh;
  $query = "SELECT count(*) as howmany FROM dissertations WHERE discipline_id = $discipline_id";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    extract($line);
  }

  if ($howmany > 0){
    return false;
  }

  return true;
}

# -------------------------------------------------------------------------------
function is_duplicate_school($fullname)
{
  global $dbh;
  $schoolfound = 0;

  $query = "SELECT id FROM schools WHERE fullname = '$fullname'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    $schoolfound = $line['id'];
  }

  if ($schoolfound > 0){
    return true;
  }

  return false;
}

# -------------------------------------------------------------------------------
function is_empty_school($school_id)
{
  global $dbh;
  $query = "SELECT count(*) as howmany FROM dissertations WHERE school_id = $school_id";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result))
  {
    extract($line);
  }

  if ($howmany > 0){
    return false;
  }

  return true;
}

# -------------------------------------------------------------------------------
function find_discipline_counts()
{
  global $dbh;

   // get all discipline counts from the database

   $disciplinecounts = array();

   $query = "SELECT discipline_id, count(*) as disciplinecount
               FROM dissertations
               GROUP BY discipline_id
            ";

   $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

   while ( $line = mysqli_fetch_array($result))
   {
    $disciplinecounts[$line['discipline_id']] = $line['disciplinecount'];
   }

   if (isset($disciplinecounts))
   {
     return $disciplinecounts;
   }
}

# -------------------------------------------------------------------------------
function find_discipline_statuses($discipline_id)
{
  global $dbh;

   // get status counts for this discipline

   GLOBAL $statuscodes;

   $statuscounts = array();

   $query = "SELECT status, count(*) as disciplinecount
               FROM dissertations
               WHERE discipline_id='$discipline_id'
               GROUP BY status
            ";

   $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

   while ( $line = mysqli_fetch_array($result))
   {
    $statuscounts[$line['status']] = $line['disciplinecount'];
   }

   foreach (range(0,4) as $one)
   {
     if (!isset($statuscounts[$one]))
     {
       $statuscounts[$one] = 0;
     }
   }
   return $statuscounts;
}

# -------------------------------------------------------------------------------
function find_dept_counts($school_id,$discipline_id)
{
  global $dbh;

   // get all department counts from the database

   $deptcounts = array();

   $query = "SELECT discipline_id, count(*) as disciplinecount
               FROM dissertations
               GROUP BY discipline_id
            ";

   $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

   while ( $line = mysqli_fetch_array($result))
   {
    $deptcounts[$line['discipline_id']] = $line['disciplinecount'];
   }

   if (isset($deptcounts))
   {
     return $deptcounts;
   }
}

# -------------------------------------------------------------------------------
function find_dept_statuses($school_id,$discipline_id)
{
  global $dbh;

   // get status counts for this school in this discipline

   GLOBAL $statuscodes;

   $statuscounts = array();

   $query = "SELECT status, count(*) as disciplinecount
               FROM dissertations
               WHERE
                discipline_id='$discipline_id' AND
                school_id='$school_id'
               GROUP BY status
            ";

   $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

   while ( $line = mysqli_fetch_array($result))
   {
    $statuscounts[$line['status']] = $line['disciplinecount'];
   }

   foreach (range(0,4) as $one)
   {
     if (!isset($statuscounts[$one]))
     {
       $statuscounts[$one] = 0;
     }
   }
   return $statuscounts;
}

# -------------------------------------------------------------------------------
function find_schools($discipline_id=null)
{
  global $dbh;
  // get all schools in a discipline (or all disciplines)
  $schools = array();
  if ($discipline_id)
  {
    // look up schools at dissertations in this discipline
    $query = "SELECT s.id, s.fullname
              FROM
                dissertations d, schools s
              WHERE
                d.school_id = s.id AND
                d.discipline_id = '$discipline_id'
              GROUP BY
                d.school_id
              ORDER BY
                s.fullname ASC
            ";
  }
  else
  {
    $query = "SELECT id, fullname
                FROM
                  schools s
                ORDER BY fullname
              ";
  }
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
  while ( $line = mysqli_fetch_array($result))
  {
    $schools[$line['id']] = $line['fullname'];
  }

  if (isset($schools))
  {
    return $schools;
  }
}

# -------------------------------------------------------------------------------
function find_school_counts()
{
  global $dbh;

   // get all school dissertation counts from the database

   $schoolcounts = array();

   $query = "SELECT school_id, count(*) as disscount
               FROM dissertations
               GROUP BY school_id
            ";

   $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

   while ( $line = mysqli_fetch_array($result))
   {
    $schoolcounts[$line['school_id']] = $line['disscount'];
   }

   if (isset($schoolcounts))
   {
     return $schoolcounts;
   }
}

# -------------------------------------------------------------------------------
function find_school_statuses($school_id)
{
  global $dbh;

   // get status counts for this school

   GLOBAL $statuscodes;

   $statuscounts = array();

   $query = "SELECT status, count(*) as disscount
               FROM dissertations
               WHERE school_id='$school_id'
               GROUP BY status
            ";

   $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

   while ( $line = mysqli_fetch_array($result))
   {
    $statuscounts[$line['status']] = $line['disscount'];
   }

   foreach (range(0,4) as $one)
   {
     if (!isset($statuscounts[$one]))
     {
       $statuscounts[$one] = 0;
     }
   }
   return $statuscounts;
}

# -------------------------------------------------------------------------------
function find_persons_school($passed_person)
{
  global $dbh;

  // get person's degree school

  $query = "SELECT
              d.id as dissertation_id,
              d.completedyear,
              d.title,
              d.abstract,
              s.fullname,
              s.country,
              s.id as schoolid
        FROM
          dissertations d,
          schools s
        WHERE
          d.person_id = ".$passed_person." AND
          d.school_id = s.id
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $thisperson['dissertation_id']  = $line['dissertation_id'];
    $thisperson['completedyear']  = $line['completedyear'];
    $thisperson['title']  = $line['title'];
    $thisperson['abstract']  = $line['abstract'];
    $thisperson['country'] = $line['country'];
    $thisperson['school'] = $line['fullname'];
    $thisperson['schoolid'] = $line['schoolid'];
  }

  if (isset($thisperson))
  {
    return $thisperson;
  }
}

# -------------------------------------------------------------------------------
function find_school($school_id)
{
  global $dbh;

  // get school

  $query = "SELECT
              s.fullname,
              s.country
        FROM
          schools s
        WHERE
          s.id = ".$school_id."
      ";

  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

  while ( $line = mysqli_fetch_array($result)) {
    $school['country'] = $line['country'];
    $school['fullname'] = $line['fullname'];
  }

  if (isset($school))
  {
    return $school;
  }
}

# -------------------------------------------------------------------------------
function get_environment_info()
{
  $host_info = array();
  $hostname = $_SERVER['SERVER_NAME'];
  if ($hostname == ""){$hostname = exec(hostname);}
#  echo "hostname = [$hostname]
";
  if ($hostname == "www.ibiblio.org" || $hostname == "www-dev.ibiblio.org" || $hostname == "login1.ibiblio.org")
  {
    # the main install on ibiblio
    $host_info['hostname']    = "ibiblio";
    $host_info['ownername']   = "mpact";
    $host_info['dotlocation'] = "/export/sunsite/users/mpact/terrelllocal/bin/dot";
    $host_info['appdir']      = "/public/html/mpact";
    $host_info['webdir']      = "http://www.ibiblio.org/mpact";
    $host_info['dotcachedir'] = "dotgraphs";
    $host_info['dotfiletype'] = "png";
    $host_info['dotfontface'] = "Times-Roman";
  }
  else if ($hostname == "trel.dyndns.org")
  {
    # my local development machine
    $host_info['hostname']    = "home";
    $host_info['ownername']   = "trel";
    $host_info['dotlocation'] = "/sw/bin/dot";
    $host_info['appdir']      = "/Library/WebServer/Documents/MPACTlocal/app";
    $host_info['webdir']      = "http://trel.dyndns.org:9000/mpactlocal/app";
    $host_info['dotcachedir'] = "dotgraphs";
    $host_info['dotfiletype'] = "png";
    $host_info['dotfontface'] = "cour";
  }
  else if ($hostname == "localhost.com" || $hostname == "trelpancake")
  {
    # my laptop
    $host_info['hostname']    = "laptop";
    $host_info['ownername']   = "trel";
    $host_info['dotlocation'] = "/opt/local/bin/dot";
    $host_info['appdir']      = "/Users/trel/Sites/MPACT";
    $host_info['webdir']      = "http://localhost.com/~trel/MPACT";
    $host_info['dotcachedir'] = "dotgraphs";
    $host_info['dotfiletype'] = "png";
    $host_info['dotfontface'] = "cour";
  }
  else
  {
    # unknown host
    #exit;
  }

  return $host_info;
}

# -------------------------------------------------------------------------------
function delete_associated_dotgraphs($passed_person)
{
  $host_info = get_environment_info();
  $group = array($passed_person);
  $ancestors = find_ancestors_for_group($group);
  $descendents = find_descendents_for_group($group);
  $entire_family_tree = array_unique($ancestors + $descendents);
  foreach ($entire_family_tree as $one)
  {
    # set the filenames
    $dotfilename = $host_info['appdir']."/".$host_info['dotcachedir']."/$one.dot";
    $imagefilename = $host_info['appdir']."/".$host_info['dotcachedir']."/$one.".$host_info['dotfiletype'];
    $imagemapfilename = $host_info['appdir']."/".$host_info['dotcachedir']."/$one.map";
    # delete each if they exist
    if (file_exists($dotfilename))
    {
      `rm $dotfilename`;
    }
    if (file_exists($imagefilename))
    {
      `rm $imagefilename`;
    }
    if (file_exists($imagemapfilename))
    {
      `rm $imagemapfilename`;
    }
    # mark as 'dirty' so cronjob can recreate images
    mark_record_as_dirty($one);
  }
}

# -------------------------------------------------------------------------------
function mark_record_as_dirty($passed_person)
{
  global $dbh;
  # mark database record for this person as dirty
  # a cronjob will pick these up and regenerate their dotgraphs
  # gets around permission issues on the server if necessary
  $query = "UPDATE people SET regenerate_dotgraph = '1' WHERE id = '".$passed_person."'";
  $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));
}

# -------------------------------------------------------------------------------
function narray_slice($array, $offset, $length) {
    # http://us3.php.net/manual/en/function.array-slice.php#73882

  //Check if this version already supports it
  if (str_replace('.', '', PHP_VERSION) >= 502)
    return array_slice($array, $offset, $length, true);

  foreach ($array as $key => $value) {

    if ($a >= $offset && $a - $offset <= $length)
      $output_array[$key] = $value;
    $a++;

  }
  return $output_array;
}

# -------------------------------------------------------------------------------
function generate_dotfile($passed_person){
  $a = find_person($passed_person);
  if ($a == null)
  {
    return 0;
  }
  else
  {
    $dotfilecontents = "";
    $dotfilecontents .= "digraph familytree\n";
    $dotfilecontents .= "{\n";
    $dotfilecontents .= "rankdir=\"LR\"\n";
    $dotfilecontents .= "node [fontname = Times, fontsize=10, shape = rect, height=.15]\n";
    # ancestors
    $upgroup = array();
    $upgroup[] = $passed_person;
    $ancestors = find_ancestors_for_group($upgroup);
    foreach ($ancestors as $one)
    {
      $person = find_person($one);
      $dotfilecontents .= "$one [label = \"".$person['fullname']."\" URL=\"mpact.php?op=show_tree&id=".$one."\"];\n";
      $advisors = find_advisors_for_person($one);
      foreach ($advisors as $adv)
      {
        $dotfilecontents .= "$adv -> $one;\n";
      }
    }
    # descendents
    $downgroup = array();
    $downgroup[] = $passed_person;
    $descendents = find_descendents_for_group($downgroup);
    foreach ($descendents as $one)
    {
      $person = find_person($one);
      $dotfilecontents .= "$one [label = \"".$person['fullname']."\" URL=\"mpact.php?op=show_tree&id=".$one."\"";
      if ($one == $passed_person){
        $dotfilecontents .= " color=\"red\" style=\"filled\" fillcolor=\"grey\"";
      }
      $dotfilecontents .= "];\n";
      $advisees = find_advisorships_under_person($one);
      foreach ($advisees as $adv)
      {
        $dotfilecontents .= "$one -> $adv;\n";
      }
    }
    $dotfilecontents .= "}\n";

    return $dotfilecontents;
  }
}

# -------------------------------------------------------------------------------
function draw_tree_dotgraph($passed_person)
{
  $person = $passed_person;
  $host_info = get_environment_info();
  if (isset($host_info['appdir']))
  {
    $webfilename = generate_dotgraph($person);
    if ($webfilename == "marked_as_dirty"){
      echo "generating graph, please reload";
    }
    else{
      echo "
";
    }
  }
  else
  {
    echo "graphics libraries are not configured";
  }
}

# -------------------------------------------------------------------------------
function generate_dotgraph($passed_person, $forcenew="no")
{
  $person = $passed_person;
  $host_info = get_environment_info();
#  print_r($host_info);
  $appcache = $host_info['appdir']."/".$host_info['dotcachedir'];
  $webcache = $host_info['webdir']."/".$host_info['dotcachedir'];
  $appfilename = "$appcache/$person.".$host_info['dotfiletype'];
#  echo "appfilename = $appfilename
\n";
  $dotfilename = "$appcache/$person.dot";
#  echo "dotfilename = $dotfilename
\n";
  $webfilename = "$webcache/$person.".$host_info['dotfiletype'];
#  echo "webfilename = $webfilename
\n";
  $appimagemap = "$appcache/$person.map";
#  echo "appimagemap = $appimagemap
\n";

  if (!file_exists($appfilename)) {
    # assumption is that the cachedir exists... (run setupmpact.sh)
    # generate dotfile
    if (!file_exists($dotfilename) or $forcenew == "force") {
#      print " - creating dotfile...\n";
      $dotfilecontents = generate_dotfile($person);
      $fh = fopen($dotfilename, 'w');
      fwrite($fh, $dotfilecontents);
      fclose($fh);
      exec("chmod 666 $dotfilename");
    }
    # generate graph
    $getandgenerategraph = "/bin/cat $dotfilename | ".$host_info['dotlocation']." -Nfontname=".$host_info['dotfontface']." -Gcharset=latin1 -Tcmapx -o$appimagemap -T".$host_info['dotfiletype']." -o$appfilename 2>&1";
#      echo "getandgenerategraph = $getandgenerategraph
";
    exec($getandgenerategraph);
    exec("chmod 666 $appimagemap");
    exec("chmod 666 $appfilename");
    if (!file_exists($appfilename)) {
      # mark as dirty if it didn't work
      mark_record_as_dirty($person);
      return "marked_as_dirty";
    }
  }
  else
  {
#    echo "SHOWING CACHED COPY
";
  }

  return $webfilename;
}

# -------------------------------------------------------------------------------
function draw_graph($passed_person)
{
  if (!$passed_person){action_box("No ID given.");}

    $person = $passed_person;
    $host_info = get_environment_info();
    if (isset($host_info['appdir']))
    {
      $appcache = $host_info['appdir']."/".$host_info['dotcachedir'];
      $webcache = $host_info['webdir']."/".$host_info['dotcachedir'];
      $appfilename = "$appcache/$person.".$host_info['dotfiletype'];
      #echo "appfilename = $appfilename
";
      $webfilename = "$webcache/$person.".$host_info['dotfiletype'];
      #echo "webfilename = $webfilename
";
      $appimagemap = "$appcache/$person.map";
      #echo "appimagemap = $appimagemap
";

      echo "";
      echo file_get_contents($appimagemap);
    }
    else
    {
      echo "graphics libraries are not configured";
    }
}

# -------------------------------------------------------------------------------
function draw_tree($passed_person)
{
  global $dbh;
        GLOBAL $statuscodes;
        GLOBAL $inspectioncodes;

        // shows a person

        if (!$passed_person){action_box("No ID given.");}
        else
        {
          $personcount = 0;
          $thisperson = array();
          $dissertation = array();

          // get person's preferred name

          $query = "SELECT
                n.firstname, n.middlename,
                n.lastname, n.suffix, p.degree
                FROM
                  names n, people p
                WHERE
                  p.preferred_name_id = n.id AND
                  p.id = '".$passed_person."'
              ";
          $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));

          while ( $line = mysqli_fetch_array($result)) {
            $thisperson['firstname']  = $line['firstname'];
            $thisperson['middlename'] = $line['middlename'];
            $thisperson['lastname']   = $line['lastname'];
            $thisperson['suffix']     = $line['suffix'];
            $thisperson['degree']     = $line['degree'];
            $personcount++;
          }

          $schoolinfo = find_persons_school($passed_person);
          $thisperson['dissertation_id'] = $schoolinfo['dissertation_id'];
          $thisperson['completedyear'] = $schoolinfo['completedyear'];
          $thisperson['country'] = $schoolinfo['country'];
          $thisperson['school'] = $schoolinfo['school'];
          $thisperson['schoolid'] = $schoolinfo['schoolid'];

          if ($thisperson['dissertation_id'] == "")
          {
            $thisperson['status'] = "";
            $thisperson['notes'] = "";
            $thisperson['title'] = "N/A";
            $thisperson['abstract'] = "N/A";
            $thisperson['abstract_html'] = "N/A";
          }
          else
          {
            $dissertation = find_dissertation($thisperson['dissertation_id']);
            $thisperson['status'] = $dissertation['status'];
            $thisperson['notes'] = $dissertation['notes'];
            $thisperson['discipline_id'] = $dissertation['discipline_id'];
            $thisperson['title'] = $dissertation['title'];
            $thisperson['abstract'] = $dissertation['abstract'];
            $thisperson['abstract_html'] = encode_linebreaks($dissertation['abstract']);
            if ($thisperson['title'] == "") { $thisperson['title'] = "N/A";}
            if ($thisperson['abstract'] == "")
            {
              $thisperson['abstract'] = "N/A";
              $thisperson['abstract_html'] = "N/A";
            }
          }

          $thisperson['advisors'] = find_advisors_for_person($passed_person);
          $thisperson['cmembers'] = find_committee_for_person($passed_person);
          $thisperson['advisorships'] = find_advisorships_under_person($passed_person);
          $thisperson['committeeships'] = find_committeeships_under_person($passed_person);

          if ($personcount < 1)
          {
            action_box("Person ".$passed_person." Not Found");
          }
          else
          {

            echo "

\n";

            # Name / Aliases
            $count = 0;
            $printme = "";
            $fullname = $thisperson['firstname']." ".$thisperson['middlename']." ".$thisperson['lastname']." ".$thisperson['suffix'];
            $printme .= "
Dissertation Information for $fullname
";
            $printme .= "
";
            if (is_admin())
            {
              if (isset($thisperson['completedyear']))
              {
                $printme .= " (Edit)";
              }
              else
              {
                $printme .= " (Create Dissertation for $fullname)";
              }
              $printme .= "
\n";
            }
            $printme .= "
";
            $printme .= "
";
            $printme .= "NAME: ";
            if (is_admin())
            {
              $printme .= "(Add)";
            }
            $printme .= "
";
            $printme .= " - ";
            $printme .= get_person_link($passed_person);
            if (is_admin())
            {
              $printme .= " (Edit)";
            }
            $printme .= "
\n";

            $aliases = 0;
            foreach (find_aliases($passed_person) as $one)
            {
              $printme .= " - (Alias) ";
              $printme .= $one['firstname']." ";
              $printme .= $one['middlename']." ";
              $printme .= $one['lastname']." ";
              $printme .= $one['suffix']." ";
              if (is_admin())
              {
                $printme .= "(Set as Primary)";
                $printme .= " (Delete)";
              }
              $printme .= "
";
              $aliases++;
            }
            $printme .=  "
";
            echo $printme;

            # Degree
            $printme = "
\n";
            $printme .= "DEGREE:
\n";
            $printme .= " - ".$thisperson['degree'];
            if (is_admin())
            {
              $printme .= " (Edit)";
            }
            $printme .=  "
";
            echo $printme;

            # Discipline
            $printme = "
\n";
            $printme .= "DISCIPLINE:
\n";
            if (isset($thisperson['discipline_id']))
            {
              $discipline = find_discipline($thisperson['discipline_id']);
              $printme .= " - ".$discipline['title']."";
              if (is_admin())
              {
                $printme .= " (Edit)";
              }
            }
            else
            {
              $printme .= " - None";
              if (is_admin())
              {
                $printme .= " (Create Dissertation for $fullname)";
              }
            }
            $printme .=  "
";
            echo $printme;

            # School
            $printme = "
\n";
            $printme .= "SCHOOL:
\n";
            if (isset($thisperson['completedyear']))
            {
              $printme .= " - ".$thisperson['school']." (".$thisperson['country'].") (".$thisperson['completedyear'].")";
              if (is_admin())
              {
                $printme .= " (Edit)";
              }
            }
            else
            {
              $printme .= " - None";
              if (is_admin())
              {
                $printme .= " (Create Dissertation for $fullname)";
              }
            }
            $printme .= "
\n";
            echo $printme;

            # Advisors
            $count = 0;
            $printme = "";
            $printme .= "
";
            $printme .=  "ADVISORS: ";
            if (is_admin() && isset($thisperson['completedyear']))
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['advisors'])){
              foreach ($thisperson['advisors'] as $one)
              {
                $printme .=  " - ";
                $printme .=  get_person_link($one);
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .=  "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
";
            echo $printme;

            # Committee Members
            $count = 0;
            $printme = "";
            $printme .= "
";
            $printme .= "COMMITTEE MEMBERS: ";
            if (is_admin() && isset($thisperson['completedyear']))
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['cmembers'])){
              foreach ($thisperson['cmembers'] as $one)
              {
                $printme .= " - ";
                $printme .= get_person_link($one);
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .= "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
\n\n";

            # Admin Notes
            if (is_admin())
            {
              if ($thisperson['notes'] != "")
              {
                $printme .=  "
";
                $printme .= "
\n";
                $printme .= "
\n";
                $printme .= "Admin Notes: ".$thisperson['notes']."
\n";
                $printme .= "</tdr>
\n";
                $printme .= "
\n";
                $printme .=  "
\n\n";
              }
            }

            $glossaryterms = find_glossaryterms();
            # Status and Inspection
            $printme .=  "
";
            $printme .= "MPACT Status: ".$statuscodes[$thisperson['status']]."
\n";
            $printme .=  "
\n\n";

            # Title and Abstract
            $printme .=  "
";
            $printme .= "Title: ".$thisperson['title']."
";
            $printme .=  "
\n";
            $printme .=  "
";
            $printme .= "Abstract: ".$thisperson['abstract_html']."
";
            $printme .=  "
\n\n";

            # print it all out...
            echo $printme;

            # URLS

            if (is_admin())
            {
              $urls = find_urls_by_person($passed_person);
              echo "
\n";
              echo "REFERENCE URLS";
              echo " (Add)";
              echo "
\n";
              if (count($urls) > 0)
              {
                echo "
\n";
              }
              else
              {
                echo " - None\n";
              }
              foreach ($urls as $one)
              {
                echo "
Updated: ".$one['updated_at']."";
                echo " (Edit)";
                echo " (Delete)";
                echo "
\n";
                echo "
".$one['url']."
\n";
                echo "
".$one['description']."
\n";
              }
              if (count($urls) > 0)
              {
                echo "
\n";
              }
              echo "
\n";
            }

            # EDIT HISTORY

            if (is_admin())
            {
              $entries = get_dissertation_history($thisperson['dissertation_id']);
              if (count($entries) > 0)
              {
                echo "
\n";
                echo "EDIT HISTORY (Show/Hide)\n";
                echo "";
                echo "
\n";
              }

              foreach ($entries as $one)
              {
                echo "
";
                echo "".$one['logged_at']."	";
                echo "".$one['user']."	";
                echo "".$one['message']."	";
                echo "
\n";
              }
              if (count($entries) > 0)
              {
                echo "
\n";
                echo "
\n";
              }
            }

            echo "		\n";

            # MPACT Scores
            $printme = "";
            $printme .=  "
MPACT Scores for $fullname
";
            $printme .=  "
";
            $mpact = mpact_scores($passed_person);
            $printme .= $mpact['output'];
            $printme .=  "
\n";
            if (is_admin())
            {
              $printme .=  "
(Recalculate)
";
            }
            echo $printme;

            # Draw FamilyTree Graph for this person
            echo "
Advisors and Advisees Graph
\n";
            echo "
";
            draw_tree_dotgraph($passed_person);
            echo "
";

            echo "

\n";

            # Students
            echo  "
Students under $fullname
\n\n";

            # Advisees
            $count = 0;
            $printme = "";
            $printme .= "
";
            $printme .= "ADVISEES: ";
            if (is_admin())
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['advisorships'])){
              foreach ($thisperson['advisorships'] as $one)
              {
                $printme .= " - ";
                $printme .= get_person_link($one);
                $schoolinfo = find_persons_school($one);
                if (isset($schoolinfo['completedyear']))
                {
                  $printme .= " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
                }
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .= "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
\n";
            echo $printme;

            # Committeeships
            $ccount = 0;
            $printme = "";
            $printme .= "
";
            $printme .= "COMMITTEESHIPS: ";
            if (is_admin())
            {
              $printme .= " (Add)";
            }
            $printme .= "
";
            if (isset($thisperson['committeeships'])){
              foreach ($thisperson['committeeships'] as $one)
              {
                $printme .= " - ";
                $printme .= get_person_link($one);
                $schoolinfo = find_persons_school($one);
                if (isset($schoolinfo['completedyear']))
                {
                  $printme .= " - ".$schoolinfo['school']." (".$schoolinfo['completedyear'].")";
                }
                if (is_admin())
                {
                  $printme .= " (Remove)";
                }
                $printme .= "
";
                $count++;
              }
            }
            if ($count < 1){$printme .= " - None";}
            $printme .=  "
";
            echo $printme;

          }

        }

}

?>