function check_uniqueness($table_name, $holder_id_column_name, $timestamp_column_name)
{
    echo "Adding index to {$table_name}. This could take a while...\n";
    $before = gettimeofday();
    dpsql_query("\n        ALTER TABLE {$table_name}\n        ADD INDEX ({$holder_id_column_name},{$timestamp_column_name})\n    ");
    $after = gettimeofday();
    $diff = $after['sec'] - $before['sec'] + 1.0E-6 * ($after['usec'] - $before['usec']);
    echo "{$diff} seconds\n";
    //   4.2 sec for user_teams_stats on .net
    // 414.0 sec for member_stats on .net
    echo "Looking for rows that violate uniqueness...\n";
    $res = dpsql_query("\n        SELECT {$holder_id_column_name}, {$timestamp_column_name}, COUNT(*) AS c\n        FROM {$table_name}\n        GROUP BY {$holder_id_column_name}, {$timestamp_column_name}\n        HAVING c > 1\n        ORDER BY {$timestamp_column_name}, {$holder_id_column_name}\n    ") or die("Aborting");
    if (mysql_num_rows($res) == 0) {
        $satisfies_uniqueness = TRUE;
    } else {
        echo "Some data in {$table_name} table does not satisfy uniqueness.\n";
        echo "Probably they are just duplicate rows.\n";
        echo "Attempting to clean them up...\n";
        echo "\n";
        $n_cleaned_cases = 0;
        $n_uncleanable_cases = 0;
        while (list($holder_id, $timestamp, $c) = mysql_fetch_row($res)) {
            echo "{$holder_id_column_name}={$holder_id} {$timestamp_column_name}={$timestamp} #rows={$c}: ";
            $res2 = dpsql_query("\n                SELECT *\n                FROM {$table_name}\n                WHERE {$holder_id_column_name}={$holder_id} AND {$timestamp_column_name}={$timestamp}\n            ");
            assert(mysql_num_rows($res2) == $c);
            if (all_rows_the_same($res2)) {
                echo "All rows the same. Deleting all but one.\n";
                $all_but_one = $c - 1;
                $delete_query = "\n                    DELETE FROM {$table_name}\n                    WHERE {$holder_id_column_name}={$holder_id} AND {$timestamp_column_name}={$timestamp}\n                    LIMIT {$all_but_one}\n                ";
                // echo "$delete_query\n";
                dpsql_query($delete_query) or die("Aborting");
                $n_cleaned_cases++;
            } else {
                echo "ROWS NOT ALL THE SAME!\n";
                $n_uncleanable_cases++;
            }
        }
        echo "{$n_cleaned_cases} cases cleaned up\n";
        echo "{$n_uncleanable_cases} cases could not be cleaned up\n";
        $satisfies_uniqueness = $n_uncleanable_cases == 0;
    }
    echo "\n";
    if ($satisfies_uniqueness) {
        echo "{$table_name} satisfies uniqueness constraint,\n";
        echo "so should be okay to transfer to past_tallies.\n";
    } else {
        echo "{$table_name} does not satisfy uniqueness constraint,\n";
        echo "so pointless to try to transfer it to past_tallies.\n";
        echo "You will have to fix it first.\n";
    }
    return $satisfies_uniqueness;
}
                 // updated in that interval, but there's no timestamp for it.)
                 if (preg_match('/^round\\d+_text$/', $field_name)) {
                     $time_field_name = str_replace('_text', '_time', $field_name);
                     $time_constraints_str .= sprintf(" AND %s = %s", $time_field_name, $page[$time_field_name]);
                 }
             }
         }
     }
     if (count($changes) > 0) {
         $changes_str = implode(",\n", $changes);
         $sql = "\n                UPDATE {$projectid}\n                SET {$changes_str}\n                WHERE image='{$image}' {$time_constraints_str}\n            ";
         if (0) {
             echo $sql;
         }
         if (1) {
             dpsql_query($sql);
             $n_ar = mysql_affected_rows();
             if ($n_ar != 1) {
                 echo "\n    WARNING: query affected {$n_ar} rows";
                 $all_warnings[] = "{$projectid} {$image} {$field_name} {$n_ar}";
             }
         }
         $n_texts_changed += count($changes);
         $n_pages_changed += 1;
     }
 }
 echo sprintf("... changed %3d texts for %3d pages", $n_texts_changed, $n_pages_changed);
 echo "\n";
 $n_total_texts_changed += $n_texts_changed;
 $n_total_pages_changed += $n_pages_changed;
 if ($n_pages_changed > 0) {
<?php

$relPath = '../../pinc/';
include_once $relPath . 'base.inc';
include_once $relPath . 'misc.inc';
include_once $relPath . 'dpsql.inc';
require_login();
echo "<h1>Cases where multiple projects have the same postednum</h1>\n";
echo "<p>\n    When multiple projects have the same postednum,\n    this usually means that a single book was split into multiple projects\n    to go through the rounds.\n    And when this is easy to detect (titles differ only by a digit),\n    this page skips over the set.\n    However, a shared postednum could also happen\n    when a project was mistakenly assigned another project's postednum.\n    This page should help find those cases.\n</p>\n";
$res = dpsql_query("\n    SELECT postednum, COUNT(*) as c\n    FROM projects\n    GROUP BY postednum\n    HAVING c > 1\n    ORDER BY postednum\n");
while (list($postednum, $count) = mysql_fetch_row($res)) {
    if (is_null($postednum)) {
        continue;
    }
    echo "<br>{$postednum}:\n";
    $res2 = dpsql_query("\n            SELECT nameofwork\n            FROM projects\n            WHERE postednum={$postednum}\n            ORDER BY nameofwork\n        ");
    $titles = array();
    while (list($title) = mysql_fetch_row($res2)) {
        $titles[] = $title;
    }
    list($left, $middles, $right) = factor_strings($titles);
    if (strings_count_up($middles)) {
        echo "skipping '{$left}&lt;N&gt;{$right}'...<br>\n";
        continue;
    }
    dpsql_dump_query("\n        SELECT FROM_UNIXTIME(modifieddate), state, nameofwork\n        FROM projects\n        WHERE postednum={$postednum}\n        ORDER BY nameofwork\n    ");
}
function strings_count_up($strings)
{
    for ($i = 0; $i < count($strings); $i++) {
        if ($strings[$i] == '' . ($i + 1)) {
<?php

$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
echo "Creating 'authors' table...\n";
dpsql_query("\n    CREATE TABLE authors (\n      author_id     MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,\n      other_names   VARCHAR(40)           NOT NULL DEFAULT '',\n      last_name     VARCHAR(25)           NOT NULL DEFAULT '',\n      byear         MEDIUMINT(9)          NOT NULL DEFAULT '0',\n      bmonth        TINYINT(4)            NOT NULL DEFAULT '0',\n      bday          TINYINT(4)            NOT NULL DEFAULT '0',\n      bcomments     VARCHAR(20)           NOT NULL DEFAULT '',\n      dyear         MEDIUMINT(9)          NOT NULL DEFAULT '0',\n      dmonth        TINYINT(4)            NOT NULL DEFAULT '0',\n      dday          TINYINT(4)            NOT NULL DEFAULT '0',\n      dcomments     VARCHAR(20)           NOT NULL DEFAULT '',\n      enabled       TINYTEXT              NOT NULL,\n      last_modified TIMESTAMP(14)         NOT NULL,\n\n      PRIMARY KEY author_id (author_id)\n    ) TYPE=MyISAM\n") or die("Aborting\n");
echo "Creating 'biographies' table...\n";
dpsql_query("\n    CREATE TABLE biographies (\n      bio_id        INT(11)       NOT NULL AUTO_INCREMENT,\n      author_id     INT(11)       NOT NULL DEFAULT '0',\n      bio           TEXT          NOT NULL,\n      last_modified TIMESTAMP(14) NOT NULL,\n\n      PRIMARY KEY bio_id (bio_id)\n    ) TYPE=MyISAM COMMENT='Contains biographies (see authors)'\n") or die("Aborting\n");
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab
the old messages as-is in the new table.  (Though if old messages
could be broken into items, those might be useful.)

So, rather than altering the existing 'news' table, mothball it
and create a new one.
*/
// -----------------------------------------------
// Mothball the old news table
echo "Mothballing the old 'news' table...\n";
dpsql_query("\n    RENAME TABLE news TO old_site_news\n") or die("Aborting.");
// -----------------------------------------------
// Create new news table.
echo "Creating the new 'news_items' table...\n";
dpsql_query("\n    CREATE TABLE news_items (\n        id           INT         NOT NULL auto_increment,\n        date_posted  INT         NOT NULL default 0,\n        news_page_id VARCHAR(8)           default NULL,\n        status       VARCHAR(8)  NOT NULL default '',\n        ordering     SMALLINT    NOT NULL default '0',\n        content      TEXT        NOT NULL,\n        PRIMARY KEY id (id)\n    ) TYPE=MyISAM\n") or die("Aborting.");
// -----------------------------------------------
// Create news_pages table
echo "Creating 'news_pages' table...\n";
dpsql_query("\nCREATE TABLE `news_pages` (\n  `news_page_id` varchar(8) NOT NULL default '',\n  `news_type` varchar(40) NOT NULL default '',\n  `modifieddate` varchar(10) \n) TYPE=MyISAM\n") or die("Aborting.");
// -----------------------------------------------
// Populate news_pages table with default values
echo "Populating 'news_pages' table...\n";
dpsql_query("\nINSERT INTO `news_pages` VALUES ('HUB', 'Activity Hub',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('P1', 'First Round Proofreading',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('P2', 'Second Round Proofreading',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('F1', 'First Round Formatting',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('F2', 'Second Round Formatting',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('FRONT', 'Front Page',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('PP', 'Post Processing',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('FAQ', 'FAQ CENTRAL',UNIX_TIMESTAMP());\n") or die("Aborting.");
dpsql_query("\nINSERT INTO `news_pages` VALUES ('STATS', 'Stats Central',UNIX_TIMESTAMP());\n") or die("Aborting.");
echo "\nDone!\n";
<?php

// One-time script to create 'image_sources' table
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
// -----------------------------------------------
// Create 'image_sources' table.
echo "Creating 'images_sources' table...\n";
dpsql_query("\nCREATE TABLE image_sources (\n  code_name varchar(10) NOT NULL default '',\n  display_name varchar(30) NOT NULL default '',\n  full_name varchar(100) NOT NULL default '',\n  info_page_visibility tinyint(3) unsigned NOT NULL default '0',\n  is_active tinyint(3) NOT NULL default '-1',\n  url varchar(200) default NULL,\n  credit varchar(200) default NULL,\n  ok_keep_images tinyint(4) NOT NULL default '-1',\n  ok_show_images tinyint(4) NOT NULL default '-1',\n  public_comment varchar(255) default NULL,\n  internal_comment text default NULL,\n  UNIQUE KEY code_name (code_name),\n  UNIQUE KEY display_name (display_name)\n) TYPE=MyISAM;\n\n  \n    \n") or die("Aborting.");
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab
function shift_range($projectid, $n_digits, $lo, $hi, $offset, $dryrun)
{
    echo "<pre>\n";
    $assertions = array('is_int($n_digits)', 'is_int($lo)', 'is_int($hi)', 'is_int($offset)', '$n_digits > 0', '$lo <= $hi', '$offset != 0', '$lo + $offset >= 0');
    $n_assertions_that_failed = 0;
    foreach ($assertions as $assertion) {
        if (eval("return {$assertion};")) {
            // good
        } else {
            echo sprintf(_("ERROR: shift_range: assertion failed: %s"), $assertion) . "\n";
            $n_assertions_that_failed++;
        }
    }
    if ($n_assertions_that_failed > 0) {
        echo _("Aborting due to assertion failures.") . "\n";
        echo "</pre>";
        return;
    }
    // --------------------------------------------------------------------
    // Move range $lo -> $hi to range $lo+$offset -> $hi+$offset.
    if ($offset < 0) {
        $start_i = $lo;
        $end_i = $hi + 1;
        $incr_i = +1;
    } else {
        $start_i = $hi;
        $end_i = $lo - 1;
        $incr_i = -1;
    }
    $padded_fmt = "%0{$n_digits}d";
    global $projects_dir;
    echo "cd {$projects_dir}/{$projectid}\n";
    chdir("{$projects_dir}/{$projectid}") or die("aborting");
    // Pass 1: Make sure that we're not shifting into occupied territory.
    // Pass 2: Do the shift.
    for ($pass = 1; $pass <= 2; $pass++) {
        echo "\n";
        echo "PASS {$pass} starts\n";
        if ($pass == 2) {
            if ($dryrun) {
                echo _("(dry run)") . "\n";
            } else {
                echo _("(the real thing!)") . "\n";
            }
        }
        for ($i = $start_i; $i != $end_i; $i += $incr_i) {
            $j = $i + $offset;
            if ($pass == 1 and $j == $start_i) {
                // From here on, we *expect* $png_filename_j [etc] to exist,
                // but they won't exist once the shift is happening.
                break;
            }
            $padded_i = sprintf($padded_fmt, $i);
            $padded_j = sprintf($padded_fmt, $j);
            echo "\n";
            echo "  {$padded_i} -> {$padded_j}\n";
            // -------------------------------------------
            // Rename .png file
            $png_filename_i = $padded_i . '.png';
            $png_filename_j = $padded_j . '.png';
            if ($pass == 1) {
                if (is_file($png_filename_j)) {
                    echo sprintf(_("ERROR: shift_range: %1\$s would become %2\$s, but that already exists."), $png_filename_i, $png_filename_j) . "\n";
                    echo "</pre>";
                    return;
                }
            } else {
                echo "    " . sprintf(_("renaming %1\$s as %2\$s"), $png_filename_i, $png_filename_j) . "\n";
                if (!$dryrun) {
                    rename($png_filename_i, $png_filename_j);
                }
            }
            // -------------------------------------------
            // Rename .txt file
            $txt_filename_i = $padded_i . '.txt';
            $txt_filename_j = $padded_j . '.txt';
            if ($pass == 1) {
                if (is_file($txt_filename_j)) {
                    echo sprintf(_("ERROR: shift_range: %1\$s would become %2\$s, but that already exists."), $txt_filename_i, $txt_filename_j) . "\n";
                    echo "</pre>";
                    return;
                }
            } else {
                echo "    " . sprintf(_("renaming %1\$s as %2\$s"), $txt_filename_i, $txt_filename_j) . "\n";
                if (!$dryrun) {
                    rename($txt_filename_i, $txt_filename_j);
                }
            }
            // -------------------------------------------
            // Check/tweak the DB.
            if ($pass == 1) {
                // Check whether a row for $png_filename_j already exists.
                $q = "SELECT image FROM {$projectid} WHERE image='{$png_filename_j}'";
                // echo "    $q\n";
                if (mysql_num_rows(dpsql_query($q)) > 0) {
                    echo sprintf(_("ERROR: shift_range: %1\$s would become %2\$s, but there is already a row in the page table for the latter."), $png_filename_i, $png_filename_j) . "\n";
                    echo "</pre>";
                    return;
                }
            } else {
                echo "    " . _("updating the page table") . "\n";
                if (!$dryrun) {
                    global $writeBIGtable;
                    if ($writeBIGtable) {
                        $q = "UPDATE project_pages SET fileid='{$padded_j}', image='{$png_filename_j}' WHERE projectid = '{$projectid}' AND  image='{$png_filename_i}'";
                        // echo "    $q\n";
                        dpsql_query($q);
                    }
                    $q = "UPDATE {$projectid} SET fileid='{$padded_j}', image='{$png_filename_j}' WHERE image='{$png_filename_i}'";
                    // echo "    $q\n";
                    dpsql_query($q);
                }
            }
        }
        echo "\n";
        echo sprintf(_("PASS %d done"), $pass) . "\n";
    }
    echo "</pre>";
}
<?php

// One-time script to create 'quiz_passes' table
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
echo "Creating 'quiz_passes' table...\n";
dpsql_query("\n    CREATE TABLE quiz_passes (\n        username  VARCHAR(25) NOT NULL default '',\n        date      INT(20)     NOT NULL default '0',\n        quiz_page VARCHAR(15) NOT NULL default '',\n        result    VARCHAR(10) NOT NULL default '',\n        INDEX (username,quiz_page)\n    ) TYPE=MyISAM\n") or die("Aborting.");
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab
    $sampleLimit = $default_sampleLimit;
}
if (empty($days)) {
    $days = $default_days;
}
// confirm the review_round_id is later than work_round_id
if (array_search($review_round_id, $rounds) <= array_search($work_round_id, $rounds)) {
    echo "<p class='error'>" . _("Review Round should be a round later than Work Round.") . "</p>";
    exit;
}
echo "<hr>";
// we should have valid information at this point
$work_round = get_Round_for_round_id($work_round_id);
$review_round = get_Round_for_round_id($review_round_id);
$time_limit = time() - $days * 24 * 60 * 60;
$res2 = dpsql_query("\n    SELECT\n        page_events.projectid,\n        state,\n        nameofwork,\n        deletion_reason,\n        FROM_UNIXTIME(MAX(timestamp)) AS time_of_latest_save\n    FROM page_events LEFT OUTER JOIN projects USING (projectid)\n    WHERE round_id='{$work_round->id}' AND \n          page_events.username='******' AND \n          event_type='saveAsDone' AND\n          timestamp>{$time_limit}\n    GROUP BY page_events.projectid\n    ORDER BY time_of_latest_save DESC\n") or die("Aborting");
$num_projects = mysql_num_rows($res2);
echo "<p>" . sprintf(_("<b>%d</b> projects with pages saved in <b>%s</b> by <b>%s</b> within the last <b>%d</b> days."), $num_projects, $work_round->id, $username, $days) . "</p>";
// ---------------------------------------------
// snippets for use in queries
$has_been_saved_in_review_round = "(state='{$review_round->page_save_state}'";
for ($rn = $review_round->round_number + 1; $rn <= MAX_NUM_PAGE_EDITING_ROUNDS; $rn++) {
    $round = get_Round_for_round_number($rn);
    $has_been_saved_in_review_round .= " OR state LIKE '{$round->id}.%'";
}
$has_been_saved_in_review_round .= ")";
// echo "$has_been_saved_in_review_round<br>\n";
$there_is_a_diff = "\n    {$work_round->text_column_name}\n    !=\n    BINARY {$review_round->text_column_name}\n";
// ---------------------------------------------
echo "<table border='1'>";
echo "<tr>";
Exemple #10
0
if ($round->is_a_mentor_round()) {
    if (user_can_work_on_beginner_pages_in_round($round)) {
        mentor_banner($round);
    }
}
if ($pagesproofed <= 20) {
    if ($uao->can_access) {
        echo "<hr width='75%'>\n";
        echo "<font face='" . $theme['font_mainbody'] . "'><b>";
        echo _("Click on the title of a book in the list below to start proofreading.");
        echo "</b></font><br><br>\n";
    }
} else {
    // Link to queues.
    echo "<hr width='75%'>\n";
    echo "<h4 align='center'>", _('Release Queues'), "</h4>";
    $res = dpsql_query("\n        SELECT COUNT(*)\n        FROM queue_defns\n        WHERE round_id='{$round->id}'\n    ");
    list($n_queues) = mysql_fetch_row($res);
    if ($n_queues == 0) {
        echo sprintf(_("%s does not have any release queues. Any projects that enter the round's waiting area will automatically become available within a few minutes."), $round->id);
        echo "\n";
    } else {
        echo sprintf(_("The <a href='%s'>%s release queues</a> show the books that are waiting to become available for work in this round."), "{$code_url}/stats/release_queue.php?round_id={$round->id}", $round->id);
        echo "\n";
    }
}
// Don't display the filter block or the special colours legend to newbies.
$show_filter_block = $pagesproofed > 20;
$allow_special_colors_legend = $pagesproofed >= 10;
show_projects_for_round($round, $show_filter_block, $allow_special_colors_legend);
// vim: sw=4 ts=4 expandtab
if (is_null($current_max_date)) {
    // The site_tally_goals table is empty.
    // We should probably assume that the
    // site admins want to keep it that way.
    exit;
}
$res2 = dpsql_query("\n    SELECT tally_name, goal\n    FROM site_tally_goals\n    WHERE date='{$current_max_date}'\n") or die("Aborting");
$values_list = '';
// Ensure that the table is defined for at least the next 35 days.
$desired_max_date = strftime('%Y-%m-%d', strtotime('+35 days'));
// What I'd *like* to be able to write:
// for ( $d = $current_max_date+1; $d <= today() + 35; $d++ )
for ($i = 1;; $i++) {
    $date = strftime('%Y-%m-%d', strtotime("{$current_max_date} + {$i} day"));
    if ($date > $desired_max_date) {
        break;
    }
    mysql_data_seek($res2, 0) or die(mysql_error());
    while (list($tally_name, $goal) = mysql_fetch_row($res2)) {
        if (!empty($values_list)) {
            $values_list .= ',';
        }
        $values_list .= "( '{$date}', '{$tally_name}', {$goal} )\n";
    }
    $values_list .= "\n";
}
if (empty($values_list)) {
    return;
}
dpsql_query("\n    INSERT INTO site_tally_goals\n    VALUES\n    {$values_list}\n") or die("Aborting");
// vim: sw=4 ts=4 expandtab
<?php

// One-time script to create 'access_log' table
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
echo "Creating table 'access_log'...\n";
dpsql_query("\nCREATE TABLE `access_log` (\n  `timestamp` INT( 20 ) NOT NULL ,\n  `subject_username` VARCHAR( 25 ) NOT NULL ,\n  `modifier_username` VARCHAR( 25 ) NOT NULL ,\n  `action` VARCHAR( 16 ) NOT NULL ,\n  `activity` VARCHAR( 10 ) NOT NULL ,\n  INDEX ( `subject_username`,`timestamp` )\n) TYPE=MyISAM;\n") or die("Aborting.");
echo "\nDone!\n";
        break;
    default:
        die("bad 'timeframe' value: '{$title_timeframe}'");
}
switch ($c_or_i) {
    case 'increments':
        $main_title = _('Pages Done Per Day');
        break;
    case 'cumulative':
        $main_title = _('Cumulative Pages Done');
        break;
    default:
        die("bad 'cori' value: '{$c_or_i}'");
}
// -----------------------------------------------------------------------------
$result = dpsql_query(select_from_site_past_tallies_and_goals($tally_name, "SELECT {date}, tally_delta, goal", $where_clause, "", "ORDER BY timestamp", ""));
list($datax, $datay1, $datay2) = dpsql_fetch_columns($result);
if ($c_or_i == 'cumulative') {
    $datay1 = array_accumulate($datay1);
    $datay2 = array_accumulate($datay2);
    // The accumulated 'actual' for today and subsequent days is bogus,
    // so delete it.
    $date_today = strftime('%Y-%m-%d', $now_timestamp);
    for ($i = 0; $i < count($datax); $i++) {
        if ($datax[$i] >= $date_today) {
            unset($datay1[$i]);
        }
    }
}
if (empty($datay1)) {
    $datay1[0] = 0;
$default_order_col = $order_col = 'state';
$default_order_dir = $order_dir = 'D';
if ($sorting == 'reserved') {
    list($order_col, $order_dir) = get_sort_col_and_dir();
}
$sql_order = sql_order_spec($order_col, $order_dir);
if ($order_col != $default_order_col) {
    // Add the default ordering as a secondary ordering.
    $sql_order .= ", " . sql_order_spec($default_order_col, $default_order_dir);
}
// We're interested in projects that have been created, but haven't *finished*
// being proofread.
$psd = get_project_status_descriptor('created');
$antipsd = get_project_status_descriptor('proofed');
$query = "\n\tSELECT\n         projectid,\n         nameofwork,\n         username,\n\t\t state\n\tFROM projects\n\tWHERE checkedoutby='{$username}'\n\t\tAND {$psd->state_selector}\n\t\tAND NOT {$antipsd->state_selector}\n\tORDER BY {$sql_order}";
$result = dpsql_query($query);
if (mysql_num_rows($result) > 0) {
    echo "<a name='reserved' id='reserved'></a><h2>{$heading_reserved}</h2>\n";
    echo sprintf("(%d projects)", mysql_num_rows($result));
    echo "<table border='1'>";
    show_headings($colspecs, 'reserved', $username);
    while ($row = mysql_fetch_object($result)) {
        echo "<tr>\n";
        echo "<td>";
        echo "<a href='{$code_url}/project.php?id={$row->projectid}'>{$row->nameofwork}</a>";
        echo "</td>\n";
        echo "<td align='center'>";
        echo $row->username;
        echo "</td>\n";
        echo "<td nowrap>";
        echo get_medium_label_for_project_state($row->state);
<?php

// One-time script to modify rules table
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
// -----------------------------------------------
// Add new columns to rules table to support round- and document-specific
// random rule selection.
// document points to the faq/FILENAME of the document the rule comes from
// anchor points to the HTML anchor within the document.
// Remove doc column as it assumes single-document guidelines.
echo "Adding and dropping columns to/from 'rules' table...\n";
dpsql_query("\n    ALTER TABLE rules \n    ADD document VARCHAR(255) AFTER id,\n    ADD anchor VARCHAR(255) AFTER document,\n    DROP COLUMN doc\n") or die("Aborting.");
// -----------------------------------------------
// Remove all existing rules
echo "Removing all existing rules...\n";
dpsql_query("\nTRUNCATE rules\n") or die("Aborting.");
echo "\nDone!\n";
<?php

// One-time script to create and seed 'site_tally_goals' table.
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
header('Content-type: text/plain');
echo "Creating 'site_tally_goals' table...\n";
dpsql_query("\n    CREATE TABLE site_tally_goals (\n        date         DATE     NOT NULL,\n        tally_name   CHAR(2)  NOT NULL,\n        goal         INT(6)   NOT NULL,\n\n        PRIMARY KEY (date, tally_name)\n    )\n") or die("Aborting");
// ------------------------------------------------------
echo "Giving it some initial data...\n";
// You can change these goal values to whatever you want,
// either here (before you run the script),
// or in the table (after you run the script).
dpsql_query("\n    INSERT INTO site_tally_goals\n    VALUES\n        ( CURDATE(),                  'P1', 2000 ),\n        ( CURDATE(),                  'P2',  100 ),\n        ( CURDATE(),                  'F1',  100 ),\n        ( CURDATE(),                  'F2',  100 ),\n        ( CURDATE() + INTERVAL 1 DAY, 'P1', 3000 ),\n        ( CURDATE() + INTERVAL 1 DAY, 'P2',  200 ),\n        ( CURDATE() + INTERVAL 1 DAY, 'F1',  200 ),\n        ( CURDATE() + INTERVAL 1 DAY, 'F2',  200 )\n") or die("Aborting");
// Now that there's some data in the table, the nightly
// run of the 'extend_site_tally_goals.php' script
// will ensure that there are goals for the next month or so.
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab
// at the end of the run) of projectID* tables already
// having the desired indexes so this is mostly a safety
// net, but it's here if you need/want it.
$start_with_sequence_number = 0;
$relPath = '../../../pinc/';
include_once $relPath . 'stages.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
echo "Adding round#_user indexes to all projectID* tables...\n";
// First, obtain the names of username fields in the rounds
$user_column_names = array();
foreach ($Round_for_round_id_ as $id => $round) {
    $user_column_names[] = $round->user_column_name;
}
// Find all project IDs
$res = dpsql_query("\n    SELECT projectid\n    FROM projects\n    ORDER BY projectid\n");
$n_projects = mysql_num_rows($res);
$messages = array();
$delay_microseconds = ceil($delay * 1000000);
// Loop through each project
$project_index = 0;
while (list($projectid) = mysql_fetch_row($res)) {
    // print out a status message
    $project_index++;
    // check that we're past our desired start sequence number
    if ($project_index < $start_with_sequence_number) {
        continue;
    }
    echo sprintf("%5d/%5d: %s:", $project_index, $n_projects, $projectid);
    // confirm the projectID* table exists (ie: not archived or deleted)
    $describe_results = mysql_query("SELECT 1 FROM {$projectid} LIMIT 0");
<?php

// One-time script to create 'special_days' table
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
// -----------------------------------------------
// Create 'special_days' table.
echo "Creating 'special_days' table...\n";
dpsql_query("\nCREATE TABLE special_days (\n  spec_code varchar(20) NOT NULL default '',\n  display_name varchar(80) NOT NULL default '',\n  enable tinyint(1) NOT NULL default '1',\n  comment varchar(255) default NULL,\n  color varchar(8) NOT NULL default '',\n  open_day tinyint(2) default NULL,\n  open_month tinyint(2) default NULL,\n  close_day tinyint(2) default NULL,\n  close_month tinyint(2) default NULL,\n  date_changes varchar(100) default NULL,\n  info_url varchar(255) default NULL,\n  image_url varchar(255) default NULL,\n  UNIQUE KEY spec_code (spec_code)\n) TYPE=MyISAM COMMENT='definitions of SPECIAL days';\n    \n    \n") or die("Aborting.");
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab
<?php

// One-time script to create 'uber_projects' table
$relPath = '../../../pinc/';
include_once $relPath . 'connect.inc';
include_once $relPath . 'dpsql.inc';
new dbConnect();
// -----------------------------------------------
// Create 'uber_projects' table.
echo "Creating 'uber_projects' table...\n";
dpsql_query("\nCREATE TABLE `uber_projects` (\n  `up_projectid` INT( 10 ) NOT NULL AUTO_INCREMENT,\n  `up_nameofwork` varchar(255) NOT NULL default '',\n  `up_topic_id` int(10) default NULL,\n  `up_contents_post_id` int(10) default NULL,\n  `up_modifieddate` int(20) NOT NULL default '0',\n  `up_enabled` tinyint(1) default '1',\n  `up_description` text default NULL,\n  `d_nameofwork` varchar(255) default NULL,\n  `d_authorsname` varchar(255) default NULL,\n  `d_language` varchar(255) default NULL ,\n  `d_comments` text default NULL,\n  `d_special` varchar(20) default NULL ,\n  `d_checkedoutby` varchar(25) default NULL,\n  `d_scannercredit` tinytext default NULL,\n  `d_clearance` text default NULL,\n  `d_year` varchar(4) default NULL,\n  `d_genre` varchar(50) default NULL,\n  `d_difficulty` varchar(20) default NULL,\n  `d_image_source` varchar(10) default NULL,\n  `d_image_preparer` VARCHAR(25)  default NULL , \n  `d_text_preparer`  VARCHAR(25)  default NULL,\n  `d_extra_credits`  TINYTEXT     default NULL,\n\n  PRIMARY KEY  (`up_projectid`)\n) TYPE=MyISAM;    \n    \n") or die("Aborting.");
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab
    echo $info;
    echo "\n";
    echo "The page_count has already been copied into the current_tallies table.\n";
    echo "In case there's anything else useful in the above data, we're going to write\n";
    echo "it to a file (which should appear in the directory containing this script).\n";
    echo "...\n";
    $time = strftime('%Y%m%d_%H%M%S');
    $filename = "team_1_data_{$time}.txt";
    $fp = fopen($filename, 'w');
    if (!$fp) {
        die("Failed to open {$filename}, so aborting");
    }
    $n = fwrite($fp, $info);
    if (!$n) {
        die("Failed to write to {$filename}, so aborting");
    }
    $r = fclose($fp);
    if (!$r) {
        die("Failed to close {$filename}, so aborting");
    }
    echo "The data appears to have been successfully saved in {$filename}.\n";
    echo "\n";
    echo "Proceeding to delete the row...\n";
    dpsql_query("\n        DELETE\n        FROM user_teams\n        WHERE id=1\n    ") or die("Aborting.");
    echo "\n";
    echo "Deleted.\n";
    echo "Maybe save this page too, just in case.\n";
    echo "\n";
}
echo "\nDone!\n";
// vim: sw=4 ts=4 expandtab