// do action
 $src = $_POST['source_id'];
 $txt = $_POST['source_text'];
 if ($txt && fetch_val("SELECT is_leaf({$src})") == 't') {
     echo "Cannot create subsource under source #{$src}. ";
     echo "Please go back and check your source reference.";
     die;
 }
 $event = $_POST['event'];
 $person = $_POST['person'];
 $tag = $_POST['tag_fk'];
 $place = $_POST['place_fk'];
 if ($place == 0) {
     $place = 1;
 }
 $note = note_to_db($_POST['event_note']);
 $event_date = pad_date($_POST['date_1']) . $_POST['date_type'] . pad_date($_POST['date_2']) . '1';
 $sort_date = parse_sort_date($_POST['sort_date'], $event_date);
 pg_query("BEGIN");
 pg_query("UPDATE EVENTS SET tag_fk={$tag}, place_fk={$place}, event_date='{$event_date}',\n                sort_date='{$sort_date}', event_note='{$note}' WHERE event_id = {$event}");
 set_last_selected_place($place);
 set_last_edit($person);
 $source_id = add_source($person, $tag, $event, $src, $txt);
 if ($tag == 31) {
     // hard-coded reference to probate
     pg_query("SELECT generate_probate_witnesses({$event})");
 }
 if ($_POST['age']) {
     // generate birth event
     add_birth($person, $event_date, $_POST['age'], $source_id);
 }
    form_submit();
    form_end();
    echo "<h3>{$_Citations}</h3>\n";
    $handle = pg_query("SELECT source_fk FROM event_citations WHERE event_fk = {$event}");
    while ($row = pg_fetch_row($handle)) {
        echo '<p>' . $row[0] . ' ';
        echo fetch_val("SELECT get_source_text({$row['0']})");
        echo "</p>\n";
    }
    echo "</body>\n</html>\n";
} else {
    // do action
    $person = $_POST['person'];
    $event = $_POST['event'];
    $node = $_POST['node'];
    $note = note_to_db($_POST['note']);
    pg_query("BEGIN");
    // $note_exists will always be 0 or 1.
    $note_exists = fetch_val("SELECT COUNT(*) FROM participant_notes\n                    WHERE person_fk={$person} AND event_fk={$event}");
    if (!$note_exists && $note != '') {
        $query = "INSERT INTO participant_notes (person_fk, event_fk, part_note)\n                    VALUES ({$person}, {$event}, '{$note}')";
    } else {
        if ($note_exists && $note != '') {
            $query = "UPDATE participant_notes SET part_note='{$note}'\n                    WHERE person_fk={$person} AND event_fk={$event}";
        } else {
            if ($note_exists && $note == '') {
                $query = "DELETE FROM participant_notes\n                    WHERE person_fk={$person} AND event_fk={$event}";
            }
        }
    }
    pg_query($query);
    }
    echo "<h2>{$title}</h2>\n";
    form_begin('place_edit', $_SERVER['PHP_SELF']);
    hidden_input('posted', 1);
    hidden_input('place_id', $place_id);
    text_input(get_place_desc(1), 80, 'level_1', $level_1);
    text_input(get_place_desc(2), 80, 'level_2', $level_2);
    text_input(get_place_desc(3), 80, 'level_3', $level_3);
    text_input(get_place_desc(4), 80, 'level_4', $level_4);
    text_input(get_place_desc(5), 80, 'level_5', $level_5);
    form_submit();
    form_end();
    echo "</body>\n</html>\n";
} else {
    $place_id = $_POST['place_id'];
    $level_1 = note_to_db($_POST['level_1']);
    $level_2 = $_POST['level_2'];
    $level_3 = $_POST['level_3'];
    $level_4 = $_POST['level_4'];
    $level_5 = $_POST['level_5'];
    if ($place_id == 0) {
        // insert new place
        pg_query("BEGIN WORK");
        $place_id = fetch_val("\n            INSERT INTO places (\n                level_1,\n                level_2,\n                level_3,\n                level_4,\n                level_5\n            )\n            VALUES (\n                '{$level_1}',\n                '{$level_2}',\n                '{$level_3}',\n                '{$level_4}',\n                '{$level_5}'\n            )\n            RETURNING place_id\n        ");
        pg_query("COMMIT");
    } else {
        // modify existing place
        pg_query("\n            UPDATE places SET\n                level_1 = '{$level_1}',\n                level_2 = '{$level_2}',\n                level_3 = '{$level_3}',\n                level_4 = '{$level_4}',\n                level_5 = '{$level_5}'\n            WHERE place_id = {$place_id}\n        ");
    }
    set_last_selected_place($place_id);
    header("Location: {$app_root}/place_manager.php");
function add_source($person, $tag, $event, $source_id, $text, $sort = 1)
{
    /*
    Inserts sources and citations depending on input, returns current source_id
    NOTE: To avoid breakage, NEVER call this routine outside of a transaction.
    Update 2009-03-26: The major logic now has been moved to plpgsql, and this func
    is left as a wrapper. Cf. ddl/functions.sql.
    */
    if (!$source_id && !$text) {
        // don't bother if nothing has been entered.
        return 0;
    } else {
        $text = note_to_db($text);
        return fetch_val("SELECT add_source({$person}, {$tag}, {$event}, {$source_id}, '{$text}', {$sort})");
    }
}
    form_submit();
    form_end();
    $row = fetch_row("SELECT ecc({$source}), rcc({$source}), ssc({$source})");
    printf("<p>{$_There_are} %s %s, %s %s {$_and} %s %s {$_associated_with_this_source}.</p>", $row[0], $row[0] == 1 ? $_event : $_events, $row[1], $row[1] == 1 ? $_relation : $_relations, $row[2], $row[2] == 1 ? $_subsource : $_subsources);
    echo "</body>\n</html>\n";
} else {
    $person = $_POST['person'];
    $source = $_POST['source'];
    $text = $_POST['text'];
    $source_date = $_POST['source_date'] ? $_POST['source_date'] : fetch_val("SELECT true_date_extract('{$text}')");
    $psource = $_POST['psource'] ? $_POST['psource'] : 0;
    $sort = $_POST['sort'] ? $_POST['sort'] : 1;
    $part_type = $_POST['part_type'];
    $ch_part_type = isset($_POST['ch_part_type']) ? $_POST['ch_part_type'] : 0;
    $sort = get_sort($psource, $text, $sort);
    $text = note_to_db($text);
    $ret = $_POST['ret'];
    $template = isset($_POST['template']) ? $_POST['template'] : false;
    if ($template) {
        if (fetch_val("\n                SELECT count(*)\n                FROM templates\n                WHERE source_fk = {$source}\n            ")) {
            pg_query("\n                UPDATE templates\n                SET template = '{$template}'\n                WHERE source_fk = {$source}\n            ");
        } else {
            pg_query("\n                INSERT INTO templates (source_fk, template)\n                VALUES ({$source}, '{$template}')\n            ");
        }
    }
    // this is a freak situation that arises when $psource = 0
    // and a rather brute hack to remedy it.
    if ($source == $psource) {
        $psource = 0;
    }
    pg_prepare("query", "UPDATE sources SET\n            parent_id = \$1,\n            sort_order = \$2,\n            source_text = \$3,\n            source_date = \$4,\n            part_type = \$5,\n            ch_part_type = \$6\n        WHERE source_id = \$7");
    }
    $tag = $_POST['tag_fk'];
    pg_query("BEGIN");
    $event = fetch_val("\n        INSERT INTO events (\n            tag_fk,\n            place_fk,\n            event_date,\n            sort_date,\n            event_note\n        )\n        VALUES (\n            {$tag},\n            {$place},\n            '{$event_date}',\n            '{$sort_date}',\n            '{$event_note}'\n        )\n        RETURNING event_id\n    ");
    set_last_selected_place($place);
    add_participant($person, $event);
    if ($_POST['coprincipal'] && has_coprincipal($tag)) {
        // constrain to events which allows for coprincipal, ie tag_type = 2
        $coprincipal = $_POST['coprincipal'];
        add_participant($coprincipal, $event);
    }
    if ($tag == 31) {
        // hard-coded reference to probate
        pg_query("SELECT generate_probate_witnesses({$event})");
    }
    $source_id = add_source($person, $tag, $event, $src, note_to_db($txt));
    $age = $_POST['age'];
    if ($age && is_numeric($age)) {
        // generate birth event
        add_birth($person, $event_date, $age, $source_id);
    }
    if ($tag == 3) {
        // hard-coded death tag, check if died young
        if ((died_young($person) || $age && $age < 16) && fetch_val("SELECT dead_child({$person})") == 'f') {
            pg_query("INSERT INTO dead_children (person_fk) VALUES ({$person})");
            pg_query("UPDATE persons SET toponym='' WHERE person_id = {$person}");
        }
    }
    pg_query("COMMIT");
    header("Location: {$app_root}/family.php?person={$person}");
}
     // birth_sources is a view, cf ddl/views.sql
     $handle = pg_query("\n            SELECT\n                source_fk\n            FROM\n                birth_sources\n            WHERE\n                person = {$person}\n        ");
     while ($row = pg_fetch_row($handle)) {
         $source_id = $row[0];
         // check for duplicates
         if (fetch_val("\n                SELECT\n                    COUNT(*)\n                FROM\n                    relation_citations\n                WHERE\n                    relation_fk = {$relation}\n                AND\n                    source_fk = {$source_id}\n            ") == 0) {
             pg_query("\n                    INSERT INTO relation_citations\n                    VALUES ({$relation}, {$source_id})\n                ");
         }
     }
 } else {
     if ($_POST['source_id']) {
         // if not bsource
         if ($_POST['source_text']) {
             // add new source
             $parent_id = $_POST['source_id'];
             $text = note_to_db($_POST['source_text']);
             // use two-param overload of add_source
             $source_id = fetch_val("SELECT add_source({$parent_id}, '{$text}')");
             // remove old citation if new source is an expansion,
             // ie. parent of new source == old source
             pg_query("\n                DELETE FROM\n                    relation_citations\n                WHERE\n                    relation_fk = {$relation}\n                AND\n                    source_fk = {$parent_id}\n            ");
         } else {
             $source_id = $_POST['source_id'];
         }
         // Entering the same source twice for the same relation will violate the
         // composite primary key (relation_fk, source_fk) constraint.
         // Test before trying to insert a relation citation.
         if ($relation && fetch_val("\n                    SELECT\n                        COUNT(*)\n                    FROM\n                        relation_citations\n                    WHERE\n                        relation_fk = {$relation}\n                    AND\n                        source_fk = {$source_id}\n                ") == 0) {
             pg_query("\n                INSERT INTO relation_citations\n                VALUES ({$relation}, {$source_id})\n            ");
         }
     }